#69128·starrocks

[Proposal] Constructing a Controllable and Precise Memory Statistics System

Author: silverbullet233Created Feb 10, 2026Updated Sep 28, 2026
Labelstype/enhancementno-issue-activity

Background

In StarRocks, troubleshooting memory-related issues such as OOM (Out Of Memory), memory leaks, or unexpected high usage remains a significant challenge. While the current MemTracker provides a foundation for monitoring, it lacks the granularity and precision required to quickly pinpoint root causes in complex production environments.

This proposal builds a robust, multi-layer memory statistics system (Query → Fragment → Operator) with a unified allocation entry point. The system ensures every byte is accounted for and correctly attributed to the responsible task or component.

Current Pain Points

PP1. When a small number of tasks consume large BE resources, both live troubleshooting and post-mortem analysis are difficult.

  • metrics can expose resource usage by task category, but cannot reliably expose per-task details due to metric tag cardinality limits.
  • show proc '/current_queries' is query-centric and does not cover system-triggered background tasks; it is not organized for node-level troubleshooting on a specific BE.
  • FE audit logs are event-oriented and do not capture in-flight resource evolution or BE-level runtime breakdown per task.
  • As a result, operators cannot directly answer: which exact tasks are consuming resources on this BE right now, and which tasks caused the spike earlier?

PP2. When a query uses unexpectedly high memory, operator-level root cause is still hard to identify.

  • Today, query memory is tracked mainly at Query → Fragment level; operator-level visibility is incomplete.
  • Without reliable operator-level memory attribution, existing signals are often insufficient for root-cause analysis when memory usage is abnormal.
  • If we can observe trustworthy operator-level peak usage and map it to the execution plan, troubleshooting efficiency improves substantially.

Root Causes

The pain points above stem from four structural gaps in the current design.

DG1. Unclear memory ownership semantics. Operator-level tracking requires a clear ownership contract: an allocation and its corresponding free must be charged to the same owner, or transferred explicitly with strict accounting. In the current model, accounting relies on thread-local MemTracker. If allocation and free happen under different Fragment/Operator contexts, they are charged to different trackers, causing attribution drift.

DG2. Fragility of thread-local context in asynchronous execution. BE execution relies on brpc/bthread scheduling and may switch underlying pthreads. In these paths, thread-local context propagation is inherently fragile and has historically caused accounting mismatches — for example, allocation charged to the process tracker while free is charged to the query pool tracker. The current mechanism also lacks proactive validation, so many issues are only found during incident debugging.

DG3. No unified resource abstraction across task types. Queries, loads, and background jobs all consume multi-dimensional resources: CPU time, Memory, Disk IO, and Network IO. Today, resource accounting is fragmented by subsystem and metric surface. BE lacks a unified abstraction to model and manage resources consistently at task scope, which limits both observability and future governance.

DG4. Over-reliance on global mem_hook limits attribution quality. mem_hook provides broad coverage by intercepting almost all BE allocations. However, allocations from StarRocks-owned structures and third-party libraries share the same accounting path, and ownership is inferred from ambient thread-local context rather than being stated explicitly. This weakens attribution boundaries and makes it difficult to identify which controllable component should be optimized first.

Key Design Decisions

The following decisions shape the entire solution. Understanding these choices — and the rationale behind them — is essential for evaluating the design trade-offs.

Decision 1: Introduce a Unified Allocator as the single memory management entry point for core structures

The root cause of DG1 and DG2 is that mem_hook cannot determine the logical owner of an allocation — it can only infer it from the current thread's thread-local MemTracker, which may not match the actual owner in async execution paths.

The Unified Allocator solves this by binding each Allocator instance to a MemTracker at construction time. Because alloc and free go through the same Allocator instance, the accounting is always consistent — no thread-local context is involved. When ownership must transfer between components (e.g. data moved into a shared cache), the transfer must happen through an explicit API rather than implicitly via context switching.

This is what makes memory attribution trustworthy: the Allocator is both the allocation mechanism and the ownership contract.

Decision 2: Unified Allocator coexists with mem_hook — it does not replace it

It is fundamentally impossible to route all BE allocations through the Unified Allocator. Third-party libraries manage their own memory internally; controlling those allocations would require owning every dependency, which is not realistic. mem_hook remains the only practical mechanism for covering allocations that StarRocks does not directly control.

The realistic goal is: every allocation that StarRocks owns and controls goes through the Unified Allocator; everything else falls back to mem_hook. This gives us a clear and stable boundary:

  • Unified Allocator: StarRocks-owned core structures (Column, Chunk, MemPool, PageCache, etc.) — attribution is precise and ownership is enforced
  • mem_hook: third-party libraries and anything outside StarRocks' direct control — attribution remains best-effort

Both paths are visible under one accounting view. Rollout is controlled by feature flags so each migration step can be validated independently.

Importantly, the underlying accounting and enforcement mechanism does not change: both the Unified Allocator and mem_hook ultimately record usage through MemTracker. Memory limits remain enforced as before. The only thing that changes for migrated structures is the allocation entry point — and because each allocation is charged through exactly one path, there is no double-counting between the two mechanisms.

This coexistence is the stable long-term architecture, not a transitional compromise. The more memory is managed through the Unified Allocator, the more precise the overall attribution becomes, and the more actionable the observability signals are for troubleshooting. Every additional structure migrated to the Unified Allocator is an incremental, independently valuable improvement — the system does not require full coverage to deliver meaningful benefits.

Decision 3: Operator-level tracking is only trustworthy after core structures migrate to the Unified Allocator

Adding a more granular MemTracker hierarchy (Query → Fragment → Operator) without first migrating core structures would produce more detailed but still unreliable numbers — the attribution drift described in DG1 and DG2 would persist at a finer granularity.

This is why the Unified Allocator is Phase 1 and operator-level tracking is Phase 2. The dependency is strict and intentional.

Proposed Solution

The following table shows how each proposed capability addresses the identified problems:

Proposed Capability Addresses Pain Points Addresses Root Causes
Unified Allocator PP1, PP2 DG1, DG2, DG4
Task-level resource observability (ResourceCtx + sys.tasks_resource_usage) PP1 DG3
Query → Fragment → Operator tracking with ownership model PP2 DG1, DG2
DEBUG-mode sanity checks PP1, PP2 DG1, DG2

0. Foundation: The Unified Allocator

Addresses DG1, DG2, and DG4. Enables all other solutions.

All other improvements in this proposal depend on one foundational change: replacing implicit, thread-local-based memory attribution with explicit, call-site-bound ownership.

The attribution problem in detail

Today, mem_hook intercepts malloc/free globally. At the point of interception, there is no direct connection between the allocation and its logical owner. The hook relies on the current thread's thread-local MemTracker to determine who to charge.

This has one critical structural weakness: the thread-local context may not match the logical owner of the data being allocated. In async execution paths (brpc callbacks, bthread scheduling), the thread executing the allocation may differ from the thread that originally created the data structure. The result is attribution drift — the same data may be charged to different trackers at alloc and free time, and there is no mechanism to detect this mismatch early.

This drift is not an edge case. It is structural: any sufficiently complex async execution pipeline will encounter it.

What the Unified Allocator changes

Each Allocator instance is bound to a MemTracker at construction time. Core structures use the Allocator as their single memory management entry point, so every alloc and free is automatically charged to the correct tracker — no thread-local context is consulted. When ownership must change (e.g., a Column passed between operators, or data moved into shared cache), an explicit transfer API is called rather than relying on context switching.

Operator-level peak usage and alloc - free only become trustworthy signals after the primary data carriers (Column, Chunk, MemPool) go through this path. This is the prerequisite for everything in Phase 2.

1. How to find memory-heavy tasks on a BE

Addresses PP1 and DG3.

Introduce a system table (e.g., sys.tasks_resource_usage) that exposes resource usage for all running tasks on a BE, including queries, loads, and background jobs. During incidents, operators can directly query this table to identify high-memory tasks. For post-mortem analysis, Manager/FE can periodically snapshot this table and persist time-series records. By comparing snapshots, we can identify which tasks caused sudden memory spikes.

Implementation model:

  • Introduce ResourceCtx as the unified resource abstraction for one task, covering CPU time, Memory, Disk IO, and Network IO.
  • Introduce ResourceCtxMgr to centrally manage all ResourceCtx instances on one BE and provide a unified query surface for external observers.
  • Task lifecycle integration:
    1. Register a ResourceCtx before task execution.
    2. Continuously update resource usage during execution.
    3. Unregister and finalize the context when the task ends.
  • For memory specifically, ResourceCtx references the task root MemTracker; existing memory accounting paths do not need to be rewritten in this phase.

2. How to find memory-heavy operators in a query

Addresses PP2 and DG1, DG2. Depends on Section 0.

Memory tracking will be refined to Query → Fragment → Operator.

Operator memory accounting follows a strict ownership model: every allocation is bound to exactly one operator MemTracker for its lifetime. All free/usage attribution must return to that owner. If ownership changes across operator boundaries or to shared components (e.g., cache), the change must happen through an explicit transfer API — not implicitly through context switching.

With this model, operator-level peak usage and alloc - free become trustworthy signals and can be mapped back to the execution plan to identify memory-heavy operators quickly.

This capability is only achievable after the core data-carrying structures (Column, Chunk, MemPool) use the Unified Allocator, as described in Section 0. Attempting to build this layer before that migration would reproduce the same attribution drift at a finer granularity.

3. Ownership-safe allocation APIs and sanity checks

Addresses DG1, DG2, and DG4. Reinforces the correctness guarantees of Sections 0 and 2.

  • Core structures use explicit allocation APIs so ownership is bound at allocation time and transfers are explicit and auditable.
  • Critical accounting is decoupled from fragile thread-local propagation in async/thread-switching paths.
  • In DEBUG mode, the tracker records allocation/free events and detects ownership mismatches early in CI — instead of waiting for production incidents.

Phased Roadmap

Phase 1: Foundation — Interface Migration

Goal: Establish the Allocator abstraction and migrate core query data structures to use it. No behavioral change; all structures continue using TrackedAllocator (TLS-based, same semantics as the current mem_hook path) as the default implementation. This phase is a pure interface migration — ownership semantics and memory accounting remain identical to today.

Completed:

  • memory::Allocator abstract interface introduced (#68788)
  • RawBuffer<T> and Buffer<T> — new column buffer implementation (#69949)

Remaining:

  • Switch the Buffer<T> alias in vectorized_fwd.h from std::vector<T, ColumnAllocator<T>> to the new column::Buffer<T>. This is the primary integration work for Phase 1 — all Column-related code depends on this alias, so the change has a wide blast radius and requires careful, incremental rollout.
  • Migrate MemPool to Allocator
  • Migrate PageCache to Allocator
  • Migrate other query-layer data structures to Allocator

Storage-layer structures (Compaction, Tablet Meta, etc.) are explicitly out of scope for this phase and will be addressed later.

Exit criteria: All migrated structures pass existing tests with no performance regression. TrackedAllocator behavior is identical to the pre-migration baseline.

To make migration progress quantifiable, MemTracker will be extended with two separate counters to distinguish the source of each allocation: one for memory charged through the Allocator path, and one for memory charged through mem_hook. The ratio of allocator-managed bytes to total bytes — measured at the query/fragment MemTracker level, where Phase 1 migration is focused — serves as a concrete indicator of how much of the controllable allocation surface has been migrated. This ratio guides prioritization of remaining work and provides a clear signal for when Phase 1 coverage is sufficient to proceed.


Phase 2: Operator MemTracker — Shadow Observation

Goal: Introduce operator-level memory tracking as a purely observational layer, with zero impact on the existing accounting tree.

A CountingAllocator is introduced as a wrapper: it delegates all allocation calls to TrackedAllocator (preserving the existing process → query pool → fragment accounting path unchanged), and additionally updates a per-operator MemTracker. Because the Operator MemTracker has no parent node, its counts do not flow into the existing hierarchy — it is a standalone observer.

This design has a useful property: the same allocations are independently recorded by both TrackedAllocator (via Fragment MemTracker) and CountingAllocator (via Operator MemTracker). Comparing the two during this phase provides a natural cross-validation mechanism to verify that operator-level attribution is correct before it is made authoritative in Phase 3.

Work items:

  • Introduce per-operator MemTracker (no parent, standalone)
  • Implement CountingAllocator wrapping TrackedAllocator with Operator MemTracker update
  • Wire query execution paths to use CountingAllocator for Column/Chunk allocation
  • Expose operator-level memory stats for observation (e.g., via query profile or internal tooling)

Exit criteria: Operator MemTracker numbers are consistent with Fragment MemTracker for representative workloads. No regression in existing memory accounting or query performance.


Phase 3: Operator MemTracker — Integration

Goal: Promote Operator MemTracker from a shadow observer to a first-class node in the memory accounting tree, enabling authoritative operator-level statistics and observability.

Operator MemTrackers are attached under their respective Fragment MemTracker. The Query → Fragment → Operator hierarchy becomes the primary observability surface, allowing peak memory usage per operator to be read from the query profile and mapped directly to the execution plan.

Work items:

  • Attach Operator MemTrackers under Fragment MemTracker
  • Validate that the three-level hierarchy produces correct aggregate numbers
  • Expose operator-level peak memory in query profile

Exit criteria: Operator-level peak memory is visible in the query profile for representative workloads. The Query → Fragment → Operator hierarchy produces correct aggregate numbers consistent with Phase 2 shadow observations.


Phase 4: Expand Allocator Coverage Beyond Query

Goal: Extend the Allocator migration to modules outside the query execution path — storage layer, data loading, and background jobs. With Phase 1–3 complete for the query layer, Phase 4 broadens coverage to the remaining controllable allocation surfaces, further improving overall attribution quality.

Specific work items will be scoped when Phase 3 is complete and the actual coverage gaps are measurable.


Phase 5: ResourceCtx and Task-Level Observability

Goal: Introduce ResourceCtx as the unified resource abstraction for all task types (queries, loads, background jobs), and expose a system table (sys.tasks_resource_usage) for real-time and historical task-level resource observability on each BE. This closes the loop on PP1.

Detailed design will be driven by the attribution quality achieved in Phase 4 — the more memory is Allocator-managed, the more trustworthy the signals exposed through ResourceCtx will be. Specific work items will be scoped at that time.


Future Directions: Memory Arbitration

The five phases above build the information infrastructure — accurate, per-task, per-operator memory attribution — that makes a more ambitious capability possible.

Today, BE relies on dozens of static configurations to pre-partition memory across modules. These are not tuning knobs; they are compensations for the fact that BE cannot see its own memory clearly enough to make decisions at runtime. When the workload shifts or the numbers are wrong, OOM happens and operators are left adjusting configs by trial and error.

With trustworthy real-time memory attribution in place, BE can implement a memory arbitration mechanism — a centralized component that actively manages memory distribution across all running tasks. When memory pressure rises, the arbitrator intervenes: it can instruct caches to release capacity, trigger spill for memory-heavy operators in specific queries, suspend or abort lower-priority background tasks to protect foreground queries, or reject new queries that cannot be safely accommodated. These decisions are made on live data, with full awareness of who is using what and why — across all task types, including queries, loads, compaction, and other background jobs.

The result is a BE that manages memory autonomously under pressure, rather than requiring operators to anticipate every workload scenario in advance through static configuration.