Skip to content

Series key: write each label set as Prometheus' Labels.String(), so values holding ; or = never merge series - #65

Draft
zzylol wants to merge 2 commits into
perf/collector-views-series-internfrom
fix/series-key-escaping
Draft

zzylol wants to merge 2 commits into
perf/collector-views-series-internfrom
fix/series-key-escaping

Conversation

@zzylol

@zzylol zzylol commented Nov 30, 2026 •

Copy link
Copy Markdown
Contributor

Summary

  • Problem. The collector's series key wrote each label as name=value; and did not escape values. So {a="b", c="d"} and {a="b;c=d"} both became 0||a=b;c=d;, and the view executor merged two series into one: one state, one sketch, with the samples of both. The asap_sketches windows (window.rs, kll_windows.rs) and the CMS / CMS-heap / CountSketch label-set items had the same flaw.
  • Change. Each label set in the key is now written the way Prometheus' Labels.String() writes it: {a="b", c="d"} and {a="b;c=d"}. Names are sorted, values are quoted as Go's strconv.Quote quotes them, and names that are not legacy label names are quoted too ({"http.method"="GET"}). Golden vectors printed by Go pin the format.
  • Effect. In different_attributes_never_share_a_series, 11 attribute sets gave 9 series before and give 11 after. CPU is unchanged within noise: asap-views-bench on q01 with 10,000 series × 10/s × 30 s, pinned to one core, builds the key on every sample in both modes. Median of 3 interleaved rounds: executor 740.1 → 740.3 ns/sample, asap_sketches 688.8 → 688.4 ns/sample.

Review guide

Behavior: before → after

The collector runs collector-views.json = q01 (DDSketch per series, 5 s windows) on metric data. One OTLP request carries two gauge points in the same window: point 1 has attributes a="b", c="d"; point 2 has a="b;c=d".

before after
series key of point 1 0||a=b;c=d; 0|{}|{a="b", c="d"}
series key of point 2 0||a=b;c=d; (same) 0|{}|{a="b;c=d"}
series the executor keeps 1 (the first point's labels) 2
states emitted for the window 1, count 2, labels a="b", c="d" 2, count 1 each, each with its own labels
asap.topk key label of a label-set item host=h1; {host="h1"}

This serves correctness of every collector view and hand-configured sketch: a series' state must hold only that series' samples.

Interfaces

matchers.rs: the signatures are unchanged and the returned text changes. The file format of the key is the interface:

 /// A series' key: `<agg_id>|<resource labels>|<labels>`.
 pub fn series_key(agg_id: AggId, resource_labels: &[KeyValue], labels: &[KeyValue], aggregate_by: &[String]) -> String;
-/// Labels as `k1=v1;k2=v2;` (sorted, or in `aggregate_by` order), values unescaped.
+/// Labels as Prometheus' `Labels.String()`: `{k1="v1", "k.2"="v2"}` (sorted, or in
+/// `aggregate_by` order), values quoted as `strconv.Quote`, non-legacy names quoted.
 pub fn attributes_key(labels: &[KeyValue], aggregate_by: &[String]) -> String;

tests/golden/series-keys.json is new: 18 {labels, key} vectors printed by Go 1.25 using Prometheus' stringImpl logic, strconv.Quote and LegacyValidation.IsValidLabelName.

Usage (condensed from different_attributes_never_share_a_series, which runs it at e8b6e15 with 11 sets):

// The q01 views file: DDSketch of `data` per series, 5 s windows.
let views = planner_views::parse(Q01).unwrap();
// The collector_views processor's executor.
let mut executor = ViewExecutor::new(&views).unwrap();
// Two points of `data` at T - 1 s: {a="b", c="d"} and {a="b;c=d"}.
let pdata = request(&[(&[], &[("a", "b"), ("c", "d")], T - 1_000, 1.0),
                      (&[], &[("a", "b;c=d")], T - 1_000, 2.0)]);
// decode_each_scalar -> observe_point: identity bytes miss -> intern_labels
// -> write_series_key gives 0|{}|{a="b", c="d"} and 0|{}|{a="b;c=d"}.
decode(&mut executor, pdata);
// The window's states: two series, count 1 each (before: one, count 2).
let drained = executor.drain().states;
assert_eq!(drained.len(), 2);

Algorithm changes

Series key text

  • Problem: {a="b", c="d"} and {a="b;c=d"} had one key, so their samples were merged into one sketch.
  • Before: for each label (sorted or in aggregate_by order), push name, =, value, ;.
  • After: push {. For each label, push , if it is not the first, then name (or "name" quoted when it is not [a-zA-Z_][a-zA-Z0-9_]*), then =, then "value" quoted. Then push }. write_quoted scans the bytes once. If none is a C0 control, ", \, DEL or 0xC2 (the lead byte of a C1 control), it copies the text in one push_str. Otherwise it escapes rune by rune like strconv.Quote: \" \\ \a \b \f \n \r \t \v, \xNN for other C0 controls and DEL, \u00NN for C1 controls.
  • Correctness: The output is the exact text of Prometheus' Labels.String() for the 18 golden vectors (attributes_key_is_prometheus_labels_string). It is unambiguous: inside quotes only \ escapes and " ends a value, and a label set is braced, so the text parses back to exactly one label list. values_holding_separators_are_different_keys and the executor test check the old collisions.
  • Complexity: Still O(total label bytes), with the same single buffer and no new allocation. The key is longer by 4 bytes per label plus 2 per set (more for quoted names). Measured cost: see Summary, unchanged within noise. On the e2e collector path the key is built only on a series' first sight, through collector_views: find a point's series by its attribute bytes (1.27 → 1.11 µs/sample) #62's identity map.
  • Assumptions and limits:
    • Non-UTF-8 values: the OTAP decoder already reads attribute bytes as UTF-8, replacing invalid bytes with U+FFFD. That text is what the series' states carry, so two points that differ only in invalid bytes are one series, as their emitted labels are identical. OTLP requires string values to be UTF-8, and the backend refuses non-UTF-8 strings. Kept as is.
    • Label names: no name is refused. A name that is not a legacy Prometheus name is quoted, as Prometheus 3 quotes UTF-8 names. Names are not translated: the collector keeps http.method, and the backend translates names when it ingests.
    • Difference from strconv.Quote: non-ASCII runes other than C1 controls are written as they are. Go also escapes other non-printable runes such as U+00A0 and U+200B, which needs Unicode tables. This affects only how the key reads, not its uniqueness (non_ascii_runes_other_than_controls_are_written_as_is).
    • Duplicate names (not valid OTLP) are each written, sorted by name and then value. Before, the first value was written twice.

Decisions and open questions

  • Needs reviewer decision: None.
  • Decided (2026-11-30):
    • Format: Prometheus Labels.String(), not a byte-separated form. Sources:
      • Prometheus model/labels/labels_common.go stringImpl (prometheus/prometheus@abe91c0c) writes {, sorted labels joined by , , names quoted when !model.LegacyValidation.IsValidLabelName(name), values via strconv.AppendQuote, then }.
      • Its Hash (labels_slicelabels.go) separates names and values with 0xff, a byte that cannot occur in UTF-8.
      • VictoriaMetrics lib/storage/metric_name.go (VictoriaMetrics@aaf9fc1f) marshalTagValue escapes bytes 0/1/2 as 0 '0', 0 '1', 0 '2' and ends each tag with byte 1, with a fast path that copies when none occurs.
      • All three are unambiguous and equally cheap here: one byte scan, then a copy in the common case. The key is a Rust String and is shown to users (as the asap.topk key label of a label-set item, and in debugging), so the readable Prometheus text wins. A 0xff- or VM-style key would need a Vec<u8> key type and would print as control bytes.
    • The key stays process-local. No other process reads it: the collector sends labels to the backend as OTLP attributes, and the backend keys series by its label map. So the backend needs no matching change. Its companion draft PR only pins that it already keeps these label sets apart (test(ingest, storage): label sets whose values hold separators or quotes stay different series ASAPQuery-backend#896).
    • No persisted-format version bump. Nothing persists the key. Keys live in in-memory maps (view_executor, window.rs, kll_windows.rs). Sketch payloads carry item hashes, and CMS-heap payloads carry the item text, but they are rebuilt every window and not stored across restarts. The emitted golden states (tests/golden/collector-views-states.bin, q01/otlp-body.pb) are unchanged: the e2e and golden tests pass with no update. One visible change: a CMS-heap top-k key label built from a label set changes from host=h1; to {host="h1"}. The demos' top-k keys are per-attribute values (/new/hot-route), not label sets, so they are unaffected.

Verification

Run on a separate build host (Rust 1.100, --features otap-engine). The rows below are from before the restack. After the restack onto df6ba01 (no conflicts, patch identical), cargo fmt --check and the changed-part tests were rerun: --lib filtered to matchers/sketches/view_executor gave 61 passed, and --test runtime filtered to the key tests gave 6 passed.

Scope Result Newly failing vs base Notes
cargo test --lib 156 passed, 1 ignored none at f91817d, 6 lib tests failed and different_attributes_never_share_a_series gave 9 of 11 series
cargo test --test runtime 13 passed none key goldens updated
cargo test --test kll_windows 32 passed none
cargo test --test collector_views_e2e --test otap_pipeline_e2e --test print_capabilities 3 passed none emitted-state goldens unchanged
cargo fmt --check, cargo clippy --features otap-engine --all-targets -- -D warnings clean — one existing cargo unused_dependencies warning, not from this PR

New tests:

  • attributes_key_is_prometheus_labels_string: each of the 18 Go-printed vectors, with and without aggregate_by. They cover ;, =, ", \, newline, other controls, the empty value, CJK and emoji, U+0085, dotted, empty and digit-led names, and a value forging "}, b=".
  • values_holding_separators_are_different_keys: 7 sets that collided or could forge quotes give 7 keys, and a label does not move across the resource boundary.
  • non_ascii_runes_other_than_controls_are_written_as_is: pins the one documented difference from strconv.Quote.
  • different_attributes_never_share_a_series (extended): 5 more sets through real OTLP decode and the identity map, with every identity hashing alike.

Measurement: asap-views-bench …/q01/collector-views.json MODE 10000 10 30 3, taskset -c 3, 3 interleaved rounds. Measured before the restack onto #62 df6ba01: before = 13a29d4, after = 22cf5b6. The restack left this diff unchanged.

mode before ns/sample (round medians) after ns/sample (round medians)
executor (observe, key built every sample) 740.1, 742.4, 736.1 → 740.1 757.3, 740.1, 740.3 → 740.3
sketches (asap_sketches, key built every sample) 688.8, 686.3, 690.2 → 688.8 699.3, 688.4, 684.7 → 688.4

On the e2e collector_views path, #62's identity map means the key is built only once per series, so its cost there is smaller still.

Follow-ups

  • Other in-process maps key series with Rust Debug text (answer_nodes::series_key, window_merge::series_key, baseline_nodes). Debug escapes quotes, so those keys are unambiguous. They are left alone to keep this diff to key construction.
  • The drift event's series attribute joins k=v with ,. It is display only, not a key.

🤖 Generated with Claude Code

https://claude.ai/code/session_01K1M6bo8kYWd83zXwh2Nobf

zzylol and others added 2 commits December 2, 2026 15:28
…es (failing first)

The series key writes each label as `name=value;` without escaping, so
`{a="b", c="d"}` and `{a="b;c=d"}` both read `a=b;c=d;` and the view
executor merges them into one series. These tests pin the fix: the key
is Prometheus' `Labels.String()` text, checked against golden vectors
printed by Go's `strconv.Quote` (tests/golden/series-keys.json).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01K1M6bo8kYWd83zXwh2Nobf
`write_series_key` / `attributes_key` wrote labels as `name=value;`
unescaped, so `{a="b", c="d"}` and `{a="b;c=d"}` had one key and the
view executor, the asap_sketches windows and the CMS / CountSketch
label-set items merged them. Each label set is now written as
Prometheus' `model/labels` `Labels.String()` writes it: `{` names sorted,
`, `-joined, `name="value"`, `}`; values quoted as Go's `strconv.Quote`
quotes them; a name that is not a legacy label name quoted too, as
Prometheus 3 does. A value with nothing to escape is copied as is, so
the hot path stays one byte scan.

The executor's identity map (bytes -> series id) is unchanged: the key
is still built only on a point's first sight.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01K1M6bo8kYWd83zXwh2Nobf
@zzylol
zzylol force-pushed the fix/series-key-escaping branch from 22cf5b6 to e8b6e15 Compare December 2, 2026 15:32
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bug Something isn't working

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant