Skip to content

feat(data_plane): sample-block codec for compressed-sample windows (Gorilla, or decimal + zstd chosen at seal) - #857

Closed
zzylol wants to merge 7 commits into
sync/planner-main-1760a69ffrom
feat/sample-block-codec
Closed

zzylol wants to merge 7 commits into
sync/planner-main-1760a69ffrom
feat/sample-block-codec

Conversation

@zzylol

@zzylol zzylol commented Nov 22, 2026 •

Copy link
Copy Markdown
Contributor

Summary

  • Problem: the Planner's compressed-sample windows (one block per series per tumbling window, decoded at query time into raw rows for exact answers) need a codec. The Planner's executor builds, seals, merges and decodes those blocks only through its SampleBlockCodec trait; its own PlainSampleBlockCodec stores 16 bytes per sample.
  • Change: a data-plane codec, data_plane::sample_blocks::CompressedSampleBlockCodec. A block is codec 0 (Gorilla: delta-of-delta timestamps, XOR values) while open. When it seals, it keeps the shorter of codec 0 and codec 1 (decimal mantissas as zigzag varints in a zstd frame; short decimals only). Ingestion and query runs build with it (RunContext::with_sample_block_codec). View files store the sealed blocks verbatim. The data plane declares sealed-window reads only until it serves a chain's open window.
  • Effect (bake-off, 1,000 series × 3,600 samples at 1 s): two-decimal log-normal latencies take 1.96 B/sample, integer counters 0.38, Zipf(1.1, 10⁶) integer gauges 1.97, the current generator's random doubles 7.39; the plain codec takes 16 for all of them. An exact quantile_over_time(0.5, data[1m]) without raw data is answered from decoded blocks, also after a restart.

Review guide

Behavior: before → after

Workload: quantile_over_time(0.5, data[1m]) and max_over_time(data[1m]) every 10 s, exact (no accuracy given). data has 2 series at 1 sample/s. raw_data_retained: false. This is the new compressed_sample_windows.rs.

Before (#852, Planner 846a70a) After
Plan none: no exact producer of the 1 m raw range without raw data Scan → SummaryTumblingWindowChain[CompressedSamples] (a width that tiles the readers) → DecodeSamplesInRange 1m (sealed reads) → Aggregate quantile / max
Answers — equal to the quantile and max computed from the samples, every 10 s step; equal again after a restart over the view files
Block bytes — the data plane's codec (the plain codec when no deployment codec is set: 16 B/sample)

Interfaces

sample_blocks/mod.rs, sample_blocks/block.rs, persist.rs, control_plane/src/lib.rs

+// data_plane::sample_blocks
+/// The data plane's sample-block codec: CompressedSamples blocks.
+pub struct CompressedSampleBlockCodec;
+impl SampleBlockCodec for CompressedSampleBlockCodec {
+    /// An open codec-0 block: O(1) per newer sample; an older sample or an equal timestamp re-encodes.
+    fn new_block(&self) -> Box<dyn OpenSampleBlock>;
+    fn decode(&self, block: &[u8]) -> Result<Vec<(i64, f64)>, KernelError>;
+    /// The samples with start_exclusive_ms < t <= end_inclusive_ms.
+    fn samples_in(&self, block: &[u8], start_exclusive_ms: i64, end_inclusive_ms: i64) -> Result<Vec<(i64, f64)>, KernelError>;
+    /// The sealed block of both blocks' samples; newer wins on an equal timestamp.
+    fn merge(&self, older: &[u8], newer: &[u8]) -> Result<Vec<u8>, KernelError>;
+}
+/// The one shared codec every run builds with and the view files decode with.
+pub fn codec() -> Arc<dyn SampleBlockCodec>;
+/// A block's codec: its first byte.
+pub enum SampleCodec { Gorilla = 0, DecimalZstd = 1 }
+/// One series' samples in one window as a block; the byte format is in block.rs's module doc.
+pub struct CompressedSamples { /* codec, count, first timestamp, body */ }
+impl CompressedSamples {
+    pub fn new() -> Self;
+    pub fn push(&mut self, timestamp_ms: i64, value: f64);
+    /// The shorter codec (codec 0 on a tie).
+    pub fn seal(&self) -> Self;
+    pub fn encoded_with(&self, codec: SampleCodec) -> Option<Self>;
+    pub fn codec(&self) -> SampleCodec;
+    pub fn len(&self) -> u32;
+    pub fn payload_bits(&self) -> u64;
+    pub fn encoded_bytes(&self) -> usize;
+    pub fn iter(&self) -> SamplesIter<'_>;
+    pub fn samples_in(&self, start_exclusive_ms: i64, end_inclusive_ms: i64) -> impl Iterator<Item = (i64, f64)> + '_;
+    pub fn merge(&self, other: &Self) -> Self;
+    pub fn to_bytes(&self) -> Vec<u8>;
+    /// Validates every byte; never panics.
+    pub fn from_bytes(bytes: &[u8]) -> Result<Self, CompressedSamplesFormatError>;
+}
+/// Why bytes are not a block (always bad input).
+pub enum CompressedSamplesFormatError { Truncated, PayloadLengthMismatch, PayloadWithoutSamples, UnknownCodec, InvalidFrame }

 // data_plane::persist
 enum StoredValue {
     Plain(Value),
     Text(u32),
     Exact(ExactAccumulator),
     Increase(IncreaseAccumulator),
     Sketch { kernel: SketchKernel, asapv1: Vec<u8> },
     HydraCmsGroup { grid: u32, group: String },
+    /// A compressed-samples state: its sealed block as the data plane's codec wrote it.
+    CompressedSamples(Vec<u8>),
 }

 // control_plane
 pub fn backend_capabilities() -> DeploymentCapabilities {
     DeploymentCapabilities {
         supported_summaries: None,
         raw_data_retained: true,
         query_time_results_retained: false,
         final_query_results_cached: true,
+        unsealed_window_reads: false,
         ..DeploymentCapabilities::default()
     }
 }

Usage:

  1. A workload with an exact range read and no raw data is planned with a CompressedSamples chain: plan_workload under backend_capabilities, so with aligned widths and sealed reads.
  2. Ingestion runs (RunContext::new(..).with_sample_block_codec(sample_blocks::codec())) append each sample to its series' open block and seal it at the window's end. The view rows hold the sealed bytes.
  3. The persist thread writes StoredValue::CompressedSamples(block) verbatim; loading restores the state with CompressedSamplesAccumulator::restore_from_disk(block, codec()).
  4. A query run's DecodeSamplesInRange calls samples_in on each window's block and hands the rows to the exact Aggregate.

How #855 uses this

  • Write path: a sealed window's state is CompressedSamplesAccumulator::block(), the bytes OpenSampleBlock::seal returned. Store them verbatim as a blob in the fragment's state column; no re-encode. persist.rs does the same in today's record format (StoredValue::CompressedSamples). It re-encodes only a block written by another codec (a state built by a run without the data plane's codec).
  • Read path: a mapped blob goes back to a state with CompressedSamplesAccumulator::restore_from_disk(bytes, sample_blocks::codec()), which validates. The executor's DecodeSamplesInRange then calls SampleBlockCodec::samples_in (and decode) on the bytes. A blob needs no state decode step before the query decodes it.
  • Open window: OpenSampleBlock::seal does not consume, so it doubles as the open window's snapshot. data-plane: tiered view storage with zero-copy state views #855 can instead serve the open window from its raw panes, as its design says. Either way, flip unsealed_window_reads to true in backend_capabilities in the PR that serves it; until then plans read sealed windows at aligned widths.

Algorithm changes

Sample-block codec (port of the closed asap_sketchlib #268 implementation, unchanged in format):

  • Before: compressed-samples states would be stored by the Planner's plain codec: 4 + 16 n bytes per block.
  • After:
    • append codes a newer sample with a delta-of-delta timestamp code (1–68 bits) and an XOR value code reusing the previous leading/trailing-zero window.
    • seal also tries codec 1 when every value is finite, not −0, and exactly m / 10^D with |m| < 2^53, D ≤ 17. Codec 1 writes varints of the mantissa deltas or deltas of deltas (the shorter), compressed with zstd level 1. seal keeps the strictly shorter codec.
    • merge is a linear merge of both blocks' samples, then a seal.
  • Correctness: both codecs are lossless bit for bit. K1–K5 check round trips, golden bytes computed by a separate reference implementation, merge, half-open trimming and code lengths. K6 checks the trait adapter.
  • Complexity: append is O(1) for newer samples, O(n) otherwise. seal is O(n) plus zstd. decode/samples_in are O(n); codec 1 decompresses once per call, bounded by 20 bytes per sample.

Bake-off (sample_block_bakeoff.rs). Release build, 1,000 series × 3,600 samples at 1 s, through the trait. One core of a shared 2.0 GHz server, so timings are noisy.

Data shape codec 0 B/sample codec 1 B/sample sealed B/sample (blocks sealed as codec 1) plain B/sample append ns seal ns decode ns
random doubles (current generator, rank-scaled Pareto(2)) 7.39 not eligible 7.39 (0/1000) 16.00 41.9 65.8 43.6
two-decimal log-normal latency (median 20 ms) 8.07 1.96 1.96 (1000/1000) 16.00 44.1 113.1 26.9
integer counter (+1…5 per sample) 1.97 0.38 0.38 (1000/1000) 16.00 39.2 96.3 22.2
Zipf(1.1, 10⁶) integer gauge 3.98 1.97 1.97 (1000/1000) 16.00 40.2 104.2 35.5
Zipf(1.1, 10⁶) counter increments 3.46 1.50 1.50 (1000/1000) 16.00 41.6 105.8 36.3

decode validates the block (one decode pass) and then decodes it (a second pass). A single-pass decode is a follow-up if query profiles show it.

Decisions and open questions

Decided:

  • The codec lives in the data plane, not in asap_sketchlib (closed fix(backend): cms_params accepts canonical w/d + legacy row_num/col_num #268) or ASAPPlanner. The format and tests are unchanged from fix(backend): cms_params accepts canonical w/d + legacy row_num/col_num #268.
  • One shared codec instance (sample_blocks::codec()), with no option to switch it.
  • View files store blocks verbatim; a foreign codec's block is re-encoded at persist time.
  • unsealed_window_reads: false until the open window is served. The data plane's view read returns sealed windows that tile the range, so an unsealed read at a mid-window T would be refused ("no rows tiling").
  • Tests that assert a sketch is selected now exclude compressed_samples. Under the new pin, exact decode plans beat DDSketch/KLL on their small workloads, so without the exclusion they would test the wrong state.

Needs reviewer decision: none.

Not in this PR: cargo clippy -- -D warnings under Rust 1.98 flags type_complexity in prometheus.rs and series_ids.rs. This PR does not touch those files, and the lints are left as they are.

Verification

Scope Result Notes
data_plane --test sample_blocks pass (6) K1–K5 with unchanged golden vectors; K6 is the trait adapter
data_plane --test compressed_sample_windows pass (1) new end-to-end test: exact answers, persistence, restart
data_plane --lib pass (36) incl. compressed_samples_are_stored_as_their_sealed_block
control_plane --test plan_workload pass (7) two tests now exclude compressed_samples
data_plane --test window_levels pass (1) multi-level chains
data_plane --test precompute_pool pass (6)
data_plane tests: concurrency (1), ingest_shards (9), no_forward (3), planner_executor_answers (10), planner_executor_parity (2), range_queries (4), result_cache (3), series_ids (2), server (10), shared_results (2), view_memory (1), view_persistence (7) pass run one target at a time, removing test binaries after each, because disk is short
cargo clippy --workspace --all-targets -- -D warnings fails only on type_complexity in untouched prometheus.rs/series_ids.rs clean with -A clippy::type_complexity; left as they are
cargo fmt --all -- --check pass
cargo check --workspace --all-targets clean at 0c302c4ea
bake-off (release) run table above

Follow-ups

@zzylol zzylol added area: data plane Runtime ingestion, storage, and query-serving data paths area: summary execution Warm-summary binding, readout, composition, and result decoding enhancement New feature or request integration: ASAPPlanner ASAPPlanner API, IR, candidate, and selected-plan integration labels Nov 22, 2026
@zzylol

zzylol commented Nov 24, 2026

Copy link
Copy Markdown
Contributor Author

Replaced by #863: the same commits rebased onto main (#852 was squash-merged). The branch feat/sample-block-codec is kept.

@zzylol zzylol closed this Nov 24, 2026
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 area: summary execution Warm-summary binding, readout, composition, and result decoding enhancement New feature or request integration: ASAPPlanner ASAPPlanner API, IR, candidate, and selected-plan integration

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant