Skip to main content

mira_core/
query.rs

1//! The read path: prune blocks, scan columns, materialize JSON.
2//!
3//! There is no query planner and no expression tree here, and that is a
4//! decision rather than an omission. Mira answers a small, known set of
5//! questions — "the last N records matching these filters", "every span of this
6//! trace", "this metric bucketed over time" — and each is a hand-written scan
7//! over a layout designed for it. A general planner spends its budget
8//! rediscovering at runtime what this module knows at compile time: which
9//! column holds the timestamp, that `parent_id` is a row index, that block
10//! directory names already carry the pruning key. That is most of what the 151
11//! transitive crates of a general engine buy.
12//!
13//! Three properties the layout hands the scan, in the order they matter:
14//!
15//! * **Blocks prune by name.** `<min_ts>-<max_ts>-<node>-<seq>-<wal_hi>` is the
16//!   whole index. A time-bounded query opens no file it will not read, and with
17//!   blocks visited newest-first a `limit` stops the scan early.
18//! * **`parent_id` is a row index.** Ids are rebased dense per block at ingest,
19//!   so attaching an attribute to its record is an array store, not a hash
20//!   join.
21//! * **Dictionary columns compare as `u16`.** `severity_text = "ERROR"` resolves
22//!   the string once against the dictionary, then scans a buffer of 16-bit
23//!   codes and never touches string data again.
24//!
25//! Everything runs against mmap'd buffers, so a cold block costs demand paging
26//! and a warm one costs memory bandwidth. Nothing allocates per row until
27//! materialization, which happens after `limit` has cut the result to size.
28//!
29//! With no write-ahead log, nothing here needs to read the open, unsealed
30//! block: ingest acknowledges an export only after the block containing it has
31//! been fsynced and renamed into place, so read-your-writes falls out of the
32//! durability rule. Turn the log on and the acknowledgement moves ahead of the
33//! seal, which breaks that — so [`search_open`] takes the open block's snapshot
34//! alongside the directory scan and merges the two into one ordered page. See
35//! [`crate::signal::Open`]; the argument is ARCHITECTURE section 4.
36
37use std::path::Path;
38use std::sync::Arc;
39// `Relaxed` alone rather than `Ordering`, which is `std::cmp::Ordering` in this
40// file.
41use std::sync::atomic::{AtomicUsize, Ordering::Relaxed};
42
43use arrow_array::cast::AsArray;
44use arrow_array::types::{
45    Float64Type, Int32Type, Int64Type, TimestampNanosecondType, UInt8Type, UInt16Type, UInt32Type,
46    UInt64Type,
47};
48use arrow_array::{Array, BooleanArray, RecordBatch, StringArray};
49use arrow_schema::DataType;
50use mira_proto::common::v1::AnyValue;
51use prost::Message;
52
53use crate::block::{self, Src};
54use crate::error::Result;
55use crate::json::Json;
56use crate::schema::AttrType;
57use crate::signal::Open;
58
59/// Comparison operator. `Contains` is substring matching on strings and matches
60/// nothing on any other type: a filter that cannot apply returns no rows rather
61/// than an error, because a query spanning signals with slightly different
62/// columns is a normal thing for an agent to try.
63#[derive(Debug, Clone, Copy, PartialEq, Eq)]
64pub enum Op {
65    Eq,
66    Ne,
67    Lt,
68    Lte,
69    Gt,
70    Gte,
71    Contains,
72}
73
74impl Op {
75    pub fn parse(s: &str) -> Option<Op> {
76        Some(match s {
77            "eq" | "=" | "==" => Op::Eq,
78            "ne" | "!=" => Op::Ne,
79            "lt" | "<" => Op::Lt,
80            "lte" | "<=" => Op::Lte,
81            "gt" | ">" => Op::Gt,
82            "gte" | ">=" => Op::Gte,
83            "contains" | "~" => Op::Contains,
84            _ => return None,
85        })
86    }
87
88    fn test_ord(self, ord: std::cmp::Ordering) -> bool {
89        use std::cmp::Ordering::*;
90        match self {
91            Op::Eq => ord == Equal,
92            Op::Ne => ord != Equal,
93            Op::Lt => ord == Less,
94            Op::Lte => ord != Greater,
95            Op::Gt => ord == Greater,
96            Op::Gte => ord != Less,
97            // Never reached: every caller handles Contains before comparing.
98            Op::Contains => false,
99        }
100    }
101}
102
103/// A scalar from a query document.
104///
105/// Deliberately loose about numbers. Queries arrive as JSON from a browser or
106/// an LLM, and both write `"200"` for `http.response.status_code` about as often
107/// as they write `200`. Rejecting the quoted form would be defensible and
108/// useless, so coercion happens at comparison time, once the column's real type
109/// is known.
110#[derive(Debug, Clone, PartialEq)]
111pub enum Value {
112    Str(String),
113    Int(i64),
114    Double(f64),
115    Bool(bool),
116}
117
118impl Value {
119    fn as_i64(&self) -> Option<i64> {
120        match self {
121            Value::Int(i) => Some(*i),
122            // A whole-valued float is the same number; a fractional one is not,
123            // and truncating it would make `duration > 0.5` mean `> 0`.
124            Value::Double(d) if d.fract() == 0.0 => Some(*d as i64),
125            Value::Str(s) => s.parse().ok(),
126            Value::Double(_) | Value::Bool(_) => None,
127        }
128    }
129
130    fn as_f64(&self) -> Option<f64> {
131        match self {
132            Value::Int(i) => Some(*i as f64),
133            Value::Double(d) => Some(*d),
134            Value::Str(s) => s.parse().ok(),
135            Value::Bool(_) => None,
136        }
137    }
138
139    fn as_bool(&self) -> Option<bool> {
140        match self {
141            Value::Bool(b) => Some(*b),
142            Value::Str(s) if s == "true" => Some(true),
143            Value::Str(s) if s == "false" => Some(false),
144            Value::Str(_) | Value::Int(_) | Value::Double(_) => None,
145        }
146    }
147
148    fn as_str(&self) -> Option<&str> {
149        match self {
150            Value::Str(s) => Some(s),
151            _ => None,
152        }
153    }
154}
155
156/// What a term filters on.
157#[derive(Debug, Clone)]
158pub enum Target {
159    /// A column of the signal's root table, by name.
160    Field(String),
161    /// An attribute key, looked up at every level the signal has — record,
162    /// resource, scope, and on traces the span's own events and links — and
163    /// unioned.
164    ///
165    /// Whether `service.name` is a resource attribute is a detail of whoever
166    /// configured the SDK, and users do not know it. Searching all of them is
167    /// what every usable tracing UI does; the star schema makes it a handful of
168    /// scans of tables that are tiny next to the root.
169    ///
170    /// The child levels are not a nicety. `Span.recordException` — the one API
171    /// call behind most of the spans anyone goes looking for — writes
172    /// `exception.type` to a span *event*, so leaving events out made the
173    /// commonest question in a tracing UI return an empty list while the value
174    /// was visible in `events[].attributes` of the very same response. A match
175    /// on a child selects the span it hangs off, which is the row the caller
176    /// asked for.
177    Attr(String),
178}
179
180/// One conjunct. Terms are AND-ed. There is no OR in V0: a disjunction over
181/// attributes is rare enough that supporting it means building a planner for a
182/// query nobody has typed yet.
183#[derive(Debug, Clone)]
184pub struct Term {
185    pub target: Target,
186    pub op: Op,
187    pub value: Value,
188}
189
190/// Which signal, and therefore which tables and which time column.
191#[derive(Debug, Clone, Copy, PartialEq, Eq)]
192pub enum Signal {
193    Logs,
194    Traces,
195}
196
197impl Signal {
198    pub fn parse(s: &str) -> Option<Signal> {
199        match s {
200            "logs" => Some(Signal::Logs),
201            "traces" | "spans" => Some(Signal::Traces),
202            _ => None,
203        }
204    }
205
206    pub fn dir(self) -> &'static str {
207        match self {
208            Signal::Logs => "logs",
209            Signal::Traces => "traces",
210        }
211    }
212
213    /// The root table's file stem.
214    fn root(self) -> &'static str {
215        match self {
216            Signal::Logs => "logs",
217            Signal::Traces => "spans",
218        }
219    }
220
221    /// The record-level attribute table.
222    fn attrs(self) -> &'static str {
223        match self {
224            Signal::Logs => "log_attrs",
225            Signal::Traces => "span_attrs",
226        }
227    }
228
229    /// The column that orders results and bounds the query.
230    fn time_col(self) -> &'static str {
231        match self {
232            Signal::Logs => "time_unix_nano",
233            Signal::Traces => "start_time_unix_nano",
234        }
235    }
236}
237
238/// A record search: filter, order by time descending, take `limit`.
239#[derive(Debug, Clone)]
240pub struct Search {
241    pub signal: Signal,
242    /// Inclusive nanosecond bounds.
243    pub from: i64,
244    pub to: i64,
245    pub terms: Vec<Term>,
246    pub limit: usize,
247    /// Start after this row. See [`Cursor`].
248    pub after: Option<Cursor>,
249    /// Also return the cursor of every row, not just of the last one.
250    ///
251    /// Off by default because a page has one `next` and that is all a reader
252    /// paging through one node needs. It is on for a reader merging pages from
253    /// several nodes — see `proxy` — which has to know where each row sits in
254    /// the global order to interleave them, and cannot recover that from the
255    /// row itself.
256    pub cursors: bool,
257}
258
259/// Where the previous page stopped.
260///
261/// Keyset, not offset, and not for tidiness: `offset: 20000` forces the engine
262/// to find and discard twenty thousand rows on every page, which turns the
263/// early exit below into a full scan and makes the last page the most expensive
264/// one. It is also *wrong* on a store that is still being written to — a batch
265/// arriving between two pages shifts every row down and the reader sees a row
266/// twice or never.
267///
268/// This is the sort key of the last row returned, so "the next page" is
269/// "everything that sorts after this", which is exact whatever else has landed
270/// meanwhile. `(node, seq)` identifies the block globally with no coordination
271/// (see [`block::node_id`]) and `row` is its offset inside it, so the key is
272/// intrinsic to the record rather than to the query that found it.
273///
274/// Rendered as `ts.node.seq.row`, in decimal, on purpose: an agent reading a
275/// response can tell what it is holding, and a human debugging a stuck reader
276/// can tell where it stopped.
277#[derive(Debug, Clone, Copy, PartialEq, Eq)]
278pub struct Cursor {
279    pub ts: i64,
280    pub node: u32,
281    pub seq: u64,
282    pub row: u32,
283}
284
285impl Cursor {
286    /// Descending: newest first, and for rows sharing a nanosecond, the
287    /// higher-numbered block and row first. Any total order would do; what
288    /// matters is that it is total, so no row can hide in a tie.
289    ///
290    /// Public because it is total across *nodes* as well as within one — `node`
291    /// is [`crate::block::node_id`] — which is what lets a merging reader
292    /// interleave pages from several replicas without asking anyone whose row
293    /// comes first. See `proxy`.
294    pub fn key(&self) -> std::cmp::Reverse<(i64, u32, u64, u32)> {
295        std::cmp::Reverse((self.ts, self.node, self.seq, self.row))
296    }
297}
298
299impl std::fmt::Display for Cursor {
300    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
301        write!(f, "{}.{}.{}.{}", self.ts, self.node, self.seq, self.row)
302    }
303}
304
305impl std::str::FromStr for Cursor {
306    type Err = String;
307
308    fn from_str(s: &str) -> std::result::Result<Cursor, String> {
309        let bad = || format!("{s:?} is not a cursor; pass back the `next` field verbatim");
310        let mut p = s.split('.');
311        let mut next = |f: &dyn Fn(&str) -> bool| p.next().filter(|v| f(v)).ok_or_else(bad);
312        // `ts` may be negative; nothing else may. Parsing the pieces by hand
313        // rather than trusting `parse` to reject `+1` or `1_000`.
314        let ts = next(&|v: &str| !v.is_empty())?.parse().map_err(|_| bad())?;
315        let digits = |v: &str| !v.is_empty() && v.bytes().all(|b| b.is_ascii_digit());
316        let c = Cursor {
317            ts,
318            node: next(&digits)?.parse().map_err(|_| bad())?,
319            seq: next(&digits)?.parse().map_err(|_| bad())?,
320            row: next(&digits)?.parse().map_err(|_| bad())?,
321        };
322        match p.next() {
323            Some(_) => Err(bad()),
324            None => Ok(c),
325        }
326    }
327}
328
329/// One matching record, kept only long enough to sort and materialize.
330///
331/// Holds a block index and a row number, not the row's data: a query over a
332/// wide window can match millions of rows and keep a hundred, and copying the
333/// other 999,900 out of the mapping in order to discard them is the easiest way
334/// to make a columnar engine slow.
335pub(crate) struct Hit {
336    ts: i64,
337    pub(crate) block: usize,
338    pub(crate) row: u32,
339}
340
341/// What a search cost, reported alongside the rows.
342///
343/// Not decoration. "How much did that cost" is the first question when a query
344/// is slow, and it is also what tells an agent its filter was too broad.
345#[derive(Debug, Default, Clone)]
346pub struct Stats {
347    pub blocks_total: usize,
348    pub blocks_scanned: usize,
349    pub rows_scanned: usize,
350    /// Rows satisfying the whole query — window, terms and `after` — not rows
351    /// on this page. `limit` cuts the page; this says how much there was to
352    /// cut, so a caller can tell "my filter is right and I am reading page one
353    /// of forty" from "my filter is wrong".
354    pub rows_matched: usize,
355    /// Series the metrics cap refused (`series::bound`); always zero on a
356    /// record search, which has no such cap.
357    ///
358    /// The counterpart to the per-series `dropped_points`, and here rather than
359    /// in the response body because the response body is a JSON array with
360    /// nowhere to hang a number that belongs to all of it. A chart with a
361    /// series missing and no way to know it is the failure mode both of these
362    /// exist to prevent.
363    pub dropped_series: usize,
364}
365
366pub struct Results {
367    /// A JSON array of row objects.
368    pub json: String,
369    pub stats: Stats,
370    /// Pass back as `after` for the next page. `None` means this was the last
371    /// one — not "ask again and see", which is the ambiguity that makes readers
372    /// poll forever.
373    pub next: Option<Cursor>,
374    /// One cursor per row in `json`, in the same order, and empty unless
375    /// [`Search::cursors`] asked for them.
376    ///
377    /// Beside the rows rather than inside them. A rendered row is the OTLP
378    /// record and nothing else (principle 3), and a reader that did not ask
379    /// for cursors should not have to step over one in every object to find
380    /// the fields it came for.
381    pub cursors: Vec<Cursor>,
382}
383
384/// The trace id this search pins down exactly, if it pins one down.
385///
386/// Only `trace_id = <32 hex chars>` qualifies, on either signal — logs blocks
387/// carry the same filter as span blocks, so "the logs for this trace" prunes
388/// exactly as hard as "the spans for it". Terms are AND-ed, so one such term is
389/// enough no matter what else is in the list: a block that cannot hold the id
390/// cannot hold a row satisfying the conjunction.
391fn trace_needle(q: &Search) -> Option<[u8; 16]> {
392    q.terms.iter().find_map(|t| match (&t.target, t.op) {
393        (Target::Field(f), Op::Eq) if f == "trace_id" => unhex(t.value.as_str()?)?.try_into().ok(),
394        _ => None,
395    })
396}
397
398/// The attribute equalities in a search, in the form a block filter answers.
399///
400/// Terms are AND-ed, so any single one the block cannot satisfy rules the whole
401/// block out — which is why a list of independent probes is enough and no
402/// expression tree is needed.
403///
404/// `numeric` records that the query scalar could be read as a number. Doubles
405/// are not in the index (see [`crate::bloom::HAS_DOUBLE`]), so a block that
406/// holds any must be scanned for a numeric query even when the text probe misses.
407struct AttrProbe {
408    hash: (u64, u64),
409    numeric: bool,
410}
411
412impl AttrProbe {
413    /// The block's own answer to "could a row here satisfy this term?".
414    fn maybe(&self, f: &crate::bloom::Filter) -> bool {
415        f.may_contain(self.hash) || (self.numeric && f.flags & crate::bloom::HAS_DOUBLE != 0)
416    }
417}
418
419fn attr_probes(q: &Search) -> Vec<AttrProbe> {
420    q.terms
421        .iter()
422        .filter(|t| t.op == Op::Eq)
423        .filter_map(|t| match &t.target {
424            Target::Attr(key) => Some(AttrProbe {
425                hash: crate::bloom::attr_hash(key, canon(&t.value).as_bytes()),
426                numeric: t.value.as_f64().is_some(),
427            }),
428            Target::Field(_) => None,
429        })
430        .collect()
431}
432
433/// The comparisons in a search that a zone map can answer.
434///
435/// Only an *unquoted* number qualifies, and that is a rule about the scan
436/// rather than about the index. A quoted scalar means a text comparison on a
437/// `str`-typed attribute (see [`AttrPred`]) and a numeric one on an `int`
438/// column, so the same term is lexicographic against one row and arithmetic
439/// against the next — two orderings, and [`crate::zone`] describes one. Since
440/// an absent key is read as "prune", a probe that describes the wrong ordering
441/// would not merely mislead, it would drop rows. `Ne` and `Contains` are out
442/// for the reason in [`crate::zone`]: they prune nothing worth the branch.
443fn range_probes(q: &Search) -> Vec<crate::zone::Probe> {
444    q.terms
445        .iter()
446        .filter(|t| !matches!(t.op, Op::Ne | Op::Contains))
447        .filter(|t| matches!(t.value, Value::Int(_) | Value::Double(_)))
448        .map(|t| crate::zone::Probe {
449            key: match &t.target {
450                Target::Attr(k) => crate::zone::attr_key(k),
451                Target::Field(f) => crate::zone::field_key(f),
452            },
453            op: t.op,
454            // The same two readings `attr_matches` and `field_pred` take of the
455            // scalar, so the interval consulted is the one the row would be
456            // compared against.
457            int: t.value.as_i64(),
458            float: t.value.as_f64(),
459        })
460        .collect()
461}
462
463/// The text an attribute of this value would have been indexed under.
464///
465/// This is the contract between [`AttrPred`] and the block index, and both
466/// sides are written against it: `Op::Eq` on a stored string is *defined* as
467/// equality with this text, and [`crate::attrs::index`] writes exactly these
468/// bytes for the str, int and bool types. Doubles are not in the index at all —
469/// the `numeric` flag covers them — so a stored double is reached through
470/// `HAS_DOUBLE` rather than through this string.
471///
472/// Every value has a text form, including a fractional double: nothing forces a
473/// producer to send `0.5` as a double rather than as `"0.5"`, and returning
474/// `None` here to mean "unindexable" made every fractional-double equality scan
475/// every block.
476fn canon(v: &Value) -> String {
477    match v {
478        Value::Str(s) => s.clone(),
479        Value::Int(i) => i.to_string(),
480        Value::Bool(b) => b.to_string(),
481        // `1.0` is written `1` by the int arm of the indexer and would be
482        // written `1` by anything rendering the number for a human, so a whole
483        // float has to canonicalise the same way or `eq: 1.0` misses `1`.
484        Value::Double(d) if d.fract() == 0.0 => (*d as i64).to_string(),
485        Value::Double(d) => d.to_string(),
486    }
487}
488
489/// Run a search against the blocks under `root`.
490///
491/// Blocking: this mmaps and page-faults. Callers on an async runtime must go
492/// through `spawn_blocking` — a hard fault stalls the whole OS thread with no
493/// yield point and no signal to the scheduler.
494pub fn search(root: &Path, q: &Search) -> Result<Results> {
495    search_open(root, q, &[])
496}
497
498/// As [`search`], but also reads `open` — snapshots of blocks that have been
499/// acknowledged and not yet published.
500///
501/// This is what keeps read-your-writes true once the write-ahead log moves the
502/// acknowledgement ahead of the seal (ARCHITECTURE section 4): without it a client that
503/// got a `200` and queried immediately would get nothing back for up to
504/// `max_block_age`. See [`crate::signal::Open`] for why a cursor stays valid
505/// across the seal.
506pub fn search_open(root: &Path, q: &Search, open_blocks: &[Arc<Open>]) -> Result<Results> {
507    let disk = block::scan(root, q.signal.dir())?;
508    let mut refs = block::sources(&disk, open_blocks);
509    let mut stats = Stats {
510        blocks_total: refs.len(),
511        ..Default::default()
512    };
513    refs.retain(|b| b.overlaps(q.from, q.to));
514    // A block whose oldest row is newer than the cursor is entirely on a page
515    // already delivered. Pruning here rather than per row is what keeps deep
516    // paging as cheap as the first page.
517    if let Some(c) = &q.after {
518        refs.retain(|b| b.min_ts <= c.ts);
519    }
520    // Newest first, so `limit` can cut the scan short.
521    refs.sort_by_key(|b| std::cmp::Reverse((b.max_ts, b.seq)));
522    let refs = &refs[..];
523
524    let scan = Scan::new(q);
525    let mut hits: Vec<Hit> = Vec::new();
526    let mut open: Vec<Option<Block>> = Vec::with_capacity(refs.len());
527
528    // Waves, widening. The first is one block wide because the commonest query
529    // there is — "the last `limit` records" — is answered by the first block and
530    // exits, and reading eleven more in parallel to throw them away would make
531    // the cheap case eleven times dearer to make the dear case faster. Doubling
532    // reaches full width after four waves and fifteen blocks, which is noise
533    // against the scan this is for.
534    let mut width = 1;
535    let mut i = 0;
536    while i < refs.len() {
537        // The early exit. With `limit` hits held, a block whose newest row
538        // predates the oldest hit cannot contribute — and since blocks are
539        // ordered by max_ts descending, neither can any block after it.
540        //
541        // Checked at the head of the wave rather than per block, which is what
542        // parallelism costs: a wave that begins before the limit is reached runs
543        // to the end even if its first block would have satisfied it. So
544        // `blocks_scanned` is now "what the scan read", not "the fewest blocks
545        // that could have answered" — the two were the same number when the loop
546        // was serial and are within one wave of each other now.
547        if hits.len() >= q.limit && hits.last().is_some_and(|w| refs[i].max_ts < w.ts) {
548            break;
549        }
550        let asked = (i + width).min(refs.len());
551        let answers = scan.wave(refs, i, asked);
552        let end = i + answers.len();
553        for done in answers {
554            let (block, found) = done?;
555            if let Some(b) = &block {
556                stats.blocks_scanned += 1;
557                stats.rows_scanned += b.root.num_rows();
558            }
559            // Counted *after* the cursor, which is what makes it a property of
560            // the query rather than of the scan. The block retain above already
561            // drops every block that lies wholly ahead of the cursor, so
562            // counting before the cursor made `rows_matched` shrink from page to
563            // page by whatever that pruning happened to remove — a number that
564            // moves when an optimisation fires is reporting the optimisation,
565            // not the query. Counting behind the cursor instead gives one
566            // meaning that holds on every page: how many matching rows are still
567            // to be read from here.
568            //
569            // It stays a lower bound in exactly one case — the early exit above,
570            // which cannot fire until `limit` hits are held and therefore cannot
571            // fire on a response whose `next` is `None`. So the count is exact
572            // whenever the answer is complete, and short only when the reader has
573            // already been told to page.
574            stats.rows_matched += found.len();
575            hits.extend(found);
576            open.push(block);
577        }
578
579        // Trim between waves, so memory is bounded by `limit` times the wave
580        // width rather than by the match count, which is not bounded by
581        // anything.
582        //
583        // Partition before sorting. `limit` is a hundred and a broad filter over
584        // one block is hundreds of thousands, so sorting the match set to throw
585        // away all but its head is the dominant cost of the commonest query
586        // there is — "the last 100 records", which matches every row it reads.
587        // `select_nth_unstable` is linear and leaves the head in the first
588        // `limit` slots; only those get ordered.
589        if hits.len() > q.limit {
590            hits.select_nth_unstable_by_key(q.limit, |h| cursor(&refs[h.block], h).key());
591            hits.truncate(q.limit);
592        }
593        hits.sort_unstable_by_key(|h| cursor(&refs[h.block], h).key());
594        i = end;
595        width = (width * 2).min(MAX_FANOUT);
596    }
597
598    let mut j = Json::new();
599    j.arr(|j| {
600        for h in &hits {
601            let b = open[h.block].as_ref().expect("a hit implies an open block");
602            b.emit_row(j, h.row);
603        }
604    });
605    Ok(Results {
606        json: j.into_string(),
607        stats,
608        // A short page is the last page. Saying so costs nothing here and saves
609        // every reader one round trip that returns nothing.
610        next: (hits.len() == q.limit)
611            .then(|| hits.last().map(|h| cursor(&refs[h.block], h)))
612            .flatten(),
613        cursors: match q.cursors {
614            true => hits.iter().map(|h| cursor(&refs[h.block], h)).collect(),
615            false => Vec::new(),
616        },
617    })
618}
619
620/// The widest a single search will fan out across blocks.
621///
622/// Past this the win is not CPU. A block scan is mostly page faults, the device
623/// answers them at its own rate, and every extra thread is one more spawn and
624/// one more shootdown for the same IO.
625const MAX_FANOUT: usize = 16;
626
627/// Threads a search may borrow beyond its own, for the whole process.
628///
629/// Fan-out is only worth anything when there is a core going spare, and this is
630/// the measurement that says so. One search over 37 blocks and 19M rows: 1.81 s
631/// serial, 0.20 s fanned out. Eight concurrent searches on the same twelve
632/// cores: throughput unchanged to within noise, and the short classes' p99 an
633/// order of magnitude worse — the cores were already busy, so every extra
634/// thread was scheduler work and nothing else.
635///
636/// So the budget is shared rather than per-search. A search takes what is idle
637/// and runs serially when nothing is, which makes the two cases above the same
638/// code with no mode to pick and nothing to configure. Bounded by the core
639/// count less the caller's own thread, because that is what "idle" means here.
640///
641/// Deliberately *not* a fair queue: a search never waits for the budget, it
642/// only asks. Waiting would trade the thing being optimised — latency — for a
643/// share of a resource the caller is about to finish with anyway.
644static SPARE: std::sync::LazyLock<AtomicUsize> = std::sync::LazyLock::new(|| {
645    AtomicUsize::new(
646        std::thread::available_parallelism()
647            .map_or(1, |n| n.get())
648            .saturating_sub(1)
649            .min(MAX_FANOUT),
650    )
651});
652
653/// Threads borrowed from [`SPARE`], returned on drop — including the drop that
654/// unwinds a panicking scan. Leaking one would degrade the process to serial
655/// scans permanently, with nothing to point at.
656pub(crate) struct Helpers(usize);
657
658impl Helpers {
659    /// `pub(crate)` for one caller that is not a scan: a test claiming the
660    /// whole budget, so it can run the same search with the fan-out off and
661    /// with it on and demand the same bytes back.
662    pub(crate) fn claim(want: usize) -> Helpers {
663        let mut got = 0;
664        let _ = SPARE.fetch_update(Relaxed, Relaxed, |n| {
665            got = n.min(want);
666            (got > 0).then(|| n - got)
667        });
668        Helpers(got)
669    }
670}
671
672impl Drop for Helpers {
673    fn drop(&mut self) {
674        SPARE.fetch_add(self.0, Relaxed);
675    }
676}
677
678/// Everything the per-block half of a search reads, and nothing it writes.
679///
680/// One struct rather than five arguments because it crosses a thread boundary:
681/// shared by reference, immutable for the whole scan, and therefore `Sync`
682/// without a lock. What is left out is as deliberate — `hits` and `stats` are
683/// the only state a block scan produces, and both are returned rather than
684/// accumulated, which is what makes the blocks independent.
685pub(crate) struct Scan<'a> {
686    q: &'a Search,
687    needle: Option<[u8; 16]>,
688    probes: Vec<AttrProbe>,
689    ranges: Vec<crate::zone::Probe>,
690    after: std::cmp::Reverse<(i64, u32, u64, u32)>,
691}
692
693impl<'a> Scan<'a> {
694    /// The per-block half of a query, prepared once.
695    ///
696    /// Everything here is derived from `q` alone, which is what lets one `Scan`
697    /// serve every block of a search and every thread scanning them.
698    pub(crate) fn new(q: &'a Search) -> Scan<'a> {
699        Scan {
700            q,
701            needle: trace_needle(q),
702            probes: attr_probes(q),
703            ranges: range_probes(q),
704            // With no cursor, every row is after the start — which is the key
705            // that sorts ahead of all of them.
706            after: q.after.map_or(
707                std::cmp::Reverse((i64::MAX, u32::MAX, u64::MAX, u32::MAX)),
708                |c| c.key(),
709            ),
710        }
711    }
712
713    /// Blocks `[from, to)` scanned at once, answered in block order.
714    ///
715    /// `std::thread::scope` and not a pool: the threads borrow the mapping, the
716    /// query and each other's nothing, and a scope is the one construct that
717    /// lets them do that without an `Arc` around every field. They are also the
718    /// wrong threads to pool — a pool exists to amortise spawns against short
719    /// tasks, and a block scan is milliseconds against a spawn's microseconds.
720    ///
721    /// The caller's own thread takes the first block, so a wave with no helpers
722    /// — the first wave of every search, and every wave on a busy node — spawns
723    /// nothing at all.
724    ///
725    /// `to` is the wave the ramp asked for and the answer may be shorter: what
726    /// [`SPARE`] hands out decides how many blocks this wave actually covers,
727    /// and the caller advances by the number of answers rather than by the
728    /// width it asked for.
729    pub(crate) fn wave(&self, refs: &[Src<'_>], from: usize, to: usize) -> Vec<Result<Scanned>> {
730        let helpers = Helpers::claim(to - from - 1);
731        if helpers.0 == 0 {
732            return vec![self.block(from, &refs[from])];
733        }
734        let to = from + 1 + helpers.0;
735        std::thread::scope(|s| {
736            let rest: Vec<_> = (from + 1..to)
737                .map(|k| s.spawn(move || self.block(k, &refs[k])))
738                .collect();
739            let mut out = Vec::with_capacity(to - from);
740            out.push(self.block(from, &refs[from]));
741            // A panic in a block scan is a bug in this file, not a bad query.
742            // Re-raising it on the caller's thread puts it where the runtime
743            // will turn it into a 500 with the original message attached;
744            // swallowing it would return a silently short answer instead.
745            out.extend(
746                rest.into_iter()
747                    .map(|h| h.join().unwrap_or_else(|e| std::panic::resume_unwind(e))),
748            );
749            out
750        })
751    }
752
753    /// One block: prune it, or open it and find the rows that match.
754    pub(crate) fn block(&self, i: usize, bref: &Src<'_>) -> Result<Scanned> {
755        // The sidecar filters (section 7.4). Both cover the case the block name cannot:
756        // a query with no useful time bound, either because it names a trace or
757        // because it names an attribute value that is rare or absent. Without
758        // them the scan runs to the end of retention to prove a negative. A
759        // 20 KB read is two orders of magnitude cheaper than the block it skips,
760        // and every damaged or missing filter reads as "scan me".
761        //
762        // `is_some_and`/`is_ok_and` rather than a `let` chain: those are stable
763        // since 1.70 and the chains are stable since 1.88, which is three years
764        // past the MSRV this workspace declares.
765        let no_trace = bref.dir.zip(self.needle.as_ref()).is_some_and(|(dir, id)| {
766            std::fs::read(dir.join(crate::bloom::TRACE_IDX))
767                .is_ok_and(|f| !crate::bloom::may_contain(&f, id))
768        });
769        if no_trace {
770            return Ok((None, Vec::new()));
771        }
772        let no_attr = !self.probes.is_empty()
773            && bref.dir.is_some_and(|dir| {
774                std::fs::read(dir.join(crate::bloom::ATTR_IDX)).is_ok_and(|bytes| {
775                    crate::bloom::Filter::open(&bytes)
776                        .is_some_and(|f| !self.probes.iter().all(|p| p.maybe(&f)))
777                })
778            });
779        if no_attr {
780            return Ok((None, Vec::new()));
781        }
782        // And the orderings, which the Bloom filter cannot help with at all:
783        // "slower than a second", "returned 5xx". Same shape, same fail-open —
784        // a block published before the zone map existed has no file here and is
785        // scanned, exactly as it was before.
786        let out_of_range = !self.ranges.is_empty()
787            && bref.dir.is_some_and(|dir| {
788                std::fs::read(dir.join(crate::zone::ZONE_IDX)).is_ok_and(|bytes| {
789                    crate::zone::Map::open(&bytes)
790                        .is_some_and(|m| !self.ranges.iter().all(|p| p.maybe(&m)))
791                })
792            });
793        if out_of_range {
794            return Ok((None, Vec::new()));
795        }
796
797        let Some(mut b) = Block::open(bref, self.q.signal)? else {
798            return Ok((None, Vec::new()));
799        };
800        // An attribute predicate is evaluated against the attribute tables, so
801        // they have to be there before `select`. Nothing else in `select`
802        // reads them: a `Target::Field` term is a column of the root.
803        if self
804            .q
805            .terms
806            .iter()
807            .any(|t| matches!(t.target, Target::Attr(_)))
808        {
809            b.detail(bref)?;
810        }
811        let sel = b.select(self.q, bref);
812        let hits = b.time().map_or_else(Vec::new, |time| {
813            sel.iter()
814                .filter_map(|&row| {
815                    let h = Hit {
816                        ts: time[row as usize],
817                        block: i,
818                        row,
819                    };
820                    (cursor(bref, &h).key() > self.after).then_some(h)
821                })
822                .collect()
823        });
824        // Rendering a row emits its attributes at every level, and the render
825        // pass runs after the fan-out has joined. Loading here rather than
826        // there keeps the page-ins parallel, at the cost of loading for a block
827        // whose hits are later sorted out of the limit — an over-approximation
828        // bounded by the blocks that matched at all, against the alternative of
829        // every block that was looked at.
830        if !hits.is_empty() {
831            b.detail(bref)?;
832        }
833        Ok((Some(b), hits))
834    }
835}
836
837/// What one block contributed: the mapping, if it was opened, and its matches.
838///
839/// The mapping comes back because the hits are row numbers into it and the
840/// rendering pass at the end of the search needs it still open. Dropping it and
841/// re-opening later would page the block in twice.
842pub(crate) type Scanned = (Option<Block>, Vec<Hit>);
843
844/// The sort key of one hit, which is also the cursor a caller pages on.
845fn cursor(bref: &Src, h: &Hit) -> Cursor {
846    Cursor {
847        ts: h.ts,
848        node: bref.node,
849        seq: bref.seq,
850        row: h.row,
851    }
852}
853
854/// The tables of one block, opened and ready to scan.
855///
856/// No `Mmap` handle is kept: every Arrow buffer read out of a block owns an
857/// `Arc<Mmap>` of its own (see `block::open_table`), so holding the
858/// `RecordBatch` is what holds the mapping. That is also why row data can be
859/// borrowed straight out of these batches with ordinary lifetimes.
860pub(crate) struct Block {
861    signal: Signal,
862    pub(crate) root: RecordBatch,
863    /// Record-level attributes; `parent_id` indexes `root` directly.
864    attrs: Option<Attrs>,
865    resource_attrs: Option<Attrs>,
866    scope_attrs: Option<Attrs>,
867    /// Rows that hang off a root row rather than being one: a span's events and
868    /// its links. Empty for logs.
869    children: Vec<Child>,
870    /// Whether the five fields above have been read yet.
871    ///
872    /// They are not read at open. `block::open_table` CRC32s every byte it
873    /// maps — that is the guarantee, not overhead — and on this corpus the
874    /// attribute tables are 42.9% of a logs block and 45.7% of a traces block
875    /// (`log_attrs` 768,352 KiB of 1,794,752; `span_attrs` 780,372 of
876    /// 1,710,020). A query with no attribute predicate that lands on a block
877    /// contributing no rows was hashing all of that to read a timestamp
878    /// column. See [`Block::detail`] for who asks for them and when.
879    detail: bool,
880}
881
882/// A child table and the attribute table keyed by its `id`.
883///
884/// Both indexes are built once when the block is opened, because both are read
885/// once per emitted span and once per attribute term: rebuilding either per
886/// span made emission quadratic in the number of spans in the block, which is
887/// the one place a `limit` does not bound the work.
888struct Child {
889    /// What the array is called in the emitted row.
890    label: &'static str,
891    rows: RecordBatch,
892    attrs: Option<Attrs>,
893    /// Child rows grouped by the root row they hang off, indexed by it.
894    by_parent: Vec<Vec<u32>>,
895    /// The root row each child `id` belongs to, indexed by the id. Child ids
896    /// are dense from zero per block, so this is an array store like every
897    /// other join here — but it is not the identity, because `id` numbers a
898    /// child and the row number is where it happens to sit.
899    parent_of_id: Vec<u32>,
900}
901
902/// An attribute table, plus the one fact about it that makes rendering a row
903/// cheap: whether `parent_id` ascends.
904///
905/// Every builder with the [`crate::schema::ATTRS`] shape appends one parent's
906/// attributes in one go, parents in ascending order, so a parent's rows are a
907/// contiguous run and two binary searches find it. [`emit_attrs`] used to scan
908/// the whole table per emitted row per level — on a 330 K-row logs block that
909/// is 66 million comparisons to render a hundred records, and it measured as
910/// *most* of an unfiltered `limit 100`, more than the scan and more than the
911/// paging docs/architecture/performance.md section 11 attributes it to. Same shape
912/// [`Block::emit_children`] already fixed for the child tables; this is the
913/// other half of it.
914///
915/// Checked at open rather than assumed, because a binary search over unsorted
916/// parents does not fail — it silently drops attributes, which is the one
917/// outcome nobody would notice.
918///
919/// [`crate::series`] reads the same shape off its own tables and so uses this
920/// rather than a second copy of the search.
921pub(crate) struct Attrs {
922    pub(crate) rows: RecordBatch,
923    ordered: bool,
924}
925
926impl Attrs {
927    pub(crate) fn new(rows: RecordBatch) -> Attrs {
928        let ordered = Attrs::parents(&rows).is_some_and(|p| p.windows(2).all(|w| w[0] <= w[1]));
929        Attrs { rows, ordered }
930    }
931
932    pub(crate) fn parents(rows: &RecordBatch) -> Option<&[u32]> {
933        rows.column(0)
934            .as_primitive_opt::<UInt32Type>()
935            .map(|c| &**c.values())
936    }
937
938    /// The rows belonging to `parent`, as a range the caller still filters —
939    /// exact when the table is ordered, the whole table when it is not.
940    ///
941    /// Takes the column the caller already downcast rather than repeating it,
942    /// since this runs once per emitted row per level.
943    ///
944    /// ponytail: that fallback is the linear scan this replaced, kept for a
945    /// table no builder in this tree produces. It is O(rows) per emitted row;
946    /// if one ever turns up, the fix is to sort it once at open rather than to
947    /// make this cleverer.
948    pub(crate) fn run(&self, parents: &[u32], parent: u32) -> std::ops::Range<usize> {
949        if !self.ordered {
950            return 0..parents.len();
951        }
952        let lo = parents.partition_point(|&p| p < parent);
953        lo..lo + parents[lo..].partition_point(|&p| p == parent)
954    }
955}
956
957/// The child tables of each signal: emitted name, row table, attribute table.
958///
959/// Links are the *out*-edge of the correlation graph — a link's `trace_id`
960/// points at another trace, usually one this node never saw — so returning them
961/// is the whole point of storing them. Events are a span's log lines and are
962/// what a waterfall shows when a row is expanded.
963fn child_tables(signal: Signal) -> &'static [(&'static str, &'static str, &'static str)] {
964    match signal {
965        Signal::Logs => &[],
966        Signal::Traces => &[
967            ("events", "span_events", "span_event_attrs"),
968            ("links", "span_links", "span_link_attrs"),
969        ],
970    }
971}
972
973impl Block {
974    fn open(bref: &Src, signal: Signal) -> Result<Option<Block>> {
975        let load = |name: &str| bref.load(name);
976
977        // No root table means the directory is being torn down by retention
978        // underneath us. Treat it as absent rather than as an error: racing a
979        // deletion of an expired block is normal, not a query failure.
980        let Some(root) = load(signal.root())? else {
981            return Ok(None);
982        };
983        Ok(Some(Block {
984            signal,
985            attrs: None,
986            resource_attrs: None,
987            scope_attrs: None,
988            children: Vec::new(),
989            detail: false,
990            root,
991        }))
992    }
993
994    /// Map everything that is not the root table: the three attribute levels
995    /// and, for traces, the child tables and their own attributes.
996    ///
997    /// Separate from [`open`](Self::open) because these are the expensive
998    /// tables and most blocks in a scan need none of them. Two callers ask,
999    /// both in `scan_one`: a query carrying an attribute predicate, before
1000    /// `select`, because the predicate is evaluated against them; and any
1001    /// block that produced a hit, because rendering a row emits its
1002    /// attributes. A block that matches nothing and is asked nothing about
1003    /// attributes never maps them and never hashes them.
1004    ///
1005    /// Idempotent, so the two callers can both fire without checking.
1006    ///
1007    /// This does not weaken the checksum: what changes is *which* tables a
1008    /// query reads, and every table it reads is still verified in full before
1009    /// a byte of it is returned. A corrupt attribute table that no query
1010    /// touches is caught by the first query that touches it.
1011    fn detail(&mut self, bref: &Src) -> Result<()> {
1012        if self.detail {
1013            return Ok(());
1014        }
1015        self.detail = true;
1016        let load = |name: &str| bref.load(name);
1017        self.attrs = load(self.signal.attrs())?.map(Attrs::new);
1018        self.resource_attrs = load("resource_attrs")?.map(Attrs::new);
1019        self.scope_attrs = load("scope_attrs")?.map(Attrs::new);
1020        for &(label, table, attrs) in child_tables(self.signal) {
1021            // A block whose spans carried no events writes no `span_events`
1022            // file at all (`publish` skips empty tables), which is absence, not
1023            // damage.
1024            if let Some(rows) = load(table)? {
1025                self.children.push(Child {
1026                    label,
1027                    by_parent: crate::series::index_by_parent(&rows),
1028                    parent_of_id: index_parent_of_id(&rows),
1029                    rows,
1030                    attrs: load(attrs)?.map(Attrs::new),
1031                });
1032            }
1033        }
1034        Ok(())
1035    }
1036
1037    /// The root's time column as a raw slice, straight out of the mapping.
1038    fn time(&self) -> Option<&[i64]> {
1039        self.root
1040            .column_by_name(self.signal.time_col())
1041            .map(|c| &**c.as_primitive::<TimestampNanosecondType>().values())
1042    }
1043
1044    /// Row numbers of `root` matching the query, ascending.
1045    fn select(&self, q: &Search, bref: &Src) -> Vec<u32> {
1046        let n = self.root.num_rows();
1047        let Some(time) = self.time() else {
1048            return Vec::new();
1049        };
1050
1051        // Time first: cheapest filter, and on a block the query only partly
1052        // covers, usually the most selective. When the block sits wholly inside
1053        // the window the comparison is skipped entirely — the directory name
1054        // already proved it, which is the point of putting the range there.
1055        // ponytail: the selection is now sized for the whole block even when
1056        // the time filter throws most of it away, where the filtered collect
1057        // this replaced grew to the match count — 4 bytes per row of one block,
1058        // for as long as the block's hits take to build, against a fan-out of
1059        // sixteen. Worth it for a 2.6x on the one predicate every query has; if
1060        // the transient ever matters, `shrink_to_fit` after the time filter
1061        // buys it back for one realloc.
1062        let mut sel: Vec<u32> = (0..n as u32).collect();
1063        if !(q.from <= bref.min_ts && q.to >= bref.max_ts) {
1064            // The `&[i64]` loop docs/architecture/not-here.md section 10 names as what
1065            // replaces intrinsics on the scan, and the one column every query
1066            // has a predicate on. `None` for the validity because the time
1067            // column is non-nullable in every signal's schema — and the scan it
1068            // replaced read the raw slice too, so a nullable one would compare
1069            // the same bytes it always did.
1070            keep(&mut sel, None, time, |t| (q.from..=q.to).contains(&t));
1071        }
1072
1073        for term in &q.terms {
1074            if sel.is_empty() {
1075                break;
1076            }
1077            match &term.target {
1078                Target::Field(name) => {
1079                    let ok = self
1080                        .root
1081                        .column_by_name(name)
1082                        .is_some_and(|c| field_filter(&mut sel, c.as_ref(), term.op, &term.value));
1083                    // Unknown column, or a value that cannot be compared
1084                    // against this column's type at all.
1085                    if !ok {
1086                        sel.clear();
1087                    }
1088                }
1089                Target::Attr(key) => {
1090                    let matched = self.attr_rows(key, term.op, &term.value, n);
1091                    sel.retain(|&i| matched[i as usize]);
1092                }
1093            }
1094        }
1095        sel
1096    }
1097
1098    /// A bitmap over root rows: does this record carry `key op value` at any
1099    /// attribute level it has — record, resource, scope, or one of its own
1100    /// child rows?
1101    fn attr_rows(&self, key: &str, op: Op, value: &Value, n: usize) -> Vec<bool> {
1102        let mut out = vec![false; n];
1103
1104        // Record level: parent_id *is* the root row number, so this is a store,
1105        // not a join. That is what rebasing ids at ingest bought.
1106        if let Some(a) = &self.attrs {
1107            for pid in attr_parents(&a.rows, key, op, value) {
1108                if let Some(slot) = out.get_mut(pid as usize) {
1109                    *slot = true;
1110                }
1111            }
1112        }
1113
1114        // Resource and scope level: parent_id is an entity id, and a foreign key
1115        // column on the root says which rows point at it. Entity ids are dense
1116        // from zero and number in the tens, so the reverse lookup is a small
1117        // boolean array rather than a hash set.
1118        for (table, fk) in [
1119            (&self.resource_attrs, "resource_id"),
1120            (&self.scope_attrs, "scope_id"),
1121        ] {
1122            let (Some(a), Some(col)) = (table, self.root.column_by_name(fk)) else {
1123                continue;
1124            };
1125            let ids = attr_parents(&a.rows, key, op, value);
1126            let Some(&top) = ids.iter().max() else {
1127                continue;
1128            };
1129            let mut wanted = vec![false; top as usize + 1];
1130            for id in ids {
1131                wanted[id as usize] = true;
1132            }
1133            for (i, &id) in col.as_primitive::<UInt16Type>().values().iter().enumerate() {
1134                if wanted.get(id as usize).copied().unwrap_or(false) {
1135                    out[i] = true;
1136                }
1137            }
1138        }
1139
1140        // Child level: a span's events and links carry attributes of their own,
1141        // and `recordException` is the reason this matters — the OTel API puts
1142        // `exception.type`, `exception.message` and `exception.stacktrace` on an
1143        // *event*, so "which spans threw NullPointerException" is a child-level
1144        // filter and nothing else. The row that matches is the span the event
1145        // hangs off: `attr_parents` gives the event's own id, and
1146        // `parent_of_id` turns that into the root row in one indexed load.
1147        //
1148        // The attribute Bloom sidecar has always covered these tables
1149        // (`attrs::index` walks every table with the ATTRS schema), so a block
1150        // holding the value was already being opened and scanned for it. What
1151        // was missing was the last hop.
1152        for c in &self.children {
1153            let Some(a) = &c.attrs else { continue };
1154            for id in attr_parents(&a.rows, key, op, value) {
1155                // Two `get`s and no `let` chain, for the MSRV reason given in
1156                // `search` above.
1157                if let Some(slot) = c
1158                    .parent_of_id
1159                    .get(id as usize)
1160                    .and_then(|&root| out.get_mut(root as usize))
1161                {
1162                    *slot = true;
1163                }
1164            }
1165        }
1166        out
1167    }
1168
1169    /// Write one root row as a JSON object, attributes merged in and child rows
1170    /// nested under it.
1171    fn emit_row(&self, j: &mut Json, row: u32) {
1172        j.obj(|j| {
1173            emit_fields(j, &self.root, row);
1174            j.key("attributes");
1175            emit_attrs(
1176                j,
1177                &[
1178                    (&self.resource_attrs, self.fk(row, "resource_id")),
1179                    (&self.scope_attrs, self.fk(row, "scope_id")),
1180                    (&self.attrs, Some(row)),
1181                ],
1182            );
1183            for c in &self.children {
1184                self.emit_children(j, c, row);
1185            }
1186        });
1187    }
1188
1189    /// The `events` / `links` array of one span.
1190    ///
1191    /// Reads the index built when the block was opened. It used to be a linear
1192    /// pass over the child table per emitted row, on the argument that `limit`
1193    /// bounds the row count — but the other factor is the block's event count,
1194    /// so the product is `limit` × events-in-block, and a block holds hundreds
1195    /// of thousands of events. One pass at open time replaces all of them.
1196    fn emit_children(&self, j: &mut Json, c: &Child, row: u32) {
1197        // No key at all rather than an empty array: most spans have neither
1198        // events nor links, and two empty arrays per span is most of the
1199        // response.
1200        let hits = match c.by_parent.get(row as usize) {
1201            Some(h) if !h.is_empty() => h,
1202            _ => return,
1203        };
1204        j.key(c.label);
1205        j.arr(|j| {
1206            for &r in hits {
1207                let r = r as usize;
1208                j.obj(|j| {
1209                    emit_fields(j, &c.rows, r as u32);
1210                    // The child's own `id`, which its attribute table keys on —
1211                    // not the span's row number.
1212                    let id = c
1213                        .rows
1214                        .column_by_name("id")
1215                        .map(|col| col.as_primitive::<UInt32Type>().value(r));
1216                    j.key("attributes");
1217                    emit_attrs(j, &[(&c.attrs, id)]);
1218                });
1219            }
1220        });
1221    }
1222
1223    fn fk(&self, row: u32, name: &str) -> Option<u32> {
1224        self.root
1225            .column_by_name(name)
1226            .map(|c| c.as_primitive::<UInt16Type>().value(row as usize) as u32)
1227    }
1228}
1229
1230/// The `parent_id` of each child row, indexed by that row's own `id`.
1231///
1232/// The inverse of [`crate::series::index_by_parent`] and the same trick: ids
1233/// are dense from zero per block, so the id is the slot. A table missing either
1234/// column indexes as empty, and every lookup then misses — which is the same
1235/// answer a scan of it would give.
1236fn index_parent_of_id(b: &RecordBatch) -> Vec<u32> {
1237    let (Some(ids), Some(parents)) = (b.column_by_name("id"), b.column_by_name("parent_id")) else {
1238        return Vec::new();
1239    };
1240    let ids = ids.as_primitive::<UInt32Type>().values();
1241    let parents = parents.as_primitive::<UInt32Type>().values();
1242    let mut out = vec![u32::MAX; ids.iter().copied().max().unwrap_or(0) as usize + 1];
1243    for (&id, &parent) in ids.iter().zip(parents) {
1244        out[id as usize] = parent;
1245    }
1246    out
1247}
1248
1249/// Every non-null column of one row, by name.
1250///
1251/// The block-local ids are skipped: the caller asked for a log line or a span
1252/// event, not for the row numbers that found it.
1253pub(crate) fn emit_fields(j: &mut Json, b: &RecordBatch, row: u32) {
1254    for (i, f) in b.schema().fields().iter().enumerate() {
1255        if matches!(
1256            f.name().as_str(),
1257            "id" | "parent_id" | "resource_id" | "scope_id"
1258        ) {
1259            continue;
1260        }
1261        let col = b.column(i);
1262        if col.is_null(row as usize) {
1263            continue;
1264        }
1265        j.key(f.name());
1266        // `body_ser` is the one Binary column that is not opaque bytes: it holds
1267        // the protobuf encoding of a non-string log body, written precisely so
1268        // that nothing is lost. Sending it through the generic Binary arm below
1269        // renders a map-valued body as a hex dump, which loses it on the way out
1270        // instead of on the way in.
1271        if f.name() == "body_ser" {
1272            emit_any(j, col.as_binary::<i32>().value(row as usize));
1273        } else {
1274            emit_value(j, col.as_ref(), row as usize);
1275        }
1276    }
1277}
1278
1279/// One `{...}` merging the attributes of several levels, most specific last.
1280fn emit_attrs(j: &mut Json, levels: &[(&Option<Attrs>, Option<u32>)]) {
1281    j.obj(|j| {
1282        let mut merged: Vec<(&str, &RecordBatch, usize)> = Vec::new();
1283        for &(table, parent) in levels {
1284            let (Some(a), Some(parent)) = (table, parent) else {
1285                continue;
1286            };
1287            // Empty for a table whose parent column is not a `u32` — which no
1288            // schema in this tree produces, and which then emits nothing rather
1289            // than panicking on a block someone else wrote.
1290            let parents = Attrs::parents(&a.rows).unwrap_or_default();
1291            for r in a.run(parents, parent).filter(|&r| parents[r] == parent) {
1292                merged.push((attr_key(&a.rows, r), &a.rows, r));
1293            }
1294        }
1295        // Sorted so output is deterministic, and stably so that within one key
1296        // the last level pushed — the most specific one — is the entry that
1297        // survives the dedup below.
1298        merged.sort_by_key(|(k, _, _)| *k);
1299        for (i, &(k, a, r)) in merged.iter().enumerate() {
1300            if merged.get(i + 1).is_some_and(|nxt| nxt.0 == k) {
1301                continue;
1302            }
1303            j.key(k);
1304            emit_attr(j, a, r);
1305        }
1306    });
1307}
1308
1309/// `parent_id`s of the attribute rows whose key matches and whose value
1310/// satisfies `op value`.
1311pub(crate) fn attr_parents(a: &RecordBatch, key: &str, op: Op, value: &Value) -> Vec<u32> {
1312    let keys = a.column(1).as_dictionary::<UInt16Type>();
1313    // Resolve the key string once. Everything after this compares u16 codes.
1314    let Some(code) = dict_index(keys.values().as_string::<i32>(), key) else {
1315        return Vec::new();
1316    };
1317    let codes = keys.keys().values();
1318    let parents = &**a.column(0).as_primitive::<UInt32Type>().values();
1319    let types = &**a.column(2).as_primitive::<UInt8Type>().values();
1320    let pred = AttrPred::new(a, op, value);
1321
1322    // Three raw buffers zipped, so the key test — which rejects most rows in a
1323    // table holding every key of every record — is a `u16` compare against a
1324    // slice the bounds check is already gone from.
1325    codes
1326        .iter()
1327        .zip(types)
1328        .zip(parents)
1329        .enumerate()
1330        .filter_map(|(i, ((&c, &ty), &p))| (c == code && pred.test(ty, i)).then_some(p))
1331        .collect()
1332}
1333
1334/// One attribute term with everything that does not depend on the row resolved
1335/// once: the four value columns downcast, the query scalar canonicalized, and —
1336/// for the string column — the predicate already evaluated against the
1337/// dictionary.
1338///
1339/// This used to be `attr_matches`, which did all of it *per row*: two
1340/// `downcast_ref`s, a `String` allocation for [`canon`], and a `parse::<f64>()`
1341/// on every ordered comparison. That measured 30.9 ns per root row against 6.1
1342/// for the allocation-free integer arm, which made an attribute filter fifteen
1343/// times dearer than a column one on the same block.
1344struct AttrPred<'a> {
1345    op: Op,
1346    /// The `str` column's dictionary codes, and which dictionary entries
1347    /// satisfy the predicate.
1348    ///
1349    /// The same trick as [`field_filter`]'s `Dictionary` arm: attribute values
1350    /// are where telemetry repeats (see [`crate::schema::ATTRS`]), so a few
1351    /// hundred string comparisons replace one per row and the row loop never
1352    /// touches string data.
1353    ///
1354    /// ponytail: evaluated over the whole dictionary, which every key in the
1355    /// table shares — so filtering on a rare key in a block whose values are
1356    /// nearly all distinct pays one comparison per distinct value to reject a
1357    /// handful of rows. The ceiling is a value column with no repetition in it,
1358    /// which is the case its dictionary encoding is already the wrong layout
1359    /// for; the upgrade path is a lazily filled memo over the same array.
1360    strs: Option<(&'a [u32], Vec<bool>)>,
1361    ints: Option<(&'a [i64], i64)>,
1362    doubles: Option<(&'a [f64], f64)>,
1363    bools: Option<(&'a BooleanArray, bool)>,
1364}
1365
1366impl AttrPred<'_> {
1367    fn new<'a>(a: &'a RecordBatch, op: Op, v: &Value) -> AttrPred<'a> {
1368        let text = canon(v);
1369        // A quoted query scalar asked for a text comparison and gets one; so
1370        // does anything that is not a number. Decided once rather than per row.
1371        let numeric = !matches!(v, Value::Str(_));
1372        // `_opt` on all four: a table whose columns are not the ATTRS shape
1373        // matches nothing here instead of panicking inside a scan thread.
1374        let strs = a
1375            .column(3)
1376            .as_dictionary_opt::<UInt32Type>()
1377            .and_then(|d| Some((d, d.values().as_string_opt::<i32>()?)))
1378            .map(|(d, values)| {
1379                let ok = (0..values.len())
1380                    .map(|i| {
1381                        let s = values.value(i);
1382                        match op {
1383                            Op::Contains => s.contains(text.as_str()),
1384                            // Equality against a string column is *defined* as
1385                            // equality with `canon`, because that is the text
1386                            // the block index holds (see [`canon`]). Widening
1387                            // it any further — say, matching the stored string
1388                            // "200.0" against `eq: 200` because both parse to
1389                            // the same number — would make the filter prune
1390                            // away blocks that do contain a match, which is the
1391                            // one failure mode a sidecar is not allowed to
1392                            // have.
1393                            Op::Eq | Op::Ne => op.test_ord(s.cmp(text.as_str())),
1394                            // Ordering is not in the index — `attr_probes` only
1395                            // takes `Op::Eq` — so there is nothing here to
1396                            // disagree with, and a number written as a string
1397                            // can be ordered as the number it is. It has to be:
1398                            // half the SDKs that emit
1399                            // `http.response.status_code` emit it as text, and
1400                            // lexicographically "1000" sorts below "400", so
1401                            // `gte: 400` would otherwise mean something
1402                            // different on each of them.
1403                            _ => match (s.parse::<f64>(), v.as_f64()) {
1404                                (Ok(x), Some(y)) if numeric => {
1405                                    x.partial_cmp(&y).is_some_and(|o| op.test_ord(o))
1406                                }
1407                                _ => op.test_ord(s.cmp(text.as_str())),
1408                            },
1409                        }
1410                    })
1411                    .collect();
1412                (&**d.keys().values(), ok)
1413            });
1414        AttrPred {
1415            op,
1416            strs,
1417            ints: a
1418                .column(4)
1419                .as_primitive_opt::<Int64Type>()
1420                .zip(v.as_i64())
1421                .map(|(c, y)| (&**c.values(), y)),
1422            doubles: a
1423                .column(5)
1424                .as_primitive_opt::<Float64Type>()
1425                .zip(v.as_f64())
1426                .map(|(c, y)| (&**c.values(), y)),
1427            bools: a.column(6).as_boolean_opt().zip(v.as_bool()),
1428        }
1429    }
1430
1431    /// Compare one attribute row against the query scalar, dispatching on the
1432    /// stored `type` rather than on the query's — the column decides what it
1433    /// is.
1434    ///
1435    /// Empty, Bytes, Slice and Map are returned in results but not filterable
1436    /// in V0, and a column whose type does not match the schema reads the same
1437    /// way: no match.
1438    fn test(&self, ty: u8, row: usize) -> bool {
1439        const STR: u8 = AttrType::Str as u8;
1440        const INT: u8 = AttrType::Int as u8;
1441        const DOUBLE: u8 = AttrType::Double as u8;
1442        const BOOL: u8 = AttrType::Bool as u8;
1443        match ty {
1444            STR => self.strs.as_ref().is_some_and(|(codes, ok)| {
1445                codes
1446                    .get(row)
1447                    .and_then(|&c| ok.get(c as usize))
1448                    .copied()
1449                    .unwrap_or(false)
1450            }),
1451            INT => self
1452                .ints
1453                .is_some_and(|(xs, y)| xs.get(row).is_some_and(|&x| self.op.test_ord(x.cmp(&y)))),
1454            DOUBLE => self.doubles.is_some_and(|(xs, y)| {
1455                xs.get(row)
1456                    .and_then(|x| x.partial_cmp(&y))
1457                    .is_some_and(|o| self.op.test_ord(o))
1458            }),
1459            BOOL => self
1460                .bools
1461                .is_some_and(|(xs, y)| row < xs.len() && self.op.test_ord(xs.value(row).cmp(&y))),
1462            _ => false,
1463        }
1464    }
1465}
1466
1467pub(crate) fn attr_key(a: &RecordBatch, row: usize) -> &str {
1468    let d = a.column(1).as_dictionary::<UInt16Type>();
1469    d.values()
1470        .as_string::<i32>()
1471        .value(d.keys().value(row) as usize)
1472}
1473
1474/// Position of `needle` in a dictionary's value array.
1475///
1476/// Linear over the dictionary, which is at most 65536 entries and in practice a
1477/// few dozen. Doing it once here is what keeps the row scan off the string data
1478/// entirely.
1479pub(crate) fn dict_index(values: &StringArray, needle: &str) -> Option<u16> {
1480    (0..values.len())
1481        .find(|&i| values.value(i) == needle)
1482        .map(|i| i as u16)
1483}
1484
1485/// Narrow `sel` to the rows of `col` satisfying `op value`.
1486///
1487/// `false` means the query value cannot be compared against this column at all,
1488/// which the caller turns into an empty result. Nothing is written to `sel`
1489/// before that decision, so a refusal leaves it untouched.
1490///
1491/// One monomorphic loop per column type, where this used to build a
1492/// `Box<dyn Fn(u32) -> bool>` and pay an indirect call per row.
1493/// docs/architecture/not-here.md section 10 rejects hand-written intrinsics on the scan
1494/// and names what replaces them: "a tight loop over `&[i64]` with no bounds
1495/// checks and no branches, which LLVM turns into NEON unasked". That is what
1496/// [`keep`] is; this function's only job is to hand it a values slice and a
1497/// comparison that inlines into it.
1498fn field_filter(sel: &mut Vec<u32>, col: &dyn Array, op: Op, v: &Value) -> bool {
1499    macro_rules! ints {
1500        ($t:ty) => {{
1501            let Some(target) = v.as_i64() else {
1502                return false;
1503            };
1504            let vals = col.as_primitive::<$t>().values();
1505            keep(sel, col.nulls(), vals, |x| {
1506                op.test_ord((x as i64).cmp(&target))
1507            });
1508        }};
1509    }
1510
1511    match col.data_type() {
1512        DataType::Timestamp(_, _) => ints!(TimestampNanosecondType),
1513        DataType::Int64 => ints!(Int64Type),
1514        DataType::Int32 => ints!(Int32Type),
1515        DataType::UInt64 => ints!(UInt64Type),
1516        DataType::UInt32 => ints!(UInt32Type),
1517        DataType::UInt16 => ints!(UInt16Type),
1518        DataType::UInt8 => ints!(UInt8Type),
1519        DataType::Float64 => {
1520            let Some(target) = v.as_f64() else {
1521                return false;
1522            };
1523            let vals = col.as_primitive::<Float64Type>().values();
1524            keep(sel, col.nulls(), vals, |x: f64| {
1525                x.partial_cmp(&target).is_some_and(|o| op.test_ord(o))
1526            });
1527        }
1528        DataType::Dictionary(_, _) => {
1529            let d = col.as_dictionary::<UInt16Type>();
1530            let values = d.values().as_string::<i32>();
1531            let Some(needle) = v.as_str() else {
1532                return false;
1533            };
1534            // Evaluate the predicate against the dictionary, not the rows: a
1535            // few dozen string comparisons replace one per row, and the scan
1536            // below is a lookup table indexed by a u16.
1537            let ok: Vec<bool> = (0..values.len())
1538                .map(|i| {
1539                    let s = values.value(i);
1540                    match op {
1541                        Op::Contains => s.contains(needle),
1542                        _ => op.test_ord(s.cmp(needle)),
1543                    }
1544                })
1545                .collect();
1546            keep(sel, col.nulls(), d.keys().values(), |c| {
1547                ok.get(c as usize).copied().unwrap_or(false)
1548            });
1549        }
1550        DataType::Boolean => {
1551            let a = col.as_boolean();
1552            let Some(target) = v.as_bool() else {
1553                return false;
1554            };
1555            keep_by(sel, a.len(), col.nulls(), |i| {
1556                op.test_ord(a.value(i).cmp(&target))
1557            });
1558        }
1559        DataType::Utf8 => {
1560            let a = col.as_string::<i32>();
1561            let Some(target) = v.as_str() else {
1562                return false;
1563            };
1564            keep_by(sel, a.len(), col.nulls(), |i| {
1565                let s = a.value(i);
1566                match op {
1567                    Op::Contains => s.contains(target),
1568                    _ => op.test_ord(s.cmp(target)),
1569                }
1570            });
1571        }
1572        DataType::FixedSizeBinary(_) => {
1573            // Trace and span ids: hex in the query, bytes on disk. Decoding the
1574            // needle once beats hex-encoding every row.
1575            let a = col.as_fixed_size_binary();
1576            let Some(target) = v.as_str().and_then(unhex) else {
1577                return false;
1578            };
1579            keep_by(sel, a.len(), col.nulls(), |i| {
1580                op.test_ord(a.value(i).cmp(target.as_slice()))
1581            });
1582        }
1583        _ => return false,
1584    }
1585    true
1586}
1587
1588/// Narrow `sel` to the rows where `p(vals[row])` holds.
1589///
1590/// Three shapes, because the first one is the whole point. A column with no
1591/// nulls, not yet narrowed by an earlier term — which is every first term on a
1592/// block the time range covers whole — walks `vals` contiguously and writes the
1593/// surviving row number unconditionally, advancing the cursor by the boolean.
1594/// No indirect call, no bounds check on the load, and no branch in the body, so
1595/// the comparison itself stays in vector registers.
1596///
1597/// `sel.len() == vals.len()` is what proves the selection is still the identity
1598/// `0..n`: [`Block::select`] only ever removes from it, and it is built
1599/// ascending, so a full-length selection has nothing missing from it.
1600///
1601/// ponytail: the two narrowed shapes stay a gather under `retain` and do not
1602/// vectorise. Making them would mean the selection becoming a bitmap so every
1603/// term reads and writes contiguously — a different engine, and worth it only
1604/// once a query with several selective terms shows up in a profile. Terms are
1605/// applied cheapest-first-by-accident today, and most queries carry one.
1606fn keep<T: Copy>(
1607    sel: &mut Vec<u32>,
1608    nulls: Option<&arrow_buffer::NullBuffer>,
1609    vals: &[T],
1610    p: impl Fn(T) -> bool,
1611) {
1612    match nulls {
1613        None if sel.len() == vals.len() => {
1614            let mut k = 0;
1615            for (i, &x) in vals.iter().enumerate() {
1616                sel[k] = i as u32;
1617                k += p(x) as usize;
1618            }
1619            sel.truncate(k);
1620        }
1621        None => sel.retain(|&i| vals.get(i as usize).is_some_and(|&x| p(x))),
1622        // An `is_null` per row is what kept this loop scalar, which is why the
1623        // case above exists at all. Every column a sealed block filters on is
1624        // non-null in practice; this is the path that stays correct when one is
1625        // not.
1626        Some(n) => {
1627            sel.retain(|&i| n.is_valid(i as usize) && vals.get(i as usize).is_some_and(|&x| p(x)));
1628        }
1629    }
1630}
1631
1632/// [`keep`] for a column with no values slice to walk: a bitmap, a variable
1633/// offset array or a fixed stride, none of which a vector register helps with.
1634/// The win here is only the closure being monomorphic rather than boxed.
1635fn keep_by(
1636    sel: &mut Vec<u32>,
1637    len: usize,
1638    nulls: Option<&arrow_buffer::NullBuffer>,
1639    p: impl Fn(usize) -> bool,
1640) {
1641    match nulls {
1642        None => sel.retain(|&i| (i as usize) < len && p(i as usize)),
1643        Some(n) => sel.retain(|&i| n.is_valid(i as usize) && p(i as usize)),
1644    }
1645}
1646
1647/// Decode hex, either case. `None` on an odd length or any non-hex byte, so a
1648/// malformed trace id matches nothing rather than matching a truncated prefix.
1649pub fn unhex(s: &str) -> Option<Vec<u8>> {
1650    if !s.len().is_multiple_of(2) {
1651        return None;
1652    }
1653    let b = s.as_bytes();
1654    (0..b.len() / 2)
1655        .map(|i| {
1656            let hi = (b[i * 2] as char).to_digit(16)?;
1657            let lo = (b[i * 2 + 1] as char).to_digit(16)?;
1658            Some((hi * 16 + lo) as u8)
1659        })
1660        .collect()
1661}
1662
1663/// Emit one cell of a root table.
1664fn emit_value(j: &mut Json, col: &dyn Array, row: usize) {
1665    match col.data_type() {
1666        // Nanoseconds, never a formatted date: every other representation
1667        // either loses precision or picks a timezone on the user's behalf, and
1668        // the UI formats them, which is where that belongs. As a *string*,
1669        // because that is what OTLP/JSON says a 64-bit integer is and because
1670        // 1.7e18 is twenty times past what a JSON number survives — see
1671        // [`Json::i64_str`].
1672        DataType::Timestamp(_, _) => {
1673            j.i64_str(col.as_primitive::<TimestampNanosecondType>().value(row));
1674        }
1675        DataType::Int64 => j.i64_str(col.as_primitive::<Int64Type>().value(row)),
1676        // 32 bits and narrower stay bare: they fit a double exactly, and a
1677        // reader doing arithmetic on `severity_number` or `status_code` should
1678        // not have to parse it first.
1679        DataType::Int32 => j.i64(col.as_primitive::<Int32Type>().value(row) as i64),
1680        DataType::UInt64 => j.u64_str(col.as_primitive::<UInt64Type>().value(row)),
1681        DataType::UInt32 => j.u64(col.as_primitive::<UInt32Type>().value(row) as u64),
1682        DataType::UInt16 => j.u64(col.as_primitive::<UInt16Type>().value(row) as u64),
1683        DataType::UInt8 => j.u64(col.as_primitive::<UInt8Type>().value(row) as u64),
1684        DataType::Float64 => j.f64(col.as_primitive::<Float64Type>().value(row)),
1685        DataType::Boolean => j.bool(col.as_boolean().value(row)),
1686        DataType::Utf8 => j.str(col.as_string::<i32>().value(row)),
1687        DataType::Binary => j.hex(col.as_binary::<i32>().value(row)),
1688        // `as_fixed_size_binary` panics on a type mismatch, exactly like the
1689        // `as_primitive`, `as_string` and `as_binary` arms above it. The match
1690        // is on `data_type()`, so a mismatch would mean the array disagreeing
1691        // with its own type — a broken Arrow build, not a broken block.
1692        DataType::FixedSizeBinary(_) => j.hex(col.as_fixed_size_binary().value(row)),
1693        DataType::Dictionary(_, _) => {
1694            let d = col.as_dictionary::<UInt16Type>();
1695            j.str(
1696                d.values()
1697                    .as_string::<i32>()
1698                    .value(d.keys().value(row) as usize),
1699            );
1700        }
1701        DataType::List(_) => {
1702            let inner = col.as_list::<i32>().value(row);
1703            j.arr(|j| {
1704                for i in 0..inner.len() {
1705                    if inner.is_null(i) {
1706                        j.null();
1707                    } else {
1708                        emit_value(j, inner.as_ref(), i);
1709                    }
1710                }
1711            });
1712        }
1713        _ => j.null(),
1714    }
1715}
1716
1717/// Emit one attribute's value from whichever column its `type` names.
1718pub(crate) fn emit_attr(j: &mut Json, a: &RecordBatch, row: usize) {
1719    const STR: u8 = AttrType::Str as u8;
1720    const INT: u8 = AttrType::Int as u8;
1721    const DOUBLE: u8 = AttrType::Double as u8;
1722    const BOOL: u8 = AttrType::Bool as u8;
1723    const BYTES: u8 = AttrType::Bytes as u8;
1724    const SLICE: u8 = AttrType::Slice as u8;
1725    const MAP: u8 = AttrType::Map as u8;
1726    match a.column(2).as_primitive::<UInt8Type>().value(row) {
1727        STR => j.str(crate::attrs::str_column(a).value(row)),
1728        // Int attributes go out as JSON strings, because that is the OTLP/JSON
1729        // encoding of an `int64` and principle 3 says OTLP decides the wire
1730        // form. The property is round-trip symmetry, not browser etiquette:
1731        // ingest reads these as strings, so what Mira emits Mira must accept —
1732        // and it is the same property in reverse that makes it safe, since a
1733        // reader that wants the number back has the exact digits rather than
1734        // whatever a double rounded them to.
1735        INT => j.i64_str(a.column(4).as_primitive::<Int64Type>().value(row)),
1736        DOUBLE => j.f64(a.column(5).as_primitive::<Float64Type>().value(row)),
1737        BOOL => j.bool(a.column(6).as_boolean().value(row)),
1738        BYTES => j.hex(a.column(7).as_binary::<i32>().value(row)),
1739        // `ser` holds the protobuf encoding of the whole `AnyValue`, so an array
1740        // or a map is a decode away rather than a reconstruction. They are not
1741        // exotic: `process.command_args` and `http.request.header.*` are arrays
1742        // by semantic convention, and `gen_ai.input.messages` — the first-class
1743        // case in ARCHITECTURE section 1 — is a kvlist.
1744        SLICE | MAP => emit_any(j, a.column(8).as_binary::<i32>().value(row)),
1745        // AttrType::Empty: the key arrived with no value at all, which is what
1746        // `null` means.
1747        _ => j.null(),
1748    }
1749}
1750
1751/// Render a protobuf-encoded `AnyValue` — the attribute `ser` column, and a log
1752/// body that was not a string — as the JSON it describes.
1753///
1754/// A decode failure becomes `null`. These bytes were written by this process
1755/// from an already-decoded message, so a failure here means the block is
1756/// damaged, and one damaged value must not take the whole response with it.
1757pub(crate) fn emit_any(j: &mut Json, bytes: &[u8]) {
1758    match AnyValue::decode(bytes) {
1759        Ok(v) => emit_any_value(j, v.value.as_ref()),
1760        Err(_) => j.null(),
1761    }
1762}
1763
1764/// Recursion is bounded by prost's own decode recursion limit (100), which
1765/// `AnyValue::decode` above has already enforced on these bytes — a hostile
1766/// client cannot nest deeply enough here to reach the stack.
1767fn emit_any_value(j: &mut Json, v: Option<&mira_proto::common::v1::any_value::Value>) {
1768    use mira_proto::common::v1::any_value::Value as Av;
1769    match v {
1770        None => j.null(),
1771        Some(Av::StringValue(s)) => j.str(s),
1772        // A string for the same reason [`emit_attr`]'s `INT` arm is one: these
1773        // bytes are an OTLP `AnyValue`, and OTLP/JSON writes its `int_value` as
1774        // a string.
1775        Some(Av::IntValue(i)) => j.i64_str(*i),
1776        Some(Av::DoubleValue(d)) => j.f64(*d),
1777        Some(Av::BoolValue(b)) => j.bool(*b),
1778        Some(Av::BytesValue(b)) => j.hex(b),
1779        Some(Av::ArrayValue(a)) => j.arr(|j| {
1780            for e in &a.values {
1781                emit_any_value(j, e.value.as_ref());
1782            }
1783        }),
1784        Some(Av::KvlistValue(m)) => j.obj(|j| {
1785            for e in &m.values {
1786                j.key(&e.key);
1787                emit_any_value(j, e.value.as_ref().and_then(|v| v.value.as_ref()));
1788            }
1789        }),
1790    }
1791}
1792
1793#[cfg(test)]
1794mod tests {
1795    use super::*;
1796    use arrow_array::builder::StringDictionaryBuilder;
1797    use arrow_array::{
1798        BinaryArray, BooleanArray, FixedSizeBinaryArray, Float64Array, Int32Array, Int64Array,
1799        ListArray, TimestampNanosecondArray, UInt8Array, UInt16Array, UInt32Array, UInt64Array,
1800    };
1801    use std::sync::Arc;
1802
1803    /// `u32::MAX` for "this column cannot be compared against this value",
1804    /// which the scan turns into an empty result rather than into every row.
1805    fn hits(col: &dyn Array, op: Op, v: &Value) -> Vec<u32> {
1806        let mut sel: Vec<u32> = (0..col.len() as u32).collect();
1807        if field_filter(&mut sel, col, op, v) {
1808            sel
1809        } else {
1810            vec![u32::MAX]
1811        }
1812    }
1813
1814    /// The predicate builder is a type-dispatch table, and a column type missing
1815    /// from it does not error — it returns no rows. So the only way an arm can be
1816    /// wrong and stay quiet is if nothing exercises it.
1817    ///
1818    /// Every arm gets the same three rows — below, equal, above — so one
1819    /// expectation checks the arm, the ordering and the null handling at once.
1820    #[test]
1821    fn every_column_type_compares_the_same_way() {
1822        let cols: Vec<(&str, Arc<dyn Array>)> = vec![
1823            (
1824                "timestamp",
1825                Arc::new(TimestampNanosecondArray::from(vec![
1826                    Some(1),
1827                    Some(2),
1828                    Some(3),
1829                    None,
1830                ])),
1831            ),
1832            (
1833                "i64",
1834                Arc::new(Int64Array::from(vec![Some(1), Some(2), Some(3), None])),
1835            ),
1836            (
1837                "i32",
1838                Arc::new(Int32Array::from(vec![Some(1), Some(2), Some(3), None])),
1839            ),
1840            (
1841                "u64",
1842                Arc::new(UInt64Array::from(vec![Some(1), Some(2), Some(3), None])),
1843            ),
1844            (
1845                "u32",
1846                Arc::new(UInt32Array::from(vec![Some(1), Some(2), Some(3), None])),
1847            ),
1848            (
1849                "u16",
1850                Arc::new(UInt16Array::from(vec![Some(1), Some(2), Some(3), None])),
1851            ),
1852            (
1853                "u8",
1854                Arc::new(UInt8Array::from(vec![Some(1), Some(2), Some(3), None])),
1855            ),
1856            (
1857                "f64",
1858                Arc::new(Float64Array::from(vec![
1859                    Some(1.0),
1860                    Some(2.0),
1861                    Some(3.0),
1862                    None,
1863                ])),
1864            ),
1865        ];
1866        for (name, col) in &cols {
1867            let c = col.as_ref();
1868            assert_eq!(hits(c, Op::Eq, &Value::Int(2)), [1], "{name} eq");
1869            assert_eq!(hits(c, Op::Ne, &Value::Int(2)), [0, 2], "{name} ne");
1870            assert_eq!(hits(c, Op::Lt, &Value::Int(2)), [0], "{name} lt");
1871            assert_eq!(hits(c, Op::Lte, &Value::Int(2)), [0, 1], "{name} lte");
1872            assert_eq!(hits(c, Op::Gt, &Value::Int(2)), [2], "{name} gt");
1873            assert_eq!(hits(c, Op::Gte, &Value::Int(2)), [1, 2], "{name} gte");
1874            // A null is not less than anything, and `ne` is where that bites:
1875            // the naive reading would return it.
1876            assert!(!hits(c, Op::Ne, &Value::Int(9)).contains(&3), "{name} null");
1877            // Quoted, because a browser and an LLM both write "2" as often as 2.
1878            assert_eq!(hits(c, Op::Eq, &Value::Str("2".into())), [1], "{name} str");
1879            // Nothing to compare against: no rows, not an error.
1880            assert_eq!(
1881                hits(c, Op::Eq, &Value::Bool(true)),
1882                [u32::MAX],
1883                "{name} bool"
1884            );
1885        }
1886
1887        // A fractional target against an integer column has no integer to be
1888        // equal to. Truncating would make `duration > 0.5` mean `duration > 0`.
1889        assert_eq!(
1890            hits(cols[1].1.as_ref(), Op::Gt, &Value::Double(1.5)),
1891            [u32::MAX]
1892        );
1893        assert_eq!(hits(cols[1].1.as_ref(), Op::Gt, &Value::Double(2.0)), [2]);
1894        // Floats compare as floats, and NaN is unordered rather than equal.
1895        let f = Float64Array::from(vec![Some(1.5), Some(f64::NAN)]);
1896        assert_eq!(hits(&f, Op::Gt, &Value::Double(1.0)), [0]);
1897        assert_eq!(
1898            hits(&f, Op::Eq, &Value::Double(f64::NAN)),
1899            Vec::<u32>::new()
1900        );
1901
1902        let b = BooleanArray::from(vec![Some(true), Some(false), None]);
1903        assert_eq!(hits(&b, Op::Eq, &Value::Bool(true)), [0]);
1904        assert_eq!(hits(&b, Op::Eq, &Value::Str("false".into())), [1]);
1905        assert_eq!(hits(&b, Op::Eq, &Value::Int(1)), [u32::MAX]);
1906
1907        let s = StringArray::from(vec![Some("alpha"), Some("beta"), None]);
1908        assert_eq!(hits(&s, Op::Eq, &Value::Str("beta".into())), [1]);
1909        assert_eq!(hits(&s, Op::Contains, &Value::Str("et".into())), [1]);
1910        assert_eq!(hits(&s, Op::Lt, &Value::Str("b".into())), [0]);
1911        assert_eq!(hits(&s, Op::Eq, &Value::Int(1)), [u32::MAX]);
1912
1913        let mut d = StringDictionaryBuilder::<UInt16Type>::new();
1914        for v in ["ERROR", "INFO", "ERROR"] {
1915            d.append_value(v);
1916        }
1917        let d = d.finish();
1918        assert_eq!(hits(&d, Op::Eq, &Value::Str("ERROR".into())), [0, 2]);
1919        // Resolved against the dictionary once. A value that is not in it cannot
1920        // match any row, and saying so costs no row scan at all.
1921        assert_eq!(
1922            hits(&d, Op::Eq, &Value::Str("TRACE".into())),
1923            Vec::<u32>::new()
1924        );
1925
1926        // Ids arrive as hex and live as bytes. The needle is decoded once, so a
1927        // needle that is not hex at all is no rows rather than every row.
1928        let ids = FixedSizeBinaryArray::try_from_iter([[1u8, 2], [3, 4]].into_iter()).unwrap();
1929        assert_eq!(hits(&ids, Op::Eq, &Value::Str("0102".into())), [0]);
1930        assert_eq!(hits(&ids, Op::Gt, &Value::Str("0102".into())), [1]);
1931        assert_eq!(hits(&ids, Op::Eq, &Value::Str("zz".into())), [u32::MAX]);
1932        assert_eq!(hits(&ids, Op::Eq, &Value::Str("010".into())), [u32::MAX]);
1933
1934        // A type the table does not know is not a panic and not an error.
1935        let l = ListArray::from_iter_primitive::<Int64Type, _, _>(vec![Some(vec![Some(1)])]);
1936        assert_eq!(hits(&l, Op::Eq, &Value::Int(1)), [u32::MAX]);
1937    }
1938
1939    /// Materialization is the same dispatch table read the other way, and its
1940    /// failure mode is worse: a column emitted under the wrong JSON type is a
1941    /// reader's bug, not ours.
1942    #[test]
1943    fn every_column_type_materializes_as_the_json_type_it_is() {
1944        let cell = |col: &dyn Array| {
1945            let mut j = Json::new();
1946            j.arr(|j| emit_value(j, col, 0));
1947            let s = j.into_string();
1948            s[1..s.len() - 1].to_owned()
1949        };
1950        let l = ListArray::from_iter_primitive::<Int64Type, _, _>(vec![Some(vec![
1951            Some(1),
1952            None,
1953            Some(3),
1954        ])]);
1955        let mut d = StringDictionaryBuilder::<UInt16Type>::new();
1956        d.append_value("ERROR");
1957        let cases: Vec<(Arc<dyn Array>, &str)> = vec![
1958            // The 64-bit trio is quoted and the narrower integers are not. The
1959            // timestamp is the case that would be silently wrong as a number:
1960            // as a double it reads back 1700000000000000000, one nanosecond off
1961            // and no parser anywhere complains.
1962            (
1963                Arc::new(TimestampNanosecondArray::from(vec![
1964                    1_700_000_000_000_000_001i64,
1965                ])),
1966                r#""1700000000000000001""#,
1967            ),
1968            (Arc::new(Int64Array::from(vec![-7i64])), r#""-7""#),
1969            (Arc::new(Int32Array::from(vec![-7i32])), "-7"),
1970            (
1971                Arc::new(UInt64Array::from(vec![u64::MAX])),
1972                r#""18446744073709551615""#,
1973            ),
1974            (Arc::new(UInt32Array::from(vec![7u32])), "7"),
1975            (Arc::new(UInt16Array::from(vec![7u16])), "7"),
1976            (Arc::new(UInt8Array::from(vec![7u8])), "7"),
1977            (Arc::new(Float64Array::from(vec![0.5f64])), "0.5"),
1978            (Arc::new(BooleanArray::from(vec![true])), "true"),
1979            (Arc::new(StringArray::from(vec!["a\"b"])), r#""a\"b""#),
1980            (
1981                Arc::new(BinaryArray::from(vec![&b"\xab\xcd"[..]])),
1982                r#""abcd""#,
1983            ),
1984            // A trace id: hex, and the same hex the query takes as a needle.
1985            (
1986                Arc::new(
1987                    FixedSizeBinaryArray::try_from_iter([[0xabu8, 0xcd]].into_iter()).unwrap(),
1988                ),
1989                r#""abcd""#,
1990            ),
1991            (Arc::new(d.finish()), r#""ERROR""#),
1992            // A null inside a list stays a null; the surrounding array does not
1993            // collapse to one. The elements are `Int64`, so they are quoted for
1994            // the same reason a scalar `Int64` is — the list arm recurses into
1995            // this same table rather than having a second encoding.
1996            (Arc::new(l), r#"["1",null,"3"]"#),
1997        ];
1998        for (col, want) in cases {
1999            assert_eq!(cell(col.as_ref()), want, "{:?}", col.data_type());
2000        }
2001
2002        // A type with no representation is null rather than a guess.
2003        let m = arrow_array::Int8Array::from(vec![1i8]);
2004        assert_eq!(cell(&m), "null");
2005    }
2006
2007    /// Everything the scalar helpers promise in their own doc comments, in one
2008    /// place, because each of them is a coercion rule a query author will hit
2009    /// and none of them is guessable from the type.
2010    #[test]
2011    fn a_scalar_coerces_to_what_the_column_needs_or_to_nothing() {
2012        for (s, want) in [
2013            ("eq", Op::Eq),
2014            ("=", Op::Eq),
2015            ("==", Op::Eq),
2016            ("ne", Op::Ne),
2017            ("!=", Op::Ne),
2018            ("lt", Op::Lt),
2019            ("<", Op::Lt),
2020            ("lte", Op::Lte),
2021            ("<=", Op::Lte),
2022            ("gt", Op::Gt),
2023            (">", Op::Gt),
2024            ("gte", Op::Gte),
2025            (">=", Op::Gte),
2026            ("contains", Op::Contains),
2027            ("~", Op::Contains),
2028        ] {
2029            assert_eq!(Op::parse(s), Some(want), "{s}");
2030        }
2031        assert_eq!(Op::parse("=~"), None);
2032        // Documented as unreachable — every caller handles Contains first — so
2033        // the guarantee is that it stays inert if one day a caller does not.
2034        use std::cmp::Ordering::*;
2035        for ord in [Less, Equal, Greater] {
2036            assert!(!Op::Contains.test_ord(ord));
2037        }
2038
2039        assert_eq!(Value::Int(3).as_i64(), Some(3));
2040        assert_eq!(Value::Double(3.0).as_i64(), Some(3));
2041        assert_eq!(Value::Double(3.5).as_i64(), None);
2042        assert_eq!(Value::Str("3".into()).as_i64(), Some(3));
2043        assert_eq!(Value::Str("3.5".into()).as_i64(), None);
2044        assert_eq!(Value::Bool(true).as_i64(), None);
2045
2046        assert_eq!(Value::Int(3).as_f64(), Some(3.0));
2047        assert_eq!(Value::Double(3.5).as_f64(), Some(3.5));
2048        assert_eq!(Value::Str("3.5".into()).as_f64(), Some(3.5));
2049        assert_eq!(Value::Str("x".into()).as_f64(), None);
2050        assert_eq!(Value::Bool(true).as_f64(), None);
2051
2052        assert_eq!(Value::Bool(false).as_bool(), Some(false));
2053        assert_eq!(Value::Str("true".into()).as_bool(), Some(true));
2054        assert_eq!(Value::Str("false".into()).as_bool(), Some(false));
2055        assert_eq!(Value::Str("TRUE".into()).as_bool(), None);
2056        assert_eq!(Value::Int(1).as_bool(), None);
2057        assert_eq!(Value::Double(1.0).as_bool(), None);
2058
2059        assert_eq!(Value::Str("x".into()).as_str(), Some("x"));
2060        assert_eq!(Value::Int(1).as_str(), None);
2061
2062        // Ids arrive from a URL, a log line or a model, so both cases and
2063        // neither-of-them all have to land somewhere predictable.
2064        assert_eq!(unhex("0aFf"), Some(vec![0x0a, 0xff]));
2065        assert_eq!(unhex(""), Some(vec![]));
2066        assert_eq!(unhex("abc"), None);
2067        assert_eq!(unhex("0g"), None);
2068        assert_eq!(unhex("0 1"), None);
2069
2070        let vals = StringArray::from(vec!["a", "b"]);
2071        assert_eq!(dict_index(&vals, "b"), Some(1));
2072        assert_eq!(dict_index(&vals, "c"), None);
2073    }
2074
2075    /// Every `AnyValue` arm, including the ones no attribute in the scan below
2076    /// carries, and bytes that are not an `AnyValue` at all. The renderer is a
2077    /// recursive decoder over attacker-supplied structure, which is the one
2078    /// shape in this file where a missing arm is a silently wrong answer.
2079    #[test]
2080    fn every_any_value_arm_renders_and_damage_renders_as_null() {
2081        use mira_proto::common::v1::any_value::Value as Av;
2082        use mira_proto::common::v1::{ArrayValue, KeyValue, KeyValueList};
2083
2084        let render = |v: Option<Av>| {
2085            let mut j = Json::new();
2086            emit_any(&mut j, &AnyValue { value: v }.encode_to_vec());
2087            j.into_string()
2088        };
2089        assert_eq!(render(None), "null");
2090        assert_eq!(render(Some(Av::StringValue("s".into()))), r#""s""#);
2091        // Quoted: an `AnyValue`'s `int_value` is an `int64`, and OTLP/JSON
2092        // writes those as strings in both directions.
2093        assert_eq!(render(Some(Av::IntValue(-1))), r#""-1""#);
2094        assert_eq!(render(Some(Av::DoubleValue(0.5))), "0.5");
2095        assert_eq!(render(Some(Av::BoolValue(true))), "true");
2096        assert_eq!(
2097            render(Some(Av::BytesValue(vec![0xbe, 0xef].into()))),
2098            r#""beef""#
2099        );
2100        // Nested both ways round, because the recursion is the only part of
2101        // this that can be wrong in a way a flat value would not show.
2102        assert_eq!(
2103            render(Some(Av::ArrayValue(ArrayValue {
2104                values: vec![
2105                    AnyValue { value: None },
2106                    AnyValue {
2107                        value: Some(Av::KvlistValue(KeyValueList {
2108                            values: vec![KeyValue {
2109                                key: "k".into(),
2110                                value: Some(AnyValue {
2111                                    value: Some(Av::IntValue(2)),
2112                                }),
2113                            }],
2114                        })),
2115                    },
2116                ],
2117            }))),
2118            r#"[null,{"k":"2"}]"#
2119        );
2120
2121        // A field number and wire type no protobuf carries. The bytes only get
2122        // here by being on disk, so this is a damaged block, not a bad request.
2123        let mut j = Json::new();
2124        emit_any(&mut j, &[0xff, 0xff, 0xff]);
2125        assert_eq!(j.into_string(), "null");
2126    }
2127
2128    /// The inverse index a child's attribute join reads: the child's own `id`
2129    /// is the slot and the value is the row it hangs off. A table missing
2130    /// either column indexes as empty and every lookup then misses, which is
2131    /// the same answer scanning it would give and not a panic.
2132    #[test]
2133    fn a_child_row_finds_its_parent_by_its_own_id() {
2134        let ids: Arc<dyn Array> = Arc::new(UInt32Array::from(vec![2u32, 0]));
2135        let parents: Arc<dyn Array> = Arc::new(UInt32Array::from(vec![7u32, 5]));
2136        let b = RecordBatch::try_from_iter([("id", ids.clone()), ("parent_id", parents)]).unwrap();
2137        let idx = index_parent_of_id(&b);
2138        assert_eq!(idx.len(), 3, "dense from zero to the largest id");
2139        assert_eq!(idx[0], 5);
2140        assert_eq!(idx[1], u32::MAX, "an id no row claims has no parent");
2141        assert_eq!(idx[2], 7);
2142
2143        let orphan = RecordBatch::try_from_iter([("id", ids)]).unwrap();
2144        assert!(index_parent_of_id(&orphan).is_empty());
2145    }
2146
2147    /// A block on disk, scanned. The predicate tables above are exercised in
2148    /// isolation; this is the path that reaches them — the time prefilter, the
2149    /// three attribute levels, and the merge that decides which of two levels
2150    /// setting the same key the caller actually sees.
2151    #[test]
2152    fn a_scan_narrows_by_time_then_by_terms_and_the_most_specific_level_wins() {
2153        use mira_proto::collector::logs::v1::ExportLogsServiceRequest;
2154        use mira_proto::common::v1::any_value::Value as Av;
2155        use mira_proto::common::v1::{
2156            AnyValue, ArrayValue, InstrumentationScope, KeyValue, KeyValueList,
2157        };
2158        use mira_proto::logs::v1::{LogRecord, ResourceLogs, ScopeLogs};
2159        use mira_proto::resource::v1::Resource;
2160
2161        let kv = |k: &str, v: Av| KeyValue {
2162            key: k.into(),
2163            value: Some(AnyValue { value: Some(v) }),
2164        };
2165        let base = 1_700_000_000_000_000_000u64;
2166        let req = ExportLogsServiceRequest {
2167            resource_logs: vec![ResourceLogs {
2168                resource: Some(Resource {
2169                    attributes: vec![
2170                        kv("service.name", Av::StringValue("checkout".into())),
2171                        // Also set per-record below, which is the whole point:
2172                        // an SDK default that one record overrides.
2173                        kv("deploy.env", Av::StringValue("prod".into())),
2174                    ],
2175                    ..Default::default()
2176                }),
2177                scope_logs: vec![ScopeLogs {
2178                    scope: Some(InstrumentationScope {
2179                        name: "mira.test".into(),
2180                        attributes: vec![kv("scope.kind", Av::StringValue("lib".into()))],
2181                        ..Default::default()
2182                    }),
2183                    log_records: (0..3)
2184                        .map(|i| LogRecord {
2185                            time_unix_nano: base + i * 1_000_000_000,
2186                            severity_number: 9 + i as i32,
2187                            severity_text: "INFO".into(),
2188                            // OTel Events carry the identity of the event here
2189                            // and not in an attribute; empty on the others,
2190                            // which is how OTLP says "this is a plain log".
2191                            event_name: if i == 0 {
2192                                "user.login".into()
2193                            } else {
2194                                String::new()
2195                            },
2196                            // The last record's body is a map rather than a
2197                            // string, which is the case `body_ser` exists for.
2198                            body: Some(AnyValue {
2199                                value: Some(if i == 2 {
2200                                    Av::KvlistValue(KeyValueList {
2201                                        values: vec![kv(
2202                                            "msg",
2203                                            Av::StringValue("structured body".into()),
2204                                        )],
2205                                    })
2206                                } else {
2207                                    Av::StringValue(format!("line {i}"))
2208                                }),
2209                            }),
2210                            attributes: vec![
2211                                kv("deploy.env", Av::StringValue("canary".into())),
2212                                kv("attempt", Av::IntValue(i as i64)),
2213                                // None of these three is filterable in V0; all
2214                                // three still have to come back in the row.
2215                                kv("payload", Av::BytesValue(vec![0xde, 0xad].into())),
2216                                kv(
2217                                    "tags",
2218                                    Av::ArrayValue(ArrayValue {
2219                                        values: vec![
2220                                            AnyValue {
2221                                                value: Some(Av::StringValue("a".into())),
2222                                            },
2223                                            AnyValue {
2224                                                value: Some(Av::IntValue(7)),
2225                                            },
2226                                        ],
2227                                    }),
2228                                ),
2229                                kv(
2230                                    "gen_ai.input.messages",
2231                                    Av::KvlistValue(KeyValueList {
2232                                        values: vec![kv("role", Av::StringValue("user".into()))],
2233                                    }),
2234                                ),
2235                                // A key that arrived with no value at all.
2236                                // Legal OTLP, and `null` is what it means.
2237                                KeyValue {
2238                                    key: "trace.hint".into(),
2239                                    value: None,
2240                                },
2241                            ],
2242                            ..Default::default()
2243                        })
2244                        .collect(),
2245                    ..Default::default()
2246                }],
2247                ..Default::default()
2248            }],
2249        };
2250
2251        let dir = std::env::temp_dir().join(format!("mira-scan-{}", std::process::id()));
2252        let _ = std::fs::remove_dir_all(&dir);
2253        let mut b = crate::logs::LogsBuilder::new();
2254        b.append_request(&req).unwrap();
2255        let sealed = b.finish().unwrap();
2256        let bref =
2257            crate::block::publish(&dir, "logs", crate::block::node_id("a"), 0, 0, &sealed).unwrap();
2258
2259        let base = base as i64;
2260        let scan = |from: i64, to: i64, terms: Vec<Term>| {
2261            search(
2262                &dir,
2263                &Search {
2264                    signal: Signal::Logs,
2265                    from,
2266                    to,
2267                    terms,
2268                    limit: 100,
2269                    after: None,
2270                    cursors: false,
2271                },
2272            )
2273            .unwrap()
2274        };
2275        let field = |n: &str, op: Op, v: Value| Term {
2276            target: Target::Field(n.into()),
2277            op,
2278            value: v,
2279        };
2280        let attr = |n: &str, op: Op, v: Value| Term {
2281            target: Target::Attr(n.into()),
2282            op,
2283            value: v,
2284        };
2285
2286        // A window the block only partly covers: the directory name proved the
2287        // block is worth opening, and only then does the timestamp get read.
2288        let r = scan(base + 500_000_000, base + 1_500_000_000, vec![]);
2289        assert_eq!(r.stats.rows_matched, 1, "{}", r.json);
2290        assert!(r.json.contains("line 1"), "{}", r.json);
2291
2292        let all = base + 10_000_000_000;
2293        assert_eq!(scan(base, all, vec![]).stats.rows_matched, 3);
2294
2295        // A column this signal does not have is no rows, not an error and not
2296        // every row — a query spanning signals is a normal thing to try.
2297        assert_eq!(
2298            scan(
2299                base,
2300                all,
2301                vec![field("duration_nano", Op::Gt, Value::Int(0))]
2302            )
2303            .stats
2304            .rows_matched,
2305            0
2306        );
2307        // Same for a value that cannot be compared against the column's type.
2308        assert_eq!(
2309            scan(
2310                base,
2311                all,
2312                vec![field("severity_number", Op::Eq, Value::Bool(true))]
2313            )
2314            .stats
2315            .rows_matched,
2316            0
2317        );
2318        // Once nothing is selected the remaining terms are skipped, so a term
2319        // that would have been expensive costs nothing.
2320        assert_eq!(
2321            scan(
2322                base,
2323                all,
2324                vec![
2325                    field("severity_number", Op::Gt, Value::Int(99)),
2326                    attr("service.name", Op::Eq, Value::Str("checkout".into())),
2327                ]
2328            )
2329            .stats
2330            .rows_matched,
2331            0
2332        );
2333        // Attributes are found without being told which level they live at.
2334        for (k, v) in [("service.name", "checkout"), ("scope.kind", "lib")] {
2335            assert_eq!(
2336                scan(base, all, vec![attr(k, Op::Eq, Value::Str(v.into()))])
2337                    .stats
2338                    .rows_matched,
2339                3,
2340                "{k}"
2341            );
2342        }
2343        assert_eq!(
2344            scan(base, all, vec![attr("attempt", Op::Gte, Value::Int(1))])
2345                .stats
2346                .rows_matched,
2347            2
2348        );
2349        // A bytes attribute is not filterable in V0. No rows, and no panic on
2350        // the way to deciding that.
2351        assert_eq!(
2352            scan(
2353                base,
2354                all,
2355                vec![attr("payload", Op::Eq, Value::Str("dead".into()))]
2356            )
2357            .stats
2358            .rows_matched,
2359            0
2360        );
2361        // That one never opened the block — `attr_probes` answered it from the
2362        // filter. `contains` is not probed, so the same term on the same
2363        // attribute reaches the row scan, which is where the decision that a
2364        // bytes value is not comparable actually has to be made.
2365        let r = scan(
2366            base,
2367            all,
2368            vec![attr("payload", Op::Contains, Value::Str("dead".into()))],
2369        );
2370        assert_eq!(r.stats.blocks_scanned, 1, "no probe, so the block is read");
2371        assert_eq!(r.stats.rows_matched, 0);
2372
2373        let row = scan(base, all, vec![]).json;
2374        // Record level beats resource level for the same key.
2375        assert!(row.contains(r#""deploy.env":"canary""#), "{row}");
2376        assert!(!row.contains("prod"), "{row}");
2377        assert!(row.contains(r#""service.name":"checkout""#), "{row}");
2378        assert!(row.contains(r#""payload":"dead""#), "{row}");
2379        // Slice and Map round-trip through `ser` as the JSON they were, because
2380        // a value nothing can read back is a value that was not stored.
2381        assert!(row.contains(r#""tags":["a","7"]"#), "{row}");
2382        assert!(
2383            row.contains(r#""gen_ai.input.messages":{"role":"user"}"#),
2384            "{row}"
2385        );
2386        // Same for a non-string body, and for the field that says the record is
2387        // an OTel Event rather than a log line.
2388        assert!(
2389            row.contains(r#""body_ser":{"msg":"structured body"}"#),
2390            "{row}"
2391        );
2392        assert!(row.contains(r#""event_name":"user.login""#), "{row}");
2393        // Empty on the wire is absent in the row, not an empty string.
2394        assert_eq!(row.matches("event_name").count(), 1, "{row}");
2395        // An attribute that arrived with no value is a key with a `null`, not a
2396        // key that vanished: the exporter sent it, so the record has it.
2397        assert!(row.contains(r#""trace.hint":null"#), "{row}");
2398
2399        // A block written before `event_name` was added to the schema. Once a
2400        // block is on disk a schema change is not revertible, so the claim that
2401        // the reader is `column_by_name` all the way down has to be checked
2402        // rather than asserted: dropping the column reproduces the old writer
2403        // exactly, and the only difference in the answer must be the field.
2404        let table = bref.dir.join("logs.arrow");
2405        let mut old = block::open_table_opt(&table).unwrap().unwrap().batches[0].clone();
2406        old.remove_column(old.schema().index_of("event_name").unwrap());
2407        // Staged and renamed rather than truncated in place: a mapping over a
2408        // truncated file is a SIGBUS, which is why `write_table` says so.
2409        let staged = bref.dir.join("logs.arrow.new");
2410        crate::block::write_table(&staged, &old).unwrap();
2411        std::fs::rename(&staged, &table).unwrap();
2412        let r = scan(base, all, vec![]);
2413        assert_eq!(r.stats.rows_matched, 3, "{}", r.json);
2414        assert!(!r.json.contains("event_name"), "{}", r.json);
2415        assert!(
2416            r.json.contains(r#""body_ser":{"msg":"structured body"}"#),
2417            "{}",
2418            r.json
2419        );
2420
2421        // One column deeper, and the one with no fallback: the time column is
2422        // what `select` filters on before it looks at anything else. A root
2423        // table without it selects nothing, so a table this build cannot make
2424        // sense of costs its own rows and no more.
2425        let mut old = block::open_table_opt(&table).unwrap().unwrap().batches[0].clone();
2426        old.remove_column(old.schema().index_of("time_unix_nano").unwrap());
2427        crate::block::write_table(&staged, &old).unwrap();
2428        std::fs::rename(&staged, &table).unwrap();
2429        let r = scan(base, all, vec![]);
2430        assert_eq!(r.json, "[]");
2431        assert_eq!(r.stats.rows_matched, 0);
2432
2433        // Retention can delete a block between the directory listing and the
2434        // read. The block still counts as present and simply contributes
2435        // nothing, rather than failing the query.
2436        std::fs::remove_file(bref.dir.join("logs.arrow")).unwrap();
2437        let r = scan(base, all, vec![]);
2438        assert_eq!((r.stats.blocks_total, r.stats.blocks_scanned), (1, 0));
2439        assert_eq!(r.json, "[]");
2440    }
2441
2442    /// The fourth attribute level: a span's own events and links.
2443    ///
2444    /// This is not a completeness exercise. The OTel API puts the fields anyone
2445    /// actually searches for on an *event* — `recordException` writes
2446    /// `exception.type`, `exception.message` and `exception.stacktrace` onto one
2447    /// — so "which spans threw a NullPointerException" is a child-level filter
2448    /// and there is no span-level equivalent to fall back on. The row came back
2449    /// with the value visible under `events[].attributes` while a filter for the
2450    /// same key returned nothing, which is the worst shape a search can have.
2451    #[test]
2452    fn an_attribute_on_a_span_event_or_link_selects_the_span_it_hangs_off() {
2453        use mira_proto::collector::trace::v1::ExportTraceServiceRequest;
2454        use mira_proto::common::v1::any_value::Value as Av;
2455        use mira_proto::common::v1::{AnyValue, InstrumentationScope, KeyValue};
2456        use mira_proto::resource::v1::Resource;
2457        use mira_proto::trace::v1::span::{Event, Link};
2458        use mira_proto::trace::v1::{ResourceSpans, ScopeSpans, Span};
2459
2460        let kv = |k: &str, v: &str| KeyValue {
2461            key: k.into(),
2462            value: Some(AnyValue {
2463                value: Some(Av::StringValue(v.into())),
2464            }),
2465        };
2466        let event = |name: &str, attrs: Vec<KeyValue>| Event {
2467            time_unix_nano: 10_050,
2468            name: name.into(),
2469            attributes: attrs,
2470            ..Default::default()
2471        };
2472        let span = |i: u64, events: Vec<Event>, links: Vec<Link>| Span {
2473            trace_id: vec![1u8; 16].into(),
2474            span_id: vec![i as u8 + 1; 8].into(),
2475            name: format!("span {i}"),
2476            start_time_unix_nano: 10_000 + i,
2477            end_time_unix_nano: 10_100 + i,
2478            attributes: vec![kv("http.method", "GET")],
2479            events,
2480            links,
2481            ..Default::default()
2482        };
2483
2484        // Span 0 carries two events and span 1 carries the throw, so the
2485        // throwing event's own id is 2 while the span it belongs to is row 1.
2486        // An implementation that treats a child id as a root row number — the
2487        // obvious mistake, since every other join in this file is exactly that —
2488        // answers "span 2" here and passes any test where each span has one
2489        // event.
2490        let req = ExportTraceServiceRequest {
2491            resource_spans: vec![ResourceSpans {
2492                resource: Some(Resource {
2493                    attributes: vec![kv("service.name", "checkout")],
2494                    ..Default::default()
2495                }),
2496                scope_spans: vec![ScopeSpans {
2497                    scope: Some(InstrumentationScope {
2498                        name: "mira.test".into(),
2499                        ..Default::default()
2500                    }),
2501                    spans: vec![
2502                        span(
2503                            0,
2504                            vec![
2505                                event("cache.miss", vec![kv("cache.key", "cart:7")]),
2506                                event("retrying", vec![]),
2507                            ],
2508                            vec![],
2509                        ),
2510                        span(
2511                            1,
2512                            vec![event(
2513                                "exception",
2514                                vec![kv("exception.type", "NullPointerException")],
2515                            )],
2516                            vec![],
2517                        ),
2518                        span(
2519                            2,
2520                            vec![],
2521                            vec![Link {
2522                                trace_id: vec![9u8; 16].into(),
2523                                span_id: vec![8u8; 8].into(),
2524                                attributes: vec![kv("link.kind", "follows_from")],
2525                                ..Default::default()
2526                            }],
2527                        ),
2528                    ],
2529                    ..Default::default()
2530                }],
2531                ..Default::default()
2532            }],
2533        };
2534
2535        let dir = std::env::temp_dir().join(format!("mira-child-attr-{}", std::process::id()));
2536        let _ = std::fs::remove_dir_all(&dir);
2537        let mut b = crate::traces::TracesBuilder::new();
2538        b.append_request(&req).unwrap();
2539        let sealed = b.finish().unwrap();
2540        let bref = crate::block::publish(&dir, "traces", crate::block::node_id("a"), 0, 0, &sealed)
2541            .unwrap();
2542
2543        let find = |key: &str, value: &str| {
2544            search(
2545                &dir,
2546                &Search {
2547                    signal: Signal::Traces,
2548                    from: 0,
2549                    to: i64::MAX,
2550                    terms: vec![Term {
2551                        target: Target::Attr(key.into()),
2552                        op: Op::Eq,
2553                        value: Value::Str(value.into()),
2554                    }],
2555                    limit: 10,
2556                    after: None,
2557                    cursors: false,
2558                },
2559            )
2560            .unwrap()
2561        };
2562
2563        // The case the bug report named, and the two either side of it: an
2564        // event attribute on a span that has siblings, an event attribute on a
2565        // span whose events are not the first in the block, and a *link*
2566        // attribute, which travels the same path through a different table.
2567        for (key, value, want) in [
2568            ("exception.type", "NullPointerException", "span 1"),
2569            ("cache.key", "cart:7", "span 0"),
2570            ("link.kind", "follows_from", "span 2"),
2571        ] {
2572            let r = find(key, value);
2573            assert_eq!(r.stats.rows_matched, 1, "{key}: {}", r.json);
2574            assert!(
2575                r.json.contains(&format!(r#""name":"{want}""#)),
2576                "{}",
2577                r.json
2578            );
2579        }
2580
2581        // The other three levels still answer, and a value nothing carries at
2582        // any of the four still matches nothing — the union must widen the
2583        // search, not defeat it.
2584        assert_eq!(find("http.method", "GET").stats.rows_matched, 3);
2585        assert_eq!(find("service.name", "checkout").stats.rows_matched, 3);
2586        assert_eq!(find("exception.type", "IOError").stats.rows_matched, 0);
2587
2588        // And the value is still rendered where it was found, so the filter and
2589        // the row now agree about where an event attribute lives.
2590        let r = find("exception.type", "NullPointerException");
2591        assert!(
2592            r.json
2593                .contains(r#""attributes":{"exception.type":"NullPointerException"}"#),
2594            "{}",
2595            r.json
2596        );
2597
2598        // Rewrite one table without one column, the way a writer that predates
2599        // it left the block. Staged and renamed rather than edited in place: a
2600        // mapping over a file being shortened is a SIGBUS, not an error.
2601        let strip = |table: &str, col: &str| {
2602            let path = bref.dir.join(format!("{table}.arrow"));
2603            let mut b = block::open_table_opt(&path).unwrap().unwrap().batches[0].clone();
2604            b.remove_column(b.schema().index_of(col).unwrap());
2605            let staged = bref.dir.join(format!("{table}.staged"));
2606            crate::block::write_table(&staged, &b).unwrap();
2607            std::fs::rename(&staged, &path).unwrap();
2608        };
2609
2610        // The last hop above is an index built from `span_events.parent_id`. Without
2611        // that column every lookup has to miss, which is the answer a scan of
2612        // the table would give — and emphatically not row zero, which is what
2613        // an index defaulting to the dense-id trick would hand back.
2614        strip("span_events", "parent_id");
2615        let r = find("exception.type", "NullPointerException");
2616        assert_eq!(r.stats.rows_matched, 0, "{}", r.json);
2617        assert!(
2618            !r.json.contains("span"),
2619            "an unjoinable event picked a span"
2620        );
2621        // The levels that do not go through that index are untouched, so this
2622        // is one broken join and not a broken block.
2623        assert_eq!(find("link.kind", "follows_from").stats.rows_matched, 1);
2624        assert_eq!(find("http.method", "GET").stats.rows_matched, 3);
2625
2626        // The root table without the column every scan starts from. No rows —
2627        // not the whole block unfiltered, which is what a scan that treated a
2628        // missing time column as "no time filter" would return.
2629        strip("spans", "start_time_unix_nano");
2630        let r = find("http.method", "GET");
2631        assert_eq!(r.stats.blocks_scanned, 1, "the block was still opened");
2632        assert_eq!(r.json, "[]");
2633        assert_eq!(r.stats.rows_matched, 0);
2634
2635        let _ = std::fs::remove_dir_all(&dir);
2636    }
2637
2638    /// Empty, bytes, array and map attributes come back in the row and match no
2639    /// filter, and those two halves have to stay in step.
2640    ///
2641    /// `gen_ai.input.messages` is a kvlist and is the first-class case in
2642    /// ARCHITECTURE section 1, so these are not exotic types nobody stores. V0 cannot
2643    /// order or substring-match them, and the only safe answer to a filter on
2644    /// one is *no rows*: matching everything would silently widen a query, and
2645    /// the row still carries the value so a caller can see what is there.
2646    ///
2647    /// `Op::Contains` rather than `Op::Eq` on purpose — an `Eq` term builds an
2648    /// attribute Bloom probe that prunes the block before the comparison is
2649    /// reached, so it never proves what the comparison does.
2650    #[test]
2651    fn an_attribute_v0_cannot_filter_still_renders_and_still_matches_nothing() {
2652        use mira_proto::collector::logs::v1::ExportLogsServiceRequest;
2653        use mira_proto::common::v1::any_value::Value as Av;
2654        use mira_proto::common::v1::{AnyValue, ArrayValue, KeyValue, KeyValueList};
2655        use mira_proto::logs::v1::{LogRecord, ResourceLogs, ScopeLogs};
2656
2657        let kv = |k: &str, v: Option<Av>| KeyValue {
2658            key: k.into(),
2659            value: v.map(|v| AnyValue { value: Some(v) }),
2660        };
2661        let req = ExportLogsServiceRequest {
2662            resource_logs: vec![ResourceLogs {
2663                scope_logs: vec![ScopeLogs {
2664                    log_records: vec![LogRecord {
2665                        time_unix_nano: 1_000,
2666                        attributes: vec![
2667                            // No value at all on the wire. Not an empty string,
2668                            // and not the key being absent.
2669                            kv("note", None),
2670                            kv("payload", Some(Av::BytesValue(vec![0xde, 0xad].into()))),
2671                            kv(
2672                                "tags",
2673                                Some(Av::ArrayValue(ArrayValue {
2674                                    values: vec![AnyValue {
2675                                        value: Some(Av::StringValue("a".into())),
2676                                    }],
2677                                })),
2678                            ),
2679                            kv(
2680                                "gen_ai.input.messages",
2681                                Some(Av::KvlistValue(KeyValueList {
2682                                    values: vec![kv("role", Some(Av::StringValue("user".into())))],
2683                                })),
2684                            ),
2685                            // The control: a type V0 *can* filter, carrying a
2686                            // value every probe below is a substring of.
2687                            kv("level", Some(Av::StringValue("a dead role".into()))),
2688                        ],
2689                        ..Default::default()
2690                    }],
2691                    ..Default::default()
2692                }],
2693                ..Default::default()
2694            }],
2695        };
2696
2697        let dir = std::env::temp_dir().join(format!("mira-unfilterable-{}", std::process::id()));
2698        let _ = std::fs::remove_dir_all(&dir);
2699        let mut b = crate::logs::LogsBuilder::new();
2700        b.append_request(&req).unwrap();
2701        let sealed = b.finish().unwrap();
2702        crate::block::publish(&dir, "logs", crate::block::node_id("a"), 0, 0, &sealed).unwrap();
2703
2704        let scan = |terms: Vec<Term>| {
2705            search(
2706                &dir,
2707                &Search {
2708                    signal: Signal::Logs,
2709                    from: 0,
2710                    to: i64::MAX,
2711                    terms,
2712                    limit: 10,
2713                    after: None,
2714                    cursors: false,
2715                },
2716            )
2717            .unwrap()
2718        };
2719        let contains = |k: &str, v: &str| {
2720            vec![Term {
2721                target: Target::Attr(k.into()),
2722                op: Op::Contains,
2723                value: Value::Str(v.into()),
2724            }]
2725        };
2726
2727        // The same operator and a probe that really is inside the stored value,
2728        // so a zero here is the attribute's *type* and not the operator or the
2729        // needle.
2730        assert_eq!(scan(contains("level", "dead")).stats.rows_matched, 1);
2731        for (key, needle) in [
2732            ("note", ""),
2733            ("payload", "dead"),
2734            ("tags", "a"),
2735            ("gen_ai.input.messages", "role"),
2736        ] {
2737            let r = scan(contains(key, needle));
2738            assert_eq!(r.stats.rows_matched, 0, "{key}: {}", r.json);
2739            // The block was opened and the comparison really ran: a zero that
2740            // came from the sidecar pruning the block would prove nothing about
2741            // what the comparison decides.
2742            assert_eq!(r.stats.blocks_scanned, 1, "{key}");
2743        }
2744
2745        // And every one of them is still in the row. An empty attribute renders
2746        // as `null`, which is what "the key arrived with no value" means — the
2747        // key disappearing would be a different statement.
2748        let row = scan(Vec::new()).json;
2749        assert!(row.contains(r#""note":null"#), "{row}");
2750        assert!(row.contains(r#""payload":"dead""#), "{row}");
2751        assert!(row.contains(r#""tags":["a"]"#), "{row}");
2752        assert!(
2753            row.contains(r#""gen_ai.input.messages":{"role":"user"}"#),
2754            "{row}"
2755        );
2756
2757        // The index that turns a child id into a root row, on a table that has
2758        // neither column: empty, so every lookup misses. The alternative — a
2759        // vector sized off whichever column *is* present — would join rows to
2760        // whatever happened to sit at that slot.
2761        let ids = Arc::new(UInt32Array::from(vec![0u32, 1])) as Arc<dyn Array>;
2762        let only_ids = RecordBatch::try_from_iter(vec![("id", ids.clone())]).unwrap();
2763        let only_parents = RecordBatch::try_from_iter(vec![("parent_id", ids)]).unwrap();
2764        assert!(index_parent_of_id(&only_ids).is_empty());
2765        assert!(index_parent_of_id(&only_parents).is_empty());
2766
2767        let _ = std::fs::remove_dir_all(&dir);
2768    }
2769
2770    /// `rows_matched` is a property of the query, not of the page.
2771    ///
2772    /// The UI prints it next to the page and the MCP tool hands it to a model as
2773    /// "how much there was", so a number that counts rows an earlier page
2774    /// already delivered reads as a result set that grows as you page through
2775    /// it.
2776    #[test]
2777    fn rows_matched_counts_what_is_left_behind_the_cursor() {
2778        use mira_proto::collector::logs::v1::ExportLogsServiceRequest;
2779        use mira_proto::common::v1::any_value::Value as Av;
2780        use mira_proto::common::v1::{AnyValue, InstrumentationScope};
2781        use mira_proto::logs::v1::{LogRecord, ResourceLogs, ScopeLogs};
2782
2783        let base = 1_700_000_000_000_000_000u64;
2784        let req = ExportLogsServiceRequest {
2785            resource_logs: vec![ResourceLogs {
2786                scope_logs: vec![ScopeLogs {
2787                    scope: Some(InstrumentationScope {
2788                        name: "mira.test".into(),
2789                        ..Default::default()
2790                    }),
2791                    log_records: (0..5)
2792                        .map(|i| LogRecord {
2793                            time_unix_nano: base + i * 1_000_000_000,
2794                            body: Some(AnyValue {
2795                                value: Some(Av::StringValue(format!("line {i}"))),
2796                            }),
2797                            ..Default::default()
2798                        })
2799                        .collect(),
2800                    ..Default::default()
2801                }],
2802                ..Default::default()
2803            }],
2804        };
2805
2806        let dir = std::env::temp_dir().join(format!("mira-paged-count-{}", std::process::id()));
2807        let _ = std::fs::remove_dir_all(&dir);
2808        let mut b = crate::logs::LogsBuilder::new();
2809        b.append_request(&req).unwrap();
2810        let sealed = b.finish().unwrap();
2811        crate::block::publish(&dir, "logs", crate::block::node_id("a"), 0, 0, &sealed).unwrap();
2812
2813        let page = |after: Option<Cursor>| {
2814            search(
2815                &dir,
2816                &Search {
2817                    signal: Signal::Logs,
2818                    from: 0,
2819                    to: i64::MAX,
2820                    terms: Vec::new(),
2821                    limit: 2,
2822                    after,
2823                    cursors: false,
2824                },
2825            )
2826            .unwrap()
2827        };
2828
2829        // Five rows, two per page. Each page reports what is still ahead of the
2830        // reader including the rows it is holding, so the sequence falls by the
2831        // page size and the last page is exact rather than being the whole
2832        // block over again.
2833        let mut cursor = None;
2834        for want in [5, 3, 1] {
2835            let r = page(cursor);
2836            assert_eq!(r.stats.rows_matched, want, "{}", r.json);
2837            cursor = r.next;
2838        }
2839        // A short page is the last page, so there is nothing to ask for again.
2840        assert_eq!(cursor, None);
2841
2842        let _ = std::fs::remove_dir_all(&dir);
2843    }
2844
2845    /// [`keep`] is three loops where there used to be one boxed closure, and
2846    /// only one of them is reachable from a full selection — so the thing to
2847    /// pin is that all three answer the same question.
2848    ///
2849    /// The contiguous branch-free loop is taken when the column has no nulls
2850    /// *and* nothing has narrowed the selection yet; a second term on the same
2851    /// block, or any null at all, gathers through `sel` instead. Every
2852    /// column-type case above enters through the first of those, which is
2853    /// exactly why the other two need their own test.
2854    #[test]
2855    fn narrowing_a_selection_agrees_with_scanning_one_whole() {
2856        let plain = Int64Array::from(vec![1, 2, 3, 4, 5, 6]);
2857        let holed = Int64Array::from(vec![Some(1), None, Some(3), Some(4), None, Some(6)]);
2858        let gt2 = |sel: &mut Vec<u32>, col: &dyn Array| {
2859            assert!(field_filter(sel, col, Op::Gt, &Value::Int(2)));
2860        };
2861
2862        let mut sel: Vec<u32> = (0..6).collect();
2863        gt2(&mut sel, &plain);
2864        assert_eq!(sel, [2, 3, 4, 5], "whole block, no nulls");
2865
2866        let mut sel = vec![1, 3, 5];
2867        gt2(&mut sel, &plain);
2868        assert_eq!(sel, [3, 5], "already narrowed by an earlier term");
2869
2870        let mut sel: Vec<u32> = (0..6).collect();
2871        gt2(&mut sel, &holed);
2872        assert_eq!(sel, [2, 3, 5], "a null is not a match, whole block");
2873
2874        let mut sel = vec![1, 3, 4];
2875        gt2(&mut sel, &holed);
2876        assert_eq!(sel, [3], "a null is not a match, narrowed");
2877
2878        // Nothing selected stays nothing selected — the length test that picks
2879        // the fast path must not read an empty selection as a full one.
2880        let mut sel: Vec<u32> = Vec::new();
2881        gt2(&mut sel, &plain);
2882        assert!(sel.is_empty());
2883
2884        // A refusal writes nothing: `select` clears the selection itself, and
2885        // a half-filtered one left behind would be an answer, not an empty
2886        // result.
2887        let mut sel: Vec<u32> = (0..6).collect();
2888        assert!(!field_filter(
2889            &mut sel,
2890            &plain,
2891            Op::Eq,
2892            &Value::Str("beta".into())
2893        ));
2894        assert_eq!(sel.len(), 6);
2895
2896        // And the same both ways round: a number against a dictionary column
2897        // has no encoding to look up, so it is a refusal rather than a miss.
2898        // `severity_text: 2` must not quietly mean "no logs", which is what a
2899        // plain `false` per row would have made it.
2900        let mut d = StringDictionaryBuilder::<UInt16Type>::new();
2901        d.append_value("warn");
2902        d.append_value("info");
2903        let dict = d.finish();
2904        let mut sel: Vec<u32> = (0..2).collect();
2905        assert!(!field_filter(&mut sel, &dict, Op::Eq, &Value::Int(2)));
2906        assert_eq!(sel.len(), 2);
2907    }
2908
2909    /// Rendering a row binary-searches its attributes, which is only right
2910    /// because every builder appends parents in ascending order.
2911    ///
2912    /// A table that is not in that order has to keep working, and the reason is
2913    /// the failure mode rather than the likelihood: a binary search over
2914    /// unsorted parents does not fail, it returns some of the rows, and an
2915    /// attribute quietly missing from a response is what nobody would notice.
2916    #[test]
2917    fn an_attribute_table_out_of_parent_order_falls_back_to_the_scan() {
2918        let table = |parents: &'static [u32]| {
2919            let mut b = crate::attrs::AttrsBuilder::new("t.key");
2920            for &p in parents {
2921                b.append(p, "k", None).unwrap();
2922            }
2923            let a = Attrs::new(b.finish().unwrap());
2924            // The slice `run` is handed below is the caller's own, so pin it to
2925            // the column the builder actually wrote before trusting it.
2926            assert_eq!(Attrs::parents(&a.rows), Some(parents));
2927            (a, parents)
2928        };
2929
2930        let (ordered, p) = table(&[0, 0, 1, 3, 3]);
2931        assert!(ordered.ordered);
2932        assert_eq!(ordered.run(p, 0), 0..2);
2933        assert_eq!(ordered.run(p, 1), 2..3);
2934        // A parent with no attributes of its own, and one past the end: both
2935        // are empty runs rather than a panic or somebody else's rows.
2936        assert_eq!(ordered.run(p, 2), 3..3);
2937        assert_eq!(ordered.run(p, 9), 5..5);
2938
2939        let (jumbled, p) = table(&[3, 0, 1, 0, 3]);
2940        assert!(!jumbled.ordered);
2941        // The whole table, which the caller still filters row by row — the
2942        // scan this replaced, reached only by a block nothing here writes.
2943        assert_eq!(jumbled.run(p, 0), 0..5);
2944
2945        // An empty table is ordered by vacuous truth and has no rows for
2946        // anyone, which is the same answer either way.
2947        let (empty, p) = table(&[]);
2948        assert_eq!(empty.run(p, 0), 0..0);
2949    }
2950
2951    /// One log block of `rows` records, through the real encoder, held in
2952    /// memory as an [`Open`] snapshot so a scan of it touches no file.
2953    fn bench_block(rows: usize) -> Open {
2954        use mira_proto::collector::logs::v1::ExportLogsServiceRequest;
2955        use mira_proto::common::v1::{InstrumentationScope, KeyValue, any_value};
2956        use mira_proto::logs::v1::{LogRecord, ResourceLogs, ScopeLogs};
2957        use mira_proto::resource::v1::Resource;
2958
2959        let sv = |k: &str, v: &str| KeyValue {
2960            key: k.into(),
2961            value: Some(AnyValue {
2962                value: Some(any_value::Value::StringValue(v.into())),
2963            }),
2964        };
2965        const SEV: [(i32, &str); 4] = [(5, "DEBUG"), (9, "INFO"), (13, "WARN"), (17, "ERROR")];
2966        const ROUTES: [&str; 6] = [
2967            "/checkout",
2968            "/cart",
2969            "/search",
2970            "/api/v1/orders",
2971            "/healthz",
2972            "/metrics",
2973        ];
2974
2975        let mut b = crate::logs::LogsBuilder::new();
2976        let mut done = 0usize;
2977        while done < rows {
2978            let take = (rows - done).min(8192);
2979            let log_records = (0..take)
2980                .map(|k| {
2981                    let i = done + k;
2982                    LogRecord {
2983                        time_unix_nano: 1_700_000_000_000_000_000 + i as u64 * 1_000,
2984                        severity_number: SEV[i % 4].0,
2985                        severity_text: SEV[i % 4].1.into(),
2986                        body: Some(AnyValue {
2987                            value: Some(any_value::Value::StringValue(format!(
2988                                "GET /api/v1/orders/{i} -> 200 in {}ms for tenant t{}",
2989                                i % 997,
2990                                i % 64
2991                            ))),
2992                        }),
2993                        attributes: vec![
2994                            sv("http.route", ROUTES[i % ROUTES.len()]),
2995                            KeyValue {
2996                                key: "http.status_code".into(),
2997                                value: Some(AnyValue {
2998                                    value: Some(any_value::Value::IntValue(
2999                                        200 + (i % 5) as i64 * 100,
3000                                    )),
3001                                }),
3002                            },
3003                        ],
3004                        ..Default::default()
3005                    }
3006                })
3007                .collect();
3008            b.append_request(&ExportLogsServiceRequest {
3009                resource_logs: vec![ResourceLogs {
3010                    resource: Some(Resource {
3011                        attributes: vec![sv("service.name", "checkout"), sv("env", "prod")],
3012                        ..Default::default()
3013                    }),
3014                    scope_logs: vec![ScopeLogs {
3015                        scope: Some(InstrumentationScope {
3016                            name: "http".into(),
3017                            attributes: vec![sv("tier", "gold")],
3018                            ..Default::default()
3019                        }),
3020                        log_records,
3021                        ..Default::default()
3022                    }],
3023                    ..Default::default()
3024                }],
3025            })
3026            .unwrap();
3027            done += take;
3028        }
3029        Open {
3030            node: 1,
3031            seq: 1,
3032            sealed: b.finish().unwrap(),
3033        }
3034    }
3035
3036    /// What one row of one block costs to filter, per predicate kind, with no
3037    /// paging and no CRC in the number.
3038    ///
3039    /// Scaled rather than `#[ignore]`d: the default 4096 rows run in the normal
3040    /// suite, so every line here is a covered correctness check on the six
3041    /// predicate shapes, and the same code is the measurement at a real row
3042    /// count.
3043    ///
3044    /// ```sh
3045    /// MIRA_BENCH_ROWS=2000000 cargo test --release -p miradb-core \
3046    ///     --lib scan_cost_per_row -- --nocapture
3047    /// ```
3048    #[test]
3049    fn scan_cost_per_row() {
3050        let rows: usize = std::env::var("MIRA_BENCH_ROWS")
3051            .ok()
3052            .and_then(|s| s.parse().ok())
3053            .unwrap_or(4_096);
3054        let open = bench_block(rows);
3055        let (lo, hi) = (open.sealed.min_ts, open.sealed.max_ts);
3056        let src = Src::open(&open);
3057        let mut b = Block::open(&src, Signal::Logs).unwrap().unwrap();
3058        // Half the cases below are attribute predicates, which `scan_one` would
3059        // have loaded the tables for before calling `select`. This measures
3060        // `select`, so it does the same thing by hand.
3061        b.detail(&src).unwrap();
3062        let n = b.root.num_rows();
3063        assert_eq!(n, rows);
3064
3065        let all = |terms: Vec<Term>| Search {
3066            signal: Signal::Logs,
3067            from: 0,
3068            to: i64::MAX,
3069            terms,
3070            limit: 100,
3071            after: None,
3072            cursors: false,
3073        };
3074        let field = |name: &str, op, value| {
3075            all(vec![Term {
3076                target: Target::Field(name.into()),
3077                op,
3078                value,
3079            }])
3080        };
3081        let attr = |key: &str, op, value| {
3082            all(vec![Term {
3083                target: Target::Attr(key.into()),
3084                op,
3085                value,
3086            }])
3087        };
3088        let cases: Vec<(&str, Search)> = vec![
3089            ("no term (whole block)", all(Vec::new())),
3090            (
3091                "time range (per-row)",
3092                Search {
3093                    from: lo + (hi - lo) / 4,
3094                    to: hi,
3095                    ..all(Vec::new())
3096                },
3097            ),
3098            (
3099                "int field  severity_number gte",
3100                field("severity_number", Op::Gte, Value::Int(9)),
3101            ),
3102            (
3103                "utf8 field body contains",
3104                field("body", Op::Contains, Value::Str("tenant t7".into())),
3105            ),
3106            (
3107                "dict field severity_text eq",
3108                field("severity_text", Op::Eq, Value::Str("ERROR".into())),
3109            ),
3110            (
3111                "attr record http.route eq",
3112                attr("http.route", Op::Eq, Value::Str("/checkout".into())),
3113            ),
3114            (
3115                "attr record http.status_code gte",
3116                attr("http.status_code", Op::Gte, Value::Int(500)),
3117            ),
3118            (
3119                "attr resource service.name eq",
3120                attr("service.name", Op::Eq, Value::Str("checkout".into())),
3121            ),
3122        ];
3123
3124        let reps = if rows > 100_000 { 5 } else { 1 };
3125        for (name, s) in &cases {
3126            let hit = b.select(s, &src).len();
3127            let t = std::time::Instant::now();
3128            for _ in 0..reps {
3129                std::hint::black_box(b.select(s, &src));
3130            }
3131            let ns = t.elapsed().as_nanos() as f64 / (reps * n) as f64;
3132            println!("{name:34} {ns:8.3} ns/row  {hit} of {n}");
3133            assert!(hit > 0, "{name} matched nothing");
3134        }
3135
3136        // And the same block through the whole read path, published and warm,
3137        // so `select` can be read as a fraction of what a query actually costs.
3138        // Everything outside it — the mmap's minor faults, the CRC32 of every
3139        // table body, the dictionary scan, `Block::open`'s two child indexes,
3140        // the cursor filter and the JSON of `limit` rows — is the "no term"
3141        // line, and that is the claim in docs/architecture/performance.md section 11 that
3142        // the per-block cost is paging rather than scanning.
3143        //
3144        // Measured twice, because the CRC is the larger half and it is paid
3145        // once per file per process rather than once per open (`block::
3146        // VERIFIED`). A block published a moment ago is inside the settle
3147        // window and re-verifies on every open, which is the first pass; the
3148        // second backdates the files to what a block even a minute old looks
3149        // like, and the difference between the two columns *is* the checksum.
3150        let dir = std::env::temp_dir().join(format!("mira-scan-cost-{}", std::process::id()));
3151        let _ = std::fs::remove_dir_all(&dir);
3152        let bref = crate::block::publish(&dir, "logs", 1, 1, 0, &open.sealed).unwrap();
3153        let one = (
3154            "no term, limit 1",
3155            Search {
3156                limit: 1,
3157                ..all(Vec::new())
3158            },
3159        );
3160        let picks = [&cases[0], &one, &cases[3], &cases[5]];
3161        let time_all = || {
3162            picks.map(|(name, s)| {
3163                let _ = search(&dir, s).unwrap();
3164                let t = std::time::Instant::now();
3165                for _ in 0..reps {
3166                    std::hint::black_box(search(&dir, s).unwrap());
3167                }
3168                (*name, t.elapsed().as_nanos() as f64 / (reps * n) as f64)
3169            })
3170        };
3171        let verifying = time_all();
3172        // Taken while every open still checksums, so the comparison below is
3173        // verified-read against cached-read and not cached against itself.
3174        let want: Vec<String> = picks
3175            .iter()
3176            .map(|(_, s)| search(&dir, s).unwrap().json)
3177            .collect();
3178
3179        // Backdating rather than sleeping out the window: the default 4,096-row
3180        // size of this test runs in `make test`, and two seconds of nothing is
3181        // not a thing to put in the normal suite.
3182        let old = std::time::SystemTime::now() - std::time::Duration::from_secs(3600);
3183        for f in std::fs::read_dir(&bref.dir).unwrap() {
3184            std::fs::File::options()
3185                .write(true)
3186                .open(f.unwrap().path())
3187                .unwrap()
3188                .set_times(std::fs::FileTimes::new().set_modified(old))
3189                .unwrap();
3190        }
3191        let settled = time_all();
3192
3193        // The share is measured; a rate would not be. Dividing the saved time by
3194        // the block's bytes gives 26-30 GB/s here, which is not `crc32fast`
3195        // being five times its documented speed — it is this denominator being
3196        // wrong twice over. `Block::open` does not load every table in the
3197        // directory, and a block this size sits in cache where the multi-GiB
3198        // corpus that produced the old 5.2 GB/s figure does not — that corpus
3199        // is bound by page cache, which is what made 885 ms look like a
3200        // checksum rate. So print what was timed and let the corpus
3201        // measurement be the corpus measurement.
3202        let bytes: u64 = std::fs::read_dir(&bref.dir)
3203            .unwrap()
3204            .map(|f| f.unwrap().metadata().unwrap().len())
3205            .sum();
3206        println!(
3207            "  block on disk: {:.1} MiB over {n} rows, {:.0} bytes/row",
3208            bytes as f64 / (1024.0 * 1024.0),
3209            bytes as f64 / n as f64,
3210        );
3211        for ((name, was), (_, now)) in verifying.iter().zip(&settled) {
3212            println!(
3213                "  full search: {name:21} {was:8.3} -> {now:8.3} ns/row  {:.2}x  \
3214                 checksum {:4.1}% of the read path",
3215                was / now,
3216                100.0 * (was - now) / was,
3217            );
3218        }
3219        // The correctness half, and the reason this is not `#[ignore]`d: a
3220        // skipped checksum must not change a single answer.
3221        for ((name, s), want) in picks.iter().zip(&want) {
3222            assert_eq!(
3223                &search(&dir, s).unwrap().json,
3224                want,
3225                "{name} read differently once its tables were cached"
3226            );
3227        }
3228        let _ = std::fs::remove_dir_all(&dir);
3229    }
3230}