Skip to main content

mira_core/
series.rs

1//! The metrics read path: match metrics, gather points, group into series.
2//!
3//! A different shape from [`crate::query::search`], and deliberately a separate
4//! function rather than a mode of it. A log search filters one root table and
5//! returns rows newest-first; a metrics query filters a *descriptor* table,
6//! gathers points from four point tables that share one id space, and then
7//! regroups them by a key that has to be stable across blocks. Folding both into
8//! one code path would mean inventing the abstraction that both are special
9//! cases of, which is a planner.
10//!
11//! The grouping key is the hard part and the reason this is not trivial. Ids are
12//! rebased per block — that is what makes the attribute joins array stores — so
13//! nothing block-local can identify a series across two blocks. The key is built
14//! from values instead: the metric's name, unit and kind, plus the merged
15//! attribute map from all four levels. That is one string built per point, which
16//! is the honest cost of a layout optimized for writing and pruning rather than
17//! for grouping.
18//!
19//! ## What V0 returns
20//!
21//! Gauges and sums come back as their own value. Histograms, exponential
22//! histograms and summaries come back as two derived series each, `<name>.count`
23//! and `<name>.sum` — the same convention Prometheus uses, and the same two
24//! numbers that answer "how often" and "how much". Bucket and quantile maths is
25//! not here: it is a heatmap feature, it needs the UI to exist first, and
26//! shipping it wrong would be worse than shipping it later. Everything needed
27//! for it is on disk already — `bucket_counts`, `bounds_id`, `scale`, `quantile`
28//! — so this is a read-path gap, not a storage one.
29//!
30//! Blocking: mmaps and page-faults, same as `search`. Callers on an async
31//! runtime must use `spawn_blocking`.
32
33use std::collections::{BTreeMap, BTreeSet, HashMap};
34use std::path::Path;
35use std::sync::Arc;
36
37use arrow_array::cast::AsArray;
38use arrow_array::types::{
39    Float64Type, Int64Type, TimestampNanosecondType, UInt8Type, UInt16Type, UInt32Type, UInt64Type,
40};
41use arrow_array::{Array, RecordBatch};
42
43use crate::block::{self, Src};
44use crate::error::Result;
45use crate::json::Json;
46use crate::query::{Attrs, Results, Stats, Term, attr_key, attr_parents, dict_index, emit_attr};
47use crate::schema::MetricKind;
48use crate::signal::Open;
49
50/// A metrics query.
51///
52/// Note what is missing: no `step`, no aggregation, no rate. Downsampling in the
53/// engine would need a fill policy, an alignment rule and a choice of aggregator
54/// per metric kind, all of which are presentation decisions the caller is better
55/// placed to make and all of which are wrong for somebody. Raw points, bounded
56/// by `max_points`, and the chart decides.
57#[derive(Debug, Clone)]
58pub struct SeriesQuery {
59    /// Exact metric name. `None` matches every metric, which is what the name
60    /// listing uses and what an exploratory query does before it knows better.
61    pub name: Option<String>,
62    /// Inclusive nanosecond bounds.
63    pub from: i64,
64    pub to: i64,
65    /// Attribute filters. A term is satisfied if it matches at *any* level —
66    /// resource, scope, metric or data point — because a caller filtering on
67    /// `service.name` should not have to know which of the four carries it.
68    pub terms: Vec<Term>,
69    pub max_series: usize,
70    /// Per series, not in total: truncating one busy series must not silently
71    /// empty the others charted beside it.
72    pub max_points: usize,
73}
74
75/// One point. Integers stay integers: an OTLP `as_int` is `sfixed64`, and a
76/// counter past 2^53 pushed through an f64 loses its low bits — which is exactly
77/// the moment a counter is interesting.
78#[derive(Debug, Clone, Copy)]
79enum Pt {
80    Int(i64),
81    Double(f64),
82}
83
84struct Series {
85    /// Rendered `"name":...,"unit":...,` etc. Built once when the series is
86    /// first seen; identical for every point in it by construction.
87    desc: String,
88    /// Rendered `{...}` attribute object.
89    attrs: String,
90    points: Vec<(i64, Pt)>,
91    /// Points dropped by `max_points`, reported rather than hidden. A chart
92    /// missing its spike because the engine quietly truncated is the failure
93    /// mode this exists to prevent.
94    dropped: usize,
95    /// The trace ids behind the points: `(time, rendered object)`, rendered
96    /// here because the block they were read from is unmapped before the
97    /// response is written.
98    exemplars: Vec<(i64, String)>,
99}
100
101impl Series {
102    /// Discard all but the newest `max` points.
103    ///
104    /// Which points a cap keeps is a correctness question, not a tuning one.
105    /// Points arrive in block-scan order, so refusing them once the buffer is
106    /// full kept whichever ones the directory listing happened to reach first
107    /// — an arbitrary subset that the sort at render time then dressed up as a
108    /// contiguous series. Newest-wins is the same rule `limit` already uses on
109    /// the record side, and it is a window a reader can reason about.
110    ///
111    /// Called at twice `max`, so every call throws away half of what it sorts
112    /// and the amortised cost is constant per point. A bounded heap would hold
113    /// exactly `max` at all times and pay `log max` on every point instead;
114    /// at these sizes the occasional sort is cheaper and much less code.
115    ///
116    /// ponytail: truncation, not downsampling. A chart that needs the whole
117    /// range at a lower resolution needs an aggregation window — until that
118    /// exists the response says `dropped_points` rather than pretending.
119    fn compact(&mut self, max: usize) {
120        // Descending, so `truncate` keeps the newest.
121        self.points.sort_unstable_by_key(|p| std::cmp::Reverse(p.0));
122        self.dropped += self.points.len() - max;
123        self.points.truncate(max);
124    }
125}
126
127/// Exemplars kept per series.
128///
129/// An exemplar is one sampled measurement per collection interval per bucket,
130/// so a well-behaved exporter sends few — but nothing in OTLP bounds it, and an
131/// unbounded array here would make one misconfigured SDK able to inflate every
132/// chart response. ponytail: a flat cap, not a reservoir sample; the first ones
133/// in a window are as good a sample as any until someone proves otherwise.
134const MAX_EXEMPLARS: usize = 64;
135
136/// One attribute as `(key, rendered JSON value)`. Rendered once and carried as
137/// a string because the same value is written into both the grouping key and
138/// the response.
139type Attr = (String, String);
140
141/// A descriptor row's cached contribution: its rendered JSON members, and the
142/// attributes every point beneath it inherits.
143type Prefix = (String, Vec<Attr>);
144
145/// The four point tables, and how many name suffixes each contributes.
146///
147/// One table per OTLP point type rather than one wide table: measured, the split
148/// layout is 2.34x smaller (73.0 vs 170.6 bytes/point), because a wide table
149/// pays for every column of every type on every row.
150const DP_TABLES: [&str; 4] = ["number_dp", "hist_dp", "exp_hist_dp", "summary_dp"];
151
152/// The suffixes a histogram's or summary's name is derived with. Named rather
153/// than written twice, because the name filter has to accept back exactly the
154/// names the renderer hands out and two literal lists would drift apart.
155const COUNT: &str = ".count";
156const SUM: &str = ".sum";
157const DERIVED: [&str; 2] = [COUNT, SUM];
158
159pub fn series(root: &Path, q: &SeriesQuery) -> Result<Results> {
160    series_open(root, q, &[])
161}
162
163/// As [`series`], but also reads the open block's snapshot — see
164/// [`crate::query::search_open`], which this mirrors exactly.
165pub fn series_open(root: &Path, q: &SeriesQuery, open: &[Arc<Open>]) -> Result<Results> {
166    let disk = block::scan(root, "metrics")?;
167    let refs = block::sources(&disk, open);
168    let mut stats = Stats {
169        blocks_total: refs.len(),
170        ..Default::default()
171    };
172    let mut out: BTreeMap<String, Series> = BTreeMap::new();
173    let mut dropped: BTreeSet<String> = BTreeSet::new();
174
175    for bref in &refs {
176        // The directory name is the whole index; a block outside the window is
177        // never opened.
178        if bref.max_ts < q.from || bref.min_ts > q.to {
179            continue;
180        }
181        stats.blocks_scanned += 1;
182        collect_block(bref, q, &mut out, &mut dropped, &mut stats)?;
183    }
184    stats.dropped_series = dropped.len();
185
186    // The last compaction of each series, and the only one for a series that
187    // never reached the trigger. Sorting ascending here as well means the
188    // render below reads `points` directly instead of cloning it.
189    for s in out.values_mut() {
190        if s.points.len() > q.max_points {
191            s.compact(q.max_points);
192        }
193        s.points.sort_unstable_by_key(|p| p.0);
194    }
195
196    // A `BTreeMap`, so this is already in key order: two identical queries
197    // produce byte-identical responses, which an ETag, a diff and a cache all
198    // depend on and which a `HashMap` iteration order does not provide. It is
199    // also already at most `max_series` long — see [`bound`].
200    let mut j = Json::new();
201    j.arr(|j| {
202        for s in out.values() {
203            let pts = &s.points;
204            j.obj(|j| {
205                j.raw(&s.desc);
206                j.key("attributes");
207                j.raw(&s.attrs);
208                if s.dropped > 0 {
209                    j.key("dropped_points");
210                    j.u64(s.dropped as u64);
211                }
212                j.key("points");
213                j.arr(|j| {
214                    for &(ts, v) in pts {
215                        j.arr(|j| {
216                            // Both 64-bit halves go out as strings, for the
217                            // reason [`Json::i64_str`] gives: a nanosecond
218                            // timestamp is ~1.7e18 and an OTLP `as_int` is an
219                            // `sfixed64`, and a counter past 2^53 read back
220                            // through a double loses exactly the low bits that
221                            // made it worth charting. A double stays a number
222                            // — it was never anything else.
223                            j.i64_str(ts);
224                            match v {
225                                Pt::Int(i) => j.i64_str(i),
226                                Pt::Double(d) => j.f64(d),
227                            }
228                        });
229                    }
230                });
231                // The answer to "which trace made this spike". Omitted rather
232                // than emitted empty, because most series have none and this is
233                // the response a chart polls.
234                if !s.exemplars.is_empty() {
235                    let mut ex = s.exemplars.clone();
236                    ex.sort_unstable_by_key(|e| e.0);
237                    j.key("exemplars");
238                    j.arr(|j| {
239                        for (_, rendered) in &ex {
240                            j.raw(rendered);
241                        }
242                    });
243                }
244            });
245        }
246    });
247    Ok(Results {
248        json: j.into_string(),
249        stats,
250        // Metrics are bounded by `max_series` and `max_points`, which cap what
251        // a chart can render rather than cut a list short. Nothing to page.
252        next: None,
253        cursors: Vec::new(),
254    })
255}
256
257/// Every metric name present in the window, with its unit and kind.
258///
259/// This is what a UI puts in a dropdown and what an agent reads before writing
260/// its first query, so it is a first-class endpoint rather than something to
261/// derive from an unfiltered `series` call — the descriptor table is tens of
262/// rows per block, while the points it describes are hundreds of thousands.
263pub fn names(root: &Path, from: i64, to: i64) -> Result<Results> {
264    names_open(root, from, to, &[])
265}
266
267/// As [`names`], but also reads the open block's snapshot. A metric name that
268/// has only ever been written to the open block is exactly the one a dropdown
269/// must not omit — it is the new one.
270pub fn names_open(root: &Path, from: i64, to: i64, open: &[Arc<Open>]) -> Result<Results> {
271    let disk = block::scan(root, "metrics")?;
272    let refs = block::sources(&disk, open);
273    let mut stats = Stats {
274        blocks_total: refs.len(),
275        ..Default::default()
276    };
277    let mut seen: HashMap<String, (String, u8)> = HashMap::new();
278
279    for bref in &refs {
280        if bref.max_ts < from || bref.min_ts > to {
281            continue;
282        }
283        stats.blocks_scanned += 1;
284        let Some(m) = load(bref, "metrics")? else {
285            continue;
286        };
287        stats.rows_scanned += m.num_rows();
288        for r in 0..m.num_rows() {
289            let name = dict_str(&m, "name", r).unwrap_or("").to_owned();
290            let unit = dict_str(&m, "unit", r).unwrap_or("").to_owned();
291            let kind = u8_col(&m, "kind", r);
292            seen.entry(name).or_insert((unit, kind));
293        }
294    }
295    stats.rows_matched = seen.len();
296
297    let mut names: Vec<&String> = seen.keys().collect();
298    names.sort_unstable();
299    let mut j = Json::new();
300    j.arr(|j| {
301        for n in names {
302            let (unit, kind) = &seen[n];
303            j.obj(|j| {
304                j.key("name");
305                j.str(n);
306                j.key("unit");
307                j.str(unit);
308                j.key("kind");
309                j.str(kind_name(*kind));
310            });
311        }
312    });
313    Ok(Results {
314        json: j.into_string(),
315        stats,
316        // Metrics are bounded by `max_series` and `max_points`, which cap what
317        // a chart can render rather than cut a list short. Nothing to page.
318        next: None,
319        cursors: Vec::new(),
320    })
321}
322
323fn kind_name(k: u8) -> &'static str {
324    match k {
325        x if x == MetricKind::Gauge as u8 => "gauge",
326        x if x == MetricKind::Sum as u8 => "sum",
327        x if x == MetricKind::Histogram as u8 => "histogram",
328        x if x == MetricKind::ExponentialHistogram as u8 => "exponential_histogram",
329        x if x == MetricKind::Summary as u8 => "summary",
330        _ => "unset",
331    }
332}
333
334fn load(bref: &Src, name: &str) -> Result<Option<RecordBatch>> {
335    bref.load(name)
336}
337
338/// Child rows grouped by `parent_id`, indexed by it.
339///
340/// Ids are rebased dense from zero per block, so the parent id *is* the slot —
341/// no hash map, and the whole thing is one pass over a `u32` buffer.
342pub(crate) fn index_by_parent(b: &RecordBatch) -> Vec<Vec<u32>> {
343    let Some(col) = b.column_by_name("parent_id") else {
344        return Vec::new();
345    };
346    let parents = col.as_primitive::<UInt32Type>().values();
347    let mut out: Vec<Vec<u32>> =
348        vec![Vec::new(); parents.iter().copied().max().unwrap_or(0) as usize + 1];
349    for (r, &p) in parents.iter().enumerate() {
350        out[p as usize].push(r as u32);
351    }
352    out
353}
354
355fn exemplar_time(b: &RecordBatch, row: u32) -> i64 {
356    b.column_by_name("time_unix_nano").map_or(0, |c| {
357        c.as_primitive::<TimestampNanosecondType>()
358            .value(row as usize)
359    })
360}
361
362fn dict_str<'a>(b: &'a RecordBatch, col: &str, row: usize) -> Option<&'a str> {
363    let c = b.column_by_name(col)?;
364    let d = c.as_dictionary::<UInt16Type>();
365    if d.is_null(row) {
366        return None;
367    }
368    Some(
369        d.values()
370            .as_string::<i32>()
371            .value(d.keys().value(row) as usize),
372    )
373}
374
375fn u8_col(b: &RecordBatch, col: &str, row: usize) -> u8 {
376    b.column_by_name(col)
377        .map_or(0, |c| c.as_primitive::<UInt8Type>().value(row))
378}
379
380/// Hold `out` to `max_series` entries by evicting its largest key.
381///
382/// The result is the same set `sort(keys).truncate(max_series)` produced, and
383/// the argument is short enough to check: the answer is the `max_series`
384/// smallest keys, and a key that belongs in it can never be the largest key of
385/// a map that is already one over — everything else in that map is smaller, so
386/// there are already `max_series` keys ahead of it. Evicting the maximum
387/// therefore only ever discards a key the sort would have truncated. It also
388/// cannot come back: the evicted key is greater than every key in the map, and
389/// the map's maximum only falls, so the same key arriving from a later block is
390/// evicted again on sight.
391///
392/// The difference is *when*, and that is the whole point. The old map grew one
393/// entry per distinct (name, unit, kind, temporality, monotonic, attributes)
394/// tuple until the query finished, each carrying a rendered descriptor, a
395/// rendered attribute object and a key concatenating both — about a kilobyte.
396/// `max_points` bounded the points inside a series and nothing bounded the
397/// series, so a `query_metric` with no `name` over a store with a request id in
398/// a data-point attribute allocated until the process died.
399///
400/// The evicted key is kept, without its payload, so the response can say how
401/// many series it is not showing. ponytail: that record is itself capped at
402/// `max_series` keys, so `dropped_series` saturates rather than counting an
403/// unbounded number of them exactly — remembering every key to count it is the
404/// allocation this function exists to prevent. `dropped_series == max_series`
405/// reads as "at least". Counting evictions instead of distinct keys was the
406/// other option and it is worse: a series above the cap is re-inserted and
407/// re-evicted once per point, so a store with 100 series and a cap of 64 would
408/// report tens of thousands dropped.
409fn bound(out: &mut BTreeMap<String, Series>, dropped: &mut BTreeSet<String>, max: usize) {
410    while out.len() > max {
411        let Some((k, _)) = out.pop_last() else { break };
412        if dropped.len() < max {
413            dropped.insert(k);
414        }
415    }
416}
417
418fn collect_block(
419    bref: &Src,
420    q: &SeriesQuery,
421    out: &mut BTreeMap<String, Series>,
422    dropped: &mut BTreeSet<String>,
423    stats: &mut Stats,
424) -> Result<()> {
425    // A missing descriptor table means retention is unlinking this block under
426    // us. Normal, not an error.
427    let Some(metrics) = load(bref, "metrics")? else {
428        return Ok(());
429    };
430    let n_metrics = metrics.num_rows();
431
432    // Name filter: resolve the string against the dictionary once, then compare
433    // u16 codes. A block whose dictionary lacks the name has no rows to check.
434    //
435    // Above the six loads below, not below them: each is an `mmap` and a CRC of
436    // the whole table body, so a block that does not hold the requested metric
437    // should cost one of them and not six.
438    let mut wanted = vec![true; n_metrics];
439    // Set when the requested name was a derived one, so only that half of the
440    // histogram is emitted rather than both.
441    let mut only_suffix = "";
442    if let Some(want) = &q.name {
443        let d = metrics
444            .column_by_name("name")
445            .map(|c| c.as_dictionary::<UInt16Type>());
446        let Some(d) = d else { return Ok(()) };
447        let names = d.values().as_string::<i32>();
448        // The descriptor dictionary holds `http.server.duration`; this function
449        // hands back series called `http.server.duration.count`. A caller
450        // pasting a name off its own previous answer — a chart legend, an agent
451        // reading the result it just got — must not get a silent empty series
452        // list, so a miss retries against the base name. A metric genuinely
453        // called `foo.count` matches on the first try and keeps winning.
454        let mut code = dict_index(names, want);
455        if code.is_none() {
456            for s in DERIVED {
457                if let Some(base) = want.strip_suffix(s) {
458                    code = dict_index(names, base);
459                    only_suffix = s;
460                    break;
461                }
462            }
463        }
464        let Some(code) = code else { return Ok(()) };
465        let codes = d.keys().values();
466        for (r, w) in wanted.iter_mut().enumerate() {
467            *w = codes[r] == code;
468        }
469    }
470
471    // Wrapped rather than raw, because `own_attrs` below runs once per matched
472    // point and `Attrs` turns each of those from a scan of the whole table into
473    // two binary searches.
474    let metric_attrs = load(bref, "metric_attrs")?.map(Attrs::new);
475    let dp_attrs = load(bref, "dp_attrs")?.map(Attrs::new);
476    // Data point ids are one dense space across all four point tables, so one
477    // list indexed by id serves every table below — the same property that lets
478    // `dp_attrs` carry no discriminant.
479    let exemplars = load(bref, "exemplars")?;
480    let by_point = exemplars.as_ref().map(index_by_parent).unwrap_or_default();
481    let resource_attrs = load(bref, "resource_attrs")?.map(Attrs::new);
482    let scope_attrs = load(bref, "scope_attrs")?.map(Attrs::new);
483
484    // For each term, which metric rows satisfy it *above* the point level. A
485    // point still qualifies if its own attributes satisfy the term, so this is
486    // one half of an OR evaluated per point below.
487    let above: Vec<Vec<bool>> = q
488        .terms
489        .iter()
490        .map(|t| {
491            let key = match &t.target {
492                crate::query::Target::Attr(k) | crate::query::Target::Field(k) => k,
493            };
494            let mut hit = vec![false; n_metrics];
495            // Metric level: parent_id is the descriptor row number.
496            if let Some(a) = &metric_attrs {
497                for pid in attr_parents(&a.rows, key, t.op, &t.value) {
498                    if let Some(s) = hit.get_mut(pid as usize) {
499                        *s = true;
500                    }
501                }
502            }
503            // Resource and scope level: parent_id is an entity id, and the
504            // descriptor row carries the foreign key.
505            for (table, fk) in [(&resource_attrs, "resource_id"), (&scope_attrs, "scope_id")] {
506                let (Some(a), Some(col)) = (table, metrics.column_by_name(fk)) else {
507                    continue;
508                };
509                let ids = attr_parents(&a.rows, key, t.op, &t.value);
510                let Some(&top) = ids.iter().max() else {
511                    continue;
512                };
513                let mut want = vec![false; top as usize + 1];
514                for id in ids {
515                    want[id as usize] = true;
516                }
517                for (r, &id) in col.as_primitive::<UInt16Type>().values().iter().enumerate() {
518                    if want.get(id as usize).copied().unwrap_or(false) {
519                        hit[r] = true;
520                    }
521                }
522            }
523            hit
524        })
525        .collect();
526
527    // Same, at the point level. Data point ids are one shared space across all
528    // four point tables — that is why `dp_attrs` needs no table discriminant —
529    // so one bitmap per term serves every table below.
530    let dp_hit: Vec<Vec<bool>> = q
531        .terms
532        .iter()
533        .map(|t| {
534            let key = match &t.target {
535                crate::query::Target::Attr(k) | crate::query::Target::Field(k) => k,
536            };
537            let mut hit = Vec::new();
538            if let Some(a) = &dp_attrs {
539                for pid in attr_parents(&a.rows, key, t.op, &t.value) {
540                    if hit.len() <= pid as usize {
541                        hit.resize(pid as usize + 1, false);
542                    }
543                    hit[pid as usize] = true;
544                }
545            }
546            hit
547        })
548        .collect();
549
550    // Attributes above the point level, rendered once per descriptor row rather
551    // than once per point. A metric with 10k points would otherwise re-render
552    // its resource attributes 10k times.
553    let mut prefix: Vec<Option<Prefix>> = vec![None; n_metrics];
554
555    for table in DP_TABLES {
556        let Some(dp) = load(bref, table)? else {
557            continue;
558        };
559        let n = dp.num_rows();
560        stats.rows_scanned += n;
561        let (Some(time), Some(mid), Some(did)) = (
562            dp.column_by_name("time_unix_nano")
563                .map(|c| &**c.as_primitive::<TimestampNanosecondType>().values()),
564            dp.column_by_name("metric_id")
565                .map(|c| &**c.as_primitive::<UInt32Type>().values()),
566            dp.column_by_name("id")
567                .map(|c| &**c.as_primitive::<UInt32Type>().values()),
568        ) else {
569            continue;
570        };
571        let vals = Values::for_table(table);
572
573        for r in 0..n {
574            let m = mid[r] as usize;
575            if !(q.from..=q.to).contains(&time[r]) || !wanted.get(m).copied().unwrap_or(false) {
576                continue;
577            }
578            let d = did[r] as usize;
579            if !(0..q.terms.len()).all(|t| {
580                above[t].get(m).copied().unwrap_or(false)
581                    || dp_hit[t].get(d).copied().unwrap_or(false)
582            }) {
583                continue;
584            }
585            stats.rows_matched += 1;
586
587            let (desc_prefix, upper) = prefix[m].get_or_insert_with(|| {
588                (
589                    describe(&metrics, m),
590                    upper_attrs(&metrics, m, &metric_attrs, &resource_attrs, &scope_attrs),
591                )
592            });
593            // The point's own attributes, merged over the inherited ones.
594            let own = own_attrs(&dp_attrs, d as u32);
595            let attrs = merge(upper, &own);
596
597            for (suffix, v) in vals.at(&dp, r) {
598                if !only_suffix.is_empty() && suffix != only_suffix {
599                    continue;
600                }
601                let key = format!("{desc_prefix}\u{1}{suffix}\u{1}{attrs}");
602                let s = out.entry(key).or_insert_with(|| Series {
603                    desc: with_suffix(desc_prefix, suffix),
604                    attrs: attrs.clone(),
605                    points: Vec::new(),
606                    dropped: 0,
607                    exemplars: Vec::new(),
608                });
609                s.points.push((time[r], v));
610                if s.points.len() >= 2 * q.max_points {
611                    s.compact(q.max_points);
612                }
613                // A histogram yields two derived series from one point, and its
614                // exemplars belong to both: whichever of `.count` and `.sum` is
615                // charted, the spike in it points at the same traces.
616                if let (Some(ex), Some(rows)) = (&exemplars, by_point.get(d)) {
617                    for &er in rows {
618                        if s.exemplars.len() >= MAX_EXEMPLARS {
619                            break;
620                        }
621                        let mut j = Json::new();
622                        j.obj(|j| crate::query::emit_fields(j, ex, er));
623                        s.exemplars.push((exemplar_time(ex, er), j.into_string()));
624                    }
625                }
626                // Applied per point, not once at the end: the whole reason
627                // `max_series` exists is that the map between here and the end
628                // is what runs the process out of memory.
629                bound(out, dropped, q.max_series);
630            }
631        }
632    }
633    Ok(())
634}
635
636/// The descriptor's identity as rendered JSON members, without the trailing
637/// comma. Doubles as the stable half of the series key.
638fn describe(metrics: &RecordBatch, row: usize) -> String {
639    let mut j = Json::new();
640    j.key("name");
641    j.str(dict_str(metrics, "name", row).unwrap_or(""));
642    j.key("unit");
643    j.str(dict_str(metrics, "unit", row).unwrap_or(""));
644    j.key("kind");
645    j.str(kind_name(u8_col(metrics, "kind", row)));
646    j.key("temporality");
647    j.u64(u8_col(metrics, "temporality", row) as u64);
648    j.key("monotonic");
649    j.bool(
650        metrics
651            .column_by_name("is_monotonic")
652            .is_some_and(|c| c.as_boolean().value(row)),
653    );
654    j.into_string()
655}
656
657/// `describe` with the derived-series suffix folded into the name, so a
658/// `.count` series reports the name a caller can query it back by.
659///
660/// That is only true because `collect_block` strips a [`DERIVED`] suffix when
661/// the descriptor dictionary does not hold the requested name. Emitting a name
662/// here that the filter there does not accept is the same bug as returning a
663/// cursor nobody can page with.
664fn with_suffix(desc: &str, suffix: &str) -> String {
665    if suffix.is_empty() {
666        return desc.to_owned();
667    }
668    // `describe` always emits `"name":"..."` first, so the closing quote of the
669    // name is the second unescaped quote after the colon. Splitting on the known
670    // prefix is cheaper and less fragile than re-rendering.
671    match desc.find("\",\"unit\"") {
672        Some(i) => format!("{}{suffix}{}", &desc[..i], &desc[i..]),
673        None => desc.to_owned(),
674    }
675}
676
677/// Attributes from the metric, resource and scope levels, sorted and deduped
678/// with the most specific level winning.
679fn upper_attrs(
680    metrics: &RecordBatch,
681    row: usize,
682    metric_attrs: &Option<Attrs>,
683    resource_attrs: &Option<Attrs>,
684    scope_attrs: &Option<Attrs>,
685) -> Vec<Attr> {
686    let fk = |name: &str| {
687        metrics
688            .column_by_name(name)
689            .map(|c| c.as_primitive::<UInt16Type>().value(row) as u32)
690    };
691    let mut v = Vec::new();
692    // Least specific first: `merge_into` keeps the last write per key.
693    for (table, parent) in [
694        (resource_attrs, fk("resource_id")),
695        (scope_attrs, fk("scope_id")),
696        (metric_attrs, Some(row as u32)),
697    ] {
698        let (Some(a), Some(p)) = (table, parent) else {
699            continue;
700        };
701        collect_attrs(a, p, &mut v);
702    }
703    dedup_last(&mut v);
704    v
705}
706
707fn own_attrs(dp_attrs: &Option<Attrs>, dp_id: u32) -> Vec<Attr> {
708    let mut v = Vec::new();
709    if let Some(a) = dp_attrs {
710        collect_attrs(a, dp_id, &mut v);
711    }
712    dedup_last(&mut v);
713    v
714}
715
716/// The rows one parent owns, rendered.
717///
718/// This runs once per matched point, so the search matters: `dp_attrs` on a
719/// block holding 7,752 points is thousands of rows, and scanning all of them
720/// per point is the quadratic shape [`Attrs`] exists to remove. Empty for a
721/// table whose parent column is not a `u32`, matching the read path — no schema
722/// in this tree writes one, and a block someone else wrote should not panic.
723fn collect_attrs(a: &Attrs, parent: u32, out: &mut Vec<Attr>) {
724    let parents = Attrs::parents(&a.rows).unwrap_or_default();
725    for r in a.run(parents, parent).filter(|&r| parents[r] == parent) {
726        let mut j = Json::new();
727        emit_attr(&mut j, &a.rows, r);
728        out.push((attr_key(&a.rows, r).to_owned(), j.into_string()));
729    }
730}
731
732fn dedup_last(v: &mut Vec<Attr>) {
733    // Stable, so entries pushed later — from the more specific level — sort
734    // after their earlier namesakes and win the dedup.
735    v.sort_by(|a, b| a.0.cmp(&b.0));
736    v.dedup_by(|a, b| {
737        if a.0 == b.0 {
738            std::mem::swap(a, b);
739            true
740        } else {
741            false
742        }
743    });
744}
745
746/// Render the union of two sorted attribute lists as a JSON object, `own`
747/// winning on collision. A merge, not a concatenation and a re-sort: `upper` is
748/// already sorted and shared by every point of the metric.
749fn merge(upper: &[Attr], own: &[Attr]) -> String {
750    let mut j = Json::new();
751    j.obj(|j| {
752        let (mut i, mut k) = (0, 0);
753        while i < upper.len() || k < own.len() {
754            let take_own = match (upper.get(i), own.get(k)) {
755                (Some(u), Some(o)) => {
756                    if u.0 == o.0 {
757                        i += 1;
758                    }
759                    o.0 <= u.0
760                }
761                (None, Some(_)) => true,
762                _ => false,
763            };
764            let (key, val) = if take_own {
765                k += 1;
766                &own[k - 1]
767            } else {
768                i += 1;
769                &upper[i - 1]
770            };
771            j.key(key);
772            j.raw(val);
773        }
774    });
775    j.into_string()
776}
777
778/// Which columns of a point table carry chartable values, resolved once per
779/// table instead of per row.
780enum Values {
781    /// `int` and `double`, exactly one set per row.
782    Number,
783    /// `count` and `sum`, emitted as `<name>.count` and `<name>.sum`.
784    CountSum,
785    None,
786}
787
788impl Values {
789    fn for_table(table: &str) -> Values {
790        match table {
791            "number_dp" => Values::Number,
792            "hist_dp" | "exp_hist_dp" | "summary_dp" => Values::CountSum,
793            _ => Values::None,
794        }
795    }
796
797    fn at(&self, dp: &RecordBatch, r: usize) -> Vec<(&'static str, Pt)> {
798        match self {
799            Values::Number => {
800                if let Some(c) = dp.column_by_name("int") {
801                    let a = c.as_primitive::<Int64Type>();
802                    if !a.is_null(r) {
803                        return vec![("", Pt::Int(a.value(r)))];
804                    }
805                }
806                if let Some(c) = dp.column_by_name("double") {
807                    let a = c.as_primitive::<Float64Type>();
808                    if !a.is_null(r) {
809                        return vec![("", Pt::Double(a.value(r)))];
810                    }
811                }
812                Vec::new()
813            }
814            Values::CountSum => {
815                let mut v = Vec::with_capacity(2);
816                if let Some(c) = dp.column_by_name("count") {
817                    let a = c.as_primitive::<UInt64Type>();
818                    if !a.is_null(r) {
819                        v.push((COUNT, Pt::Int(a.value(r) as i64)));
820                    }
821                }
822                if let Some(c) = dp.column_by_name("sum") {
823                    let a = c.as_primitive::<Float64Type>();
824                    if !a.is_null(r) {
825                        v.push((SUM, Pt::Double(a.value(r))));
826                    }
827                }
828                v
829            }
830            Values::None => Vec::new(),
831        }
832    }
833}
834
835#[cfg(test)]
836mod tests {
837    use super::*;
838    use arrow_array::{ArrayRef, Float64Array, Int64Array, UInt32Array, UInt64Array};
839    use mira_proto::collector::metrics::v1::ExportMetricsServiceRequest;
840    use mira_proto::common::v1::any_value::Value as AnyVal;
841    use mira_proto::common::v1::{AnyValue, InstrumentationScope, KeyValue};
842    use mira_proto::metrics::v1::metric::Data;
843    use mira_proto::metrics::v1::number_data_point::Value as NumValue;
844    use mira_proto::metrics::v1::{
845        Exemplar, ExponentialHistogram, ExponentialHistogramDataPoint, Gauge, Histogram,
846        HistogramDataPoint, Metric, NumberDataPoint, ResourceMetrics, ScopeMetrics, Sum, Summary,
847        SummaryDataPoint, exemplar,
848    };
849    use mira_proto::resource::v1::Resource;
850
851    /// A named temporary directory, emptied first so a crashed run does not
852    /// hand the next one a half-written store.
853    fn tmp(name: &str) -> std::path::PathBuf {
854        let d = std::env::temp_dir().join(format!("mira-{name}-{}", std::process::id()));
855        let _ = std::fs::remove_dir_all(&d);
856        d
857    }
858
859    fn kv(k: &str, v: &str) -> KeyValue {
860        KeyValue {
861            key: k.into(),
862            value: Some(AnyValue {
863                value: Some(AnyVal::StringValue(v.into())),
864            }),
865        }
866    }
867
868    /// Publish `metrics` as one block, and hand back its directory so a test
869    /// can damage it the way retention or an older writer would.
870    fn publish(
871        dir: &std::path::Path,
872        seq: u64,
873        resource: Option<Resource>,
874        scope: Option<InstrumentationScope>,
875        metrics: Vec<Metric>,
876    ) -> std::path::PathBuf {
877        let req = ExportMetricsServiceRequest {
878            resource_metrics: vec![ResourceMetrics {
879                resource,
880                scope_metrics: vec![ScopeMetrics {
881                    scope,
882                    metrics,
883                    ..Default::default()
884                }],
885                ..Default::default()
886            }],
887        };
888        let mut b = crate::metrics::MetricsBuilder::new();
889        b.append_request(&req).unwrap();
890        let sealed = b.finish().unwrap();
891        crate::block::publish(dir, "metrics", crate::block::node_id("a"), seq, 0, &sealed)
892            .unwrap()
893            .dir
894    }
895
896    /// A gauge of one integer point per timestamp, the simplest thing that
897    /// produces a series.
898    fn gauge(name: &str, points: &[(u64, i64)]) -> Metric {
899        Metric {
900            name: name.into(),
901            data: Some(Data::Gauge(Gauge {
902                data_points: points
903                    .iter()
904                    .map(|&(t, v)| NumberDataPoint {
905                        time_unix_nano: t,
906                        value: Some(NumValue::AsInt(v)),
907                        ..Default::default()
908                    })
909                    .collect(),
910            })),
911            ..Default::default()
912        }
913    }
914
915    fn query(dir: &std::path::Path, q: &SeriesQuery) -> Results {
916        series(dir, q).unwrap()
917    }
918
919    /// The query every test below varies one field of.
920    fn wide() -> SeriesQuery {
921        SeriesQuery {
922            name: None,
923            from: 0,
924            to: i64::MAX,
925            terms: Vec::new(),
926            max_series: 100,
927            max_points: 100,
928        }
929    }
930
931    /// A histogram comes back as two series called `<name>.count` and
932    /// `<name>.sum`, and those are the names a chart legend shows and an agent
933    /// reads off its own previous answer. Matching only the base name against
934    /// the descriptor dictionary made that round trip return an empty list with
935    /// a 200, which reads as "the metric stopped reporting".
936    #[test]
937    fn a_derived_series_name_queries_back_to_the_series_it_names() {
938        let dir = std::env::temp_dir().join(format!("mira-derived-{}", std::process::id()));
939        let _ = std::fs::remove_dir_all(&dir);
940
941        let req = ExportMetricsServiceRequest {
942            resource_metrics: vec![ResourceMetrics {
943                scope_metrics: vec![ScopeMetrics {
944                    metrics: vec![
945                        Metric {
946                            name: "http.server.duration".into(),
947                            data: Some(Data::Histogram(Histogram {
948                                data_points: vec![HistogramDataPoint {
949                                    time_unix_nano: 1_000,
950                                    count: 3,
951                                    sum: Some(1.5),
952                                    ..Default::default()
953                                }],
954                                ..Default::default()
955                            })),
956                            ..Default::default()
957                        },
958                        // A gauge whose name already ends in `.count`. The base
959                        // name has to win the lookup, or this metric becomes
960                        // unreachable the moment the stripping is added.
961                        Metric {
962                            name: "queue.depth.count".into(),
963                            data: Some(Data::Gauge(Gauge {
964                                data_points: vec![NumberDataPoint {
965                                    time_unix_nano: 1_000,
966                                    value: Some(NumValue::AsInt(42)),
967                                    ..Default::default()
968                                }],
969                            })),
970                            ..Default::default()
971                        },
972                    ],
973                    ..Default::default()
974                }],
975                ..Default::default()
976            }],
977        };
978
979        let mut b = crate::metrics::MetricsBuilder::new();
980        b.append_request(&req).unwrap();
981        let sealed = b.finish().unwrap();
982        crate::block::publish(&dir, "metrics", crate::block::node_id("a"), 0, 0, &sealed).unwrap();
983
984        let ask = |name: &str| {
985            series(
986                &dir,
987                &SeriesQuery {
988                    name: Some(name.into()),
989                    from: 0,
990                    to: 10_000,
991                    terms: Vec::new(),
992                    max_series: 100,
993                    max_points: 100,
994                },
995            )
996            .unwrap()
997            .json
998        };
999
1000        // The base name still returns both halves.
1001        let both = ask("http.server.duration");
1002        for half in [COUNT, SUM] {
1003            assert!(
1004                both.contains(&format!(r#""name":"http.server.duration{half}""#)),
1005                "{both}"
1006            );
1007        }
1008
1009        // Each derived name returns exactly the series it names, and only it.
1010        let c = ask("http.server.duration.count");
1011        assert!(c.contains(r#""name":"http.server.duration.count""#), "{c}");
1012        assert!(!c.contains(SUM), "{c}");
1013        // Both halves of a point are strings when the value is an integer: the
1014        // timestamp is nanoseconds and a `.count` is a `uint64`, so both are
1015        // 64-bit and both go out the OTLP/JSON way. `.sum` below is a double
1016        // and stays a bare number, which is what makes this pair worth having.
1017        assert!(c.contains(r#"["1000","3"]"#), "{c}");
1018        let s = ask("http.server.duration.sum");
1019        assert!(s.contains(r#""name":"http.server.duration.sum""#), "{s}");
1020        assert!(!s.contains(COUNT), "{s}");
1021        assert!(s.contains(r#"["1000",1.5]"#), "{s}");
1022
1023        // A metric that really is called `x.count` matches before the suffix is
1024        // stripped.
1025        let q = ask("queue.depth.count");
1026        assert!(q.contains(r#""name":"queue.depth.count""#), "{q}");
1027        assert!(q.contains(r#"["1000","42"]"#), "{q}");
1028
1029        // The retry widens the lookup; it does not make it match anything. A
1030        // derived name on a metric that has no derived series is still empty,
1031        // and so is a base name nothing carries.
1032        assert_eq!(ask("queue.depth.count.sum"), "[]");
1033        assert_eq!(ask("nope.count"), "[]");
1034
1035        let _ = std::fs::remove_dir_all(&dir);
1036    }
1037
1038    /// `max_series` bounds the map, not just the render.
1039    ///
1040    /// A high-cardinality attribute — a request id, a customer id, a pod name in
1041    /// a cluster that recycles them — makes one metric name expand into a series
1042    /// per distinct value. Accumulating them all and truncating at the end meant
1043    /// the cap the caller set had no effect on the memory the query took, and
1044    /// the store is the one thing here with no bound on how many values it
1045    /// holds.
1046    #[test]
1047    fn the_series_cap_bounds_the_map_and_says_what_it_refused() {
1048        let dir = std::env::temp_dir().join(format!("mira-cap-{}", std::process::id()));
1049        let _ = std::fs::remove_dir_all(&dir);
1050
1051        // Ten series of one metric, distinguished only by an attribute, and
1052        // named so that key order is the order a reader would guess.
1053        let req = ExportMetricsServiceRequest {
1054            resource_metrics: vec![ResourceMetrics {
1055                scope_metrics: vec![ScopeMetrics {
1056                    metrics: vec![Metric {
1057                        name: "rpc.duration".into(),
1058                        data: Some(Data::Gauge(Gauge {
1059                            data_points: (0..10)
1060                                .map(|i| NumberDataPoint {
1061                                    time_unix_nano: 1_000,
1062                                    value: Some(NumValue::AsInt(i)),
1063                                    attributes: vec![mira_proto::common::v1::KeyValue {
1064                                        key: "peer".into(),
1065                                        value: Some(mira_proto::common::v1::AnyValue {
1066                                            value: Some(
1067                                                mira_proto::common::v1::any_value::Value::StringValue(
1068                                                    format!("p{i}"),
1069                                                ),
1070                                            ),
1071                                        }),
1072                                    }],
1073                                    ..Default::default()
1074                                })
1075                                .collect(),
1076                        })),
1077                        ..Default::default()
1078                    }],
1079                    ..Default::default()
1080                }],
1081                ..Default::default()
1082            }],
1083        };
1084
1085        let mut b = crate::metrics::MetricsBuilder::new();
1086        b.append_request(&req).unwrap();
1087        let sealed = b.finish().unwrap();
1088        crate::block::publish(&dir, "metrics", crate::block::node_id("a"), 0, 0, &sealed).unwrap();
1089
1090        let ask = |max_series: usize| {
1091            series(
1092                &dir,
1093                &SeriesQuery {
1094                    name: None,
1095                    from: 0,
1096                    to: 10_000,
1097                    terms: Vec::new(),
1098                    max_series,
1099                    max_points: 100,
1100                },
1101            )
1102            .unwrap()
1103        };
1104
1105        // Under the cap: everything, and nothing refused.
1106        let r = ask(100);
1107        assert_eq!(r.json.matches(r#""peer""#).count(), 10, "{}", r.json);
1108        assert_eq!(r.stats.dropped_series, 0);
1109
1110        // Over it: the smallest keys survive, which is the same set the old
1111        // sort-then-truncate produced — that equivalence is the whole safety
1112        // argument for evicting the maximum as we go, so it is what this checks
1113        // rather than the count alone.
1114        let r = ask(8);
1115        for i in 0..10 {
1116            assert_eq!(
1117                r.json.contains(&format!(r#""peer":"p{i}""#)),
1118                i < 8,
1119                "p{i}: {}",
1120                r.json
1121            );
1122        }
1123        assert_eq!(r.stats.dropped_series, 2);
1124
1125        // The ponytail ceiling, asserted rather than left to be discovered: the
1126        // record of what was refused is itself capped at `max_series`, so with
1127        // six dropped and a cap of four the answer is four and reads as "at
1128        // least". Remembering every key exactly is the allocation the cap
1129        // exists to prevent.
1130        let r = ask(4);
1131        assert_eq!(r.json.matches(r#""peer""#).count(), 4, "{}", r.json);
1132        assert_eq!(r.stats.dropped_series, 4);
1133
1134        let _ = std::fs::remove_dir_all(&dir);
1135    }
1136
1137    /// A point's value lives in whichever column its table set, and a row that
1138    /// set none must yield no point rather than a zero. A gauge with no `value`
1139    /// on the wire means "not reported"; charting it as 0 invents a reading
1140    /// nobody took, and on a `.sum` it would drag an average down.
1141    ///
1142    /// The null cases are built by hand because today's writer never emits
1143    /// them — `count` is non-nullable and every gauge point has one of `int`
1144    /// and `double`. The reader is the half that outlives the writer that wrote
1145    /// the block, so it is the half that has to survive them.
1146    #[test]
1147    fn a_point_yields_the_value_of_whichever_column_its_table_actually_set() {
1148        for (table, want) in [
1149            ("number_dp", "number"),
1150            ("hist_dp", "countsum"),
1151            ("exp_hist_dp", "countsum"),
1152            ("summary_dp", "countsum"),
1153            // Not a point table. `collect_block` only ever asks about the four,
1154            // so this arm is what stops a fifth table added later from being
1155            // charted as whatever its first two columns happen to be called.
1156            ("logs", "none"),
1157        ] {
1158            let got = match Values::for_table(table) {
1159                Values::Number => "number",
1160                Values::CountSum => "countsum",
1161                Values::None => "none",
1162            };
1163            assert_eq!(got, want, "{table}");
1164        }
1165
1166        /// `(suffix, value)` as text, because `Pt` is deliberately not `Eq` —
1167        /// comparing two charted doubles for equality is a bug everywhere else.
1168        fn shape(v: Vec<(&'static str, Pt)>) -> Vec<String> {
1169            v.into_iter()
1170                .map(|(s, p)| match p {
1171                    Pt::Int(i) => format!("{s}=i{i}"),
1172                    Pt::Double(d) => format!("{s}=d{d}"),
1173                })
1174                .collect()
1175        }
1176
1177        let num = RecordBatch::try_from_iter(vec![
1178            (
1179                "int",
1180                Arc::new(Int64Array::from(vec![Some(7), None, None])) as ArrayRef,
1181            ),
1182            (
1183                "double",
1184                Arc::new(Float64Array::from(vec![None, Some(0.5), None])) as ArrayRef,
1185            ),
1186        ])
1187        .unwrap();
1188        assert_eq!(shape(Values::Number.at(&num, 0)), ["=i7"]);
1189        assert_eq!(shape(Values::Number.at(&num, 1)), ["=d0.5"]);
1190        assert!(shape(Values::Number.at(&num, 2)).is_empty());
1191
1192        // A writer that never emitted the column at all, rather than emitting
1193        // it null: the reader must fall through to the other one, not index a
1194        // column that is not there.
1195        let only_double = RecordBatch::try_from_iter(vec![(
1196            "double",
1197            Arc::new(Float64Array::from(vec![1.25])) as ArrayRef,
1198        )])
1199        .unwrap();
1200        assert_eq!(shape(Values::Number.at(&only_double, 0)), ["=d1.25"]);
1201
1202        let cs = RecordBatch::try_from_iter(vec![
1203            (
1204                "count",
1205                Arc::new(UInt64Array::from(vec![None, Some(4), Some(4), None])) as ArrayRef,
1206            ),
1207            (
1208                "sum",
1209                Arc::new(Float64Array::from(vec![Some(1.5), None, Some(2.5), None])) as ArrayRef,
1210            ),
1211        ])
1212        .unwrap();
1213        assert_eq!(shape(Values::CountSum.at(&cs, 0)), [".sum=d1.5"]);
1214        assert_eq!(shape(Values::CountSum.at(&cs, 1)), [".count=i4"]);
1215        assert_eq!(
1216            shape(Values::CountSum.at(&cs, 2)),
1217            [".count=i4", ".sum=d2.5"]
1218        );
1219        assert!(shape(Values::CountSum.at(&cs, 3)).is_empty());
1220
1221        // The half of a histogram that is missing is missing, not zero: a
1222        // `sum`-less point charts a `.count` series and no `.sum` series at
1223        // all. `starts_with`, not `==`: `shape` renders the value into the
1224        // string, so an equality against the bare suffix could never match and
1225        // would hold however many `.sum` points came back.
1226        assert!(
1227            !shape(Values::CountSum.at(&cs, 1))
1228                .iter()
1229                .any(|s| s.starts_with(SUM))
1230        );
1231        assert!(shape(Values::None.at(&cs, 2)).is_empty());
1232    }
1233
1234    /// Every kind OTLP can declare gets a name a caller can read, including the
1235    /// two that were added last and the descriptor with no `data` at all.
1236    ///
1237    /// This is the dropdown an agent reads before writing its first query. A
1238    /// kind rendered as the wrong word — or an exponential histogram rendered
1239    /// as "unset" because the match arm was never added — is a metric the
1240    /// caller cannot tell apart from one that is not reporting.
1241    #[test]
1242    fn every_metric_kind_reports_the_name_a_dropdown_shows() {
1243        let dir = tmp("series-kinds");
1244        let point = NumberDataPoint {
1245            time_unix_nano: 1_000,
1246            value: Some(NumValue::AsInt(1)),
1247            ..Default::default()
1248        };
1249        let named = |name: &str, unit: &str, data: Option<Data>| Metric {
1250            name: name.into(),
1251            unit: unit.into(),
1252            data,
1253            ..Default::default()
1254        };
1255        publish(
1256            &dir,
1257            0,
1258            None,
1259            None,
1260            vec![
1261                // No `data` oneof: a descriptor somebody's exporter believes in
1262                // that owns no points. It still belongs in the listing.
1263                named("a.declared", "1", None),
1264                named(
1265                    "b.gauge",
1266                    "By",
1267                    Some(Data::Gauge(Gauge {
1268                        data_points: vec![point.clone()],
1269                    })),
1270                ),
1271                named(
1272                    "c.sum",
1273                    "1",
1274                    Some(Data::Sum(Sum {
1275                        data_points: vec![point],
1276                        ..Default::default()
1277                    })),
1278                ),
1279                named(
1280                    "d.hist",
1281                    "s",
1282                    Some(Data::Histogram(Histogram {
1283                        data_points: vec![HistogramDataPoint {
1284                            time_unix_nano: 1_000,
1285                            count: 2,
1286                            sum: Some(3.0),
1287                            ..Default::default()
1288                        }],
1289                        ..Default::default()
1290                    })),
1291                ),
1292                named(
1293                    "e.exp",
1294                    "s",
1295                    Some(Data::ExponentialHistogram(ExponentialHistogram {
1296                        data_points: vec![ExponentialHistogramDataPoint {
1297                            time_unix_nano: 1_000,
1298                            count: 2,
1299                            sum: Some(3.0),
1300                            ..Default::default()
1301                        }],
1302                        ..Default::default()
1303                    })),
1304                ),
1305                named(
1306                    "f.summary",
1307                    "s",
1308                    Some(Data::Summary(Summary {
1309                        data_points: vec![SummaryDataPoint {
1310                            time_unix_nano: 1_000,
1311                            count: 2,
1312                            sum: 3.0,
1313                            ..Default::default()
1314                        }],
1315                    })),
1316                ),
1317            ],
1318        );
1319
1320        let r = names(&dir, 0, 10_000).unwrap();
1321        assert_eq!(
1322            r.json,
1323            concat!(
1324                r#"[{"name":"a.declared","unit":"1","kind":"unset"},"#,
1325                r#"{"name":"b.gauge","unit":"By","kind":"gauge"},"#,
1326                r#"{"name":"c.sum","unit":"1","kind":"sum"},"#,
1327                r#"{"name":"d.hist","unit":"s","kind":"histogram"},"#,
1328                r#"{"name":"e.exp","unit":"s","kind":"exponential_histogram"},"#,
1329                r#"{"name":"f.summary","unit":"s","kind":"summary"}]"#,
1330            )
1331        );
1332
1333        // The same words come back on the series themselves, and the three
1334        // aggregate kinds each split into the two derived halves.
1335        let json = query(&dir, &wide()).json;
1336        for (name, kind) in [
1337            ("b.gauge", "gauge"),
1338            ("c.sum", "sum"),
1339            ("d.hist.count", "histogram"),
1340            ("d.hist.sum", "histogram"),
1341            ("e.exp.count", "exponential_histogram"),
1342            ("e.exp.sum", "exponential_histogram"),
1343            ("f.summary.count", "summary"),
1344            ("f.summary.sum", "summary"),
1345        ] {
1346            assert!(
1347                json.contains(&format!(r#""name":"{name}","unit":"#))
1348                    && json.contains(&format!(r#""kind":"{kind}""#)),
1349                "{name}/{kind}: {json}"
1350            );
1351        }
1352        // A descriptor with no points charts nothing, however loudly it is
1353        // declared.
1354        assert!(!json.contains("a.declared"), "{json}");
1355
1356        let _ = std::fs::remove_dir_all(&dir);
1357    }
1358
1359    /// A block outside the window is never opened, and a series over the point
1360    /// cap keeps its newest points and says how many it dropped.
1361    ///
1362    /// Both are the difference between a chart and a lie. Opening every block
1363    /// makes the directory name — the whole index — worthless; keeping an
1364    /// arbitrary subset of points and sorting it at render time draws a
1365    /// contiguous line through whichever rows the directory listing reached
1366    /// first, with no sign that anything is missing.
1367    #[test]
1368    fn a_series_is_bounded_by_the_window_asked_for_and_the_points_it_can_chart() {
1369        let dir = tmp("series-bounds");
1370        let pts: Vec<(u64, i64)> = (1..=6).map(|i| (i as u64 * 1_000, i)).collect();
1371        publish(&dir, 0, None, None, vec![gauge("m", &pts)]);
1372        // Hours later, so it lands in its own partition and its own directory
1373        // name. Nothing in the window below can reach it.
1374        publish(
1375            &dir,
1376            1,
1377            None,
1378            None,
1379            vec![gauge("m", &[(9_000_000_000_000, 99)])],
1380        );
1381
1382        let mut q = wide();
1383        q.to = 10_000;
1384        q.max_points = 4;
1385        let r = query(&dir, &q);
1386
1387        assert_eq!(r.stats.blocks_total, 2);
1388        assert_eq!(r.stats.blocks_scanned, 1, "the far block was opened");
1389        // Six points offered, four charted, and the two dropped are the two
1390        // oldest — not the two the scan happened to see last.
1391        assert!(r.json.contains(r#""dropped_points":2"#), "{}", r.json);
1392        assert!(
1393            r.json
1394                .contains(r#""points":[["3000","3"],["4000","4"],["5000","5"],["6000","6"]]"#),
1395            "{}",
1396            r.json
1397        );
1398
1399        // Under the cap there is no `dropped_points` member at all: a chart
1400        // must be able to treat its presence as "something is missing".
1401        let mut q = wide();
1402        q.to = 10_000;
1403        let r = query(&dir, &q);
1404        assert!(!r.json.contains("dropped_points"), "{}", r.json);
1405        assert!(r.json.contains(r#"["1000","1"]"#), "{}", r.json);
1406
1407        let _ = std::fs::remove_dir_all(&dir);
1408    }
1409
1410    /// A term is satisfied at whichever of the four levels carries the
1411    /// attribute, and a block missing a level is filtered by the levels it has.
1412    ///
1413    /// Whether `service.name` is a resource attribute or a data point one is a
1414    /// detail of whoever configured the SDK. A filter that only looked at the
1415    /// point level would return nothing for the single most common metrics
1416    /// query there is, with a 200 and an empty list.
1417    #[test]
1418    fn a_term_is_satisfied_at_whichever_level_carries_the_attribute() {
1419        let dir = tmp("series-levels");
1420        publish(
1421            &dir,
1422            0,
1423            Some(Resource {
1424                attributes: vec![kv("service.name", "api")],
1425                ..Default::default()
1426            }),
1427            Some(InstrumentationScope {
1428                attributes: vec![kv("otel.lib", "sdk")],
1429                ..Default::default()
1430            }),
1431            vec![
1432                Metric {
1433                    metadata: vec![kv("tier", "gold")],
1434                    ..gauge("m1", &[(1_000, 1)])
1435                },
1436                Metric {
1437                    ..gauge("m2", &[(1_000, 2)])
1438                },
1439            ],
1440        );
1441        // No resource and no scope: both attribute tables are empty, so
1442        // `publish` never writes them. Filtering must fall back to the levels
1443        // this block does have rather than treating the absence as a match.
1444        publish(
1445            &dir,
1446            1,
1447            None,
1448            None,
1449            vec![Metric {
1450                metadata: vec![kv("tier", "gold")],
1451                ..gauge("m3", &[(1_000, 3)])
1452            }],
1453        );
1454
1455        // Point-level attributes, added after the fact so each metric above
1456        // stays readable.
1457        let with_pod = |name: &str, v: i64, pod: &str| Metric {
1458            data: Some(Data::Gauge(Gauge {
1459                data_points: vec![NumberDataPoint {
1460                    time_unix_nano: 1_000,
1461                    value: Some(NumValue::AsInt(v)),
1462                    attributes: vec![kv("pod", pod)],
1463                    ..Default::default()
1464                }],
1465            })),
1466            ..Metric {
1467                name: name.into(),
1468                ..Default::default()
1469            }
1470        };
1471        publish(
1472            &dir,
1473            2,
1474            Some(Resource {
1475                attributes: vec![kv("service.name", "db")],
1476                ..Default::default()
1477            }),
1478            None,
1479            vec![with_pod("m4", 4, "p4")],
1480        );
1481
1482        let ask = |key: &str, want: &str| {
1483            let mut q = wide();
1484            q.to = 10_000;
1485            q.terms = vec![Term {
1486                target: crate::query::Target::Attr(key.into()),
1487                op: crate::query::Op::Eq,
1488                value: crate::query::Value::Str(want.into()),
1489            }];
1490            let r = query(&dir, &q);
1491            let mut names: Vec<String> = Vec::new();
1492            for m in ["m1", "m2", "m3", "m4"] {
1493                if r.json.contains(&format!(r#""name":"{m}""#)) {
1494                    names.push(m.to_owned());
1495                }
1496            }
1497            names
1498        };
1499
1500        // Resource level. The second block has no resource attributes at all
1501        // and must not match on the strength of not having them.
1502        assert_eq!(ask("service.name", "api"), ["m1", "m2"]);
1503        assert_eq!(ask("service.name", "db"), ["m4"]);
1504        // Scope level.
1505        assert_eq!(ask("otel.lib", "sdk"), ["m1", "m2"]);
1506        // Metric level — `Metric.metadata`, which is per descriptor row and so
1507        // reaches both blocks that declare it.
1508        assert_eq!(ask("tier", "gold"), ["m1", "m3"]);
1509        // Point level.
1510        assert_eq!(ask("pod", "p4"), ["m4"]);
1511        // A term nothing carries at any level matches nothing, rather than
1512        // falling back to "no opinion" and matching everything.
1513        assert!(ask("tier", "bronze").is_empty());
1514        assert!(ask("nope", "x").is_empty());
1515
1516        let _ = std::fs::remove_dir_all(&dir);
1517    }
1518
1519    /// The four attribute levels merge with the most specific winning, and the
1520    /// merged map is what identifies the series.
1521    ///
1522    /// Attributes are half the grouping key, so getting the precedence wrong
1523    /// does not just mislabel a line — it splits one series into two, or fuses
1524    /// two into one, and neither is visible in the response.
1525    #[test]
1526    fn attributes_from_every_level_merge_with_the_most_specific_winning() {
1527        let dir = tmp("series-merge");
1528        publish(
1529            &dir,
1530            0,
1531            Some(Resource {
1532                attributes: vec![kv("env", "prod"), kv("region", "eu")],
1533                ..Default::default()
1534            }),
1535            None,
1536            vec![Metric {
1537                // Same key as the resource carries, one level down.
1538                metadata: vec![kv("env", "staging")],
1539                data: Some(Data::Gauge(Gauge {
1540                    data_points: vec![NumberDataPoint {
1541                        time_unix_nano: 1_000,
1542                        value: Some(NumValue::AsInt(1)),
1543                        // And again, one level further down.
1544                        attributes: vec![kv("env", "canary"), kv("pod", "x")],
1545                        ..Default::default()
1546                    }],
1547                })),
1548                ..Metric {
1549                    name: "m".into(),
1550                    ..Default::default()
1551                }
1552            }],
1553        );
1554
1555        let json = query(&dir, &wide()).json;
1556        // `env` resolves to the point's own value; the keys only an upper level
1557        // carries survive; and the losing values appear nowhere.
1558        assert!(
1559            json.contains(r#""attributes":{"env":"canary","pod":"x","region":"eu"}"#),
1560            "{json}"
1561        );
1562        assert!(
1563            !json.contains("prod") && !json.contains("staging"),
1564            "{json}"
1565        );
1566
1567        let _ = std::fs::remove_dir_all(&dir);
1568    }
1569
1570    /// Exemplars are capped per series, because nothing in OTLP bounds how many
1571    /// an exporter attaches to a point.
1572    ///
1573    /// Without the cap one misconfigured SDK inflates every chart response that
1574    /// touches its metric — and this is the response a chart polls on a timer.
1575    #[test]
1576    fn exemplars_are_capped_so_one_exporter_cannot_inflate_every_chart_response() {
1577        let dir = tmp("series-exemplars");
1578        publish(
1579            &dir,
1580            0,
1581            None,
1582            None,
1583            vec![Metric {
1584                data: Some(Data::Gauge(Gauge {
1585                    data_points: vec![NumberDataPoint {
1586                        time_unix_nano: 1_000,
1587                        value: Some(NumValue::AsInt(1)),
1588                        exemplars: (0..MAX_EXEMPLARS as i64 + 6)
1589                            .map(|i| Exemplar {
1590                                time_unix_nano: 1_000 + i as u64,
1591                                value: Some(exemplar::Value::AsInt(i)),
1592                                trace_id: vec![7u8; 16].into(),
1593                                ..Default::default()
1594                            })
1595                            .collect(),
1596                        ..Default::default()
1597                    }],
1598                })),
1599                ..Metric {
1600                    name: "m".into(),
1601                    ..Default::default()
1602                }
1603            }],
1604        );
1605
1606        let json = query(&dir, &wide()).json;
1607        // Points carry their timestamp as a bare array element, so every
1608        // occurrence of the key is one exemplar object.
1609        assert_eq!(
1610            json.matches(r#""time_unix_nano""#).count(),
1611            MAX_EXEMPLARS,
1612            "{json}"
1613        );
1614        // Capped, not dropped: the ones that are there carry the trace id that
1615        // is the whole point of an exemplar.
1616        assert!(json.contains(r#""trace_id":"07070707"#), "{json}");
1617
1618        let _ = std::fs::remove_dir_all(&dir);
1619    }
1620
1621    /// A table shaped differently from the one this reader writes contributes
1622    /// nothing, rather than panicking or charting garbage.
1623    ///
1624    /// Two things produce that shape and neither is an error: retention
1625    /// unlinking a block while a query walks it, and a block written by another
1626    /// version of the binary — the block directory is the manifest, so there is
1627    /// no schema version to check against and no coordinator to ask.
1628    #[test]
1629    fn a_table_the_reader_did_not_write_contributes_nothing_instead_of_panicking() {
1630        let dir = tmp("series-ragged");
1631        publish(&dir, 0, None, None, vec![gauge("ok", &[(1_000, 1)])]);
1632        let unlinked = publish(&dir, 1, None, None, vec![gauge("gone", &[(1_000, 2)])]);
1633        let ragged = publish(&dir, 2, None, None, vec![gauge("ragged", &[(1_000, 3)])]);
1634
1635        // Retention got here first: the descriptor table is gone, but the
1636        // directory is still listed.
1637        std::fs::remove_file(unlinked.join("metrics.arrow")).unwrap();
1638
1639        // An older writer's point table, with no `id` column to join
1640        // attributes and exemplars on. Staged and renamed, because a mapping
1641        // over a file being truncated is a SIGBUS, not an error.
1642        let table = ragged.join("number_dp.arrow");
1643        let mut b = crate::block::open_table_opt(&table)
1644            .unwrap()
1645            .unwrap()
1646            .batches[0]
1647            .clone();
1648        b.remove_column(b.schema().index_of("id").unwrap());
1649        let staged = ragged.join("number_dp.arrow.staged");
1650        crate::block::write_table(&staged, &b).unwrap();
1651        std::fs::rename(&staged, &table).unwrap();
1652
1653        let r = query(&dir, &wide());
1654        assert_eq!(r.stats.blocks_scanned, 3, "all three were in the window");
1655        assert!(r.json.contains(r#""name":"ok""#), "{}", r.json);
1656        assert!(!r.json.contains("gone"), "{}", r.json);
1657        assert!(!r.json.contains("ragged"), "{}", r.json);
1658
1659        // The name listing reads only the descriptor table, so the ragged block
1660        // still names its metric and the unlinked one names nothing.
1661        let n = names(&dir, 0, 10_000).unwrap();
1662        assert_eq!(
1663            n.json,
1664            concat!(
1665                r#"[{"name":"ok","unit":"","kind":"gauge"},"#,
1666                r#"{"name":"ragged","unit":"","kind":"gauge"}]"#,
1667            )
1668        );
1669
1670        // The same tolerance one layer down, where the missing column is the
1671        // one the whole index is built on.
1672        let no_parent = RecordBatch::try_from_iter(vec![(
1673            "id",
1674            Arc::new(UInt32Array::from(vec![0u32, 1])) as ArrayRef,
1675        )])
1676        .unwrap();
1677        assert!(index_by_parent(&no_parent).is_empty());
1678
1679        // And on a descriptor this renderer did not render: the suffix is
1680        // dropped rather than spliced into the middle of some other member.
1681        // Returning the input unchanged keeps the string valid JSON, which a
1682        // `find`-and-insert on a miss would not.
1683        assert_eq!(
1684            with_suffix(r#""kind":"histogram""#, COUNT),
1685            r#""kind":"histogram""#
1686        );
1687        assert_eq!(
1688            with_suffix(r#""name":"x","unit":"s""#, ""),
1689            r#""name":"x","unit":"s""#
1690        );
1691        assert_eq!(
1692            with_suffix(r#""name":"x","unit":"s""#, COUNT),
1693            r#""name":"x.count","unit":"s""#
1694        );
1695
1696        let _ = std::fs::remove_dir_all(&dir);
1697    }
1698
1699    /// What one data point costs to render, at the point count that makes the
1700    /// attribute join visible.
1701    ///
1702    /// Scaled rather than `#[ignore]`d, exactly like
1703    /// [`crate::query::scan_cost_per_row`]: the default 2,000 points run in the
1704    /// normal suite as a correctness check on the merge, and the same code is
1705    /// the measurement at a real point count.
1706    ///
1707    /// ```sh
1708    /// MIRA_BENCH_POINTS=50000 cargo test --release -p miradb-core \
1709    ///     --lib series_cost_per_point -- --nocapture
1710    /// ```
1711    ///
1712    /// The shape is the one a real exporter produces and the one the old
1713    /// [`collect_attrs`] was quadratic in: a few distinct attribute sets over
1714    /// many timestamps, so the series map stays small while `dp_attrs` grows
1715    /// with the point count. Scanning the whole table per point is `2n²`
1716    /// comparisons; the run search is two per point.
1717    #[test]
1718    fn series_cost_per_point() {
1719        let n: usize = std::env::var("MIRA_BENCH_POINTS")
1720            .ok()
1721            .and_then(|s| s.parse().ok())
1722            .unwrap_or(2_000);
1723        let dir = tmp("series-bench");
1724        const PODS: usize = 20;
1725        let points: Vec<NumberDataPoint> = (0..n)
1726            .map(|i| NumberDataPoint {
1727                time_unix_nano: 1_000 + i as u64,
1728                value: Some(NumValue::AsInt(i as i64)),
1729                attributes: vec![
1730                    kv("k8s.pod.name", &format!("checkout-{}", i % PODS)),
1731                    kv("cloud.availability_zone", &format!("z{}", i % 3)),
1732                ],
1733                ..Default::default()
1734            })
1735            .collect();
1736        publish(
1737            &dir,
1738            0,
1739            Some(Resource {
1740                attributes: vec![kv("service.name", "checkout")],
1741                ..Default::default()
1742            }),
1743            None,
1744            vec![Metric {
1745                name: "http.server.requests".into(),
1746                data: Some(Data::Gauge(Gauge {
1747                    data_points: points,
1748                })),
1749                ..Default::default()
1750            }],
1751        );
1752        let q = SeriesQuery {
1753            name: Some("http.server.requests".into()),
1754            max_points: n,
1755            ..wide()
1756        };
1757
1758        // Once to fault the block in, so the number below is the join and not
1759        // the first touch of every page.
1760        let warm = query(&dir, &q);
1761        assert_eq!(warm.stats.rows_matched, n);
1762
1763        let t = std::time::Instant::now();
1764        let r = query(&dir, &q);
1765        let el = t.elapsed();
1766
1767        // The correctness half, which is why this is not `#[ignore]`d: every
1768        // point kept its own pod and inherited the resource's service, so the
1769        // binary search found the right run and not its neighbour.
1770        let series = r.json.matches(r#""name":"#).count();
1771        assert_eq!(series, PODS * 3, "one series per distinct attribute set");
1772        for pod in 0..PODS {
1773            assert!(
1774                r.json
1775                    .contains(&format!(r#""k8s.pod.name":"checkout-{pod}""#)),
1776                "pod {pod} lost its own attributes"
1777            );
1778        }
1779        assert!(r.json.contains(r#""service.name":"checkout""#));
1780
1781        println!(
1782            "series: {n} points in {el:?}  {:.3} us/point  {series} series",
1783            el.as_secs_f64() * 1e6 / n as f64,
1784        );
1785        let _ = std::fs::remove_dir_all(&dir);
1786    }
1787}