Skip to main content

mira_core/
lib.rs

1//! Mira storage engine.
2//!
3//! Three layers, in dependency order:
4//!
5//! * [`schema`] — the OTAP-shaped Arrow schemas that are simultaneously the
6//!   in-memory and the on-disk layout. There is no translation step.
7//! * [`identity`] — the stable entity key that correlation joins on.
8//! * [`attrs`] — the attribute tables and Resource-Scope preamble every signal
9//!   shares.
10//! * [`signal`] — the one shape every signal's encoder presents to the flusher.
11//! * [`logs`] / [`traces`] / [`metrics`] — OTLP protobuf into those schemas,
12//!   with block-local id rebasing.
13//! * [`block`] — atomic publish of immutable block directories and zero-copy
14//!   mmap reads back out of them.
15//!
16//! See `docs/architecture/` for why each of those is shaped the way it is.
17
18#![deny(unsafe_op_in_unsafe_fn)]
19
20pub mod attrs;
21pub mod block;
22pub mod bloom;
23pub mod diag;
24pub mod error;
25pub mod frame;
26pub mod identity;
27pub mod json;
28pub mod logs;
29pub mod metrics;
30pub mod offload;
31pub mod query;
32pub mod schema;
33pub mod series;
34pub mod signal;
35pub mod traces;
36pub mod wal;
37pub mod zone;
38
39pub use error::{Error, Result};
40pub use signal::{Sealed, SignalBuilder};
41
42/// Backs [`degraded_syncs`].
43static DEGRADED_SYNCS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
44
45/// How many syncs have fallen back to `fsync(2)`.
46///
47/// Zero on a volume that implements write barriers, which is every volume Mira
48/// is meant to run on. Non-zero means the durability promise on this node is
49/// weaker than the one [`sync_all`] documents, and it is reported by
50/// `/api/v1/stats` so that is a fact an operator can see rather than infer.
51pub fn degraded_syncs() -> u64 {
52    DEGRADED_SYNCS.load(std::sync::atomic::Ordering::Relaxed)
53}
54
55/// `File::sync_all`, with the fallback Apple targets need and `std` does not do.
56///
57/// On an Apple target both `sync_all` and `sync_data` compile to
58/// `fcntl(F_FULLFSYNC)` — std's `os_fsync`/`os_datasync` in `sys/fs/unix.rs`,
59/// with no error handling around the `fcntl` beyond `cvt_r`. That is the
60/// correct barrier and it is why an ack is not an fsync (section 4), but not
61/// every filesystem implements it: a Docker Desktop bind mount is FUSE and
62/// answers `ENOTSUP`, and some network volumes answer `EINVAL`. std turns
63/// either into an error, so a publish that a plain `fsync(2)` would have
64/// satisfied fails instead, and the node goes unready over a volume that works.
65///
66/// So: try the barrier, and on exactly those two errnos degrade to `fsync` and
67/// count it. Counting is the whole point — a fallback nobody can see is silent
68/// durability loss, which is worse than the failure it replaces.
69pub fn sync_all(file: &std::fs::File) -> std::io::Result<()> {
70    sync_with(file, std::fs::File::sync_all)
71}
72
73/// `File::sync_data`, degrading the same way [`sync_all`] does.
74pub fn sync_data(file: &std::fs::File) -> std::io::Result<()> {
75    sync_with(file, std::fs::File::sync_data)
76}
77
78/// The seam the two above share, and the one a test can drive: `strong` is the
79/// barrier that might not be supported, and there is no way to make a real
80/// filesystem refuse `F_FULLFSYNC` on demand inside a unit test.
81#[cfg(not(all(target_vendor = "apple", feature = "weak-sync-ab")))]
82fn sync_with(
83    file: &std::fs::File,
84    strong: impl Fn(&std::fs::File) -> std::io::Result<()>,
85) -> std::io::Result<()> {
86    match strong(file) {
87        Ok(()) => Ok(()),
88        Err(e) => degrade(file, e),
89    }
90}
91
92/// ponytail: measurement arm, never a release. `weak-sync-ab` replaces every
93/// barrier in the tree with a plain `fsync(2)` so the device-barrier term can
94/// be priced end to end against an otherwise identical binary
95/// (`scripts/measure/ab.sh`; the answer is in performance-barrier.md).
96/// It trades the power-loss guarantee `sync_all` documents, so it is a
97/// compile-time feature and not a config key or an environment variable: a
98/// released binary has no code path that reaches it, and `--features` is
99/// visible in the build line of whoever measured.
100#[cfg(all(target_vendor = "apple", feature = "weak-sync-ab"))]
101fn sync_with(
102    file: &std::fs::File,
103    _strong: impl Fn(&std::fs::File) -> std::io::Result<()>,
104) -> std::io::Result<()> {
105    use std::os::fd::AsRawFd;
106    // SAFETY: `file` owns the descriptor and outlives the call.
107    match unsafe { libc::fsync(file.as_raw_fd()) } {
108        0 => Ok(()),
109        _ => Err(std::io::Error::last_os_error()),
110    }
111}
112
113#[cfg(all(target_vendor = "apple", not(feature = "weak-sync-ab")))]
114fn degrade(file: &std::fs::File, e: std::io::Error) -> std::io::Result<()> {
115    use std::os::fd::AsRawFd;
116    if !matches!(e.raw_os_error(), Some(libc::ENOTSUP | libc::EINVAL)) {
117        return Err(e);
118    }
119    // SAFETY: `file` owns the descriptor and outlives the call.
120    if unsafe { libc::fsync(file.as_raw_fd()) } != 0 {
121        return Err(std::io::Error::last_os_error());
122    }
123    DEGRADED_SYNCS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
124    Ok(())
125}
126
127/// Everywhere else `sync_all` is already `fsync`, so there is nothing to
128/// degrade to and an error is an error.
129#[cfg(not(target_vendor = "apple"))]
130fn degrade(_file: &std::fs::File, e: std::io::Error) -> std::io::Result<()> {
131    Err(e)
132}
133
134// Not under `weak-sync-ab`: that arm deletes the barrier these assert on.
135#[cfg(all(test, not(feature = "weak-sync-ab")))]
136mod sync_tests {
137    use super::*;
138    use std::io::Error;
139
140    /// One test, not three, because the counter is process-global and
141    /// `cargo test` runs a crate's tests on many threads: three tests each
142    /// asserting a delta on one counter is a race, and the first draft of this
143    /// module was exactly that. No `tempfile` either — the dependency budget is
144    /// a product property (`docs/architecture/performance.md` section 11) for one file.
145    #[test]
146    fn the_barrier_runs_and_only_enotsup_degrades() {
147        let path = std::env::temp_dir().join(format!("mira-sync-{}", std::process::id()));
148        let file = std::fs::File::create(&path).expect("create");
149
150        // A real volume has the barrier, so nothing degrades.
151        sync_all(&file).expect("sync_all");
152        sync_data(&file).expect("sync_data");
153        assert_eq!(degraded_syncs(), 0, "a real volume degrades nothing");
154
155        // EIO is a write that failed, not a feature that is missing.
156        let e = sync_with(&file, |_| Err(Error::from_raw_os_error(libc::EIO)))
157            .expect_err("EIO must not be swallowed");
158        assert_eq!(e.raw_os_error(), Some(libc::EIO));
159
160        // No errno at all — a `std` error that never came from the kernel.
161        let e = sync_with(&file, |_| Err(Error::other("synthetic")))
162            .expect_err("no errno, no fallback");
163        assert!(e.raw_os_error().is_none());
164        assert_eq!(degraded_syncs(), 0, "neither of those is a missing barrier");
165
166        // The whole point of the wrapper, and the only way to reach the
167        // fallback: `strong` refuses the way a FUSE mount refuses, `fsync(2)`
168        // on the real descriptor underneath still works, and the counter says
169        // it happened. Elsewhere `sync_all` is already `fsync`, so there is
170        // nothing to degrade to and every errno stays an error.
171        for (i, errno) in [libc::ENOTSUP, libc::EINVAL].into_iter().enumerate() {
172            let r = sync_with(&file, |_| Err(Error::from_raw_os_error(errno)));
173            if cfg!(target_vendor = "apple") {
174                r.unwrap_or_else(|e| panic!("errno {errno} should have degraded, got {e}"));
175                assert_eq!(degraded_syncs(), i as u64 + 1);
176            } else {
177                assert_eq!(
178                    r.expect_err("no fallback off Apple").raw_os_error(),
179                    Some(errno)
180                );
181                assert_eq!(degraded_syncs(), 0);
182            }
183        }
184
185        let _ = std::fs::remove_file(&path);
186    }
187}
188
189#[cfg(test)]
190mod tests {
191    use super::*;
192    use arrow_array::{Array, StringArray, UInt32Array, UInt64Array};
193    use mira_proto::collector::logs::v1::ExportLogsServiceRequest;
194    use mira_proto::common::v1::{AnyValue, InstrumentationScope, KeyValue, any_value::Value};
195    use mira_proto::logs::v1::{LogRecord, ResourceLogs, ScopeLogs};
196    use mira_proto::resource::v1::Resource;
197
198    fn kv(k: &str, v: &str) -> KeyValue {
199        KeyValue {
200            key: k.into(),
201            value: Some(AnyValue {
202                value: Some(Value::StringValue(v.into())),
203            }),
204        }
205    }
206
207    fn request(service: &str, n: usize, base_ts: u64) -> ExportLogsServiceRequest {
208        request_from(service, &[], n, base_ts)
209    }
210
211    /// `extra` carries non-identifying resource attributes, so that a caller can
212    /// simulate an exporter that starts reporting more about the same instance.
213    fn request_from(
214        service: &str,
215        extra: &[KeyValue],
216        n: usize,
217        base_ts: u64,
218    ) -> ExportLogsServiceRequest {
219        let mut attributes = vec![
220            kv("service.name", service),
221            kv("service.instance.id", "7f3a"),
222        ];
223        attributes.extend_from_slice(extra);
224        ExportLogsServiceRequest {
225            resource_logs: vec![ResourceLogs {
226                resource: Some(Resource {
227                    attributes,
228                    ..Default::default()
229                }),
230                scope_logs: vec![ScopeLogs {
231                    scope: Some(InstrumentationScope {
232                        name: "test".into(),
233                        ..Default::default()
234                    }),
235                    log_records: (0..n)
236                        .map(|i| LogRecord {
237                            time_unix_nano: base_ts + i as u64,
238                            severity_number: 9,
239                            severity_text: "INFO".into(),
240                            body: Some(AnyValue {
241                                value: Some(Value::StringValue(format!("line {i}"))),
242                            }),
243                            attributes: vec![kv("http.method", "GET")],
244                            trace_id: vec![7u8; 16].into(),
245                            span_id: vec![3u8; 8].into(),
246                            ..Default::default()
247                        })
248                        .collect(),
249                    ..Default::default()
250                }],
251                ..Default::default()
252            }],
253        }
254    }
255
256    /// The load-bearing property of the whole engine: what we write, we can read
257    /// back out of a mapping with zero buffer copies. If this fails, Mira is just
258    /// another columnar store with an extra memcpy.
259    #[test]
260    fn roundtrip_is_zero_copy_and_prunable() {
261        let root = std::env::temp_dir().join(format!("mira-test-{}", std::process::id()));
262        let _ = std::fs::remove_dir_all(&root);
263
264        let mut b = logs::LogsBuilder::new();
265        // Two identical requests from the same service: interned once.
266        assert_eq!(
267            b.append_request(&request("checkout", 500, 1_000)).unwrap(),
268            500
269        );
270        assert_eq!(
271            b.append_request(&request("checkout", 500, 2_000)).unwrap(),
272            500
273        );
274        // Same instance, now reporting one more non-identifying attribute. A
275        // second resource row, but it must NOT be a second entity.
276        assert_eq!(
277            b.append_request(&request_from(
278                "checkout",
279                &[kv("k8s.node.name", "node-4")],
280                100,
281                3_000
282            ))
283            .unwrap(),
284            100
285        );
286        assert_eq!(
287            b.append_request(&request("payments", 100, 3_100)).unwrap(),
288            100
289        );
290
291        let sealed = b.finish().unwrap();
292        assert_eq!(sealed.num_rows, 1200);
293        assert_eq!(sealed.min_ts, 1_000);
294        assert_eq!(sealed.max_ts, 3_199);
295        // Every table the on-disk format promises, named exactly as its file.
296        assert_eq!(
297            sealed.tables.iter().map(|(n, _)| *n).collect::<Vec<_>>(),
298            schema::LOGS_BLOCK_TABLES
299        );
300        let rows = |t: &str| sealed.table(t).unwrap().num_rows();
301        // checkout(2 attrs) + checkout-with-node(3) + payments(2).
302        assert_eq!(rows("resources"), 3);
303        assert_eq!(rows("resource_attrs"), 7);
304        assert_eq!(rows("scope_attrs"), 1);
305        assert_eq!(rows("log_attrs"), 1200);
306
307        // The load-bearing correlation invariant: attribute drift does not fork
308        // an entity. Three resource rows, two entities.
309        let keys = sealed
310            .table("resources")
311            .unwrap()
312            .column_by_name("key")
313            .unwrap()
314            .as_any()
315            .downcast_ref::<UInt64Array>()
316            .unwrap();
317        assert_eq!(
318            keys.value(0),
319            keys.value(1),
320            "attribute drift must not fork the entity"
321        );
322        assert_ne!(keys.value(0), keys.value(2));
323
324        let node = block::node_id("replica-a");
325        let published = block::publish(&root, "logs", node, 1, 0, &sealed).unwrap();
326        assert_eq!(published.node, node);
327        // A second replica publishing the same time range must not collide.
328        assert_ne!(node, block::node_id("replica-b"));
329
330        // Catalog comes back from directory names alone — no file opened.
331        let catalog = block::scan(&root, "logs").unwrap();
332        assert_eq!(catalog, vec![published.clone()]);
333        assert!(catalog[0].overlaps(0, 1_500));
334        assert!(!catalog[0].overlaps(10_000, 20_000));
335
336        // Zero-copy read back. require_alignment(true) is on inside open_table,
337        // so this call errors rather than silently copying.
338        let logs = block::open_table(&published.dir.join("logs.arrow")).unwrap();
339        assert_eq!(logs.batches.len(), 1);
340        let rb = &logs.batches[0];
341        assert_eq!(rb.num_rows(), 1200);
342
343        // THE load-bearing invariant: every buffer of every column points into
344        // the mapping. If this ever drops below n/n, Mira has silently become a
345        // store that memcpies its whole working set on every read.
346        let (inside, total) = logs.zero_copy_ratio();
347        assert_eq!(inside, total, "{inside}/{total} buffers zero-copy");
348        assert!(total >= 13, "expected one buffer per column at least");
349
350        let ids = rb
351            .column_by_name("id")
352            .unwrap()
353            .as_any()
354            .downcast_ref::<UInt32Array>()
355            .unwrap();
356        assert_eq!(ids.value(0), 0);
357        assert_eq!(ids.value(1199), 1199, "ids must be dense and block-local");
358
359        let body = rb
360            .column_by_name("body")
361            .unwrap()
362            .as_any()
363            .downcast_ref::<StringArray>()
364            .unwrap();
365        assert_eq!(body.value(0), "line 0");
366
367        // A join inside a block is safe precisely because ids were rebased.
368        let attrs = block::open_table(&published.dir.join("log_attrs.arrow")).unwrap();
369        let parents = attrs.batches[0]
370            .column_by_name("parent_id")
371            .unwrap()
372            .as_any()
373            .downcast_ref::<UInt32Array>()
374            .unwrap();
375        assert_eq!(parents.value(1199), 1199);
376
377        // Retention is an unlink of the directory.
378        assert_eq!(block::expire(&root, "logs", 10_000).unwrap(), 1);
379        assert!(block::scan(&root, "logs").unwrap().is_empty());
380
381        let _ = std::fs::remove_dir_all(&root);
382    }
383
384    /// The two inputs to the seal decision. Both were wrong in ways that only
385    /// show up in production: a block sized by row count alone balloons on large
386    /// bodies, and a dictionary discovered full mid-append leaves a half-written
387    /// row that fails every subsequent flush.
388    #[test]
389    fn seal_decision_sees_bodies_and_dictionary_pressure() {
390        let mut small = logs::LogsBuilder::new();
391        small
392            .append_request(&request("checkout", 100, 1_000))
393            .unwrap();
394
395        let prompt = "x".repeat(32 << 10);
396        let mut req = request("checkout", 100, 1_000);
397        for sl in &mut req.resource_logs[0].scope_logs {
398            for r in &mut sl.log_records {
399                r.body = Some(AnyValue {
400                    value: Some(Value::StringValue(prompt.clone())),
401                });
402            }
403        }
404        let mut big = logs::LogsBuilder::new();
405        big.append_request(&req).unwrap();
406        // Same row count, same schema, three orders of magnitude apart. Counting
407        // fixed-width columns only would make these two numbers equal.
408        assert!(small.approx_bytes() < 64 << 10, "{}", small.approx_bytes());
409        assert!(big.approx_bytes() > 3 << 20, "{}", big.approx_bytes());
410
411        // A request wider than an empty block's dictionary is refused headroom
412        // up front, not discovered part way through an append.
413        let mut wide = request("checkout", 1, 1_000);
414        wide.resource_logs[0].scope_logs[0].log_records[0].attributes = (0..=schema::DICT_CAP)
415            .map(|i| kv(&format!("k{i}"), "v"))
416            .collect();
417        assert!(!small.has_headroom_for(&wide));
418        assert!(small.has_headroom_for(&request("checkout", 10, 1)));
419    }
420
421    /// Spans are the only signal with grandchildren: an event belongs to a span
422    /// and its attributes belong to the event. Both hops are block-local ids, and
423    /// getting either wrong turns a join into a cross product that still returns
424    /// plausible-looking rows.
425    #[test]
426    fn span_events_and_links_are_child_tables_with_their_own_ids() {
427        use mira_proto::collector::trace::v1::ExportTraceServiceRequest;
428        use mira_proto::trace::v1::span::{Event, Link};
429        use mira_proto::trace::v1::{ResourceSpans, ScopeSpans, Span, Status, status::StatusCode};
430
431        // Two spans, the second with two events and one link, so a bug that
432        // parents events to the wrong span shows up as a wrong parent_id rather
433        // than as a coincidentally-correct zero.
434        let span = |i: u64, events: usize, links: usize| Span {
435            trace_id: vec![1u8; 16].into(),
436            span_id: vec![i as u8; 8].into(),
437            name: "GET /checkout".into(),
438            kind: 2,
439            start_time_unix_nano: 10_000 + i,
440            end_time_unix_nano: 10_000 + i + 500,
441            attributes: vec![kv("http.method", "GET")],
442            status: Some(Status {
443                code: StatusCode::Error as i32,
444                message: "boom".into(),
445            }),
446            events: (0..events)
447                .map(|e| Event {
448                    time_unix_nano: 10_100 + e as u64,
449                    name: "exception".into(),
450                    attributes: vec![kv("exception.type", "IOError")],
451                    ..Default::default()
452                })
453                .collect(),
454            // No attributes on the link — the common case, and it leaves
455            // span_link_attrs empty, which the publish check below relies on.
456            links: (0..links)
457                .map(|_| Link {
458                    trace_id: vec![9u8; 16].into(),
459                    span_id: vec![8u8; 8].into(),
460                    ..Default::default()
461                })
462                .collect(),
463            ..Default::default()
464        };
465
466        let mut b = traces::TracesBuilder::new();
467        let req = ExportTraceServiceRequest {
468            resource_spans: vec![ResourceSpans {
469                resource: Some(Resource {
470                    attributes: vec![
471                        kv("service.name", "checkout"),
472                        kv("service.instance.id", "7f3a"),
473                    ],
474                    ..Default::default()
475                }),
476                scope_spans: vec![ScopeSpans {
477                    scope: Some(InstrumentationScope {
478                        name: "test".into(),
479                        ..Default::default()
480                    }),
481                    spans: vec![span(0, 0, 0), span(1, 2, 1)],
482                    ..Default::default()
483                }],
484                ..Default::default()
485            }],
486        };
487        assert!(b.has_headroom_for(&req));
488        assert_eq!(b.append_request(&req).unwrap(), 2);
489
490        let sealed = b.finish().unwrap();
491        assert_eq!(sealed.num_rows, 2);
492        assert_eq!(
493            sealed.tables.iter().map(|(n, _)| *n).collect::<Vec<_>>(),
494            schema::TRACES_BLOCK_TABLES
495        );
496        // The block's range spans start..end, not start..start: a query for the
497        // instant a long span ended has to find it.
498        assert_eq!(sealed.min_ts, 10_000);
499        assert_eq!(sealed.max_ts, 10_501);
500
501        let rows = |t: &str| sealed.table(t).unwrap().num_rows();
502        assert_eq!(rows("span_events"), 2);
503        assert_eq!(rows("span_links"), 1);
504        assert_eq!(rows("span_event_attrs"), 2);
505        assert_eq!(rows("span_link_attrs"), 0);
506        assert_eq!(rows("span_attrs"), 2);
507
508        let u32col = |t: &str, c: &str| {
509            sealed
510                .table(t)
511                .unwrap()
512                .column_by_name(c)
513                .unwrap()
514                .as_any()
515                .downcast_ref::<UInt32Array>()
516                .unwrap()
517                .clone()
518        };
519        // Both events hang off span 1, and they carry ids 0 and 1 of their own —
520        // the ids span_event_attrs.parent_id refers to. Sharing the span's id
521        // here is the bug this test exists to catch.
522        assert_eq!(u32col("span_events", "parent_id").values(), &[1, 1]);
523        assert_eq!(u32col("span_events", "id").values(), &[0, 1]);
524        assert_eq!(u32col("span_event_attrs", "parent_id").values(), &[0, 1]);
525        assert_eq!(u32col("span_links", "parent_id").values(), &[1]);
526
527        // An empty table costs ~1-2.5 KB of Arrow IPC framing and is not written.
528        // A traces block has nine tables and a service that emits no span links
529        // would otherwise pay for four of them on every seal.
530        let root = std::env::temp_dir().join(format!("mira-tr-{}", std::process::id()));
531        let _ = std::fs::remove_dir_all(&root);
532        let published =
533            block::publish(&root, "traces", block::node_id("a"), 1, 0, &sealed).unwrap();
534        assert!(!published.dir.join("span_link_attrs.arrow").exists());
535        assert!(
536            block::open_table_opt(&published.dir.join("span_link_attrs.arrow"))
537                .unwrap()
538                .is_none()
539        );
540        let ev = block::open_table_opt(&published.dir.join("span_events.arrow"))
541            .unwrap()
542            .unwrap();
543        let (inside, total) = ev.zero_copy_ratio();
544        assert_eq!(inside, total, "{inside}/{total} buffers zero-copy");
545        let _ = std::fs::remove_dir_all(&root);
546
547        let spans = sealed.table("spans").unwrap();
548        let durations = spans
549            .column_by_name("duration_nano")
550            .unwrap()
551            .as_any()
552            .downcast_ref::<UInt64Array>()
553            .unwrap();
554        assert_eq!(durations.values(), &[500, 500]);
555
556        // Links point out of the block, so their ids stay raw. Rebasing these
557        // would silently repoint a link at a local row.
558        let lt = sealed.table("span_links").unwrap();
559        let lt = lt
560            .column_by_name("trace_id")
561            .unwrap()
562            .as_any()
563            .downcast_ref::<arrow_array::FixedSizeBinaryArray>()
564            .unwrap();
565        assert_eq!(lt.value(0), &[9u8; 16]);
566    }
567
568    /// A span with a zero start time is malformed; folding it into the block's
569    /// range would make the directory name claim to cover the epoch, and every
570    /// temporal query would then have to open the block to find nothing.
571    #[test]
572    fn malformed_span_times_do_not_widen_the_block_range() {
573        use mira_proto::collector::trace::v1::ExportTraceServiceRequest;
574        use mira_proto::trace::v1::{ResourceSpans, ScopeSpans, Span};
575
576        let mut b = traces::TracesBuilder::new();
577        b.append_request(&ExportTraceServiceRequest {
578            resource_spans: vec![ResourceSpans {
579                scope_spans: vec![ScopeSpans {
580                    spans: vec![
581                        Span {
582                            name: "no-clock".into(),
583                            ..Default::default()
584                        },
585                        Span {
586                            name: "backwards".into(),
587                            start_time_unix_nano: 5_000,
588                            end_time_unix_nano: 4_000,
589                            ..Default::default()
590                        },
591                        Span {
592                            name: "fine".into(),
593                            start_time_unix_nano: 6_000,
594                            end_time_unix_nano: 6_100,
595                            ..Default::default()
596                        },
597                    ],
598                    ..Default::default()
599                }],
600                ..Default::default()
601            }],
602        })
603        .unwrap();
604
605        let sealed = b.finish().unwrap();
606        assert_eq!(
607            sealed.num_rows, 3,
608            "malformed spans are stored, not dropped"
609        );
610        assert_eq!(sealed.min_ts, 5_000);
611        assert_eq!(sealed.max_ts, 6_100);
612        // end < start saturates to zero rather than wrapping to 584 years.
613        let d = sealed.table("spans").unwrap();
614        let d = d
615            .column_by_name("duration_nano")
616            .unwrap()
617            .as_any()
618            .downcast_ref::<UInt64Array>()
619            .unwrap();
620        assert_eq!(d.values(), &[0, 0, 100]);
621    }
622
623    /// All five metric types through one request, because the layout's whole
624    /// premise is that they go to different tables while sharing one point id
625    /// space — and a shared counter is exactly the kind of thing that works for
626    /// one type and silently collides for four.
627    #[test]
628    fn every_metric_type_lands_in_its_own_table_from_one_id_space() {
629        use arrow_array::{Float64Array, ListArray, UInt8Array};
630        use mira_proto::collector::metrics::v1::ExportMetricsServiceRequest;
631        use mira_proto::metrics::v1::metric::Data;
632        use mira_proto::metrics::v1::number_data_point::Value as NumValue;
633        use mira_proto::metrics::v1::summary_data_point::ValueAtQuantile;
634        use mira_proto::metrics::v1::{
635            AggregationTemporality, Exemplar, ExponentialHistogram, ExponentialHistogramDataPoint,
636            Gauge, Histogram, HistogramDataPoint, Metric, NumberDataPoint, ResourceMetrics,
637            ScopeMetrics, Sum, Summary, SummaryDataPoint,
638            exponential_histogram_data_point::Buckets,
639        };
640
641        let number = |t: u64, v: i64| NumberDataPoint {
642            attributes: vec![kv("route", "/checkout")],
643            time_unix_nano: t,
644            start_time_unix_nano: 1, // process start: must not widen the block
645            value: Some(NumValue::AsInt(v)),
646            ..Default::default()
647        };
648        // Two histogram points sharing one bounds array, so the interning is
649        // actually exercised rather than merely present.
650        let hist = |t: u64| HistogramDataPoint {
651            time_unix_nano: t,
652            count: 3,
653            sum: Some(1.5),
654            bucket_counts: vec![1, 1, 1],
655            explicit_bounds: vec![0.1, 0.5],
656            exemplars: vec![Exemplar {
657                time_unix_nano: t,
658                trace_id: vec![4u8; 16].into(),
659                span_id: vec![5u8; 8].into(),
660                ..Default::default()
661            }],
662            ..Default::default()
663        };
664
665        let metrics = vec![
666            Metric {
667                name: "http.server.request.count".into(),
668                unit: "{request}".into(),
669                data: Some(Data::Sum(Sum {
670                    data_points: vec![number(1_000, 7), number(2_000, 9)],
671                    aggregation_temporality: AggregationTemporality::Cumulative as i32,
672                    is_monotonic: true,
673                })),
674                metadata: vec![kv("owner", "checkout-team")],
675                ..Default::default()
676            },
677            Metric {
678                name: "process.memory".into(),
679                data: Some(Data::Gauge(Gauge {
680                    data_points: vec![number(1_500, 42)],
681                })),
682                ..Default::default()
683            },
684            Metric {
685                name: "http.server.duration".into(),
686                data: Some(Data::Histogram(Histogram {
687                    data_points: vec![hist(1_100), hist(2_100)],
688                    aggregation_temporality: AggregationTemporality::Delta as i32,
689                })),
690                ..Default::default()
691            },
692            Metric {
693                name: "rpc.duration".into(),
694                data: Some(Data::ExponentialHistogram(ExponentialHistogram {
695                    data_points: vec![ExponentialHistogramDataPoint {
696                        time_unix_nano: 1_200,
697                        count: 4,
698                        scale: 3,
699                        zero_count: 1,
700                        positive: Some(Buckets {
701                            offset: 2,
702                            bucket_counts: vec![1, 2],
703                        }),
704                        ..Default::default()
705                    }],
706                    aggregation_temporality: AggregationTemporality::Delta as i32,
707                })),
708                ..Default::default()
709            },
710            Metric {
711                name: "legacy.latency".into(),
712                data: Some(Data::Summary(Summary {
713                    data_points: vec![SummaryDataPoint {
714                        time_unix_nano: 3_000,
715                        count: 10,
716                        sum: 5.0,
717                        quantile_values: vec![
718                            ValueAtQuantile {
719                                quantile: 0.5,
720                                value: 0.4,
721                            },
722                            ValueAtQuantile {
723                                quantile: 0.99,
724                                value: 0.9,
725                            },
726                        ],
727                        ..Default::default()
728                    }],
729                })),
730                ..Default::default()
731            },
732        ];
733
734        let mut b = metrics::MetricsBuilder::new();
735        let req = ExportMetricsServiceRequest {
736            resource_metrics: vec![ResourceMetrics {
737                resource: Some(Resource {
738                    attributes: vec![kv("service.name", "checkout")],
739                    ..Default::default()
740                }),
741                scope_metrics: vec![ScopeMetrics {
742                    metrics,
743                    ..Default::default()
744                }],
745                ..Default::default()
746            }],
747        };
748        assert!(b.has_headroom_for(&req));
749        // 3 number + 2 histogram + 1 exponential + 1 summary.
750        assert_eq!(b.append_request(&req).unwrap(), 7);
751
752        let sealed = b.finish().unwrap();
753        assert_eq!(sealed.num_rows, 7);
754        assert_eq!(
755            sealed.tables.iter().map(|(n, _)| *n).collect::<Vec<_>>(),
756            schema::METRICS_BLOCK_TABLES
757        );
758        let rows = |t: &str| sealed.table(t).unwrap().num_rows();
759        assert_eq!(rows("metrics"), 5);
760        assert_eq!(rows("number_dp"), 3);
761        assert_eq!(rows("hist_dp"), 2);
762        assert_eq!(rows("exp_hist_dp"), 1);
763        assert_eq!(rows("summary_dp"), 1);
764        assert_eq!(rows("exemplars"), 2);
765        assert_eq!(rows("metric_attrs"), 1);
766        // Two histogram points, one bounds row: the interning is the reason
767        // hist_dp measured 1.67x smaller.
768        assert_eq!(rows("hist_bounds"), 1);
769
770        // start_time_unix_nano is process start and must not widen the block —
771        // otherwise every cumulative metric makes its block match every query.
772        assert_eq!(sealed.min_ts, 1_000);
773        assert_eq!(sealed.max_ts, 3_000);
774
775        let u32col = |t: &str, c: &str| {
776            sealed
777                .table(t)
778                .unwrap()
779                .column_by_name(c)
780                .unwrap()
781                .as_any()
782                .downcast_ref::<UInt32Array>()
783                .unwrap()
784                .clone()
785        };
786        // THE invariant of this layout: one id space across four tables. Sum
787        // takes 0-1, gauge 2, histogram 3-4, exponential 5, summary 6 — never
788        // the same number twice, which is what lets dp_attrs and exemplars key
789        // on a point without a table discriminant.
790        assert_eq!(u32col("number_dp", "id").values(), &[0, 1, 2]);
791        assert_eq!(u32col("hist_dp", "id").values(), &[3, 4]);
792        assert_eq!(u32col("exp_hist_dp", "id").values(), &[5]);
793        assert_eq!(u32col("summary_dp", "id").values(), &[6]);
794        assert_eq!(u32col("exemplars", "parent_id").values(), &[3, 4]);
795        // Only the three number points carry attributes here, and dp_attrs
796        // points straight at them.
797        assert_eq!(u32col("dp_attrs", "parent_id").values(), &[0, 1, 2]);
798        // Both histogram points share bounds row 0.
799        assert_eq!(u32col("hist_dp", "bounds_id").values(), &[0, 0]);
800
801        // Temporality and monotonicity live on the descriptor, not on 300,000
802        // points that would each repeat them.
803        let kinds = sealed.table("metrics").unwrap();
804        let kind = kinds
805            .column_by_name("kind")
806            .unwrap()
807            .as_any()
808            .downcast_ref::<UInt8Array>()
809            .unwrap();
810        assert_eq!(kind.values(), &[2, 1, 3, 4, 5]);
811
812        // Quantiles round-trip as two parallel lists.
813        let sd = sealed.table("summary_dp").unwrap();
814        let q = sd
815            .column_by_name("quantile")
816            .unwrap()
817            .as_any()
818            .downcast_ref::<ListArray>()
819            .unwrap()
820            .value(0);
821        let q = q.as_any().downcast_ref::<Float64Array>().unwrap();
822        assert_eq!(q.values(), &[0.5, 0.99]);
823
824        // And the whole thing survives a publish/mmap round trip. A List column
825        // has three buffers of its own; if any of them were copied, this drops
826        // below n/n.
827        let root = std::env::temp_dir().join(format!("mira-me-{}", std::process::id()));
828        let _ = std::fs::remove_dir_all(&root);
829        let published =
830            block::publish(&root, "metrics", block::node_id("a"), 1, 0, &sealed).unwrap();
831        for t in ["number_dp", "hist_dp", "hist_bounds", "summary_dp"] {
832            let m = block::open_table(&published.dir.join(format!("{t}.arrow"))).unwrap();
833            let (inside, total) = m.zero_copy_ratio();
834            assert_eq!(inside, total, "{t}: {inside}/{total} buffers zero-copy");
835        }
836        // Nothing in this request had exemplar attributes, so that table is
837        // absent rather than 2.5 KB of framing.
838        assert!(!published.dir.join("exemplar_attrs.arrow").exists());
839        let _ = std::fs::remove_dir_all(&root);
840    }
841
842    /// The read path end to end: publish two blocks, then filter on a resource
843    /// attribute, a record attribute, a dictionary column and a raw field, and
844    /// check that pruning actually skips work rather than merely returning the
845    /// right rows by scanning everything.
846    #[test]
847    fn search_filters_across_attribute_levels_and_prunes_by_time() {
848        use query::{Op, Search, Signal, Target, Term, Value as QV};
849
850        let root = std::env::temp_dir().join(format!("mira-q-{}", std::process::id()));
851        let _ = std::fs::remove_dir_all(&root);
852
853        // Two blocks, two services, disjoint time ranges. Block 1 is older.
854        for (seq, (service, base)) in [("checkout", 1_000u64), ("payments", 5_000)]
855            .into_iter()
856            .enumerate()
857        {
858            let mut b = logs::LogsBuilder::new();
859            b.append_request(&request(service, 10, base)).unwrap();
860            let sealed = b.finish().unwrap();
861            block::publish(&root, "logs", block::node_id("a"), seq as u64, 0, &sealed).unwrap();
862        }
863
864        let q = |terms: Vec<Term>, from: i64, to: i64, limit: usize| Search {
865            signal: Signal::Logs,
866            from,
867            to,
868            terms,
869            limit,
870            after: None,
871            cursors: false,
872        };
873        let attr = |k: &str, v: &str| Term {
874            target: Target::Attr(k.into()),
875            op: Op::Eq,
876            value: QV::Str(v.into()),
877        };
878        let field = |c: &str, op: Op, v: QV| Term {
879            target: Target::Field(c.into()),
880            op,
881            value: v,
882        };
883
884        // service.name is a *resource* attribute; the user does not know that
885        // and should not have to. It resolves through resources -> resource_id.
886        let r = query::search(
887            &root,
888            &q(vec![attr("service.name", "payments")], 0, i64::MAX, 100),
889        )
890        .unwrap();
891        assert_eq!(r.stats.rows_matched, 10);
892        assert!(r.json.contains("\"service.name\":\"payments\""));
893        assert!(!r.json.contains("checkout"));
894        // Time did not prune this — both blocks are in the window — but the
895        // attribute filter did: the "checkout" block never carried the value, so
896        // its sidecar ruled it out before it was opened.
897        assert_eq!(r.stats.blocks_scanned, 1);
898
899        // http.method is a *record* attribute, on every row of both blocks.
900        let r = query::search(
901            &root,
902            &q(vec![attr("http.method", "GET")], 0, i64::MAX, 100),
903        )
904        .unwrap();
905        assert_eq!(r.stats.rows_matched, 20);
906
907        // A key that exists nowhere matches nothing rather than erroring.
908        let r = query::search(&root, &q(vec![attr("nope", "x")], 0, i64::MAX, 100)).unwrap();
909        assert_eq!(r.stats.rows_matched, 0);
910        assert_eq!(r.json, "[]");
911
912        // Time pruning happens on the directory name, before any file is
913        // opened: the older block is never touched.
914        let r = query::search(&root, &q(vec![], 5_000, 9_000, 100)).unwrap();
915        assert_eq!(r.stats.blocks_total, 2);
916        assert_eq!(
917            r.stats.blocks_scanned, 1,
918            "the 1_000-range block must prune"
919        );
920        assert_eq!(r.stats.rows_matched, 10);
921
922        // Dictionary column, substring op: resolved once against the dictionary
923        // and then matched on u16 codes.
924        let r = query::search(
925            &root,
926            &q(
927                vec![field("severity_text", Op::Contains, QV::Str("NF".into()))],
928                0,
929                i64::MAX,
930                100,
931            ),
932        )
933        .unwrap();
934        assert_eq!(r.stats.rows_matched, 20);
935
936        // A numeric field given as a string, which is what a browser and an LLM
937        // both send. Coercion happens once the column's type is known.
938        let r = query::search(
939            &root,
940            &q(
941                vec![field("severity_number", Op::Gte, QV::Str("9".into()))],
942                0,
943                i64::MAX,
944                100,
945            ),
946        )
947        .unwrap();
948        assert_eq!(r.stats.rows_matched, 20);
949
950        // FixedSizeBinary queried as hex.
951        let r = query::search(
952            &root,
953            &q(
954                vec![field("trace_id", Op::Eq, QV::Str("07".repeat(16)))],
955                0,
956                i64::MAX,
957                100,
958            ),
959        )
960        .unwrap();
961        assert_eq!(r.stats.rows_matched, 20);
962        // ...and a malformed one matches nothing instead of a prefix.
963        let r = query::search(
964            &root,
965            &q(
966                vec![field("trace_id", Op::Eq, QV::Str("07".into()))],
967                0,
968                i64::MAX,
969                100,
970            ),
971        )
972        .unwrap();
973        assert_eq!(r.stats.rows_matched, 0);
974
975        // Terms are AND-ed.
976        let r = query::search(
977            &root,
978            &q(
979                vec![attr("service.name", "checkout"), attr("http.method", "GET")],
980                0,
981                i64::MAX,
982                100,
983            ),
984        )
985        .unwrap();
986        assert_eq!(r.stats.rows_matched, 10);
987
988        // THE early exit: with a limit satisfied by the newest block, the older
989        // one is never opened even though it overlaps the window.
990        let r = query::search(&root, &q(vec![], 0, i64::MAX, 5)).unwrap();
991        assert_eq!(r.stats.blocks_scanned, 1);
992        assert_eq!(r.json.matches("\"body\"").count(), 5);
993        // Newest first. The timestamp is quoted because OTLP/JSON says a 64-bit
994        // integer is a string — see [`json::Json::i64_str`].
995        assert!(r.json.starts_with("[{\"time_unix_nano\":\"5009\","));
996        // Block-local plumbing never reaches the caller.
997        assert!(!r.json.contains("resource_id"));
998        assert!(!r.json.contains("\"id\""));
999        // Scope name is synthesised into scope_attrs at ingest and merges in
1000        // here, so all three attribute levels are present on one row.
1001        assert!(r.json.contains("\"otel.scope.name\":\"test\""));
1002
1003        let _ = std::fs::remove_dir_all(&root);
1004    }
1005
1006    /// A query reads the attribute tables when it needs them and not before —
1007    /// and every table it does read is still checksummed in full.
1008    ///
1009    /// The two halves are one test on purpose, because each is the other's
1010    /// guard. Corrupt one block's `log_attrs.arrow` and leave everything else
1011    /// alone:
1012    ///
1013    ///   - a query with no attribute predicate that the damaged block does not
1014    ///     contribute a row to *succeeds*, having scanned that block's root
1015    ///     table and never touched its attributes;
1016    ///   - a query with an attribute predicate over it fails `BadChecksum`;
1017    ///   - a query that emits one of its rows fails `BadChecksum`.
1018    ///
1019    /// Reverting `query::Block::open` to loading the attribute tables eagerly
1020    /// fails the first assertion — the corrupt file is read by a query that
1021    /// never looks at it. Dropping the CRC check, or rendering a block without
1022    /// having loaded its detail through the verified path, fails the other
1023    /// two: a bad block would be served.
1024    #[test]
1025    fn a_corrupt_attribute_table_is_caught_by_every_query_that_reads_it_and_no_other() {
1026        use query::{Op, Search, Signal, Target, Term, Value as QV};
1027
1028        let root = std::env::temp_dir().join(format!("mira-attr-crc-{}", std::process::id()));
1029        let _ = std::fs::remove_dir_all(&root);
1030
1031        // Different row counts, so a body substring picks one block out. Block
1032        // 0 is older and smaller, and it is the one that gets damaged.
1033        let mut dirs = Vec::new();
1034        for (seq, (service, n, base)) in [("checkout", 3usize, 1_000u64), ("payments", 10, 5_000)]
1035            .into_iter()
1036            .enumerate()
1037        {
1038            let mut b = logs::LogsBuilder::new();
1039            b.append_request(&request(service, n, base)).unwrap();
1040            let sealed = b.finish().unwrap();
1041            let p = block::publish(&root, "logs", block::node_id("a"), seq as u64, 0, &sealed);
1042            dirs.push(p.unwrap().dir);
1043        }
1044        let damaged = dirs[0].join("log_attrs.arrow");
1045
1046        // One byte, inside the region the footer's `mira.crc32.len` covers. The
1047        // CRC is checked before a single byte of the body is parsed, so this is
1048        // an error and not a malformed-Arrow panic — and the assertion below is
1049        // what says the mutation landed where it was aimed.
1050        let mut bytes = std::fs::read(&damaged).unwrap();
1051        bytes[64] ^= 0xff;
1052        std::fs::write(&damaged, &bytes).unwrap();
1053        assert!(
1054            matches!(block::open_table(&damaged), Err(Error::BadChecksum { .. })),
1055            "the corruption must be detectable at all, or the rest proves nothing"
1056        );
1057
1058        let q = |terms: Vec<Term>, limit: usize| Search {
1059            signal: Signal::Logs,
1060            from: 0,
1061            to: i64::MAX,
1062            terms,
1063            limit,
1064            after: None,
1065            cursors: false,
1066        };
1067        let body = |v: &str| Term {
1068            target: Target::Field("body".into()),
1069            op: Op::Contains,
1070            value: QV::Str(v.into()),
1071        };
1072
1073        // `contains` has no zone summary, so nothing prunes: both blocks are
1074        // opened and every row of both is compared. Only the ten-row block
1075        // holds "line 7", so the damaged block contributes nothing and is never
1076        // rendered.
1077        let r = query::search(&root, &q(vec![body("line 7")], 100)).unwrap();
1078        assert_eq!(r.stats.blocks_total, 2);
1079        assert_eq!(r.stats.blocks_scanned, 2, "neither block may prune");
1080        assert_eq!(r.stats.rows_scanned, 13, "3 + 10 root rows, all compared");
1081        assert_eq!(r.stats.rows_matched, 1);
1082
1083        // ...and the same query over a token no row holds still reads both root
1084        // tables and still does not care that one block's attributes are junk.
1085        let r = query::search(&root, &q(vec![body("zqxjw")], 100)).unwrap();
1086        assert_eq!(r.stats.blocks_scanned, 2);
1087        assert_eq!(r.stats.rows_matched, 0);
1088
1089        // An attribute predicate is evaluated against the attribute tables, so
1090        // now it is read — and refused. "http.method" is on every row of both
1091        // blocks, so the bloom sidecar cannot prune the damaged one.
1092        let attr = Term {
1093            target: Target::Attr("http.method".into()),
1094            op: Op::Eq,
1095            value: QV::Str("GET".into()),
1096        };
1097        let e = query::search(&root, &q(vec![attr], 100))
1098            .err()
1099            .expect("an attribute predicate over a damaged block must not succeed");
1100        assert!(
1101            matches!(&e, Error::BadChecksum { path, .. } if path == &damaged),
1102            "an attribute predicate must verify what it reads, got {e}"
1103        );
1104
1105        // And so is rendering: a row of the damaged block emits its attributes,
1106        // so a query that reaches it fails rather than returning a row with
1107        // attributes read out of unverified bytes.
1108        let e = query::search(&root, &q(vec![], 100))
1109            .err()
1110            .expect("rendering a row of a damaged block must not succeed");
1111        assert!(
1112            matches!(&e, Error::BadChecksum { path, .. } if path == &damaged),
1113            "a rendered row must verify what it reads, got {e}"
1114        );
1115
1116        // The undamaged block on its own is still perfectly readable: the
1117        // failure above is this file's, not the query's.
1118        let r = query::search(&root, &q(vec![body("line 9")], 100)).unwrap();
1119        assert_eq!(r.stats.rows_matched, 1);
1120
1121        let _ = std::fs::remove_dir_all(&root);
1122    }
1123
1124    /// Paging must be a partition of the one-shot answer: every row once, in
1125    /// the same order, no matter where the page boundaries land.
1126    ///
1127    /// The hard part is ties. Four blocks here carry *identical* timestamps, so
1128    /// every instant is shared by four rows in four different blocks — which is
1129    /// exactly what a boundary falling mid-nanosecond looks like, and exactly
1130    /// what a cursor of "the last timestamp I saw" gets wrong. Real ingest makes
1131    /// these constantly: a batch of records stamped by one call to the clock.
1132    #[test]
1133    fn paging_returns_every_row_once_even_across_ties() {
1134        use query::{Cursor, Search, Signal};
1135
1136        let root = std::env::temp_dir().join(format!("mira-page-{}", std::process::id()));
1137        let _ = std::fs::remove_dir_all(&root);
1138
1139        // Two clusters of two blocks. Within a cluster the timestamps are the
1140        // same to the nanosecond; the clusters are far apart, so the older one
1141        // can be pruned by name once paging has passed it.
1142        for seq in 0..4u64 {
1143            let base = if seq < 2 { 5_000 } else { 1_000 };
1144            let mut req = request("svc", 25, base);
1145            // Five records per nanosecond, so ties exist *inside* a block as
1146            // well as across them. That matters: within a block rows arrive in
1147            // ascending row order and the sort key runs descending, so a sort
1148            // that ignores the tiebreak reorders them, the page boundary lands
1149            // in the middle of the reordering, and rows come back twice.
1150            for (i, r) in req.resource_logs[0].scope_logs[0]
1151                .log_records
1152                .iter_mut()
1153                .enumerate()
1154            {
1155                r.time_unix_nano = base + i as u64 / 5;
1156            }
1157            let mut b = logs::LogsBuilder::new();
1158            b.append_request(&req).unwrap();
1159            let sealed = b.finish().unwrap();
1160            block::publish(&root, "logs", block::node_id("a"), seq, 0, &sealed).unwrap();
1161        }
1162
1163        let page = |limit: usize, after| {
1164            query::search(
1165                &root,
1166                &Search {
1167                    signal: Signal::Logs,
1168                    from: 0,
1169                    to: i64::MAX,
1170                    terms: vec![],
1171                    limit,
1172                    after,
1173                    cursors: false,
1174                },
1175            )
1176            .unwrap()
1177        };
1178
1179        let all = page(1_000, None);
1180        assert_eq!(all.json.matches("\"body\"").count(), 100);
1181        assert!(all.next.is_none(), "a short page is the last page");
1182
1183        // 100 rows at 7 a page is 14 full pages and a remainder — so boundaries
1184        // land inside a tie group on most of them.
1185        let mut rows = Vec::new();
1186        let mut after = None;
1187        let mut deepest = 0;
1188        for _ in 0..100 {
1189            let r = page(7, after);
1190            rows.push(r.json[1..r.json.len() - 1].to_owned());
1191            deepest = r.stats.blocks_scanned;
1192            match r.next {
1193                Some(c) => after = Some(c),
1194                None => break,
1195            }
1196        }
1197        assert_eq!(rows.len(), 15);
1198        assert_eq!(
1199            format!("[{}]", rows.join(",")),
1200            all.json,
1201            "paged reads must reassemble the one-shot answer byte for byte"
1202        );
1203
1204        // And the last page is cheaper than the first, not dearer: the two
1205        // newest blocks are ruled out by name once the cursor is past them.
1206        // This is the whole reason the cursor is a key and not an offset.
1207        assert_eq!(all.stats.blocks_scanned, 4);
1208        assert_eq!(deepest, 2);
1209
1210        // A cursor from a different query shape is still just a position, and a
1211        // cursor past the end yields nothing rather than wrapping.
1212        let end = Cursor {
1213            ts: 0,
1214            node: 0,
1215            seq: 0,
1216            row: 0,
1217        };
1218        assert_eq!(page(7, Some(end)).json, "[]");
1219
1220        // Round-trips through the wire form, which is the only form a caller
1221        // ever sees.
1222        let c = page(7, None).next.unwrap();
1223        assert_eq!(c.to_string().parse::<Cursor>(), Ok(c));
1224        for bad in ["", "1.2.3", "1.2.3.4.5", "1.-2.3.4", "a.2.3.4", "1.2.3.x"] {
1225            assert!(bad.parse::<Cursor>().is_err(), "{bad:?} parsed");
1226        }
1227
1228        let _ = std::fs::remove_dir_all(&root);
1229    }
1230
1231    /// "Every span of trace X" carries no time bound, so block names prune
1232    /// nothing and the scan reads the whole signal. The Bloom sidecar is the
1233    /// only thing standing between that query and every block on disk.
1234    #[test]
1235    fn a_trace_lookup_opens_only_the_block_holding_the_trace() {
1236        use mira_proto::collector::trace::v1::ExportTraceServiceRequest;
1237        use mira_proto::trace::v1::{ResourceSpans, ScopeSpans, Span};
1238        use query::{Op, Search, Signal, Target, Term, Value as QV};
1239
1240        let root = std::env::temp_dir().join(format!("mira-bloom-{}", std::process::id()));
1241        let _ = std::fs::remove_dir_all(&root);
1242
1243        // Ids from a hash, not a counter: the filter's premise is that trace ids
1244        // are uniform, and 0,1,2,… would test a distribution that cannot occur.
1245        let tid = |n: u64| {
1246            let mut b = [0u8; 16];
1247            b[..8].copy_from_slice(&identity::hash64(&n.to_le_bytes()).to_le_bytes());
1248            b[8..].copy_from_slice(&identity::hash64(&(!n).to_le_bytes()).to_le_bytes());
1249            b
1250        };
1251
1252        const BLOCKS: u64 = 8;
1253        for seq in 0..BLOCKS {
1254            let mut b = traces::TracesBuilder::new();
1255            // Overlapping time ranges on every block, so nothing here can be
1256            // credited to time pruning.
1257            let spans = (0..4)
1258                .map(|i| Span {
1259                    trace_id: tid(seq * 4 + i).to_vec().into(),
1260                    span_id: vec![i as u8 + 1; 8].into(),
1261                    name: "GET /checkout".into(),
1262                    start_time_unix_nano: 1_000 + i,
1263                    end_time_unix_nano: 1_100 + i,
1264                    ..Default::default()
1265                })
1266                .collect();
1267            b.append_request(&ExportTraceServiceRequest {
1268                resource_spans: vec![ResourceSpans {
1269                    resource: Some(Resource::default()),
1270                    scope_spans: vec![ScopeSpans {
1271                        spans,
1272                        ..Default::default()
1273                    }],
1274                    ..Default::default()
1275                }],
1276            })
1277            .unwrap();
1278            let sealed = b.finish().unwrap();
1279            assert!(
1280                sealed.sidecars.iter().any(|(n, _)| *n == bloom::TRACE_IDX),
1281                "traces publish a trace filter"
1282            );
1283            block::publish(&root, "traces", block::node_id("a"), seq, 0, &sealed).unwrap();
1284        }
1285
1286        // The same ids on the logs side. A trace investigation is two questions
1287        // — the spans, then the logs written under them — and the second one has
1288        // no more of a time bound than the first, so it needs the same filter.
1289        for seq in 0..BLOCKS {
1290            let mut req = request("checkout", 4, 1_000);
1291            for (i, r) in req.resource_logs[0].scope_logs[0]
1292                .log_records
1293                .iter_mut()
1294                .enumerate()
1295            {
1296                r.trace_id = tid(seq * 4 + i as u64).to_vec().into();
1297            }
1298            let mut b = logs::LogsBuilder::new();
1299            b.append_request(&req).unwrap();
1300            let sealed = b.finish().unwrap();
1301            block::publish(&root, "logs", block::node_id("a"), seq, 0, &sealed).unwrap();
1302        }
1303
1304        let lookup = |signal, id: String| Search {
1305            signal,
1306            from: 0,
1307            to: i64::MAX,
1308            terms: vec![Term {
1309                target: Target::Field("trace_id".into()),
1310                op: Op::Eq,
1311                value: QV::Str(id),
1312            }],
1313            limit: 100,
1314            after: None,
1315            cursors: false,
1316        };
1317
1318        let hex = |b: [u8; 16]| b.iter().map(|x| format!("{x:02x}")).collect::<String>();
1319        for signal in [Signal::Traces, Signal::Logs] {
1320            let r = query::search(&root, &lookup(signal, hex(tid(17)))).unwrap();
1321            assert_eq!(r.stats.blocks_total, BLOCKS as usize);
1322            assert_eq!(r.stats.blocks_scanned, 1, "{signal:?}: skip the rest");
1323            assert_eq!(r.stats.rows_matched, 1);
1324
1325            // An id in no block at all: with 8 filters probed, a false positive
1326            // is possible, so this asserts the bound rather than zero.
1327            let r = query::search(&root, &lookup(signal, hex(tid(9_999)))).unwrap();
1328            assert_eq!(r.stats.rows_matched, 0);
1329            assert!(r.stats.blocks_scanned <= 1, "{}", r.stats.blocks_scanned);
1330        }
1331
1332        // Deleting a sidecar has to cost a block read, never a lost span.
1333        let one = block::scan(&root, "traces").unwrap();
1334        for b in &one {
1335            std::fs::remove_file(b.dir.join(bloom::TRACE_IDX)).unwrap();
1336        }
1337        let r = query::search(&root, &lookup(Signal::Traces, hex(tid(17)))).unwrap();
1338        assert_eq!(r.stats.blocks_scanned, BLOCKS as usize);
1339        assert_eq!(r.stats.rows_matched, 1);
1340
1341        let _ = std::fs::remove_dir_all(&root);
1342    }
1343
1344    /// A scan wide enough to fan out answers exactly as a narrow one would.
1345    ///
1346    /// Twenty-four blocks is past the width the waves ramp to, so this runs the
1347    /// merge at every wave size there is, with several threads reading mappings
1348    /// at once. What it pins is not speed. Blocks are scanned concurrently and
1349    /// merged in wave order, so a merge that loses the global ordering — or a
1350    /// `Hit` whose block index no longer addresses the mapping it came from —
1351    /// produces a page ordered by wave instead of by timestamp. Every one-block
1352    /// test in this file passes with that bug in place; paging is what catches
1353    /// it, because the boundary between two pages is exactly where a
1354    /// mis-ordering shows up as a row returned twice or not at all.
1355    ///
1356    /// The serial half is forced, not hoped for: holding the whole fan-out
1357    /// budget is the only way to make a wave one block wide on demand, and
1358    /// without it this would be two runs of whatever the machine felt like
1359    /// doing. The other half takes the budget back and runs at whatever width
1360    /// `cargo test`'s own parallelism leaves free, which is the arrangement
1361    /// every other multi-block test in this file is already under.
1362    #[test]
1363    fn a_scan_wide_enough_to_fan_out_answers_exactly_as_a_narrow_one() {
1364        use query::{Search, Signal};
1365
1366        let root = std::env::temp_dir().join(format!("mira-fanout-{}", std::process::id()));
1367        let _ = std::fs::remove_dir_all(&root);
1368
1369        // Interleaved in time, not stacked: block 7 holds rows older than block
1370        // 3's and newer than block 11's, so no wave boundary lines up with a
1371        // timestamp boundary and the merge has to do real work on every one.
1372        const BLOCKS: u64 = 24;
1373        for seq in 0..BLOCKS {
1374            let base = 1_000_000 + (seq * 7 % BLOCKS) * 1_000;
1375            let mut req = request("svc", 10, base);
1376            for (i, r) in req.resource_logs[0].scope_logs[0]
1377                .log_records
1378                .iter_mut()
1379                .enumerate()
1380            {
1381                r.time_unix_nano = base + i as u64;
1382            }
1383            let mut b = logs::LogsBuilder::new();
1384            b.append_request(&req).unwrap();
1385            let sealed = b.finish().unwrap();
1386            block::publish(&root, "logs", block::node_id("a"), seq, 0, &sealed).unwrap();
1387        }
1388
1389        let page = |limit: usize, after| {
1390            query::search(
1391                &root,
1392                &Search {
1393                    signal: Signal::Logs,
1394                    from: 0,
1395                    to: i64::MAX,
1396                    terms: vec![],
1397                    limit,
1398                    after,
1399                    cursors: false,
1400                },
1401            )
1402            .unwrap()
1403        };
1404
1405        // Serial: the whole fan-out budget is held elsewhere, so every wave is
1406        // one block wide and the loop is the one this replaced.
1407        let held = query::Helpers::claim(usize::MAX);
1408        let serial = page(1_000, None);
1409        drop(held);
1410
1411        // No `limit` to exit on, so every block is read and every wave runs.
1412        let all = page(1_000, None);
1413        assert_eq!(all.stats.blocks_scanned, BLOCKS as usize);
1414        assert_eq!(all.json.matches("\"body\"").count(), 240);
1415        assert_eq!(all.json, serial.json, "fanning out changed the answer");
1416
1417        let mut rows = Vec::new();
1418        let mut after = None;
1419        for _ in 0..100 {
1420            let r = page(7, after);
1421            rows.push(r.json[1..r.json.len() - 1].to_owned());
1422            match r.next {
1423                Some(c) => after = Some(c),
1424                None => break,
1425            }
1426        }
1427        assert_eq!(
1428            format!("[{}]", rows.join(",")),
1429            all.json,
1430            "a fanned-out scan must page like a serial one"
1431        );
1432
1433        let _ = std::fs::remove_dir_all(&root);
1434    }
1435
1436    /// A three-service call chain, walked with the frame algebra (section 7.3).
1437    ///
1438    /// One fixture for the whole of `frame.rs`, because the interesting claims
1439    /// are all about how its pieces relate and each of them needs the same
1440    /// store. In order:
1441    ///
1442    /// - `anchor` gives back the trace and the *one* service of the row that
1443    ///   matched, not everything in the window.
1444    /// - The expanders do not commute. `peers` alone finds nothing, because the
1445    ///   log that anchored the frame was written seconds after the request it
1446    ///   describes and the trace blocks do not overlap that window at all;
1447    ///   `traces` first measures the real extent and then `peers` finds all
1448    ///   three. This is the bug the algebra exists to make unwriteable, and it
1449    ///   is silent — the wrong order returns a confident, short answer.
1450    /// - `map` reconstructs the topology from `parent_span_id` alone, including
1451    ///   the entry edge for the root span and the error the leaf reported.
1452    #[test]
1453    fn a_frame_walk_reconstructs_a_call_chain_from_one_log_line() {
1454        use mira_proto::collector::trace::v1::ExportTraceServiceRequest;
1455        use mira_proto::trace::v1::{ResourceSpans, ScopeSpans, Span, Status};
1456        use query::{Op, Search, Signal, Target, Term, Value as QV};
1457
1458        let root = std::env::temp_dir().join(format!("mira-frame-{}", std::process::id()));
1459        let _ = std::fs::remove_dir_all(&root);
1460
1461        // Spans start here; the logs are written five seconds later, which is
1462        // what makes the widening observable rather than incidental.
1463        const T0: u64 = 1_000_000_000;
1464        const LOG_TS: u64 = T0 + 5_000_000_000;
1465        let tid = |n: u8| [n; 16];
1466        let sid = |svc: u8, n: u8| [svc, n, 0, 0, 0, 0, 0, 0];
1467
1468        // gateway -> api -> db, three traces, the third failing at the leaf.
1469        let svc = |name: &str, spans: Vec<Span>| ResourceSpans {
1470            resource: Some(Resource {
1471                // The same pair `request` writes on the logs side, so the two
1472                // signals land on the same `resources.key` and the join below
1473                // is a real cross-signal join rather than two disjoint sets
1474                // that happen to be counted together.
1475                attributes: vec![kv("service.name", name), kv("service.instance.id", "7f3a")],
1476                ..Default::default()
1477            }),
1478            scope_spans: vec![ScopeSpans {
1479                spans,
1480                ..Default::default()
1481            }],
1482            ..Default::default()
1483        };
1484        let span = |t: u8, id: [u8; 8], parent: Option<[u8; 8]>, dur: u64, bad: bool| Span {
1485            trace_id: tid(t).to_vec().into(),
1486            span_id: id.to_vec().into(),
1487            parent_span_id: parent.map(|p| p.to_vec()).unwrap_or_default().into(),
1488            name: "GET /checkout".into(),
1489            start_time_unix_nano: T0 + u64::from(t),
1490            end_time_unix_nano: T0 + u64::from(t) + dur,
1491            status: bad.then(|| Status {
1492                code: 2,
1493                ..Default::default()
1494            }),
1495            ..Default::default()
1496        };
1497        let mut b = traces::TracesBuilder::new();
1498        b.append_request(&ExportTraceServiceRequest {
1499            resource_spans: vec![
1500                svc(
1501                    "gateway",
1502                    (1..=3)
1503                        .map(|t| span(t, sid(1, t), None, 900, false))
1504                        .collect(),
1505                ),
1506                svc(
1507                    "api",
1508                    (1..=3)
1509                        .map(|t| span(t, sid(2, t), Some(sid(1, t)), 500, false))
1510                        .collect(),
1511                ),
1512                svc(
1513                    "db",
1514                    (1..=3)
1515                        .map(|t| span(t, sid(3, t), Some(sid(2, t)), 100, t == 3))
1516                        .collect(),
1517                ),
1518            ],
1519        })
1520        .unwrap();
1521        let sealed = b.finish().unwrap();
1522        block::publish(&root, "traces", block::node_id("a"), 0, 0, &sealed).unwrap();
1523
1524        // One log line per trace, from `api`, long after the request finished —
1525        // the shape of an async worker logging what it did.
1526        let mut req = request("api", 3, LOG_TS);
1527        for (i, r) in req.resource_logs[0].scope_logs[0]
1528            .log_records
1529            .iter_mut()
1530            .enumerate()
1531        {
1532            r.trace_id = tid(i as u8 + 1).to_vec().into();
1533            r.body = Some(AnyValue {
1534                value: Some(Value::StringValue(if i == 2 {
1535                    "boom".into()
1536                } else {
1537                    "fine".into()
1538                })),
1539            });
1540        }
1541        let mut b = logs::LogsBuilder::new();
1542        b.append_request(&req).unwrap();
1543        let sealed = b.finish().unwrap();
1544        block::publish(&root, "logs", block::node_id("a"), 0, 0, &sealed).unwrap();
1545
1546        // "The error I am looking at", as a search a UI would send.
1547        let q = Search {
1548            signal: Signal::Logs,
1549            from: LOG_TS as i64 - 1_000_000_000,
1550            to: LOG_TS as i64 + 1_000_000_000,
1551            terms: vec![Term {
1552                target: Target::Field("body".into()),
1553                op: Op::Eq,
1554                value: QV::Str("boom".into()),
1555            }],
1556            limit: 10,
1557            after: None,
1558            cursors: false,
1559        };
1560        let (f, st) = frame::anchor(&root, &q, &[]).unwrap();
1561        assert_eq!(f.traces, vec![tid(3)], "one row matched, so one trace");
1562        assert_eq!(f.entities.len(), 1, "the service that wrote the line, only");
1563        let api = f.entities[0];
1564        assert!(!f.truncated);
1565        assert_eq!(st.rows_matched, 1);
1566
1567        // Wrong order: the trace blocks end five seconds before this window
1568        // opens, so there is nothing to join against.
1569        let (early, _) = frame::expand(&root, &f, &[frame::Expand::Peers], &[]).unwrap();
1570        assert_eq!(early.entities, f.entities, "peers before traces finds none");
1571
1572        let ops = [frame::Expand::Traces, frame::Expand::Peers];
1573        let (walked, st) = frame::expand(&root, &f, &ops, &[]).unwrap();
1574        assert_eq!(
1575            walked.from,
1576            T0 as i64 + 3,
1577            "the window reaches back to the first span of the trace"
1578        );
1579        assert_eq!(walked.to, q.to, "the traces end inside the window already");
1580        assert_eq!(walked.entities.len(), 3, "gateway, api and db");
1581        // Six span rows read for three matches, twice — once per expander.
1582        assert_eq!((st.rows_scanned, st.rows_matched), (18, 6));
1583
1584        let names = frame::names_of(&root, &walked, &[]).unwrap();
1585        assert_eq!(
1586            names.get(&api).map(String::as_str),
1587            Some("api"),
1588            "the key harvested from a log row is the key the spans carry"
1589        );
1590        let mut got: Vec<&str> = names.values().map(String::as_str).collect();
1591        got.sort_unstable();
1592        assert_eq!(got, ["api", "db", "gateway"]);
1593
1594        // The topology, from `parent_span_id` and nothing else.
1595        let m = frame::map(&root, 0, i64::MAX, 1_000_000, &[]).unwrap();
1596        let edge = |from: &str, to: &str| {
1597            let (fk, tk) = (key_of(&names, from), key_of(&names, to));
1598            let from = if from == "entry" {
1599                "\"entry\"".to_owned()
1600            } else {
1601                format!("\"{fk}\"")
1602            };
1603            format!("\"from\":{from},\"to\":\"{tk}\"")
1604        };
1605        for (a, b) in [("entry", "gateway"), ("gateway", "api"), ("api", "db")] {
1606            assert!(m.json.contains(&edge(a, b)), "{a} -> {b} in {}", m.json);
1607        }
1608        assert!(
1609            m.json.contains("\"unresolved\":0"),
1610            "every parent is in the same block: {}",
1611            m.json
1612        );
1613        assert_eq!(
1614            m.json.matches("\"errors\":1").count(),
1615            2,
1616            "the failing leaf shows on its node and on its one in-edge: {}",
1617            m.json
1618        );
1619
1620        // The facet a service picker is built from.
1621        let e = frame::entities(&root, 0, i64::MAX, &[]).unwrap();
1622        assert_eq!(e.stats.rows_matched, 3);
1623        assert!(
1624            e.json.find("gateway") > e.json.find("db"),
1625            "sorted by name, for a human: {}",
1626            e.json
1627        );
1628
1629        let _ = std::fs::remove_dir_all(&root);
1630    }
1631
1632    /// The `resources.key` a name maps back to, for asserting on rendered ids.
1633    fn key_of(names: &std::collections::HashMap<u64, String>, name: &str) -> u64 {
1634        names
1635            .iter()
1636            .find(|(_, v)| *v == name)
1637            .map_or(0, |(k, _)| *k)
1638    }
1639
1640    /// The attribute filter has one dangerous property, and every case here is
1641    /// an instance of it: a query scalar is compared against whatever type the
1642    /// SDK happened to store, so `{eq: "200"}` finds an integer `200` and
1643    /// `{eq: true}` finds a boolean. A filter that indexed the typed bytes would
1644    /// disagree with that rule and prune the block holding the row — and a
1645    /// pruned block is not a slow query, it is a row that silently does not
1646    /// exist. Indexing the value's *text* is what keeps the two in step.
1647    #[test]
1648    fn the_attribute_filter_skips_blocks_without_losing_coercions() {
1649        use query::{Op, Search, Signal, Target, Term, Value as QV};
1650
1651        let root = std::env::temp_dir().join(format!("mira-attrs-{}", std::process::id()));
1652        let _ = std::fs::remove_dir_all(&root);
1653
1654        let attr = |k: &str, v: Value| KeyValue {
1655            key: k.into(),
1656            value: Some(AnyValue { value: Some(v) }),
1657        };
1658
1659        const BLOCKS: u64 = 8;
1660        for seq in 0..BLOCKS {
1661            // Overlapping time ranges, so nothing below can be credited to the
1662            // block name.
1663            let mut req = request("checkout", 2, 1_000);
1664            let mut attrs = vec![attr(
1665                "k8s.pod.name",
1666                Value::StringValue(format!("api-{seq}")),
1667            )];
1668            // One block carries the three non-string types.
1669            if seq == 3 {
1670                attrs.push(attr("http.status_code", Value::IntValue(200)));
1671                attrs.push(attr("retry", Value::BoolValue(true)));
1672                attrs.push(attr("ratio", Value::DoubleValue(1.5)));
1673                // The same kind of number, stored as text — which is what a
1674                // good half of the SDKs emitting a status code actually send.
1675                attrs.push(attr("status.text", Value::StringValue("404".into())));
1676            }
1677            for r in &mut req.resource_logs[0].scope_logs[0].log_records {
1678                r.attributes = attrs.clone();
1679            }
1680            let mut b = logs::LogsBuilder::new();
1681            b.append_request(&req).unwrap();
1682            let sealed = b.finish().unwrap();
1683            let names: Vec<_> = sealed.sidecars.iter().map(|(n, _)| *n).collect();
1684            assert_eq!(
1685                names,
1686                [bloom::ATTR_IDX, zone::ZONE_IDX, bloom::TRACE_IDX],
1687                "logs sidecars"
1688            );
1689            block::publish(&root, "logs", block::node_id("a"), seq, 0, &sealed).unwrap();
1690        }
1691
1692        let find_op = |key: &str, op: Op, value: QV| {
1693            query::search(
1694                &root,
1695                &Search {
1696                    signal: Signal::Logs,
1697                    from: 0,
1698                    to: i64::MAX,
1699                    terms: vec![Term {
1700                        target: Target::Attr(key.into()),
1701                        op,
1702                        value,
1703                    }],
1704                    limit: 100,
1705                    after: None,
1706                    cursors: false,
1707                },
1708            )
1709            .unwrap()
1710        };
1711        let find = |key: &str, value: QV| find_op(key, Op::Eq, value);
1712        let s = |v: &str| QV::Str(v.into());
1713
1714        // The plain case: one block holds the value, seven are ruled out
1715        // without being opened.
1716        let r = find("k8s.pod.name", s("api-5"));
1717        assert_eq!(r.stats.blocks_total, BLOCKS as usize);
1718        assert_eq!(r.stats.blocks_scanned, 1, "the filter must skip the rest");
1719        assert_eq!(r.stats.rows_matched, 2);
1720
1721        // A value in no block at all. This is the query the filter exists for —
1722        // it has no early exit, so unfiltered it reads all of retention to prove
1723        // a negative. One false positive is allowed for; eight would mean the
1724        // filter is not working.
1725        let r = find("k8s.pod.name", s("api-99"));
1726        assert_eq!(r.stats.rows_matched, 0);
1727        assert!(r.stats.blocks_scanned <= 1, "{}", r.stats.blocks_scanned);
1728
1729        // The coercions. Each of these must find the two rows in block 3.
1730        for (key, value) in [
1731            ("http.status_code", QV::Int(200)),
1732            ("http.status_code", s("200")),
1733            // A whole double reaches an integer column through `as_i64`.
1734            ("http.status_code", QV::Double(200.0)),
1735            ("retry", QV::Bool(true)),
1736            ("retry", s("true")),
1737            // Doubles are not indexed at all; block 3 declares it holds some and
1738            // is scanned, and the other seven are still skipped.
1739            ("ratio", QV::Double(1.5)),
1740            ("ratio", s("1.5")),
1741        ] {
1742            let r = find(key, value.clone());
1743            assert_eq!(r.stats.rows_matched, 2, "{key} = {value:?}");
1744        }
1745
1746        // The reverse direction, which used to be the asymmetry: every other
1747        // arm parses a string, so `eq: "200"` finds an integer column, but the
1748        // string column read only `Value::Str` and `eq: 404` against text was
1749        // unconditionally false. The index never agreed — it holds the text
1750        // "404" either way and pointed straight at the block.
1751        let r = find("status.text", QV::Int(404));
1752        assert_eq!(r.stats.rows_matched, 2);
1753        assert_eq!(r.stats.blocks_scanned, 1, "and it is still pruned");
1754
1755        // Ordering against a number stored as text is numeric, not
1756        // lexicographic. "404" is below 500 both ways, but above 99 only one of
1757        // them — a byte comparison puts '4' before '9' and answers no.
1758        //
1759        // These are also the queries the zone map exists for: an ordering has no
1760        // value to hash, so the attribute filter cannot rule out a single block
1761        // and all eight used to be opened to find the one. The map has to agree
1762        // with the numeric reading above — it folds the parseable text into its
1763        // double range for exactly that reason.
1764        let r = find_op("status.text", Op::Lt, QV::Int(500));
1765        assert_eq!(r.stats.rows_matched, 2);
1766        assert_eq!(r.stats.blocks_scanned, 1, "the zone map must skip the rest");
1767        let r = find_op("status.text", Op::Gt, QV::Int(99));
1768        assert_eq!(r.stats.rows_matched, 2);
1769        assert_eq!(r.stats.blocks_scanned, 1);
1770        // An ordering no block can reach opens nothing at all. Block 3's only
1771        // status code is 200; the other seven have no such key, and a key the
1772        // map does not hold is a key with no comparable value.
1773        let r = find_op("http.status_code", Op::Gte, QV::Int(500));
1774        assert_eq!(r.stats.rows_matched, 0);
1775        assert_eq!(r.stats.blocks_scanned, 0);
1776        // A quoted scalar asked for a text comparison and still gets one.
1777        assert_eq!(
1778            find_op("status.text", Op::Gt, s("99")).stats.rows_matched,
1779            0
1780        );
1781        // `contains` renders the scalar rather than refusing it.
1782        assert_eq!(
1783            find_op("status.text", Op::Contains, QV::Int(40))
1784                .stats
1785                .rows_matched,
1786            2
1787        );
1788
1789        // A string that cannot be read as a number must still prune the block
1790        // that holds doubles — otherwise `HAS_DOUBLE` would disable the filter
1791        // for every text query in a block with one float in it.
1792        let r = find("ratio", s("banana"));
1793        assert_eq!(r.stats.rows_matched, 0);
1794        assert!(r.stats.blocks_scanned <= 1, "{}", r.stats.blocks_scanned);
1795
1796        // Deleting a sidecar has to cost a block read, never a lost row. Both
1797        // of them: a block published before either index existed still answers
1798        // every query, slowly.
1799        for b in block::scan(&root, "logs").unwrap() {
1800            std::fs::remove_file(b.dir.join(bloom::ATTR_IDX)).unwrap();
1801            std::fs::remove_file(b.dir.join(zone::ZONE_IDX)).unwrap();
1802        }
1803        let r = find("k8s.pod.name", s("api-5"));
1804        assert_eq!(r.stats.blocks_scanned, BLOCKS as usize);
1805        assert_eq!(r.stats.rows_matched, 2);
1806        let r = find_op("status.text", Op::Lt, QV::Int(500));
1807        assert_eq!(r.stats.blocks_scanned, BLOCKS as usize);
1808        assert_eq!(r.stats.rows_matched, 2);
1809
1810        let _ = std::fs::remove_dir_all(&root);
1811    }
1812
1813    /// The headroom hint is a conservative guess, and a big export makes it
1814    /// guess wrong. It has to stay wrong in that direction — counting distinct
1815    /// keys would mean hashing every request on the hot path — so what matters
1816    /// is that the guess is never mistaken for the real ceiling.
1817    ///
1818    /// `pipeline::flusher` relies on exactly this: on an empty block it skips
1819    /// the hint and appends, because the hint saying no is not evidence that the
1820    /// data does not fit.
1821    #[test]
1822    fn a_large_export_the_headroom_hint_rejects_still_fits_one_block() {
1823        // 20k records x 4 attributes = 80,000 attribute rows, past DICT_CAP,
1824        // from a grand total of five distinct keys.
1825        let mut req = request("checkout", 20_000, 1_000);
1826        for r in &mut req.resource_logs[0].scope_logs[0].log_records {
1827            r.attributes = vec![
1828                kv("http.method", "GET"),
1829                kv("http.route", "/checkout"),
1830                kv("net.peer.name", "db"),
1831                kv("http.scheme", "https"),
1832            ];
1833        }
1834
1835        let mut b = logs::LogsBuilder::new();
1836        assert!(
1837            !b.has_headroom_for(&req),
1838            "the hint is expected to be conservative here; if it stopped being \
1839             so, this test is no longer testing anything"
1840        );
1841        // ...and yet.
1842        assert_eq!(b.append_request(&req).unwrap(), 20_000);
1843        let sealed = b.finish().unwrap();
1844        assert_eq!(sealed.num_rows, 20_000);
1845        assert_eq!(sealed.table("log_attrs").unwrap().num_rows(), 80_000);
1846    }
1847
1848    /// The cold tier: an aged block is rewritten compressed in place, and every
1849    /// read path keeps working over a directory that is mid-rewrite.
1850    #[test]
1851    fn compaction_shrinks_aged_blocks_without_changing_what_they_answer() {
1852        use query::{Op, Search, Signal, Target, Term, Value as QV};
1853
1854        let root = std::env::temp_dir().join(format!("mira-cold-{}", std::process::id()));
1855        let _ = std::fs::remove_dir_all(&root);
1856
1857        // One block an hour and a half old, one from a minute ago.
1858        let now = 4 * block::COLD_AFTER_NS;
1859        let old = (now - 90 * 60 * 1_000_000_000) as u64;
1860        let new = (now - 60 * 1_000_000_000) as u64;
1861        let mut dirs = Vec::new();
1862        for (seq, base) in [old, new].into_iter().enumerate() {
1863            let mut b = logs::LogsBuilder::new();
1864            b.append_request(&request("checkout", 500, base)).unwrap();
1865            let sealed = b.finish().unwrap();
1866            let node = block::node_id("a");
1867            dirs.push(
1868                block::publish(&root, "logs", node, seq as u64, 0, &sealed)
1869                    .unwrap()
1870                    .dir,
1871            );
1872        }
1873        let size = |dir: &std::path::Path| {
1874            std::fs::read_dir(dir)
1875                .unwrap()
1876                .filter_map(|e| e.ok())
1877                .filter(|e| e.path().extension().is_some_and(|x| x == "arrow"))
1878                .map(|e| e.metadata().unwrap().len())
1879                .sum::<u64>()
1880        };
1881        let before = size(&dirs[0]);
1882
1883        // A crash between two tables leaves a directory holding both tiers. The
1884        // codec is per-batch IPC metadata, so that has to read, and the next
1885        // sweep has to finish rather than skip it.
1886        let partial = dirs[0].join("log_attrs.arrow");
1887        let staged = dirs[0].join("log_attrs.staged");
1888        let batch = block::open_table(&partial).unwrap().batches[0].clone();
1889        // Staged then renamed, not written over the live name: `batch` still
1890        // points into the mapping of `partial`, and truncating a mapped file is
1891        // a SIGBUS on the next page touched. This is the constraint `compact`
1892        // is built around, not a detail of the test.
1893        block::write_table_zstd(&staged, &batch).unwrap();
1894        drop(batch);
1895        std::fs::rename(&staged, &partial).unwrap();
1896        assert!(block::open_table(&dirs[0].join("logs.arrow")).is_ok());
1897
1898        let n = block::compact(
1899            &root,
1900            "logs",
1901            block::node_id("a"),
1902            now - block::COLD_AFTER_NS,
1903        )
1904        .unwrap();
1905        assert_eq!(n, 1, "only the aged block is cold");
1906        assert!(dirs[0].join("cold").exists());
1907        assert!(!dirs[1].join("cold").exists(), "the fresh block is hot");
1908        let after = size(&dirs[0]);
1909        assert!(after * 2 < before, "{before} -> {after} is not a tier");
1910
1911        // Idempotent: the marker means the second sweep does no IO at all.
1912        let stamp = std::fs::metadata(dirs[0].join("logs.arrow"))
1913            .unwrap()
1914            .modified()
1915            .unwrap();
1916        assert_eq!(
1917            block::compact(
1918                &root,
1919                "logs",
1920                block::node_id("a"),
1921                now - block::COLD_AFTER_NS
1922            )
1923            .unwrap(),
1924            0
1925        );
1926        assert_eq!(
1927            std::fs::metadata(dirs[0].join("logs.arrow"))
1928                .unwrap()
1929                .modified()
1930                .unwrap(),
1931            stamp
1932        );
1933
1934        // The trade, stated: the cold block gives up zero-copy, the hot one does
1935        // not. Nothing else about either read changes.
1936        let cold = block::open_table(&dirs[0].join("logs.arrow")).unwrap();
1937        let (inside, total) = cold.zero_copy_ratio();
1938        assert_eq!(cold.batches[0].num_rows(), 500);
1939        // Not zero: arrow leaves an empty buffer — an all-valid null mask — as a
1940        // zero-length slice of the mapping rather than allocating nothing.
1941        assert!(
1942            inside < total,
1943            "{inside}/{total} — a decompressed buffer is a copy"
1944        );
1945        let hot = block::open_table(&dirs[1].join("logs.arrow")).unwrap();
1946        let (inside, total) = hot.zero_copy_ratio();
1947        assert_eq!(inside, total, "the hot tier stays zero-copy");
1948
1949        // And the answer is the same one the plain block gave: both blocks, both
1950        // attribute levels, through the sidecars that compaction left alone.
1951        let r = query::search(
1952            &root,
1953            &Search {
1954                signal: Signal::Logs,
1955                from: 0,
1956                to: i64::MAX,
1957                terms: vec![Term {
1958                    target: Target::Attr("service.name".into()),
1959                    op: Op::Eq,
1960                    value: QV::Str("checkout".into()),
1961                }],
1962                limit: 2_000,
1963                after: None,
1964                cursors: false,
1965            },
1966        )
1967        .unwrap();
1968        assert_eq!(r.stats.rows_matched, 1_000);
1969        assert_eq!(r.stats.blocks_scanned, 2);
1970
1971        let _ = std::fs::remove_dir_all(&root);
1972    }
1973
1974    /// A block that has been to an object store and back answers exactly what
1975    /// it answered before it left — in both tiers.
1976    ///
1977    /// This is the claim `--offload` has to make and the only one worth
1978    /// testing at this level. Everything below the query is what would break
1979    /// if the copy were not byte-exact: `Block::open` checks `mira.crc32` over
1980    /// the whole body on every table it maps, so a single flipped or dropped
1981    /// byte is an `Error::BadChecksum` here and not a wrong answer. The cold
1982    /// block is in the set on purpose — it carries a `cold` marker and ZSTD
1983    /// table bodies, so a copy that moved only `*.arrow` would leave a block
1984    /// that reads as hot and a compaction sweep that rewrites it again.
1985    #[test]
1986    fn an_offloaded_block_comes_back_answering_the_same_query() {
1987        use query::{Op, Search, Signal, Target, Term, Value as QV};
1988
1989        let root = std::env::temp_dir().join(format!("mira-offload-e2e-{}", std::process::id()));
1990        let store = root.join("cold-store");
1991        let data = root.join("data");
1992        let _ = std::fs::remove_dir_all(&root);
1993
1994        let now = 4 * block::COLD_AFTER_NS;
1995        let node = block::node_id("a");
1996        let mut dirs = Vec::new();
1997        for (seq, base) in [
1998            (now - 90 * 60 * 1_000_000_000) as u64,
1999            (now - 60 * 1_000_000_000) as u64,
2000        ]
2001        .into_iter()
2002        .enumerate()
2003        {
2004            let mut b = logs::LogsBuilder::new();
2005            b.append_request(&request("checkout", 500, base)).unwrap();
2006            let sealed = b.finish().unwrap();
2007            dirs.push(
2008                block::publish(&data, "logs", node, seq as u64, 0, &sealed)
2009                    .unwrap()
2010                    .dir,
2011            );
2012        }
2013        // One of the two through the cold tier, so the round trip is tested
2014        // over both on-disk shapes rather than only the uncompressed one.
2015        assert_eq!(
2016            block::compact(&data, "logs", node, now - block::COLD_AFTER_NS).unwrap(),
2017            1
2018        );
2019
2020        let ask = || {
2021            query::search(
2022                &data,
2023                &Search {
2024                    signal: Signal::Logs,
2025                    from: 0,
2026                    to: i64::MAX,
2027                    terms: vec![Term {
2028                        target: Target::Attr("service.name".into()),
2029                        op: Op::Eq,
2030                        value: QV::Str("checkout".into()),
2031                    }],
2032                    limit: 2_000,
2033                    after: None,
2034                    cursors: false,
2035                },
2036            )
2037            .unwrap()
2038        };
2039        let before = ask();
2040        assert_eq!(
2041            (before.stats.rows_matched, before.stats.blocks_scanned),
2042            (1_000, 2)
2043        );
2044
2045        // The sweep retention would run: copy, then unlink, block by block.
2046        let t = offload::Target::parse(&format!("file://{}", store.display())).unwrap();
2047        let dropped =
2048            block::expire_with(&data, "logs", i64::MAX, &|b| t.push("logs", b).map(|_| ()))
2049                .unwrap();
2050        assert_eq!(dropped, 2);
2051        assert!(ask().stats.rows_matched == 0, "the local copies are gone");
2052
2053        // The store's own listing is the catalog: no index was written, and
2054        // what comes back out of `readdir` is what went in.
2055        let listed = t.list("logs").unwrap();
2056        assert_eq!(listed.len(), 2);
2057        for b in &listed {
2058            assert!(t.pull("logs", b, &data, node).unwrap());
2059        }
2060
2061        let after = ask();
2062        assert_eq!(after.stats.rows_matched, before.stats.rows_matched);
2063        assert_eq!(after.stats.blocks_scanned, before.stats.blocks_scanned);
2064        // Byte-identical rendered rows, not just the same count: a copy that
2065        // reordered tables or lost a sidecar could still match on totals.
2066        assert_eq!(after.json, before.json);
2067        // The tier survived with the bytes. `cold` is written last by
2068        // `compact` and is the only thing that stops the next sweep rewriting
2069        // an already-compressed block, so a copy that dropped it would cost
2070        // one pointless full rewrite per restored block per hour.
2071        let cold: Vec<_> = block::scan(&data, "logs")
2072            .unwrap()
2073            .iter()
2074            .map(|b| b.dir.join("cold").exists())
2075            .collect();
2076        assert_eq!(cold, vec![true, false], "one cold, one hot, as they left");
2077        // And the compressed one is still compressed, which `open_table`
2078        // answering at all already proves the CRC over: a ZSTD body whose
2079        // checksum did not survive the copy is `BadChecksum`, not a wrong row.
2080        let hot = block::open_table(&dirs[1].join("logs.arrow")).unwrap();
2081        assert_eq!(hot.zero_copy_ratio().0, hot.zero_copy_ratio().1);
2082        let (inside, total) = block::open_table(&dirs[0].join("logs.arrow"))
2083            .unwrap()
2084            .zero_copy_ratio();
2085        assert!(inside < total, "the restored cold block decompressed");
2086
2087        let _ = std::fs::remove_dir_all(&root);
2088    }
2089
2090    /// The startup guard has to say yes to an ordinary local directory. It
2091    /// cannot be tested against a real NFS mount here, so this is the half that
2092    /// catches the failure that would actually happen: a guard that refuses
2093    /// everything, or one that errors on a path it should ignore.
2094    #[test]
2095    fn the_filesystem_guard_passes_a_local_directory() {
2096        let dir = std::env::temp_dir().join(format!("mira-fs-{}", std::process::id()));
2097        std::fs::create_dir_all(&dir).unwrap();
2098        block::check_filesystem(&dir).unwrap();
2099        // A path that does not exist is not a filesystem verdict.
2100        block::check_filesystem(&dir.join("nope")).unwrap();
2101        let _ = std::fs::remove_dir_all(&dir);
2102    }
2103
2104    /// The other startup guard. `create_dir_all` says yes to a directory that
2105    /// already exists whatever its mode, so without this a read-only data
2106    /// directory reaches a listening socket and fails one export at a time.
2107    #[test]
2108    fn the_write_guard_refuses_a_read_only_directory() {
2109        use std::os::unix::fs::PermissionsExt;
2110
2111        let dir = std::env::temp_dir().join(format!("mira-w-{}", std::process::id()));
2112        let _ = std::fs::remove_dir_all(&dir);
2113        std::fs::create_dir_all(&dir).unwrap();
2114        block::check_writable(&dir).unwrap();
2115        // And it left nothing behind.
2116        assert_eq!(std::fs::read_dir(&dir).unwrap().count(), 0);
2117
2118        std::fs::set_permissions(&dir, std::fs::Permissions::from_mode(0o555)).unwrap();
2119        // Root defeats the mode bits entirely, so ask the filesystem rather
2120        // than assume: where a bare write still succeeds, the guard passing is
2121        // the right answer and there is nothing here to assert.
2122        let blocked = std::fs::write(dir.join("canary"), []).is_err();
2123        let verdict = block::check_writable(&dir);
2124        assert_eq!(
2125            verdict.is_err(),
2126            blocked,
2127            "the guard must agree with the filesystem: {verdict:?}"
2128        );
2129        assert!(
2130            !blocked || matches!(verdict, Err(Error::NotWritable { .. })),
2131            "{verdict:?}"
2132        );
2133        std::fs::set_permissions(&dir, std::fs::Permissions::from_mode(0o755)).unwrap();
2134
2135        // A directory that is not there at all is a different error, but still
2136        // an error rather than a successful start.
2137        assert!(block::check_writable(&dir.join("nope")).is_err());
2138        let _ = std::fs::remove_dir_all(&dir);
2139    }
2140
2141    #[test]
2142    fn corrupt_body_is_caught_not_returned_as_data() {
2143        let dir = std::env::temp_dir().join(format!("mira-crc-{}", std::process::id()));
2144        std::fs::create_dir_all(&dir).unwrap();
2145        let path = dir.join("logs.arrow");
2146
2147        let mut b = logs::LogsBuilder::new();
2148        b.append_request(&request("checkout", 64, 1_000)).unwrap();
2149        let sealed = b.finish().unwrap();
2150        block::write_table(&path, sealed.table("logs").unwrap()).unwrap();
2151        assert!(block::open_table(&path).is_ok());
2152
2153        // Flip one bit deep in the body. Arrow's own reader would decode this
2154        // into wrong answers without complaint.
2155        let mut bytes = std::fs::read(&path).unwrap();
2156        let mid = bytes.len() / 2;
2157        bytes[mid] ^= 0x01;
2158        std::fs::write(&path, &bytes).unwrap();
2159
2160        assert!(matches!(
2161            block::open_table(&path),
2162            Err(Error::BadChecksum { .. })
2163        ));
2164
2165        // Truncated from the front, and not an Arrow file at all. arrow-rs seeks
2166        // straight to the trailer and never looks at the magic, so both of these
2167        // reach the decoder as garbage unless we check first.
2168        for junk in [&b"ARROW"[..], &[0u8; 64][..]] {
2169            std::fs::write(&path, junk).unwrap();
2170            assert!(
2171                matches!(block::open_table(&path), Err(Error::BadMagic { .. })),
2172                "{junk:?} decoded as a block"
2173            );
2174        }
2175
2176        // A real Arrow file, written by arrow-rs rather than by us, so the magic
2177        // and the footer are both valid and only the checksum is absent. Reading
2178        // it would be reading something no version of Mira wrote.
2179        let batch = sealed.table("logs").unwrap();
2180        let mut w = arrow_ipc::writer::FileWriter::try_new(
2181            std::fs::File::create(&path).unwrap(),
2182            &batch.schema(),
2183        )
2184        .unwrap();
2185        w.write(batch).unwrap();
2186        w.finish().unwrap();
2187        // `.err().expect` rather than `expect_err`: a `MappedTable` is an mmap
2188        // and a schema, and deriving `Debug` on it to print one in a test that
2189        // must never see one is the wrong direction.
2190        let e = block::open_table(&path)
2191            .err()
2192            .expect("a file with no checksum in it was read as a block");
2193        assert!(matches!(e, Error::MissingMetadata { .. }), "{e}");
2194
2195        let _ = std::fs::remove_dir_all(&dir);
2196    }
2197
2198    /// The block directory is the manifest, which means everything else on the
2199    /// volume is noise it has to survive: a `.DS_Store`, a directory somebody
2200    /// else made, a block half-published by a process that was killed.
2201    ///
2202    /// None of these are hypothetical. Replicas share a volume by design (section 10),
2203    /// and the catalog is rebuilt by `readdir` on every start.
2204    #[test]
2205    fn the_catalog_ignores_everything_it_did_not_write() {
2206        let root = std::env::temp_dir().join(format!("mira-junk-{}", std::process::id()));
2207        let _ = std::fs::remove_dir_all(&root);
2208        let node = block::node_id("a");
2209
2210        let seal = |base: u64| {
2211            let mut b = logs::LogsBuilder::new();
2212            b.append_request(&request("checkout", 4, base)).unwrap();
2213            b.finish().unwrap()
2214        };
2215        let published = block::publish(&root, "logs", node, 0, 0, &seal(1_000)).unwrap();
2216        let partition = published.dir.parent().unwrap().to_path_buf();
2217        let name = published.dir.file_name().unwrap().to_str().unwrap();
2218
2219        // A file where a partition directory should be, a directory whose name
2220        // is not a block name, and a block name with one field too many — which
2221        // is what a future format version would look like from here.
2222        std::fs::write(root.join("logs").join(".DS_Store"), b"junk").unwrap();
2223        for junk in ["not-a-block", &format!("{name}-1")] {
2224            std::fs::create_dir_all(partition.join(junk)).unwrap();
2225        }
2226        assert_eq!(block::scan(&root, "logs").unwrap(), vec![published.clone()]);
2227
2228        // A publish killed between staging and rename leaves the staging
2229        // directory behind. The name is unique per block, so nothing reuses it
2230        // and it is `sweep_staging` at boot that clears it — filtered by signal
2231        // and node, so a directory belonging to another replica sharing the
2232        // volume, or to another signal, survives untouched.
2233        let stale = root
2234            .join(".tmp")
2235            .join(format!("logs-{node:08x}-{:012}-x", 1));
2236        let other_node = root.join(".tmp").join("logs-deadbeef-000000000001-x");
2237        let other_signal = root.join(".tmp").join(format!("traces-{node:08x}-1-x"));
2238        for d in [&stale, &other_node, &other_signal] {
2239            std::fs::create_dir_all(d).unwrap();
2240            std::fs::write(d.join("logs.arrow"), b"leftovers").unwrap();
2241        }
2242        assert_eq!(block::sweep_staging(&root, "logs", node).unwrap(), 1);
2243        assert!(!stale.exists());
2244        assert!(other_node.is_dir() && other_signal.is_dir());
2245        // Sweeping a data directory that never staged anything is not an error.
2246        assert_eq!(
2247            block::sweep_staging(&root.join("nope"), "logs", node).unwrap(),
2248            0
2249        );
2250
2251        let second = block::publish(&root, "logs", node, 1, 0, &seal(2_000)).unwrap();
2252        assert!(block::open_table(&second.dir.join("logs.arrow")).is_ok());
2253        assert_eq!(block::scan(&root, "logs").unwrap().len(), 2);
2254
2255        // And retention takes the block, not the junk beside it.
2256        assert_eq!(block::expire(&root, "logs", i64::MAX).unwrap(), 2);
2257        assert!(block::scan(&root, "logs").unwrap().is_empty());
2258        assert!(partition.join("not-a-block").is_dir());
2259
2260        let _ = std::fs::remove_dir_all(&root);
2261    }
2262
2263    /// Every codec writes a file the reader reads back identically. LZ4 is not
2264    /// written by the engine — it exists so the `tier` example can price the
2265    /// pure-Rust codec against the C one — and an untested writer is how that
2266    /// comparison ends up measuring a bug.
2267    #[test]
2268    fn every_codec_round_trips_the_same_rows() {
2269        let dir = std::env::temp_dir().join(format!("mira-codec-{}", std::process::id()));
2270        let _ = std::fs::remove_dir_all(&dir);
2271        std::fs::create_dir_all(&dir).unwrap();
2272
2273        let mut b = logs::LogsBuilder::new();
2274        b.append_request(&request("checkout", 500, 1_000)).unwrap();
2275        let sealed = b.finish().unwrap();
2276        let batch = sealed.table("logs").unwrap();
2277
2278        type Writer = fn(&std::path::Path, &arrow_array::RecordBatch) -> Result<()>;
2279        let write: [(&str, Writer); 3] = [
2280            ("plain", block::write_table),
2281            ("zstd", block::write_table_zstd),
2282            ("lz4", block::write_table_lz4),
2283        ];
2284        let mut sizes = Vec::new();
2285        for (name, f) in write {
2286            let path = dir.join(format!("{name}.arrow"));
2287            f(&path, batch).unwrap();
2288            let read = block::open_table(&path).unwrap();
2289            assert_eq!(read.batches, vec![batch.clone()], "{name}");
2290            sizes.push((name, std::fs::metadata(&path).unwrap().len()));
2291        }
2292        let plain = sizes[0].1;
2293        for (name, size) in &sizes[1..] {
2294            assert!(*size < plain, "{name} is {size} against {plain} plain");
2295        }
2296
2297        let _ = std::fs::remove_dir_all(&dir);
2298    }
2299}