Skip to content

data-plane: tiered view storage with zero-copy state views - #855

Closed
zzylol wants to merge 45 commits into
sync/planner-main-1760a69ffrom
feat/tiered-view-storage
Closed

zzylol wants to merge 45 commits into
sync/planner-main-1760a69ffrom
feat/tiered-view-storage

Conversation

@zzylol

@zzylol zzylol commented Nov 21, 2026 •

Copy link
Copy Markdown
Contributor

Design: docs/design/tiered-view-storage.md. Stacked on #852. Implements the approved design and its zero-copy revision: cold view windows are read from mapped segments through state views, never rebuilt. Pins ProjectASAP/ASAPPlanner#1447 (executor: mapped state columns, streaming SummaryMerge) and ProjectASAP/asap_sketchlib#271 (DDSketch, KLL and Count-Min views). B1 results are in the PR comments. With every read cold in a 3 GiB cgroup, the working set is 456 MiB and anon is 352 MiB, against 1300 MiB and 1273 MiB with tiering off, and q01 latency is unchanged (1.1–1.3 s). V22 (compressed samples) waits for the backend codec PR.

Summary

Keep recently read view windows decoded in a bounded heap cache, and serve all other windows from the view files the data plane already writes for recovery: sealed segments are mapped and decoded in place from a columnar format. The persistence files become the cold tier, so each window is encoded and written once. Under a cgroup memory.max the data plane then slows down instead of being OOM-killed, and disk use becomes bounded by retention.

Review guide

  1. The tests (list below): each fails today for the reason given. Approval of the tests comes before the implementation.
  2. Measured expectations (design section of the same name): without rollup levels the dashboard reads every window at every evaluation, so tiering trades memory for decode CPU there; with rollup levels most fine windows go idle at no query cost.
  3. Decided at review (design section): mmap read path, recency hot policy, columnar fragments, no budget without a cgroup limit (idle eviction only), old files renamed *.stale.

Behavior: before → after

Dashboard plan (KLL quantile, Max, Rate, Increase chains, 15 s windows, 1 h retention), 10k series per metric, 1 sample/s, measured in process on a 56-core x86 server:

Before After (expected, to be measured by B1/B2)
View windows all decoded in the heap: 3.1 GB, RSS 3.9 GB cache bounded by --view-cache-max-bytes (default from the cgroup's memory.max); the rest in the files (1.46 GB per hour today, less with columnar fragments), reclaimable page cache
View files recovery only; one file per group, grows without trimming the same bytes are the cold tier; time segments deleted past retention
Under a small memory.max OOM kill answered; cold reads cost decode time per window (about 31 ms per 10k rows with today's row-wise format), more when the page cache was reclaimed
Restart decodes every window in retention (26 s here) indexes record heads only; first queries decode what they read

Interfaces

 // data_plane/src/engine.rs
 pub struct EngineOptions {
     pub view_sync_interval_ms: u64,
+    /// Bytes of decoded view windows the window cache may hold; `None`: from the cgroup's memory.max, or no budget.
+    pub view_cache_max_bytes: Option<u64>,
+    /// A cached window not read for this long leaves the cache; `None`: twice the longest reader interval; `Some(0)`: never.
+    pub view_cache_idle_ms: Option<u64>,
+    /// Milliseconds of windows per view file segment (default 15 min).
+    pub view_segment_ms: i64,
+    /// Mapped sealed segments, or `pread`.
+    pub view_read: ViewRead,
+    #[doc(hidden)] pub cold_decode_delay_ms: u64,
+    #[doc(hidden)] pub unpersistable_views: Vec<PhysicalASAPNodeId>,
 }

 // data_plane/src/persist.rs
+pub const FORMAT_VERSION: u32 = 2;
+pub enum ViewRead { Mmap, Pread }
+/// One view's fragment of one window in a segment.
+pub struct WindowLocation { .. }
+impl WindowLocation {
+    pub fn read(&self, schema: &SchemaRef, how: ViewRead) -> Result<Batch, Error>;
+    pub fn segment_path(&self) -> &Path;
+    pub fn offset(&self) -> u64;
+    pub fn len(&self) -> u32;
+    pub fn is_sealed(&self) -> bool;
+    pub fn maps(&self, address: usize) -> bool;
+}
+pub type ViewIndex = BTreeMap<PhysicalASAPNodeId, Vec<((i64, i64), WindowLocation)>>;
 pub struct Written {
     pub bytes: u64,
     pub sync_ns: u64,
     pub not_persisted: u64,
+    pub locations: Vec<(PhysicalASAPNodeId, WindowLocation)>,
 }
 impl ViewFiles {
+    pub fn with_segment_ms(self, segment_ms: i64) -> Self;
+    pub fn seal(&mut self, group: usize) -> io::Result<()>;
+    pub fn delete_expired(&mut self, group: usize, oldest_kept_end_ms: i64) -> io::Result<usize>;
+    pub fn index(&mut self, groups: &[Vec<(MaterializedView, SchemaRef)>]) -> io::Result<ViewIndex>;
 }

 // data_plane/src/window_cache.rs (new)
+pub struct WindowKey { pub view: PhysicalASAPNodeId, pub end_ms: i64 }
+pub struct WindowCache { .. }
+impl WindowCache {
+    pub fn new(max_bytes: Option<u64>, idle: Option<Duration>) -> Self;
+    pub fn insert(&self, key: WindowKey, batches: Arc<Vec<Batch>>, bytes: u64, now: Instant);
+    pub fn get(&self, key: WindowKey, now: Instant) -> Option<Arc<Vec<Batch>>>;
+    pub fn get_or_load(&self, key: WindowKey, now: Instant, load: impl FnOnce() -> Result<(Arc<Vec<Batch>>, u64), Error>) -> Result<Arc<Vec<Batch>>, Error>;
+    pub fn evict_idle(&self, now: Instant);
+    pub fn set_target_bytes(&self, target: Option<u64>);
+    pub fn remove(&self, key: WindowKey);
+    pub fn stats(&self) -> CacheStats;
+}

 // data_plane/src/memory_budget.rs (new)
+pub struct CgroupMemory { pub max_bytes: Option<u64>, pub current_bytes: u64, pub anon_bytes: u64, pub file_bytes: u64 }
+pub fn read_cgroup(dir: &Path) -> io::Result<CgroupMemory>;
+pub fn default_view_cache_budget(cgroup: &CgroupMemory, other_pools_bytes: u64) -> Option<u64>;
+pub fn monitored_target(budget: Option<u64>, cgroup: &CgroupMemory, cached_bytes: u64) -> Option<u64>;

CLI: --view-cache-max-bytes, --view-cache-idle-ms, --view-segment-ms, --view-read mmap|pread. Until the implementation, install refuses any non-default tiering option, and the new functions return "not implemented" (or panic, for the cache and budget).

Algorithm

  • Commit: the window is appended Pending and inserted into the cache; persist threads encode its columnar fragments and append the record to the group's active segment, then acknowledge the locations; the committer turns the window Stored.
  • Read: tiling windows are streamed lazily; a Stored window not in the cache is decoded once (single flight) from its fragment: borrowed from the mapping for sealed segments, pread for the active one; inserted if it fits.
  • Evict: CLOCK over cached Stored windows, by idle time and the byte budget; a 1 s monitor of memory.current/memory.stat lowers the target when anonymous memory runs high.

Tests (failing first)

Test Where Fails today because
V1 parity, every read cold (instant and range; run with PARITY_INGEST_THREADS=1,4,8) tests/planner_executor_parity.rs with_every_view_read_cold_* install refuses view_cache_max_bytes
V2 every state family reads back from its fragment (active, mapped, pread) src/persist.rs Written::locations is empty
V3 one view's fragment reads alone; a damaged one is an error src/persist.rs as V2
V4 idle entries leave, read ones stay src/window_cache.rs cache not implemented (panics)
V5 the byte budget holds; oversized windows not kept; lowered target src/window_cache.rs as V4
V6 concurrent cold reads decode once src/window_cache.rs as V4
V7 a window leaves memory only after it is written tests/view_tiering.rs install refuses the options
V8 windows that cannot be written stay in memory tests/view_tiering.rs as V7
V9 segments roll and expire; files bounded src/persist.rs, tests/view_tiering.rs seal/delete_expired not implemented; install refuses view_segment_ms
V10 a segment deleted during a read stays readable tests/view_tiering.rs as V7
V11 restart indexes without decoding tests/view_tiering.rs tiering metrics missing
V12 a torn segment tail is cut at restart src/persist.rs, tests/view_tiering.rs no segments, index not implemented
V13 old-format and other-plan files set aside src/persist.rs index not implemented
V14 cgroup budget and monitor src/memory_budget.rs not implemented
V15 no OOM under memory.max scripts/tiered_views_cgroup.sh + examples/tier_bench.rs manual run; the tiered arm is refused today
V16 concurrent commits, evictions and queries answer alike tests/view_tiering.rs as V7
V17 metrics tests/view_tiering.rs as V7
V18 mapped reads borrow fixed-width columns src/persist.rs as V2
V19 an unlinked sealed segment stays readable src/persist.rs as V2
B1/B2 examples/tier_bench.rs (VIEW_CACHE_MAX_BYTES, VIEW_READ, COLD=1) reported, not CI
B3 examples/view_read_bench.rs reported, not CI

Verification

See the test run in the PR comments: every new test fails for the reason above; the existing tests are unchanged.

Follow-ups

  • Planner cost model for "view on disk" (requirements list in the document; separate repo).
  • Hierarchical rollup levels make the cold tier nearly free on dashboards.

zzylol and others added 4 commits November 21, 2026 00:08
Design and test plan for computing ingestion-time views on every ingest
shard: refresh groups compiled into push pipelines split at pipeline
breakers, one instance per (shard, window), partial outputs combined at
window close by a rule derived from the plan (concatenate per-series
states, merge mergeable states, single partition otherwise), commits in
window order. Implementation follows after the test plan is approved.
…st plan

Records each decision with options, precedents (push and streaming
engines), corpus evidence (what the Planner puts at ingestion time over
3,731 public queries) and conclusion, with result slots for E1-E5.
Rebased on the sharded ingestion: seal travels with the coordinator's
flush, combine runs on the window-task pool, views of a source run
inline on the shard thread, non-mergeable breakers are a list awaiting
ordered-merge. Test plan revised to T1-T19 and B1-B2.
…ng until implemented)

Tests from the approved test plan of docs/design/parallel-precompute.md,
written before the implementation:

- T1, T2 in planner_executor_parity.rs: push answers and stored view rows
  against the reference and the window path, K = 1, 2, 4, 8.
- T3-T19 in push_precompute.rs. Each runs its fixture in window mode
  first, then in push mode.
- B1/B2: ingest_bench takes PRECOMPUTE_MODE=push and, when paced,
  reports the newest window's commit lag.

Interface only, no push logic: EngineOptions.precompute_mode
(--precompute-mode, refused at install when push),
precompute_memory_budget_bytes, the test hooks slow_refreshes (the same
shape as the precompute task pool's) and panic_in_combine_of_window_end_ms,
pipelines::{CombineRule, BreakerRule, combine_rule, combine_rules}
(returning "not implemented"), and Snapshot::view_rows for comparing stored
views.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01K1M6bo6sg4cEjJJhktNtL9
@zzylol zzylol added area: data plane Runtime ingestion, storage, and query-serving data paths documentation Improvements or additions to documentation enhancement New feature or request labels Nov 21, 2026
…ailing until implemented)

Tests from the approved test plan of docs/design/tiered-view-storage.md,
written before the implementation:

- V1 in planner_executor_parity.rs: every parity workload, instant and
  range, with every view window read cold from the view files.
- V2, V3, V9, V12, V13, V18, V19 in persist.rs: columnar fragments of
  every view state family, read from the active segment, mapped and by
  pread; fragment isolation; segment roll and expiry; torn tails;
  old-format files; borrowed columns; unlinked segments.
- V4-V6 in window_cache.rs, V14 in memory_budget.rs.
- V7-V12, V16, V17 in tests/view_tiering.rs, against an in-memory control.
- V15, B1, B2: examples/tier_bench.rs and scripts/tiered_views_cgroup.sh;
  B3: examples/view_read_bench.rs.

Interface only, no tiering logic: EngineOptions view_cache_max_bytes,
view_cache_idle_ms, view_segment_ms, view_read and two test hooks (install
refuses non-default values), the matching CLI flags, persist::{ViewRead,
WindowLocation, ViewIndex, FORMAT_VERSION}, Written::locations,
ViewFiles::{with_segment_ms, seal, delete_expired, index} (returning
"not implemented"), and the window_cache and memory_budget modules
(panicking "not implemented").
@zzylol zzylol changed the title docs(data-plane): design tiered view storage (hot windows in the heap, cold windows in the view files) data-plane: tiered view storage — design and failing-first tests Nov 21, 2026
@zzylol zzylol added the test: end-to-end Process-boundary, differential, conformance, and full-stack tests label Nov 21, 2026
@zzylol

zzylol commented Nov 21, 2026

Copy link
Copy Markdown
Contributor Author

Test run at 29b1db94 (56-core x86 server, debug build; only the tests covering the changed code):

  • cargo test -p data_plane --lib -- persist:: window_cache:: memory_budget::: 3 passed (the existing persist tests), 15 failed, each at the intended point: Written::locations empty / "view segments are not implemented" (V2, V3, V9, V12, V13, V18, V19), "the window cache is not implemented" (V4–V6), "the cgroup memory budget is not implemented" (V14). The test fixtures themselves (one view batch per state family, built with Batch::try_new) construct fine.
  • --test view_tiering: 8 failed: install refuses the tiering options (V7, V8, V9, V10, V16, V17); V11 runs its first phase and fails on asap_view_cold_reads_total missing; V12 fails on "no segments".
  • --test view_persistence: 7 passed (unchanged).
  • --test planner_executor_parity: the two existing tests pass after the Views refactor; the two V1 tests fail because install refuses view_cache_max_bytes.
  • cargo fmt --all clean; cargo clippy -p data_plane --tests --examples no warnings.

zzylol and others added 10 commits November 21, 2026 10:06
Takes the precompute task pool, series-split windows and SlowRefresh
hooks; the test hook slow_refreshes is the pool's, the duplicate field
from the test commit is dropped.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01K1M6bo6sg4cEjJJhktNtL9
…w pipeline instances

--precompute-mode push (docs/design/parallel-precompute.md, D1-D9):

- Push groups. A refresh group whose run splits by series, carries no
  state across windows and reads no view is built by push, once an
  install probe shows that its Scans read exactly the window. Other
  groups keep the window path on the precompute task pool.
- Instances. Each ingest shard (series hash, D3) keeps one instance of
  the group's compiled ingestion run per open window. The instance runs
  over a PushStore whose raw-data slots are streams fed inline on the
  shard thread. One morsel is converted once per slot and reaches every
  view of its source with no queue and no raw buffer (D2). The run's
  non-Send future lives in the shard's LocalPool.
- Seal and commit. After the flush that closes a window, the
  coordinator sends Seal to every shard. Each shard ends its streams
  and sends its partial (idle shards an empty one). The committer
  combines the partials with the series-split merge of the task pool
  (Concatenate) and commits them through the same reorder buffer,
  barriers and persistence.
- Raw data. Metrics read only by push groups keep no raw data, and push
  groups no longer hold raw-data cutoffs back.
- Memory budget (--precompute-memory-budget-bytes). Open state is the
  instances' run memory. A window fails only when it is the only one
  open on every shard and still over the budget. While an older window
  is open anywhere, the state is allowed over the budget until the
  seal frees it.
- Hooks. slow_refreshes delays a pushed window's combine, and
  panic_in_combine_of_window_end_ms makes it panic. The panic is caught
  and fails that window only.
- Metrics:
  - asap_phase_* {phase="precompute_push|precompute_seal", group,
    shard}, precompute_combine {group} and precompute_commit;
  - asap_precompute_state_bytes, asap_precompute_open_instances and
    asap_window_commit_lag_seconds;
  - asap_samples_total{outcome="late_for_views"}, counted at routing in
    either mode.
- pipelines::combine_rule(s) implement the rule table. Every node is
  checked before the groups are read, so an unknown breaker is named.

Test fixes, keeping each test's stated intent:

- T5 regroups by the series' first label column when a scan has no
  `job` column.
- T7 collects the rules seen, rather than keying them by a payload prefix.
- T13 seals the window behind a barrier before sending the late sample,
  and expects 4 late samples per metric that an ingestion-time view
  reads.
- T14 runs one precompute thread, because the task pool's slots would
  otherwise hold more windows than the test writes.
- T1 takes PARITY_PUSH_SHARDS.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01K1M6bo6sg4cEjJJhktNtL9
…schema

Every Scan of every open window that reads a metric in one schema now
shares one conversion of the morsel, as the window path shares a chunk's
conversion through RawReads. The executor re-applies each slot's time
range and predicates.

Measured at 10k series × 2 metrics, 10 samples/s, 4 shards, unpaced:
push folding fell from about 1.75× the window path's precompute CPU to
the same (122 s against 123 s for 60M samples).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01K1M6bo6sg4cEjJJhktNtL9
…fore folding

Each fold runs every view of the group, so a 10 Hz scrape's share of a
shard (a few thousand rows) costs more per sample than a large morsel.
A shard now buffers its routed samples and folds them once
--push-batch-samples are pending (default 32,768) or the oldest is
--push-batch-max-ms old (default 1,000). A seal folds what is pending
first, so batching never delays a window's commit. A fold gives each
window's instance a morsel of its own samples only, so a large window
does not cost a small window's run its memory.

T15 folds every request as it comes (MorselBatching 0), because it
measures open state request by request.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01K1M6bo6sg4cEjJJhktNtL9
… bounded window cache

Implements docs/design/tiered-view-storage.md:

- Format version 2 (segment.rs): per group a directory of time segments;
  each record holds one columnar fragment per view (text keys into a
  per-segment dictionary, fixed-width plain columns, a state column of the
  existing stored state forms), 8-byte aligned. Sealed segments are
  mapped and decoded in place (keys and fixed-width columns borrowed from
  the mapping); the active segment, and --view-read=pread, use pread.
  Segments roll every --view-segment-ms and are deleted once past the
  group's retention. Version 1 files and other plans' segments are renamed
  *.stale.
- Window states (store.rs): each window is a slot shared by every
  snapshot: Pending until its persist thread writes it, then Stored (its
  fragment) or Pinned (not writable, or no persistence). Reads decode
  Stored windows lazily through the window cache.
- Window cache (window_cache.rs): CLOCK, byte budget, idle eviction,
  single-flight decode.
- Memory budget (memory_budget.rs): default budget from the cgroup's
  memory.max less the bounded pools and 10 % headroom; a 1 s monitor
  lowers the cache's target while anonymous memory runs high.
- Startup indexes record heads only; nothing is decoded until read.
- Metrics: asap_view_cache_{bytes,entries,hits,misses,evictions},
  asap_view_{pending,pinned,file}_bytes, asap_view_cold_reads_total,
  asap_view_cold_read_bytes_total, phase="view_decode".

Tests: V2 adds the Counter state; V7 turns the result cache off so its
second query reads views; V10 slows cold decodes to a second each;
precompute_pool and view_persistence read the per-group directories.
…the cgroup working set

- A cold read of a mapped segment advises MADV_WILLNEED over the fragment,
  so the decode does not fault it in page by page (the mapping is
  MADV_RANDOM).
- V2/V18 compare DDSketch states by their answers: a DDSketch read back is
  shrunk, so its ASAPv1 bytes may be shorter than the written state's.
- tier_bench takes WORKLOAD and prints the cgroup's working set
  (memory.current less inactive_file), anon and file; view_read_bench
  measures pread before mmap, since a mapped page cannot be dropped from
  the page cache.
…es included

An empty window's fixed-width columns were copied into an empty Vec<u8>,
whose dangling pointer is not aligned for u32/f64, and Arrow refused it
(caught as "decoding a view window panicked" in the cold parity run).
Copies now go through 8-byte words. Adds a test reading an empty window
back from the active and a sealed segment, both ways.

tier_bench: RESULT_CACHE=0 makes every round read its views, and
VIEW_CACHE_MAX_BYTES=off keeps every window decoded even in a cgroup.
…on for approval)

States stored on disk are used where they are mapped: per-family view
layouts in the columnar fragment, read-only view types with merge_into and
estimates in asap_sketchlib, a Mapped state storage and a streaming
SummaryMerge in the executor; decode-to-owned only for heap top-k,
UnivMon and Hydra. Adds compressed-sample windows in the data plane and
revised tests V2/V18 plus V20-V22. Motivation measured: with every window
read cold, the 1 h quantile's merge decodes all 240 windows at once
(anonymous memory peaks at 2.54 GB, above keeping them decoded).
@zzylol zzylol changed the title data-plane: tiered view storage — design and failing-first tests data-plane: tiered view storage (design, tests, implementation; zero-copy revision pending) Nov 21, 2026
zzylol and others added 2 commits November 21, 2026 19:41
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01K1M6bo6sg4cEjJJhktNtL9
…never rebuilt

State columns of DDSketch, KLL, Count-Min and every exact family are
written in the executor's mapped layout (MAPPED_STATES: u32 offsets, then
the states, each 8-byte aligned) and read back with
StateColumn::from_mapped over the segment's mapping (a copy for pread):
SummaryMerge folds each mapped state into its accumulator, so a query over
cold windows allocates only its accumulators. Other families keep the
StoredValue column.

Pins ASAPPlanner exec/mapped-state-views (e1eafe97) and asap_sketchlib
feat/zero-copy-views (1cdc3c7).

Tests: V20 (view_cold_allocations.rs, counting allocator): a 30 min
quantile over 180 cold windows allocates at least 10x less at once than
the windows take decoded, with the same answers. V18 checks that the KLL
states' addresses lie in the mapping. V2 compares KLL states by answers
(a view rebuilt as an accumulator sorts level 0). V10's cold decode delay
is 3 s per window.
@zzylol

zzylol commented Nov 21, 2026

Copy link
Copy Markdown
Contributor Author

B1 rerun with zero-copy state views (backend 028a8b69, executor ASAPPlanner#1447 e1eafe97, sketchlib asap_sketchlib#271 1cdc3c7).

Dashboard-heavy plan, 10k series per metric, 1 sample/s, 70 min of data, view files on a rotating disk; each arm in a cgroup with memory.max = 3 GiB, swap off; result cache off, so every round reads its views; 8 cores; three rounds of the four instant queries. Working set = memory.current − inactive_file. "After" is after round 3; "peak" is the 1 s-sampled maximum over the whole run (feeding included).

Window cache Working set after Anon after Peak working set Peak anon q01 quantile 1 h (rounds 2–3) q03 max 30 m (rounds 2–3) OOM
tiering off (all decoded) 1300 MiB 1273 MiB 1297 MiB 1270 MiB 1.23–1.33 s 0.17–0.21 s 0
default (from memory.max) 1238 MiB 1210 MiB 1235 MiB 1208 MiB 1.21–1.44 s 0.21 s 0
512 MiB 961 MiB 923 MiB 960 MiB 922 MiB 0.84–1.19 s 0.18–0.22 s 0
0 (every read cold, page cache warm) 456 MiB 352 MiB 453 MiB 352 MiB 1.13–1.14 s 0.20–0.23 s 0
0, page cache dropped before each round 363 MiB 357 MiB 365 MiB 360 MiB 3.4–3.9 s 0.20 s 0
  • View files: 750 MiB, which was 1.07 GB with the row-wise format. With the cache at 0, a query reads every window from its mapped segment, and the windows' pages count as file, not anon (RssFile is about 540 MiB).
  • Before the revision, the same budget-0 run peaked at 2.54 GB anon and took 10–14 s for q01, because every cold window was rebuilt and the merge collected all of them.
  • Tests: V1 parity with every read cold passes at 1 and 4 shards, and so do precompute_pool, view_persistence, view_tiering and the lib tests. V20 (view_cold_allocations) passes: a 30-minute quantile over 180 cold windows allocates at least 10× less at once than those windows take decoded.

@zzylol zzylol changed the title data-plane: tiered view storage (design, tests, implementation; zero-copy revision pending) data-plane: tiered view storage with zero-copy state views Nov 21, 2026
ASAPPlanner exec/mapped-state-views 7a6b2fb5, asap_sketchlib
feat/zero-copy-views 93d56ef: a stored DDSketch's bucket counts are
written as u32 when they all fit (u64 otherwise), with a width flag in
its view layout; the fragment stores the view bytes as they are.
zzylol and others added 2 commits November 22, 2026 02:58
…ite load generator

examples/remote_write_load.rs sends Remote Write from another host:
- per-series protobuf prefixes are encoded once;
- each thread keeps one keep-alive connection;
- the sender is paced to the wall clock or stamps samples in the past;
- 503s get an exponential backoff.

The design doc's B section records the sweep over K = 4–56 CPUs (28 physical cores
plus SMT points), window-ready latency, request-size checks and where each mode
stops scaling.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01K1M6bo6sg4cEjJJhktNtL9
…e), patched over the Planner's pin

A 1 h quantile_over_time over 240 cold windows x 10,000 series at 10 Hz
(tier_bench, 3 GiB, cache 0) drops from 9.4 s to 3.0 s; the other
dashboard queries are unchanged.
zzylol added a commit that referenced this pull request Nov 22, 2026
…in 846a70a

ASAPPlanner main adds wider tumbling-window levels (SummaryMergeWindows,
#1440) read through TimeRangeCover, plus #1436 and #1447, and pins
asap_sketchlib 389530c. Re-pinned to both; the data plane compiles
unchanged. With the new plans, queries over levels failed with "materialized view N
has no rows tiling" (parity 0/4 on dashboard-heavy-10hz). Each wider
level is a view in its own refresh group whose run merges the next
narrower level's stored windows; the executor runs both operators. Three
fixes make the windows exist:

- A level starts with the chain it is built from: a group now starts at
  the first sample of any metric scanned below the views it reads
  (`started_by`), not only of a metric it scans. A wider level scans
  nothing, so it never started and its view stayed empty. Raw-sample
  eviction still follows only the metrics a group scans.
- A view another group reads keeps the windows its readers have yet to
  read, whatever its retention (ViewStore::hold_for_readers and
  reader_committed). The plan sizes retention for a reader right behind
  the view; a pass closing many windows queues them group by group, so
  the narrow group commits far ahead, back to the group's longest
  retention, which may exceed the view's (dashboard-heavy's 10 s group
  holds a 1 h and a 30 min view).
- When the watermark jumps and groups skip windows past their retention,
  a group whose views another group reads keeps building the windows
  that reader needs (bounded by the reader's skip point, in reverse plan
  order); a reader of a group that skipped further skips as far, to its
  next boundary. One run builds all of a level's views over every chain
  below it, so a level holding a 21 min view over a 10 min chain needs
  that chain back 21 min (random-mixed range plans).

Tests:
- New window_levels: a 1 h sum and a 30 min max sharing the narrow
  level, two hours of samples in one request (one pass closes every
  window), answers at each 15 s step against sums and maxima computed
  from the samples; the plan is checked to have levels and a cover.
  Without the hold: windows fail (view N has no rows tiling); without
  the start rule: 422.
- Parity: the reference runs every group's windows in window-end order
  (from the #855 re-pin work), PARITY_WORKLOAD=name filters workloads,
  and dashboard-heavy-10hz is added. 192/192 queries and 162/162 range
  steps at 1, 4 and 8 ingest shards (dashboard-heavy-10hz 4/4 on both
  plans).
- precompute_pool plans without levels (common::inputs_without_levels
  excludes both operators): its tests time refresh groups of the plan
  shapes they pick.
… into tiered view storage

Conflicts: ViewStore keeps the tiered slots and applies #852's reader holds in push(); Cargo pins Planner 846a70a and sketchlib 389530c, still patched to #271's 355093f.
…ndow answers from the rows that exist

PromQL over a range that starts before the first sample answers from the
samples there are; the store refused instead until a window had filled
(a 6 h query got nothing for the first 6 h). Each view now records the
start of its first stored window, and a read clips its range to it. A gap
after the first window is still missing data and is still refused.
The live demo refused 1 h, 30 min and 6 h queries for hours after it
started: each group's first window was the first one starting at or
after the declared stream start, so the window spanning the start was
never built, and a wider level with no window yet read as missing data.
With PromQL semantics a query answers from the samples there are.

- Every group's first window is the one holding the stream start
  (nothing arrives before it, so it is complete), so every group and
  every level of a window chain starts at the same instant.
- ViewStore knows the declared stream start: a read reaching back
  before a view's first window (or before the stream start, for a view
  with no window yet) answers from the rows that exist.
- New test queries_answer_from_the_samples_there_are_before_their_window_fills
  (window_levels): the 1 h sum and 30 min max are exact at every 15 s step
  from the first sample on, levels and covers included.
- view_files_stay_bounded_by_retention bounds the segments by the
  retention the store applies (the plan's plus the retention margin):
  the first window now starts one window earlier, still within it.

Parity: 384/384 queries and 324/324 range steps.
The refusal printed the range after clipping it to the view's first
stored window, which depends on how far the watermark jumped (windows
past retention are skipped): two engines refusing the same query, one
shard and eight, printed different ranges, and ingest_shards'
a_shard_running_ahead_does_not_close_windows_early failed under load
(1 in 18 runs, comparing two 422s). Now it prints the requested range:
0 failures in 30 loaded runs.
zzylol and others added 11 commits November 22, 2026 22:13
…requests

In window mode the single ingest coordinator was the bottleneck under
many small Remote Write requests: the #854 sweep measured 0.1-0.5M
samples/s, falling as shards were added, with the coordinator thread
busy. Every request reached every shard; each shard reported each batch
with a clone of its raw data, each report started a coordinator pass
with a flush of every shard, each eviction message produced another
report (another pass), and because the coordinator's snapshot shared the
shards' raw data, every append copied the shard's pane lists.

- A shard drains every batch already queued to it and sends one report
  (sample times, counts, first samples): one report, and at most one
  pass, per drained queue instead of per request.
- Reports no longer carry raw data. A shard sends its raw data only with
  its answer to a flush (Command::Flushed(shard, raw_data)), which is
  what the windows closing behind that flush read.
- Eviction (Maintain) sends no report, so it starts no pass.
- When no query reads raw samples (no query-time Scan), the coordinator
  publishes no raw data and lets each pass's snapshot go once its closed
  windows are queued: a shard's next append owns its raw data again
  instead of copying its pane lists (only queued refreshes hold them
  until they run). Ingestion::queries_read_raw_data says which.

Measured on two 40-vCPU hosts (engine pinned to 40 cores with 32 ingest
and 32 precompute threads; 12 sender processes x 4 threads on the other
host; the 10 Hz dashboard plan, 2 x 100,000 series):
- as fast as accepted: 0.16M samples/s before (coordinator 1.00 core)
  -> 8.02M after (coordinator 0.45 core, engine 39.7 cores);
- paced at the wall clock, 3M and 4M samples/s offered (2 x 150,000 and
  2 x 200,000 series): every sample accepted, none late; engine 24.9
  and 26.3 cores, coordinator 0.86 and 0.83.

Parity: 384/384 queries and 324/324 range steps at 1, 4 and 8 shards;
ingest_shards, window_levels, view_tiering and the other suites pass.
precompute_pool's byte-identity test at 12 threads fails intermittently
under load with and without this change (1 of 3 runs on 8368fcf).
…rkers

In the 4-user final run (2,800 series, a 1 h range panel at 15 s steps
refreshed by each user every 15 s), almost every query's p50 was 10-35
ms and p99 about 735 ms at the client, and Remote Write ticks took about
530 ms (110 ms with one user), while the engine used about 1.2 cores
and its own query latencies were a few ms.

A range request grouped every step's answer by series and serialized
the JSON inside the async handler, without an await: about 0.85 s for
241 steps of 2,800 series (profile: label-map comparisons, float
formatting), even when the result cache answers every step. Each such
request held a runtime worker for that long; connections queued on that
worker, instant queries and Remote Write included, waited behind it, and
with every worker busy no timer or socket is polled at all.

The matrix is now built and serialized on the blocking pool
(spawn_blocking), and the handler returns the bytes.

New test range_isolation: an instant query and a Remote Write request,
each measured 20 times alone and while four users refresh a 1 h / 15 s
range over a warm result cache, on a runtime of two workers. Without the
fix nothing else runs (the test's watchdog fails it: no progress in
300 s); with it, the instant query's median is 0.46 ms alone and with
ranges, and the write's 0.43 ms. RANGE_ISOLATION_SERIES and
RANGE_ISOLATION_QUERY_THREADS measure at other scales (2,800 series: a
warm range takes about 0.85 s).

Parity: 384/384 queries and 324/324 range steps.
A warm 1 h range panel (241 steps of 2,800 series, every step from the
result cache) spent about a second building its body: grouping the step
answers by comparing label maps in a BTreeMap, then serializing through
serde with a String per value. Most of q05's cost in the final runs.

range_response_body writes the matrix JSON directly:
- each series' labels are one Arc shared by every step's answer, so a
  series is found by that pointer, its labels compared only once (series
  still sorted by labels);
- each step's time and each series' labels are formatted once;
- values go straight into the buffer through ryu's shortest digits, in
  Display's notation (no exponent, no ".0"); where two shortest digit
  strings round-trip ryu may pick the other last digit, which reads back
  as the same f64.
MatrixResponse and MatrixResult are gone; the test keeps the serde
version as the reference.

examples/matrix_bench (2,800 series x 241 steps, labels shared per
series as cached, on a 40-vCPU host): median 1.06 s -> 116 ms; the body
is the same size (22,929,340 bytes).

Tests: range_body_equals_the_serde_matrix (byte for byte against the
serde matrix: shared and unshared label Arcs, escaped label text, NaN,
+-Inf, -0, 1e21, 1e-7, sub-second times);
values_are_written_as_display_writes_them (a million random bit
patterns: each reads back as the same f64 in Display's notation, under
1% differ from Display's text). Parity: 384/384 queries and 324/324
range steps.
`max by (job) (max_over_time(queue_depth[1h])) > max by (job)
(max_over_time(queue_depth[1h] offset 1h))` took about 616 ms per
evaluation in the 4-user final run. This example plans the comparison
and both sides over SERIES series (default 1,000) sampled every 15 s
for 2.5 h, and times one evaluation of each, computed alone (no result
cache, no shared query-time results).

On a 40-vCPU host, 1,000 series: the comparison 132 ms, the side
without the offset 7.5 ms, the offset side 66 ms. The plan reads the
plain side's 1 h through a TimeRangeCover over the 1 min, 5 min and
15 min levels (a few windows per series), but the offset side through
TimeShift + TimeRange over the 15 s chain: 240 windows per series,
240,000 rows merged per evaluation. The time is CPU in the executor's
SummaryMerge (GroupTable::group_ids hashing each row's series key).
Remedies are upstream: a cover under TimeShift (offset 1h stays on the
levels' grid), and a cheaper merge grouping.

`OFFSET_BENCH_ONLY_BEFORE=1 offset_bench [SERIES] [RUNS]` times only
the offset side, for profiling.
…ld (#858)

The data plane maps every retained view segment. Pages read while a segment
was young (pread while it was the active segment, then the mapping while it
was the newest sealed one) stay on the active LRU list: without memory
pressure the kernel never ages them. On a live run, segments of one refresh
group older than about 70 min each kept about 107 MB of 172 MB resident with
none of it referenced, so the cgroup's working set (memory.current minus
inactive_file) counted gigabytes of page cache no query reads.

Queries read a view's newest windows on every evaluation, and an older
window only once more, when it leaves a range's far edge. So once a newer
sealed segment exists, a refresh group's older sealed segments are marked
cold, once each, on roll, on seal and after indexing at startup:

- madvise(MADV_COLD) over the segment's mapping deactivates the pages it
  maps and keeps them cached;
- posix_fadvise(POSIX_FADV_DONTNEED) over the file drops the pages that are
  cached but not mapped (read with pread while the segment was active),
  which MADV_COLD cannot reach. They are clean: a sealed segment is synced.
  A later read maps or reads them again.

Answers cannot change: the advice only moves or drops clean page cache.

Why advice and not munmap with re-mapping on demand: unmapping does not
touch the LRU lists. The pages stay cached and active, so the working set
would not drop, and re-mapping adds a lock and a remap path to every read.

New counter asap_view_segments_marked_cold_total. A unit test checks that
only segments behind the newest sealed one are marked, each once, and that
a cold segment reads back the same rows.
* fix(data_plane): delete each view's windows at its own retention

View segments were per refresh group, and a group's segment was deleted
only once every view in it was past retention: so at the group's longest
retention. On a live run, one group held all the 15 s views: a quantile
sketch view read back 1 h, other views 30 min, 5 min and 1 h, and a max
view read back 6 h. Each 15-minute segment lived for 6 h, and the sketch
view's part, about 107 MB of each 172 MB segment, stayed on disk and in the
page cache 5 h past its 1 h retention (5.4 GB of view files).

Segments are now per refresh group and retention: a group's views of one
retention share a directory group-<g>/retention-<ms>/, and each window's
record is written once per retention (its own texts and grids). A view's
windows are deleted when every window in a segment of its retention is past
that retention of the newest window. Indexing records each view's
retention; delete_expired takes the newest window end and applies each
retention. A segment written before the split, directly in group-<g>/, is
loaded and deleted at the group's longest retention, as before.

Chosen over punching holes (fallocate PUNCH_HOLE) in shared segments,
which keeps the file sizes and needs per-view extents tracked and page-
aligned, and over compaction, which rewrites live data; separate files need
no new on-disk structure and keep "a segment is deleted whole".

Also fixes delete_expired dropping the rest of a group's sealed list when
one unlink failed.

A unit test writes a 20 ms and a 1000 ms view of one group and checks that
the short view's old segments are gone after its retention while the long
view's stay and read back.

* test(data_plane): old-layout segments expire at the group's longest retention; an unlink failure keeps the sealed list

Two unit tests for the per-retention split: segments written directly in
group-<g>/ before it are indexed, read back, and deleted only past the
group's longest retention; and a failed unlink no longer drops the rest of
a retention's sealed list, so a later call deletes them.
Moves asap-planner and asap-executor from 846a70a to e13aa23: #1463
(TimeRangeCover.offset_ms, a cover under `offset`) and the cost-model
changes #1448-#1461. No interface change reaches the backend; the
asap_sketchlib pin and the #271 patch are unchanged (the Planner still
pins 389530c).

examples/offset_bench (1,000 series, a 40-vCPU host): the offset side
`max by (job) (max_over_time(queue_depth[1h] offset 1h))` now reads the
1 min / 5 min / 15 min levels through a cover: 66 ms -> 7.5 ms, like the
side without the offset (7.4 ms); the comparison 132 ms -> 13.3 ms.

Parity (release build): 384/384 queries and 324/324 range steps at 1, 4
and 8 shards; precompute_pool 6/6; the other data_plane suites pass.
In debug builds, planning demo-complex-shapes with raw data kept trips
the Planner's own assertion that the MILP optimum equals plan_cost
(stage3-plan-selection lib.rs:352; e.g. 0.0595/s vs 0.0767/s for
`(sum by (job) (increase(http_errors_total[1h])) / on(job) group_left()
sum by (job) (increase(http_requests_total[1h]))) > 0.01`, and the other
group_left join): a Planner bug at e13aa23, reproduced with the
control_plane binary alone, so the debug parity and precompute_pool
tests fail on that workload until the Planner fixes it.
…ver coverage)

Moves asap-planner and asap-executor from e13aa23 to 90a6e86: #1464 (an
offset cover's coverage is its range that much earlier) and #1466
(retained raw rows charged by their exact rate). #1466 fixes the
Planner's debug assertion that the MILP optimum equals plan_cost, which
failed planning demo-complex-shapes with raw data kept (the two
group_left joins over 1 h ranges). No interface change reaches the
backend; asap_sketchlib stays at the Planner's 389530c (plus the #271
patch).

Debug build: parity 384/384 queries and 324/324 range steps
(demo-complex-shapes 7/7 with raw data kept and without), precompute_pool
6/6. Release build: parity 384/384 and 324/324 at 1, 4 and 8 shards.
Push precompute now commits into tiered view storage and keeps the demo
branch's behaviour: windows from the stream start, the drained shard
queues and flush-carried raw data of the coordinator, multi-level window
chains (groups reading other groups stay on the window path), allowed
lateness and backpressure.

- engine.rs: both option sets; a shard drains its queue, appends, and
  folds each batch into its push instances in the same pass; Seal is
  handled in order with samples.
- store.rs: ViewStore::rows reads each window through its slot (pending,
  cached or decoded from its fragment).
- planner_executor_parity.rs: data_plane_over takes the view mode; T1 for
  push runs with every view read cold from the view files.
- A shard counts samples late for views again (the merged shard loop
  dropped the counter).
- A wider window-chain level (SummaryMergeWindows) gets the WindowPath
  combine rule: its group reads another group's views and runs after them.
- Push tests expect the empty window holding the stream start, which the
  demo branch now builds first.
- T2 compares push's stored windows from the window path's oldest:
  windows past retention leave lazily and expired windows are skipped
  depending on commit order, and no query reads either. The failure
  message names the first differing window and both runs' stats.
- Clippy at the current toolchain: Rc morsels, type aliases for view
  rows, is_multiple_of, an intended lock across await in T14.
On the demo workload (19 queries, 14 metrics, 2,800 series per label set at
10 Hz, 45 min per arm on identical hosts) push used 1,589 against 1,620
core-seconds, a 750 against 941 MB peak working set and no raw samples,
with the same window latency (2.03 against 2.07 s mean), query latency and
answers. Under catch-up load it accepted 3.59M against 2.22M samples/s at
869 against 2,111 core-seconds. --precompute-mode window keeps the window
path; the library default stays Window for the window-path tests.

docs: parallel-precompute.md records the A/B; demo-plan.md section 4 says
the demo runs push.
Remote Write is decoded in place from a per-thread decompression buffer, without building a WriteRequest; a series is found by the bytes of its encoded labels in a per-thread cache, and only a new one is parsed, validated and interned. Same samples, series and errors as before: tests/remote_write_reference.rs keeps the old decoder and compares. A body over 32 MiB decompresses into a fresh buffer that is not kept, whatever the outcome. The push precompute test seals each window before the next opens (barriers), so a lone over-budget window is deterministic.
…e segment dictionary (#865)

A view window read back from its file was charged Batch::memory_bytes, which counts the segment's shared text dictionary once per text column (about 5.9 MB per window against 0.4-1.6 MB real), so the 2 GiB window cache held about 360 windows and thrashed. Both paths now charge window_batch_bytes (plus a read-back window's mapped state columns), and ViewStore::bytes counts each live segment dictionary once. Demo replay, minutes 6-12: hit ratio 0.808 -> 0.988, cold reads 55.2 -> 3.8 MB/s.
@zzylol

zzylol commented Nov 24, 2026

Copy link
Copy Markdown
Contributor Author

Landed on main via #864 (squash 910ecbc), together with #854 and #861 and the review fixes. The branch feat/tiered-view-storage is kept unchanged.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area: data plane Runtime ingestion, storage, and query-serving data paths documentation Improvements or additions to documentation enhancement New feature or request test: end-to-end Process-boundary, differential, conformance, and full-stack tests

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant