Skip to content

collector_views: find a point's series by its attribute bytes (1.27 → 1.11 µs/sample) - #62

Draft
zzylol wants to merge 1 commit into
feat/collector-views-lineage-deltasfrom
perf/collector-views-series-intern
Draft

zzylol wants to merge 1 commit into
feat/collector-views-lineage-deltasfrom
perf/collector-views-series-intern

Conversation

@zzylol

@zzylol zzylol commented Nov 30, 2026 •

Copy link
Copy Markdown
Contributor

Summary

  • Problem. collector_views spends most of its per-sample CPU on the walk from OTLP point to series id, not on sketches. Every point was decoded into an Observation (each label copied and checked as UTF-8), and then a sorted k=v; series-key string was built, hashed and compared, even though nearly every point belongs to a series already seen. On the q01 replay (10,000 series × 10 samples/s), the collector used 1.265 µs/sample. ASAPQuery-backend uses ≈1.24 µs/sample for the same work (OTLP decode + series lookup + sketch update).
  • Change. The processor now reads float points in place (decode_each_scalar). Each point's labels stay as bytes: its identity is the resource labels, series-scope labels and point string attributes, length-prefixed, written into one reused buffer. ViewExecutor::observe_point looks the identity up in a per-metric map from identity bytes to series id. Only on a miss does it decode the labels and go through the old series-key path, and then it remembers the identity.
  • Effect. Same replay: 1.107 µs/sample (median of 3; was 1.265), now below ASAPQuery-backend's ≈1.24. The emitted states are byte-identical: the golden file matches on both decode paths.

Review guide

Behavior: before → after

The input is the e2e replay: the collector binary (colA: OTLP receiver → fanout → collector_views + raw_forward → OTLP exporter to a dummy sink) pinned to 2 CPUs, with collector-views.json = q01 on data (DDSketch, 5 s windows). A paced feeder sends 10,000 series × 10 samples/s (100,000 samples/s) as OTLP/HTTP, 10,000 points per request, with 4 string attributes per point. Collector CPU is read from /proc over 40 s after a 25 s warm-up.

before (#60 head 0f77113) after (832011c)
collector µs/sample, runs (interleaved) 1.320, 1.255, 1.265 1.107, 1.130, 1.057
median 1.265 1.107 (−12.5%)
ASAPQuery-backend, same work (reference) ≈1.24 ≈1.24
plain passthrough (reference) 0.23 0.23
feeder rows sent / failed requests 7,500,000 / 0 7,500,000 / 0
emitted states golden bytes the same golden bytes

Profile (perf, 499 Hz, the whole collector process), as a share of collector CPU and the µs/sample it amounts to:

before (1.38 µs run) after (1.11 µs run)
point walk in codec (attribute loop, label copy + UTF-8 check → identity write) 27.3% ≈ 0.38 µs 19.7% ≈ 0.22 µs
series-key build (write_series_key / write_attributes_key) 5.9% ≈ 0.08 µs 0.4% (misses only)
observe routing + map lookup (incl. hashing) 8.4% ≈ 0.12 µs 11.1% ≈ 0.12 µs
OTLP protobuf parsing (otel-arrow views) 14.5% ≈ 0.20 µs 16.9% ≈ 0.19 µs
memcmp / memmove 9.0% 8.8%
malloc / free (mostly per-batch executor runs) 8.4% 10.7%
executor runs + sketch updates (DDSketch try_add ≈3%) 18.6% ≈ 0.26 µs 23.1% ≈ 0.26 µs
kernel (socket copies) + other 8.0% 9.4%

This serves the collector-views evaluation: the collector should not cost more CPU per sample than ASAPQuery-backend spends ingesting the same raw samples.

Interfaces

codec.rs

 /// Every point as an `Observation`, rewritten in one buffer (stays).
 pub fn decode_each(pdata: OtapPdata, f: impl FnMut(&Observation)) -> Result<usize, CodecError>;
+/// Like `decode_each`, but passes only float points, each read in place with its labels still
+/// encoded; envelope points are validated as `decode_each` does, then skipped. The collector-views path.
+pub fn decode_each_scalar(
+    pdata: OtapPdata,
+    f: impl FnMut(&ScalarPoint<'_>),
+) -> Result<usize, CodecError>;
+
+/// One float data point, read in place: its labels stay encoded in `identity` until `labels()`.
+pub struct ScalarPoint<'a> {
+    /// Metric name.
+    pub metric: &'a str,
+    /// Point timestamp (ms).
+    pub timestamp_ms: u64,
+    /// The value (an integer point's, as `f64`).
+    pub value: f64,
+    /// The Resource's string attributes, as `Observation::resource_labels`.
+    pub resource_labels: &'a [KeyValue],
+    /// As `Observation::source`.
+    pub source: &'a Arc<SourceDescriptor>,
+    /// Resource labels, series-scope labels and point string attributes in received order: two
+    /// counted sections and one uncounted section of (u32 len, key, u32 len, value) pairs.
+    /// Equal identity ⇒ same series; the converse holds only for the same attribute order.
+    pub identity: &'a [u8],
+    /// The series scope's labels (`Observation::labels` starts with them).
+    series_labels: &'a [KeyValue],
+    /// Where the point's attributes start in `identity`.
+    attributes_at: usize,
+}
+impl ScalarPoint<'_> {
+    /// `Observation::labels` of this point: series-scope labels, then each string attribute (lossy UTF-8).
+    pub fn labels(&self) -> Vec<KeyValue>;
+}

view_executor.rs

 /// The collector views of one installed plan, built on the executor (stays).
 pub struct ViewExecutor {
     compiled: CompiledPhysicalDAG,
     metrics: HashMap<String, SourceMetric, ahash::RandomState>,
     pool: LocalPool,
     counts: Vec<ViewCounts>,
 }
 impl ViewExecutor {
     /// Takes one point as an `Observation` (tests, `asap-views-bench`).
     pub fn observe(&mut self, obs: &Observation);
+    /// `observe` of a point read in place by `decode_each_scalar`: a point whose identity was
+    /// seen before finds its series without decoding its labels. The processor's path.
+    pub fn observe_point(&mut self, point: &ScalarPoint<'_>);
 }
 /// One source metric: its series and the run groups reading it (private; stays).
 struct SourceMetric {
     ids: HashMap<String, u32, ahash::RandomState>,
+    /// `ScalarPoint::identity` → series id, one entry per attribute order a series arrived in.
+    by_identity: HashMap<Box<[u8]>, u32, IdentityHasher>,
     series: Vec<Option<Series>>,
     free_ids: Vec<u32>,
     groups: Vec<RunGroup>,
     key: String,
     codes: Vec<u32>,
 }

Usage: the processor's path, as collector_views.rs runs it for each OTLP message:

// Message::PData from the receiver: one ExportMetricsServiceRequest, e.g. 10,000 points of
// `data`, each with attributes region/service/job/label_0.
let executor = &mut self.executor; // the views of collector-views.json (q01: DDSketch, 5 s windows)
// Each float point is passed as a ScalarPoint borrowing the request bytes and one identity buffer;
// observe_point finds its series id by `point.identity` (a map hit for every point after a
// series' first point in a window), then appends (id, ts, value) to the window's rows.
if let Err(error) = decode_each_scalar(pdata, |point| executor.observe_point(point)) {
    effects.info(&format!("collector_views: dropping input: {error}")).await;
}
// Builds the rows on the executor and closes the windows the data passed: the same states,
// byte for byte, as before (the golden test).
let closed = self.executor.flush();

Algorithm changes

Series lookup per point

  • Problem. For a point of an already-known series (49 of every 50 points here: 10 samples/s × 5 s windows), the old path still did all the work of a first sighting: 4 label copies with UTF-8 checks, a ≈60-byte key string built, hashed and compared. That cost ≈0.46 µs of the 1.38 µs/sample in the profile.
  • Before:
    1. push_data_point writes series-scope labels and string attributes into the scratch Observation (set_label).
    2. intern runs write_series_key(resource, labels) (sorted k=v;).
    3. It looks up ids[key]; on a miss it creates the series.
  • After:
    1. push_data_point appends each string attribute to the identity (after the scope's prefix of resource and series labels). Nothing is copied into a String and nothing is UTF-8 checked.
    2. intern_point looks up by_identity[identity]. The hash map compares the full bytes, so a hit is exact.
    3. On a miss: labels() decodes the labels, intern_labels runs the old steps 2–3, and by_identity gets identity → id.
  • Correctness:
    • The identity encodes every byte of what the old path used for a series (resource labels, series-scope labels, string attributes, each key and value length-prefixed, and sections counted), so two different label sets never have the same identity.
    • Equal identities produce equal Observation labels, and therefore the same series key and id. A miss always falls back to the old key path, so the canonical key alone still decides which series a point belongs to. This means the same attributes in a different order end up in one series, as before; the second order just gets its own identity entry.
    • Evicted series lose their identities before free_ids can be reused.
    • Tests:
      • golden bytes on both paths;
      • equal_attributes_in_different_requests_are_one_series;
      • different_attributes_never_share_a_series;
      • evicted_identities_are_forgotten.
    • In unit tests, IdentityHasher hashes every identity to 0, so each lookup there is decided by a full byte compare, as it is on a hash collision.
  • Complexity:
    • Per hit: one copy of the attribute bytes into the reused buffer, one hash and one compare of ≈70 bytes, and no allocation (it was 4 string writes, a sort check, building and hashing a key string, and a compare).
    • Per miss: the old cost, plus decoding the labels and one boxed copy of the identity.
    • Memory: one identity (≈70 bytes) per series and attribute order.
    • Per eviction pass: one retain over by_identity.
    • Measured: −0.16 µs/sample.
  • Assumptions and limits:
    • A producer that varies attribute order from point to point gets one identity entry per order (all correct). A producer that sends invalid UTF-8 gets the same lossy labels as before.
    • observe(&Observation) (tests, bench) still uses the key path.

Decisions and open questions

  • Needs reviewer decision: None.
  • Decided (2026-11-30):
    • Identity-bytes map in front of the existing series key, rather than replacing the key. The key stays the single definition of a series (its byte layout is locked by the parity tests), and the identity is only a cache in front of it.
    • Rejected: hashing the attributes to a u64 and storing only the hash. That needs a separate verify step against the stored labels, which fails for a second attribute order. Keying the map by the bytes gets the full compare for free.
  • Seen, not changed: the series key itself does not tell a=b;c=d (two labels) apart from a="b;c=d" (one label whose value contains ; and =). This PR keeps that behaviour (the identity map sits in front of the key), and the new test leaves such values out. Changing it would change the locked key layout.

Verification

Run with --features collector in a separate target dir.

Scope Result Newly failing Notes
cargo fmt --check pass –
cargo clippy --features collector --all-targets -- -D warnings pass –
lib: view_executor collector_views codec matchers baseline_nodes raw_forward 56 passed none includes the series-key byte-parity tests (matchers)
tests/collector_views_e2e.rs 2 passed none emitted_states_match_the_golden_bytes now checks decode_each_scalar + observe_point and decode_each + observe against the golden bytes; otlp_in_view_states_out runs the processor (new path) against direct observe
tests/otap_pipeline_e2e.rs 1 passed none decode_each / decode_pdata_to_observations callers

New tests:

  • equal_attributes_in_different_requests_are_one_series: points with equal attributes, sent in three requests in two attribute orders, form one series (count 4, labels in first-seen order), with one identity entry per order.
  • different_attributes_never_share_a_series: label sets whose bytes differ only in how they split (ab=c vs a=bc, a resource label vs the same point attribute, one label vs two) stay distinct series across two requests, with every hash colliding.
  • evicted_identities_are_forgotten: after eviction and reuse of an id, the old identity does not find the new series.

The end-to-end measurement is in the before → after table. The harness is the replay described there, with 3 interleaved runs per binary.

Follow-ups

  • The rest of the per-sample cost is mostly outside this path:
    • OTLP protobuf parsing in otel-arrow's views (≈0.19 µs);
    • the attribute loop (≈0.22 µs);
    • the executor runs per flush (≈0.26 µs; one Arrow batch per request);
    • allocator traffic, mostly from those runs.
  • The routing still hashes the metric name once per point (<1%).
  • Possible next steps, not done here:
    • skip attribute decoding for metrics no view reads;
    • batch the executor runs across requests.

🤖 Generated with Claude Code

https://claude.ai/code/session_01K1M6bo8kYWd83zXwh2Nobf

@zzylol zzylol added the enhancement New feature or request label Nov 30, 2026
The collector-views path decoded every OTLP point into an Observation
(copying and UTF-8-checking each label) and then built, hashed and
compared a sorted series-key string per point, though nearly every point
is of a series seen before.

decode_each_scalar passes each float point as a ScalarPoint whose labels
stay encoded: its identity is the resource labels, series scope labels
and point string attributes as length-prefixed bytes, written into one
reused buffer. ViewExecutor::observe_point looks the identity up in a
per-metric map of identity bytes to series id; only a miss decodes the
labels and goes through the series key as before, then remembers the
identity. The map compares the bytes on every hit, so a hash collision
is never a match. Evicted series drop their identities before their ids
are reused.

On the 10,000-series, 100,000 samples/s q01 replay the collector takes
1.107 us per sample instead of 1.265 (median of 3). Emitted states are
unchanged: the golden bytes match through both decode paths.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01K1M6bo8kYWd83zXwh2Nobf
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

enhancement New feature or request

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant