Skip to main content

mira/
main.rs

1//! Mira: OTLP in, immutable Arrow blocks out, one binary.
2
3mod alert;
4mod api;
5mod config;
6#[cfg(test)]
7mod e2e;
8mod json;
9mod mcp;
10mod pipeline;
11mod proxy;
12mod rca;
13mod receiver;
14mod telemetry;
15mod term;
16mod tui;
17mod ui;
18mod update;
19
20use std::io::IsTerminal;
21use std::net::SocketAddr;
22use std::path::{Path, PathBuf};
23use std::sync::atomic::Ordering::Relaxed;
24use std::time::Duration;
25
26use axum::Router;
27use axum::response::{IntoResponse, Response};
28use axum::routing::get;
29use clap::{Arg, ArgAction, ArgMatches, value_parser};
30
31use config::Config;
32
33/// The whole command tree, in one place.
34///
35/// This was a `const USAGE` and a flat `match` per mode, on the argument that a
36/// parser crate is more code than the flag set it parses. That was true of the
37/// parsing and false of everything around it: the usage text, the generated CLI
38/// page and — once shell completion was asked for — a script per shell all
39/// restate the same flags, with nothing holding them together. One tree is what
40/// `--help`, `mira completion` and the parser now all read, so a flag is
41/// accepted, documented and completed in the same edit.
42///
43/// Five crates against a tree of 148: `clap`, `clap_builder`, `clap_lex`,
44/// `anstyle` and `clap_complete`. `derive` is off because it costs `syn` and
45/// its tree to generate a struct this file would rather write out, and `color`
46/// is off because everything else this binary prints already decides its own
47/// colour from `is_terminal`.
48fn cli() -> clap::Command {
49    clap::Command::new("mira")
50        .version(env!("CARGO_PKG_VERSION"))
51        .about("OTLP in, immutable Arrow blocks out, one binary.")
52        .after_help(
53            "Flags override the config file, which overrides the defaults. Every value\n\
54             can also come from the file via ${env:VAR} — see https://miradb.dev/config/.",
55        )
56        // The bare command is the storage node, so it carries the server's flags
57        // itself rather than behind a `serve` verb nobody had to type before.
58        .arg(config_arg())
59        .arg(
60            Arg::new("node")
61                .long("node")
62                .value_name("NAME")
63                .help("this replica's name, hashed into its block directory names"),
64        )
65        .arg(
66            Arg::new("grpc")
67                .long("grpc")
68                .value_name("ADDR")
69                .value_parser(value_parser!(SocketAddr))
70                .help("where OTLP/gRPC listens"),
71        )
72        .arg(http_arg())
73        .arg(data_dir_arg())
74        .arg(
75            Arg::new("retention")
76                .long("retention")
77                .value_name("DURATION")
78                .value_parser(config::duration)
79                .help("how long a block is kept before it is deleted"),
80        )
81        .arg(offload_arg())
82        .arg(max_request_bytes_arg())
83        .arg(
84            Arg::new("queue")
85                .long("queue")
86                .value_name("N")
87                .value_parser(config::positive)
88                .help("exports queued for one signal before the next has to wait"),
89        )
90        .arg(
91            Arg::new("shards")
92                .long("shards")
93                .value_name("N")
94                .value_parser(config::whole)
95                .help("flushers per signal, or 0 for one per two cores"),
96        )
97        .arg(
98            Arg::new("telemetry-interval")
99                .long("telemetry-interval")
100                .value_name("DURATION")
101                .value_parser(config::duration)
102                .help("how often --self-telemetry samples this node's counters"),
103        )
104        .arg(
105            Arg::new("alerts")
106                .long("alerts")
107                .value_name("FILE")
108                .value_parser(value_parser!(PathBuf))
109                .help("KYAML alerting rules; absent means alerting is off"),
110        )
111        .arg(
112            Arg::new("wal")
113                .long("wal")
114                .action(ArgAction::SetTrue)
115                .help("acknowledge on the write-ahead log rather than on the block"),
116        )
117        .arg(
118            Arg::new("self-telemetry")
119                .long("self-telemetry")
120                .action(ArgAction::SetTrue)
121                .help("store this node's own counters in this node"),
122        )
123        .subcommand(
124            clap::Command::new("mira")
125                // `tui` stays because it is what someone types when they have
126                // not read the usage, and answering that is cheaper than a "no
127                // such subcommand" they have to think about.
128                .visible_alias("tui")
129                .about("open the terminal UI over the same blocks")
130                .after_help(
131                    "With --data-dir it reads a block directory in-process and needs no\n\
132                     server running; with --addr it queries one over HTTP.",
133                )
134                .arg(config_arg())
135                .arg(data_dir_arg())
136                .arg(
137                    Arg::new("addr")
138                        .long("addr")
139                        .value_name("HOST[:PORT]")
140                        .value_parser(tui::parse_addr)
141                        .help("query a running node instead of reading a directory"),
142                ),
143        )
144        .subcommand(
145            clap::Command::new("proxy")
146                .about("one OTLP and query surface in front of N storage nodes")
147                .after_help(
148                    "It stores nothing: exports are split by entity and forwarded, and\n\
149                     /api/v1/query is answered by merging every replica's page on the\n\
150                     cursor order. The reads it cannot merge — correlate, map, metrics\n\
151                     and entities — answer 501 naming themselves rather than returning\n\
152                     one node's share of the answer.",
153                )
154                .arg(config_arg())
155                .arg(http_arg())
156                .arg(max_request_bytes_arg())
157                .arg(
158                    Arg::new("replica")
159                        .long("replica")
160                        .value_name("URL")
161                        // Repeatable, unlike every other flag here, because the
162                        // value is a list and `--replica a --replica b` is what
163                        // a process manager's args array already looks like. The
164                        // file form is one comma-separated string; see
165                        // `config::replicas`.
166                        .action(ArgAction::Append)
167                        .value_parser(config::replicas)
168                        .help("a storage node to forward to; repeatable"),
169                ),
170        )
171        .subcommand(
172            clap::Command::new("offload")
173                .about("move blocks between a data directory and an object store")
174                .after_help(
175                    "--offload sends a block to an object store just before retention\n\
176                     deletes it, under the same directory name it had locally — so the\n\
177                     store's own listing is the catalog and there is nothing else to keep\n\
178                     in sync.\n\n\
179                     `push` is the same copy in the other direction and deletes nothing.\n\
180                     It is how a volume a scale-down left behind is re-homed: push it,\n\
181                     then restore it into a node that is still running. Give it a URI of\n\
182                     its own — file:///archive/${node} — so the restore pulls back one\n\
183                     node's blocks rather than the whole archive.",
184                )
185                .subcommand_required(true)
186                .arg_required_else_help(true)
187                .subcommand(offload_verb("list", "list what the store holds"))
188                .subcommand(
189                    offload_verb(
190                        "restore",
191                        "copy every block the store has and this node does not into --data-dir",
192                    )
193                    .arg(data_dir_arg()),
194                )
195                .subcommand(
196                    offload_verb("push", "copy this node's blocks into the store")
197                        .arg(data_dir_arg()),
198                ),
199        )
200        .subcommand(update::cli())
201        .subcommand(
202            clap::Command::new("completion")
203                .about("print a shell completion script")
204                .after_help(
205                    "The script is generated from this binary's own command tree, so it\n\
206                     completes exactly the flags this version accepts:\n\n  \
207                     mira completion bash > /etc/bash_completion.d/mira\n  \
208                     mira completion zsh  > \"${fpath[1]}/_mira\"\n  \
209                     mira completion fish > ~/.config/fish/completions/mira.fish",
210                )
211                .arg(
212                    Arg::new("shell")
213                        .required(true)
214                        .value_name("SHELL")
215                        .value_parser(value_parser!(clap_complete::Shell)),
216                ),
217        )
218}
219
220/// The five flags more than one mode takes, written once.
221///
222/// A subcommand that shares a flag has to share its spelling, its value name and
223/// its help line too, or `mira --help` and `mira proxy --help` describe the same
224/// thing two ways.
225fn config_arg() -> Arg {
226    Arg::new("config")
227        .long("config")
228        .value_name("FILE")
229        .value_parser(value_parser!(PathBuf))
230        .help("KYAML configuration file; flags override what it sets")
231}
232
233fn data_dir_arg() -> Arg {
234    Arg::new("data-dir")
235        .long("data-dir")
236        .value_name("PATH")
237        .value_parser(value_parser!(PathBuf))
238        .help("the block directory, which is the whole manifest")
239}
240
241fn http_arg() -> Arg {
242    Arg::new("http")
243        .long("http")
244        .value_name("ADDR")
245        .value_parser(value_parser!(SocketAddr))
246        .help("where OTLP/HTTP, the query API, MCP and the UI listen")
247}
248
249fn max_request_bytes_arg() -> Arg {
250    Arg::new("max-request-bytes")
251        .long("max-request-bytes")
252        .value_name("SIZE")
253        .value_parser(config::bytes)
254        .help("the largest export either listener will decode")
255}
256
257fn offload_arg() -> Arg {
258    Arg::new("offload")
259        .long("offload")
260        .value_name("URI")
261        .help("where a block goes before retention unlinks it")
262}
263
264/// The three `offload` verbs, which differ only in direction.
265///
266/// `--data-dir` is added by the two that copy rather than here: `list` reads the
267/// store's own listing and never touches a local directory, and a flag that does
268/// nothing is what `config::check_keys` exists to prevent.
269fn offload_verb(name: &'static str, about: &'static str) -> clap::Command {
270    clap::Command::new(name)
271        .about(about)
272        .arg(config_arg())
273        .arg(offload_arg())
274}
275
276/// One getter for a value that may not have been given *or* may not exist here.
277///
278/// `ArgMatches::get_one` panics on an id the matched subcommand does not
279/// declare, and one [`Config`] is built for the server, the proxy and the three
280/// `offload` verbs, which declare three different subsets of the same flags.
281/// "Not given" and "not a flag of this mode" are the same answer to
282/// [`load_from`], so they are the same answer here.
283fn opt<T: Clone + Send + Sync + 'static>(m: &ArgMatches, id: &str) -> Option<T> {
284    m.try_get_one::<T>(id).ok().flatten().cloned()
285}
286
287/// [`opt`] for a repeatable flag, flattened.
288///
289/// Twice, because each `--replica` already parses to a comma-separated list:
290/// once over the occurrences and once over what each one held.
291fn many(m: &ArgMatches, id: &str) -> Vec<String> {
292    m.try_get_many::<Vec<String>>(id)
293        .ok()
294        .flatten()
295        .into_iter()
296        .flatten()
297        .flatten()
298        .cloned()
299        .collect()
300}
301
302/// Precedence is flag > file > default.
303///
304/// The file is read first and anything clap actually saw then overwrites it. No
305/// flag carries a `default_value`, which is what keeps "not given" distinct from
306/// "given the same value the default has" — `--retention 7d` has to win over a
307/// file that says an hour even when 7d is also the built-in.
308fn load_from(m: &ArgMatches) -> Result<Config, String> {
309    let mut cfg = match opt::<PathBuf>(m, "config") {
310        Some(p) => Config::load(&p)?,
311        None => Config::default(),
312    };
313    if let Some(v) = opt::<String>(m, "node") {
314        cfg.node = v;
315    }
316    if let Some(v) = opt::<SocketAddr>(m, "grpc") {
317        cfg.grpc = v;
318    }
319    if let Some(v) = opt::<SocketAddr>(m, "http") {
320        cfg.http = v;
321    }
322    if let Some(v) = opt::<PathBuf>(m, "data-dir") {
323        cfg.data_dir = v;
324    }
325    if let Some(v) = opt::<Duration>(m, "retention") {
326        cfg.retention = v;
327    }
328    if let Some(v) = opt::<String>(m, "offload") {
329        cfg.offload = Some(v);
330    }
331    if let Some(v) = opt::<usize>(m, "max-request-bytes") {
332        cfg.max_request_bytes = v;
333    }
334    if let Some(v) = opt::<usize>(m, "queue") {
335        cfg.queue = v;
336    }
337    if let Some(v) = opt::<usize>(m, "shards") {
338        cfg.shards = v;
339    }
340    if let Some(v) = opt::<Duration>(m, "telemetry-interval") {
341        cfg.telemetry_interval = v;
342    }
343    if let Some(v) = opt::<PathBuf>(m, "alerts") {
344        cfg.alerts = Some(v);
345    }
346    cfg.replicas.extend(many(m, "replica"));
347    // These two take no value. They are the settings whose file form has to be
348    // able to say `false` — to turn off what an inherited config turned on — and
349    // whose flag form never does, because a flag is only ever typed to enable
350    // something the file did not. So they are an or, not an assignment.
351    cfg.wal |= opt::<bool>(m, "wal").unwrap_or_default();
352    cfg.self_telemetry |= opt::<bool>(m, "self-telemetry").unwrap_or_default();
353    Ok(cfg)
354}
355
356/// `mira offload list`, `mira offload restore` and `mira offload push`.
357///
358/// All three are `readdir` against one side or the other and nothing else.
359/// There is no state here to be stale, no index to rebuild and nothing to
360/// reconcile with a running server: a `restore` into the data directory of a
361/// live node is a block appearing in it, which is the same event as a publish
362/// and is already how the read path learns about anything (section 4).
363///
364/// `push` copies and does not unlink, and that is the design rather than
365/// caution. A node derives two numbers from the blocks it still holds locally,
366/// and emptying the directory walks both backwards: the WAL watermark
367/// ([`mira_core::block::wal_watermarks`]) falls to `0` for any signal left with
368/// no block, so the next boot replays a log that has already been absorbed, and
369/// the block sequence resumes at `max(seq) + 1` over the local scan, so the
370/// node reissues `(node, seq)` pairs that are still alive wherever they were
371/// copied — and `Cursor` is documented as a total order over exactly that pair.
372/// The case this verb exists for is a volume that is about to be deleted, where
373/// freeing space on it buys nothing at all, let alone those two.
374///
375/// ponytail: `push` reads the directory live, so a block being compacted at
376/// that moment — `<table>.arrow.<node>.tmp` renamed over `<table>.arrow` — can
377/// be copied mid-rewrite. It is meant for a volume whose server is stopped,
378/// which is the case it was asked for; holding it against a running one needs
379/// the compaction lock this module deliberately does not have.
380fn offload_cmd(verb: &str, m: &ArgMatches) -> Result<(), String> {
381    let cfg = load_from(m)?;
382    // Not `required(true)` on the flag, because `storage.offload` in --config is
383    // the other way to say it and a node that already has one in its file should
384    // not have to repeat it here.
385    let uri = cfg
386        .offload
387        .as_deref()
388        .ok_or("mira offload needs --offload URI, or storage.offload in --config")?;
389    let target = mira_core::offload::Target::parse(uri).map_err(|e| e.to_string())?;
390    let node = mira_core::block::node_id(&cfg.node);
391    if verb == "restore" {
392        // The same guard `serve_with` runs, for the same reason and before the
393        // same `mmap`: restoring a corpus onto a network mount and then
394        // pointing a server at it is a SIGBUS deferred by one command.
395        mira_core::block::check_filesystem(&cfg.data_dir).map_err(|e| e.to_string())?;
396    }
397    let (mut blocks, mut bytes) = (0u64, 0u64);
398    for signal in pipeline::SIGNALS {
399        // The verb chooses which side is the source. Both sides are the same
400        // `scan` over the same names, which is the property section 3.2's
401        // naming scheme exists to have — a store needs no listing code of its
402        // own, and neither does reading one backwards.
403        let source = match verb {
404            "push" => mira_core::block::scan(&cfg.data_dir, signal),
405            _ => target.list(signal),
406        };
407        for b in source.map_err(|e| e.to_string())? {
408            let name = b.dir.file_name().unwrap_or_default().to_string_lossy();
409            let size = block_bytes(&b.dir);
410            blocks += 1;
411            bytes += size;
412            let what = match verb {
413                "restore" => match target
414                    .pull(signal, &b, &cfg.data_dir, node)
415                    .map_err(|e| e.to_string())?
416                {
417                    true => "restored",
418                    false => "present",
419                },
420                "push" => match target.push(signal, &b).map_err(|e| e.to_string())? {
421                    true => "pushed",
422                    false => "present",
423                },
424                _ => "",
425            };
426            println!(
427                "{signal:<8} {} .. {}  {:>10}  {name} {what}",
428                tui::stamp(b.min_ts),
429                tui::stamp(b.max_ts),
430                size,
431            );
432        }
433    }
434    println!("{blocks} blocks, {bytes} bytes");
435    Ok(())
436}
437
438/// Sum of the block's files. Not derivable from the name — the name carries
439/// everything needed to *prune*, which is the claim the layout makes; how many
440/// bytes are behind it is a `stat` per file and only this command wants it.
441fn block_bytes(dir: &Path) -> u64 {
442    std::fs::read_dir(dir)
443        .into_iter()
444        .flatten()
445        .flatten()
446        .filter_map(|e| e.metadata().ok())
447        .filter(|m| m.is_file())
448        .map(|m| m.len())
449        .sum()
450}
451
452/// The two background tasks `mira_core::diag` needs to be readable.
453///
454/// A function rather than the body of the `if` that gates it, because
455/// `tracing::enabled!` reads the *current* dispatcher and a `tokio::spawn`ed
456/// task does not inherit the scoped one a test can install — so the gate and
457/// the tasks behind it cannot both be reached through the call site, and the
458/// instrument the ingest diagnosis is read from would be the one part of it
459/// never run under test.
460fn spawn_probes() {
461    // A task that does no work at all, so how late it wakes is a property
462    // of the runtime and not of the load. See `diag::RUNTIME_LAG`.
463    tokio::spawn(async {
464        loop {
465            let t = std::time::Instant::now();
466            tokio::time::sleep(std::time::Duration::from_millis(50)).await;
467            mira_core::diag::RUNTIME_LAG
468                .record(t.elapsed().as_nanos().saturating_sub(50_000_000) as u64);
469        }
470    });
471    tokio::spawn(async {
472        let mut t = tokio::time::interval(std::time::Duration::from_secs(5));
473        loop {
474            t.tick().await;
475            // Cumulative from start, so two dumps are a rate and one is a
476            // mean over the run.
477            tracing::debug!(target: "mira::probe", "{}", mira_core::diag::dump());
478        }
479    });
480}
481
482/// Where a `mira mira` invocation should read from.
483///
484/// `--addr` wins if given; otherwise the same `data_dir` the server would use,
485/// so `mira mira --config mira.yaml` looks at exactly the directory that config
486/// writes to.
487fn tui_source(m: &ArgMatches) -> Result<tui::Source, String> {
488    let cfg = match opt::<PathBuf>(m, "config") {
489        Some(p) => Config::load(&p)?,
490        None => Config::default(),
491    };
492    Ok(match opt::<String>(m, "addr") {
493        Some(a) => tui::Source::Remote(a),
494        None => tui::Source::Local(opt::<PathBuf>(m, "data-dir").unwrap_or(cfg.data_dir)),
495    })
496}
497
498/// The guards `serve_with` runs, for a `mira mira --data-dir` that maps exactly
499/// the same blocks with no server in front of it.
500///
501/// Without them [`mira_core::block::scan`] reads `ENOENT` as an empty directory,
502/// so a typo or a volume that never mounted prints `no rows in this window ·
503/// 0/0 blocks` — indistinguishable from a healthy empty store, and "is the data
504/// gone" is the question this feature exists to answer at 3am. A network
505/// filesystem is worse: it reaches `mmap` and leaves on `SIGBUS`, with nothing
506/// printed at all, where the server would have refused with a paragraph naming
507/// the mount.
508///
509/// `check_writable` is deliberately not here. The TUI writes nothing, and a
510/// read-only mount is the normal way to look at a detached volume.
511///
512/// The two cases with nothing to check are decided here rather than at the call
513/// site, because both of them are rules about this check and not about the
514/// caller. A remote source is somebody else's directory: the server answering
515/// on that address ran these on its own way up, and this process never maps one
516/// of its blocks. And off a terminal `tui::run` refuses a redirected stdin or
517/// stdout on its first line, which outranks a diagnosis of a directory nothing
518/// was going to be drawn from anyway.
519fn check_source(src: &tui::Source, on_a_tty: bool) -> Result<(), Box<dyn std::error::Error>> {
520    let tui::Source::Local(dir) = src else {
521        return Ok(());
522    };
523    if !on_a_tty {
524        return Ok(());
525    }
526    if !dir.is_dir() {
527        return Err(format!(
528            "{} is not a directory. `mira mira --data-dir` reads an existing block \
529             directory in place and creates nothing, so this is a volume that never \
530             mounted, a typo, or the path a different replica writes to. An empty \
531             but real directory is fine and shows no rows.",
532            dir.display()
533        )
534        .into());
535    }
536    // `check_filesystem`'s FUSE arm warns rather than refusing — the magic
537    // number cannot tell gcsfuse from a local overlay, so only a human can — and
538    // this process installs no subscriber, because one stray line lands in the
539    // middle of a frame. So: one stderr subscriber for the length of the call,
540    // before `Term::enter` takes the screen. Routing it rather than reprinting
541    // the sentence keeps the wording in `block.rs`, where the check lives.
542    let to_stderr = tracing_subscriber::fmt()
543        .with_writer(std::io::stderr)
544        .with_ansi(std::io::stderr().is_terminal())
545        .without_time()
546        .finish();
547    tracing::subscriber::with_default(to_stderr, || mira_core::block::check_filesystem(dir))?;
548    Ok(())
549}
550
551fn main() {
552    if let Err(e) = run() {
553        // Returning the error from `main` would print it with `Debug`, which
554        // for `Error::Io` is a struct dump with `Os { code: 13, .. }` in it and
555        // for `Error::NetworkFilesystem` throws away the paragraph explaining
556        // what to do instead. Everything that reaches here is aimed at whoever
557        // typed the command; they need the sentence, not the struct.
558        eprintln!("mira: {e}");
559        std::process::exit(1);
560    }
561}
562
563/// A refusal from the parser, as an error from this binary.
564///
565/// `-h` and `-V` come through here too and are not refusals: clap prints them
566/// on stdout and exits 0, which is what `mira -h | less` needs, so they take
567/// its exit rather than this one. Everything else would take clap's other exit
568/// — its own `error:` prefix, on stderr, code 2 — and this binary's contract is
569/// `mira: <sentence>` and code 1 for anything a supervisor might read. The
570/// sentence is clap's; only the prefix and the code are ours.
571fn clap_error(e: &clap::Error) -> Box<dyn std::error::Error> {
572    if !e.use_stderr() {
573        e.exit();
574    }
575    e.to_string()
576        .trim_start_matches("error: ")
577        .trim_end()
578        .to_owned()
579        .into()
580}
581
582fn run() -> Result<(), Box<dyn std::error::Error>> {
583    // `-h`, `--help` and `-V` are clap's now, on every subcommand rather than
584    // only the two that used to hoist them — and `mira update --version v0.1.0`
585    // installs that tag instead of printing this binary's version, because the
586    // root's version flag is not propagated into a subcommand that declares its
587    // own. Both of those were hand-written special cases here.
588    let m = cli().try_get_matches().map_err(|e| clap_error(&e))?;
589    let string = |e: String| -> Box<dyn std::error::Error> { e.into() };
590
591    // Before the tracing subscriber: the installer writes its own progress to
592    // this terminal, and an `info!` line interleaved with a `sudo` prompt is a
593    // prompt someone does not answer.
594    if let Some(("update", sub)) = m.subcommand() {
595        return update::run(sub).map_err(string);
596    }
597    if let Some(("completion", sub)) = m.subcommand() {
598        let shell = sub
599            .get_one::<clap_complete::Shell>("shell")
600            .copied()
601            .expect("required");
602        clap_complete::generate(shell, &mut cli(), "mira", &mut std::io::stdout());
603        return Ok(());
604    }
605    if let Some(("offload", sub)) = m.subcommand() {
606        let (verb, args) = sub.subcommand().expect("subcommand_required");
607        return offload_cmd(verb, args).map_err(string);
608    }
609    if let Some(("mira", sub)) = m.subcommand() {
610        // No tracing subscriber on this path, and no runtime. Both write to the
611        // terminal the TUI has just taken over, and one stray `info!` in the
612        // middle of a frame corrupts the whole screen.
613        let src = tui_source(sub).map_err(string)?;
614        // The same two guards `serve_with` runs, for the same reason and before
615        // the same mmap — see `check_source`, which is also where the two cases
616        // it has nothing to say about are written down.
617        let on_a_tty = std::io::stdin().is_terminal() && std::io::stdout().is_terminal();
618        check_source(&src, on_a_tty)?;
619        return tui::run(src).map_err(Into::into);
620    }
621
622    tracing_subscriber::fmt()
623        .with_env_filter(
624            tracing_subscriber::EnvFilter::try_from_default_env()
625                .unwrap_or_else(|_| "mira=info,mira_core=info".into()),
626        )
627        // Colour only for a terminal. `with_ansi` defaults to on and does not
628        // check, so without this every field name in every line reaches a log
629        // file, a collector, or an agent wrapped in escape codes.
630        .with_ansi(std::io::stdout().is_terminal())
631        .init();
632    let rt = tokio::runtime::Builder::new_multi_thread()
633        .enable_all()
634        .build()?;
635    // After the subscriber and inside the runtime, unlike the three above: the
636    // proxy is a server and wants both, it just has no storage under it.
637    match m.subcommand() {
638        Some(("proxy", sub)) => rt.block_on(proxy_cmd(sub)),
639        _ => rt.block_on(serve(&m)),
640    }
641}
642
643/// `mira proxy`: the HTTP surface of [`proxy`] and nothing else.
644///
645/// No data directory, no flusher, no gRPC listener. gRPC is left off rather
646/// than proxied because splitting an export by entity means decoding it, and a
647/// tonic service that decodes in order to re-encode to three HTTP clients is a
648/// second transport to keep in step for a hop that is inside one deployment.
649/// Point collectors at 4318; see `docs/architecture/replicas.md` section 12.
650async fn proxy_cmd(m: &ArgMatches) -> Result<(), Box<dyn std::error::Error>> {
651    let cfg = load_from(m).map_err(|e| -> Box<dyn std::error::Error> { e.into() })?;
652    let p = proxy::Proxy::new(cfg.replicas.clone(), cfg.max_request_bytes)
653        .map_err(|e| -> Box<dyn std::error::Error> { e.into() })?;
654    let socket = tokio::net::TcpListener::bind(cfg.http).await?;
655    let addr = socket.local_addr()?;
656    tracing::info!(
657        http = %addr,
658        replicas = %cfg.replicas.join(" "),
659        max_request_bytes = cfg.max_request_bytes,
660        "mira proxy listening"
661    );
662    axum::serve(socket, proxy::router(p))
663        .with_graceful_shutdown(shutdown())
664        .await?;
665    Ok(())
666}
667
668async fn serve(m: &ArgMatches) -> Result<(), Box<dyn std::error::Error>> {
669    let cfg = load_from(m).map_err(|e| -> Box<dyn std::error::Error> { e.into() })?;
670    serve_with(cfg, shutdown()).await
671}
672
673/// The server proper, with its stop edge passed in rather than taken from the
674/// process. A test can hold that edge; nothing else needs to.
675async fn serve_with(
676    cfg: Config,
677    stop_signal: impl std::future::Future<Output = ()>,
678) -> Result<(), Box<dyn std::error::Error>> {
679    // A setting only the other mode reads is a setting that does nothing, and
680    // doing nothing in silence is what `config::check_keys` exists to prevent.
681    // The likely typo is `mira --replica ...` for `mira proxy --replica ...`,
682    // which would otherwise start a storage node that looks like a proxy.
683    if !cfg.replicas.is_empty() {
684        return Err(
685            "--replica / proxy.replicas is read by `mira proxy`; this is a storage node".into(),
686        );
687    }
688
689    // First, because a rules file that does not parse is a deployment that
690    // believes it is being paged and is not. Nothing has been created, bound or
691    // mapped at this point, so the failure is a message and an exit rather than
692    // a half-started node.
693    let rules = match &cfg.alerts {
694        Some(p) => alert::Rules::load(p)?,
695        None => alert::Rules::off(),
696    };
697
698    // Named, because `File exists (os error 17)` on its own sends whoever reads
699    // it looking for a bug in Mira rather than at the path they passed.
700    std::fs::create_dir_all(&cfg.data_dir).map_err(|e| {
701        format!(
702            "cannot create data directory {}: {e}. Mira makes this path on first \
703             start, so this is a parent that is not writable or something that is \
704             not a directory already sitting there (in Kubernetes: a subPath that \
705             names a file, or a volume mounted readOnly).",
706            cfg.data_dir.display()
707        )
708    })?;
709    // Before anything is mapped. A network mount is not a slow start, it is a
710    // SIGBUS the first time the server hiccups, and by then there is a process
711    // to explain rather than a flag to change.
712    mira_core::block::check_filesystem(&cfg.data_dir)?;
713    mira_core::block::check_writable(&cfg.data_dir)?;
714
715    let node = mira_core::block::node_id(&cfg.node);
716
717    // Both sockets are bound here, before a flusher starts and long before the
718    // line that says which addresses Mira is listening on. tonic binds inside
719    // its own future, so a port still held by the container that is shutting
720    // down used to surface as `mira: transport error` *after* the log line
721    // claiming the address — the most common way a start fails, reported as the
722    // least useful sentence Mira can print.
723    let taken = |addr: std::net::SocketAddr, what: &str, e: std::io::Error| {
724        format!(
725            "cannot bind {addr} for {what}: {e}. Nothing has started yet, so this \
726             is another process on the port — most often the previous instance \
727             still draining (in Kubernetes: a terminationGracePeriodSeconds \
728             shorter than the drain takes, or two replicas sharing a hostPort)."
729        )
730    };
731    let grpc_socket = tonic::transport::server::TcpIncoming::bind(cfg.grpc)
732        .map_err(|e| taken(cfg.grpc, "OTLP/gRPC", e))?
733        // `serve_with_incoming` ignores the builder's TCP settings, and tonic's
734        // default is nodelay on: without this every small export pays a Nagle
735        // delay that `serve` would not have charged it.
736        .with_nodelay(Some(true));
737    let http_socket = tokio::net::TcpListener::bind(cfg.http)
738        .await
739        .map_err(|e| taken(cfg.http, "OTLP/HTTP and the query API", e))?;
740    // The bound addresses, not the requested ones: `--grpc 127.0.0.1:0` is a
741    // real thing to ask for and the "listening" line is the only place the
742    // chosen port is ever written down.
743    let (grpc_addr, http_addr) = (grpc_socket.local_addr()?, http_socket.local_addr()?);
744
745    // Read before `cfg.data_dir` moves into the pipeline config, and before the
746    // uptime clock starts, so the "listening" line below can print what was
747    // actually resolved rather than what was asked for.
748    let data_dir = std::sync::Arc::new(cfg.data_dir.clone());
749    let _ = *START;
750    // Opened before the flushers, because they take a handle to it, and before
751    // anything is served, because replay has to reach the flushers ahead of the
752    // first live export or the sequences interleave.
753    let wal = match cfg.wal {
754        true => Some(std::sync::Arc::new(mira_core::wal::Wal::open(
755            &cfg.data_dir,
756            node,
757        )?)),
758        false => None,
759    };
760    // The node *name*, not the hashed `node` above: a series is labelled with
761    // what an operator typed, and the hash is a filename detail.
762    let node_name = cfg.node.clone();
763    let pcfg = std::sync::Arc::new(pipeline::Config {
764        data_dir: cfg.data_dir,
765        node,
766        retention: cfg.retention,
767        // Parsed here rather than in the sweep, so `--offload s3://…` is a
768        // refusal to start with the sentence explaining why, not a warning
769        // logged every minute while retention quietly deletes.
770        offload: cfg
771            .offload
772            .as_deref()
773            .map(mira_core::offload::Target::parse)
774            .transpose()?,
775        queue: cfg.queue,
776        shards: pipeline::shard_count(
777            cfg.shards,
778            std::thread::available_parallelism().map_or(1, |n| n.get()),
779        ),
780        wal: wal.clone(),
781        ..Default::default()
782    });
783    // One channel and block sequence per signal per shard, so a slow flush on
784    // one cannot stall another.
785    let (logs, o_logs, h_logs) = pipeline::spawn::<mira_core::logs::LogsBuilder>(&pcfg);
786    let (traces, o_traces, h_traces) = pipeline::spawn::<mira_core::traces::TracesBuilder>(&pcfg);
787    let (metrics, o_metrics, h_metrics) =
788        pipeline::spawn::<mira_core::metrics::MetricsBuilder>(&pcfg);
789    let flushers = [h_logs, h_traces, h_metrics];
790    // In `pipeline::SIGNALS` order, which is what `Api::open` indexes with.
791    let open_blocks = [o_logs, o_traces, o_metrics];
792    if wal.is_some() {
793        replay(
794            &pcfg.data_dir,
795            node,
796            logs.clone(),
797            traces.clone(),
798            metrics.clone(),
799        )
800        .await?;
801    }
802    // After the replay, so the first sample is of a node that has finished
803    // recovering rather than of one part-way through it.
804    //
805    // The handle is kept rather than detached, because the sampler holds an
806    // `Ingest` clone and a flusher only stops when the last one drops. Detached,
807    // it is the one holder that never lets go: every stop would sit out the full
808    // `DRAIN_GRACE` waiting for a channel that cannot close, and turning
809    // self-telemetry on would silently make each restart fifteen seconds slower.
810    let sampler = cfg.self_telemetry.then(|| {
811        tracing::info!(
812            interval_s = cfg.telemetry_interval.as_secs(),
813            "storing this node's own telemetry in this node"
814        );
815        tokio::spawn(telemetry::run(
816            node_name,
817            pcfg.data_dir.clone(),
818            cfg.telemetry_interval,
819            metrics.clone(),
820        ))
821    });
822    let recv = receiver::Receivers {
823        logs,
824        traces,
825        metrics,
826        max_request_bytes: cfg.max_request_bytes,
827    };
828    pipeline::spawn_retention(pcfg);
829
830    // One `watch` rather than two oneshots because both servers need the same
831    // edge and neither owns it.
832    let (stop, stop_rx) = tokio::sync::watch::channel(());
833    let stopped = |mut rx: tokio::sync::watch::Receiver<()>| async move {
834        let _ = rx.changed().await;
835    };
836
837    let grpc = tokio::spawn(
838        tonic::transport::Server::builder()
839            .add_service(recv.logs_server())
840            .add_service(recv.traces_server())
841            .add_service(recv.metrics_server())
842            .serve_with_incoming_shutdown(grpc_socket, stopped(stop_rx.clone())),
843    );
844
845    // One listener for all of it: `/v1/*` is OTLP in, `/api/v1/*` is query out
846    // and `/api/v1/stats` is this node describing itself, `/mcp` is the agent
847    // surface, `/health` and `/readyz` are the probes, `/` and `/{file}` are the
848    // UI. The UI's wildcard is one segment deep, so it cannot swallow any of the
849    // others.
850    let api = api::Api {
851        data_dir: std::sync::Arc::clone(&data_dir),
852        open: open_blocks,
853        alerts: std::sync::Arc::new(alert::Engine::new(rules)),
854        // Cloned from the receiver rather than kept back from `spawn`, so there
855        // is visibly one handle and the router is what holds it: every copy of
856        // `Api` here lives in the served router and is dropped with it, which
857        // is what lets the logs flusher finish.
858        logs: Some(recv.logs.clone()),
859    };
860    // Always routed, even with no rules: `/api/v1/alerts` answering `[]` is how
861    // the UI, the TUI and an agent learn that alerting is off, and a 404 is
862    // indistinguishable from an old build.
863    //
864    // Without the ingest handle, and that is not tidiness: the evaluator's task
865    // never returns, so an `Ingest` clone in it is one the flusher never sees
866    // dropped and every shutdown on an alerting node would sit out the full
867    // `DRAIN_GRACE`. The evaluator only ever reads.
868    alert::spawn(api::Api {
869        logs: None,
870        ..api.clone()
871    });
872    // The two tasks `mira_core::diag` needs to be readable, spawned only when
873    // someone has asked to read it. The probes in `submit` and in the log are
874    // always on and cost ~150 ns an export; these two are a 20 Hz wakeup and a
875    // formatted line, which is not worth running on every node forever for an
876    // answer nobody is looking at.
877    if tracing::enabled!(target: "mira::probe", tracing::Level::DEBUG) {
878        spawn_probes();
879    }
880    let serve = axum::serve(
881        http_socket,
882        receiver::http_router(recv)
883            // Only the query router is timed. Layering the merged router would
884            // put OTLP exports and UI asset fetches in the same average, which
885            // is a latency number that means nothing.
886            .merge(api::router(api.clone()).layer(axum::middleware::from_fn(timed)))
887            .merge(mcp::router(api.clone()))
888            .merge(alert::router(api))
889            .merge(ops_router(std::sync::Arc::clone(&data_dir)))
890            .merge(ui::router()),
891    )
892    .with_graceful_shutdown(stopped(stop_rx));
893    // `IntoFuture`, not `Future`, so it cannot be spawned directly.
894    let http = tokio::spawn(async move { serve.await });
895
896    // One line, still one line, because it is what gets grepped out of a pod log
897    // and pasted into an issue. What it carries is every resolved value whose
898    // being wrong is silent: the node id, because it is the only externally
899    // visible thing that distinguishes two replicas' blocks and a collision is
900    // diagnosed here; the data directory, because a config that resolved
901    // `${env:MIRA_DATA}` to nothing writes a week of telemetry into `./data`
902    // inside a container and loses it at the next restart; the retention,
903    // because it is the one value whose mistake is irreversible — too short and
904    // the sweep has already deleted what it was going to delete by the time
905    // anyone reads this line; the request cap, because too small is a 413 the
906    // sender reports as Mira being broken. The UI URL is spelled out because
907    // `http://0.0.0.0:4318/` is not a thing anyone guesses from `http=0.0.0.0:4318`.
908    //
909    // `retention` is printed in the syntax `--retention` accepts, so the line
910    // round-trips: whatever it says can be pasted back in.
911    tracing::info!(
912        grpc = %grpc_addr, http = %http_addr,
913        ui = %format!("http://{http_addr}/"),
914        node = %cfg.node, node_id = format!("{node:08x}"),
915        data_dir = %data_dir.display(),
916        retention = %format!("{}s", cfg.retention.as_secs()),
917        max_request_bytes = cfg.max_request_bytes,
918        "mira listening"
919    );
920
921    let (mut grpc, mut http) = (grpc, http);
922    let mut flushers = flushers;
923    let mut wedged = false;
924    tokio::select! {
925        r = &mut grpc => r??,
926        r = &mut http => r??,
927        // A flusher cannot see its channel close while the listeners still hold
928        // an `Ingest`, so one that returns before the stop signal has failed and
929        // said why on its way out. Carrying on is what this used to do: the other
930        // two signals keep working, that one answers every export with a 503
931        // forever, and every probe stays green. A crashloop is the honest shape
932        // of "this process cannot store logs" — the orchestrator reports it, and
933        // the restart is the recovery for the case that caused it, a data
934        // directory that was not there yet.
935        _ = first_stopped(&mut flushers) => wedged = true,
936        _ = stop_signal => tracing::info!("draining"),
937    }
938
939    // Before the drain, and awaited so the cancellation has actually landed:
940    // dropping the sampler's `Ingest` clone is what lets the metrics flusher see
941    // its channel close. A self-sample lost to the abort is the least important
942    // row this process will ever not write.
943    if let Some(s) = sampler {
944        s.abort();
945        let _ = s.await;
946    }
947    drain(stop, grpc, http, flushers, DRAIN_GRACE).await;
948    tracing::info!("stopped");
949    if wedged {
950        // The other two signals were still drained above; only then is this
951        // process allowed to be a failed one.
952        return Err("a flusher stopped, so one signal can no longer be stored; \
953                    exiting for the supervisor to restart (the cause is logged above)"
954            .into());
955    }
956    Ok(())
957}
958
959/// How long a stop is allowed to take before the process leaves without it.
960///
961/// Bounded below by `pipeline::Config::max_block_age`: step 1 of [`drain`] only
962/// makes progress once the block an in-flight export is waiting on seals, and
963/// with the listener closed nothing else will grow it. So this is a multiple of
964/// that constant, not a number chosen freely.
965const DRAIN_GRACE: std::time::Duration = std::time::Duration::from_secs(15);
966
967/// Stop accepting, then let everything already in flight land.
968///
969/// Three ordered steps, and the order is the whole point.
970///
971/// 1. Stop accepting, but let in-flight exports run to their acknowledgement.
972///    Skipping this is not a data-loss bug — the queued job is still sealed
973///    below — it is a *duplicate* bug: the exporter sees a reset, OTLP tells it
974///    to retry, and it re-sends data that did get stored. Every rolling restart
975///    would double-write whatever was in flight.
976/// 2. Await the servers, which drops the last `Ingest` clone per signal and so
977///    closes each flusher's channel.
978/// 3. A flusher answering a closed channel seals whatever is open, publishes it
979///    and acks the waiters (`pipeline::flusher`). Exiting before that lands is
980///    what turns step 1's ack into a reset after all.
981///
982/// ponytail: bounded by `grace` because a hung fsync must not outlive the
983/// orchestrator's grace period and become a SIGKILL with no explanation in the
984/// log. Whatever had not landed by then is lost, which is why the bound is a
985/// last resort and not a policy.
986async fn drain<G, H>(
987    stop: tokio::sync::watch::Sender<()>,
988    grpc: tokio::task::JoinHandle<G>,
989    http: tokio::task::JoinHandle<H>,
990    flushers: [pipeline::Flushers; 3],
991    grace: std::time::Duration,
992) {
993    let _ = stop.send(());
994    let landed = async move {
995        let _ = grpc.await;
996        let _ = http.await;
997        for h in flushers {
998            // Awaited unconditionally: `first_stopped` may already have run one
999            // of these to completion, and a drained set answers at once rather
1000            // than panicking the way a twice-polled `JoinHandle` would.
1001            let _ = h.await;
1002        }
1003    };
1004    if tokio::time::timeout(grace, landed).await.is_err() {
1005        tracing::warn!(?grace, "did not drain in time; exiting anyway");
1006    }
1007}
1008
1009/// Push everything the log holds that no block claims back through the
1010/// flushers, before the listeners open.
1011///
1012/// Ordering is the reason this is not a background task. A replayed frame keeps
1013/// the sequence it already has, and `Ingest::replay` puts that sequence back
1014/// among the log's unpublished before it queues the frame, which is what stops
1015/// a shard sealing beside it from computing a watermark over it — but that only
1016/// covers frames already read off disk. A frame still sitting in a segment is
1017/// in nobody's pending set, so a live export sealing first would claim a
1018/// watermark past it and the next boot would not replay it. Draining the whole
1019/// log before the first new export is framed is the blunt guarantee that this
1020/// never happens. It is also the reason nobody is waiting: the client that sent
1021/// this either got its answer before the crash or gave up long before this
1022/// process started.
1023///
1024/// One `spawn_blocking` for the whole log, not one per frame. The channel is
1025/// bounded at `ingest.queue` and the sends are blocking, so the flushers set the pace and
1026/// a multi-gigabyte log is decoded at the rate it can be sealed rather than
1027/// into memory all at once.
1028async fn replay(
1029    dir: &Path,
1030    node: u32,
1031    logs: pipeline::Ingest<mira_proto::collector::logs::v1::ExportLogsServiceRequest>,
1032    traces: pipeline::Ingest<mira_proto::collector::trace::v1::ExportTraceServiceRequest>,
1033    metrics: pipeline::Ingest<mira_proto::collector::metrics::v1::ExportMetricsServiceRequest>,
1034) -> Result<(), Box<dyn std::error::Error>> {
1035    use mira_core::wal::Signal;
1036
1037    let dir = dir.to_path_buf();
1038    let started = std::time::Instant::now();
1039    let done = tokio::task::spawn_blocking(move || {
1040        let watermarks = mira_core::block::wal_watermarks(&dir, node)?;
1041        let mut undecodable = 0u64;
1042        let out = mira_core::wal::Wal::replay(&dir, node, watermarks, |signal, seq, body| {
1043            let pushed = match signal {
1044                Signal::Logs => logs.replay(body, seq),
1045                Signal::Traces => traces.replay(body, seq),
1046                Signal::Metrics => metrics.replay(body, seq),
1047            };
1048            match pushed {
1049                Ok(()) | Err(pipeline::Rejected::Failed(_)) => {
1050                    // A frame that passed its checksum and then would not decode
1051                    // is one export, and it is already unrecoverable — stopping
1052                    // the boot over it would lose every frame behind it too.
1053                    undecodable += u64::from(pushed.is_err());
1054                    Ok(())
1055                }
1056                // The flusher is gone, so nothing after this would land either.
1057                Err(_) => Err(mira_core::Error::WalCorrupt {
1058                    path: dir.clone(),
1059                    why: "the flusher for this signal stopped during replay",
1060                }),
1061            }
1062        })?;
1063        Ok::<_, mira_core::Error>((out, undecodable))
1064    })
1065    .await??;
1066
1067    let (out, undecodable) = done;
1068    if undecodable > 0 {
1069        tracing::error!(
1070            frames = undecodable,
1071            "write-ahead log frames passed their checksum and would not decode as OTLP; \
1072             those exports are gone"
1073        );
1074    }
1075    if out.torn_segments > 0 {
1076        // Expected after a hard kill, and only after one. Info, not warn: the
1077        // torn frame is the export that was mid-write when the process died,
1078        // which the sender never got an acknowledgement for and has retried.
1079        tracing::info!(
1080            segments = out.torn_segments,
1081            "write-ahead log segments ended in a torn frame; that is what a crash looks like"
1082        );
1083    }
1084    if out.replayed > 0 || out.skipped > 0 {
1085        tracing::info!(
1086            replayed = out.replayed,
1087            skipped = out.skipped,
1088            bytes = out.bytes,
1089            elapsed_ms = started.elapsed().as_millis() as u64,
1090            "recovered from the write-ahead log"
1091        );
1092    }
1093    Ok(())
1094}
1095
1096/// Resolve as soon as any one flusher has returned.
1097async fn first_stopped(flushers: &mut [pipeline::Flushers; 3]) {
1098    let [logs, traces, metrics] = flushers;
1099    tokio::select! {
1100        _ = logs => {}
1101        _ = traces => {}
1102        _ = metrics => {}
1103    }
1104}
1105
1106/// The three endpoints that answer for the process rather than for the data:
1107/// liveness, readiness, and everything this node counts about itself.
1108///
1109/// Here rather than in `api.rs` because `/health` and `/readyz` must not touch
1110/// the block directory — no query engine, nothing that can be slow, nothing that
1111/// can fail for a reason that is not the process's fault. `/api/v1/stats` does
1112/// open the directory, which is why it is a query-namespace URL and not a probe.
1113///
1114/// `/health` and `/readyz` used to be the same handler, on the argument that
1115/// Mira has no warm-up and no cluster to join, so there is no state in which it
1116/// is alive and not ready. A node whose disk is full is exactly that state: the
1117/// process is fine, answers every request, and cannot store a byte. That is the
1118/// state readiness exists for — it is what takes the node out of the Service's
1119/// endpoints so the exporters retry somewhere that can — so the two are now
1120/// different answers. Liveness stays a constant 200: a flusher that stops takes
1121/// the process with it (`serve_with`), so answering at all *is* the liveness
1122/// answer, and restarting a node whose volume is full fixes nothing.
1123fn ops_router(data_dir: std::sync::Arc<PathBuf>) -> Router {
1124    Router::new()
1125        .route("/health", get(health))
1126        .route("/readyz", get(readyz))
1127        .route("/api/v1/stats", get(stats))
1128        .with_state(data_dir)
1129}
1130
1131/// Liveness, plus what the ingest path has refused so far.
1132async fn health() -> Response {
1133    // A flusher that stops takes the process with it (see `serve_with`), so
1134    // answering at all is the liveness answer. The counters are here so that the
1135    // probe and the log agree about how much has been refused, and because a
1136    // shedding node is the case where an operator is looking at exactly this.
1137    let mut j = mira_core::json::Json::new();
1138    j.obj(|j| {
1139        j.key("status");
1140        j.str("ok");
1141        for r in &pipeline::REJECTS {
1142            j.key(r.signal);
1143            j.obj(|j| {
1144                j.key("shed");
1145                j.u64(r.shed.load(Relaxed));
1146                j.key("failed");
1147                j.u64(r.failed.load(Relaxed));
1148            });
1149        }
1150    });
1151    json_ok(j.into_string())
1152}
1153
1154/// Readiness: 200 while exports can be made durable, 503 once they cannot.
1155async fn readyz() -> Response {
1156    ready(pipeline::stalled())
1157}
1158
1159/// Readiness is one question: can this instance accept an export and make it
1160/// durable? Everything else about the process is `/health`'s.
1161///
1162/// Split from the handler so both answers are testable without a disk that has
1163/// actually filled up — and so the only input is the one fact the decision turns
1164/// on. The threshold itself is `pipeline::UNREADY_AFTER`, and its whole job is to
1165/// make this a *sustained* condition: a probe that flips on one failed publish
1166/// would deregister a node for every EIO and every restart of the volume
1167/// underneath it, and an endpoint list that changes every ten seconds costs more
1168/// exports than the node it was protecting.
1169fn ready(stalled: Option<(&'static str, u64)>) -> Response {
1170    let mut j = mira_core::json::Json::new();
1171    j.obj(|j| match stalled {
1172        None => {
1173            j.key("status");
1174            j.str("ok");
1175        }
1176        Some((signal, secs)) => {
1177            j.key("status");
1178            j.str("unavailable");
1179            j.key("signal");
1180            j.str(signal);
1181            j.key("stalled_s");
1182            j.u64(secs);
1183            j.key("reason");
1184            j.str(
1185                "this node has not been able to store an export for this signal; \
1186                 the usual cause is a full or unwritable volume",
1187            );
1188        }
1189    });
1190    let code = match stalled {
1191        None => axum::http::StatusCode::OK,
1192        Some(_) => axum::http::StatusCode::SERVICE_UNAVAILABLE,
1193    };
1194    (
1195        code,
1196        [(axum::http::header::CONTENT_TYPE, "application/json")],
1197        j.into_string(),
1198    )
1199        .into_response()
1200}
1201
1202/// Queries served and what they cost, since start.
1203///
1204/// Sum and max rather than a histogram: a p99 needs buckets, buckets need a
1205/// registry, and a registry is the metrics subsystem this endpoint exists to not
1206/// be. The mean says whether the engine is in the shape it was benchmarked in
1207/// and the max says whether anything pathological has run at all, which is the
1208/// pair an operator acts on; a real p99 is measured at the caller, where the
1209/// queue in front of Mira is also counted.
1210static QUERIES: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
1211static QUERY_NANOS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
1212static QUERY_MAX_NANOS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
1213
1214/// When the process started, so the counters below have a denominator. Forced in
1215/// `serve_with` rather than left to first touch, or "uptime" would mean "seconds
1216/// since someone first asked".
1217static START: std::sync::LazyLock<std::time::Instant> =
1218    std::sync::LazyLock::new(std::time::Instant::now);
1219
1220/// Wrapped around the query router only, so OTLP writes and UI asset fetches do
1221/// not land in the read latency an operator is reading.
1222async fn timed(req: axum::extract::Request, next: axum::middleware::Next) -> Response {
1223    let t = std::time::Instant::now();
1224    let res = next.run(req).await;
1225    let ns = t.elapsed().as_nanos() as u64;
1226    QUERIES.fetch_add(1, Relaxed);
1227    QUERY_NANOS.fetch_add(ns, Relaxed);
1228    QUERY_MAX_NANOS.fetch_max(ns, Relaxed);
1229    res
1230}
1231
1232/// Everything this node knows about itself, in one document.
1233///
1234/// The shape is the argument. Mira is a telemetry backend, so the wrong move is
1235/// to grow a second one inside it: no exposition format, no registry, no
1236/// histograms, no scrape endpoint on a second port and no crate to render any of
1237/// that. What is served is the counters the ingest path already keeps, plus the
1238/// two facts only the filesystem has, in the same JSON object every `/api/v1`
1239/// read already answers with — so the UI's `fetch`, an agent and `curl | jq` all
1240/// speak it without being told. Rates are left to the reader: `uptime_s` is the
1241/// denominator, and two polls give the interval rate, which is the only rate
1242/// that is true of *now* rather than of the whole run.
1243async fn stats(
1244    axum::extract::State(dir): axum::extract::State<std::sync::Arc<PathBuf>>,
1245) -> Response {
1246    // `scan` and `statfs` are filesystem work, and a cold readdir over a week of
1247    // blocks stalls the OS thread it lands on exactly like a query does. So it
1248    // goes where queries go.
1249    let disk = tokio::task::spawn_blocking(move || {
1250        (
1251            mira_core::block::free_fraction(&dir).ok(),
1252            pipeline::SIGNALS.map(|s| mira_core::block::scan(&dir, s).ok().map(|b| b.len() as u64)),
1253        )
1254    })
1255    .await;
1256    // `null`, not zero, when the filesystem would not answer: "no blocks" and "I
1257    // could not look" are different operational facts and a zero conflates them.
1258    let (free, on_disk) = disk.unwrap_or((None, [None; 3]));
1259
1260    let now = std::time::SystemTime::now()
1261        .duration_since(std::time::UNIX_EPOCH)
1262        .unwrap_or_default()
1263        .as_secs();
1264    // `then_some` and not `then`: one saturating subtraction is cheaper to do
1265    // than to defer behind a closure, and that closure is a body only a signal
1266    // with a block already open would ever enter.
1267    let age = |since: u64| (since != 0).then_some(now.saturating_sub(since));
1268    let queries = QUERIES.load(Relaxed);
1269
1270    let mut j = mira_core::json::Json::new();
1271    j.obj(|j| {
1272        j.key("uptime_s");
1273        j.u64(START.elapsed().as_secs());
1274        j.key("peak_rss_bytes");
1275        j.u64(peak_rss());
1276        j.key("free_fraction");
1277        match free {
1278            Some(f) => j.f64(f),
1279            None => j.null(),
1280        }
1281        // Zero on any volume that implements write barriers. Non-zero says this
1282        // one does not, and that the durability promise here is `fsync`'s
1283        // rather than `F_FULLFSYNC`'s — see `mira_core::sync_all`.
1284        j.key("degraded_syncs");
1285        j.u64(mira_core::degraded_syncs());
1286        j.key("queries");
1287        j.obj(|j| {
1288            j.key("count");
1289            j.u64(queries);
1290            j.key("mean_ms");
1291            j.f64(QUERY_NANOS.load(Relaxed) as f64 / queries.max(1) as f64 / 1e6);
1292            j.key("max_ms");
1293            j.f64(QUERY_MAX_NANOS.load(Relaxed) as f64 / 1e6);
1294        });
1295        j.key("signals");
1296        j.obj(|j| {
1297            for (r, blocks) in pipeline::REJECTS.iter().zip(on_disk) {
1298                j.key(r.signal);
1299                j.obj(|j| {
1300                    for (k, v) in [
1301                        ("shed", r.shed.load(Relaxed)),
1302                        ("failed", r.failed.load(Relaxed)),
1303                        ("refused", r.refused.load(Relaxed)),
1304                        ("blocks_published", r.published.load(Relaxed)),
1305                        ("rows", r.rows.load(Relaxed)),
1306                        ("bytes", r.bytes.load(Relaxed)),
1307                    ] {
1308                        j.key(k);
1309                        j.u64(v);
1310                    }
1311                    // Absent-as-null again: nothing open, and never stalled, are
1312                    // both "no age to report" rather than "an age of zero".
1313                    for (k, v) in [
1314                        ("blocks_on_disk", blocks),
1315                        ("open_block_age_s", age(r.open_since.load(Relaxed))),
1316                        ("stalled_s", age(r.stalled_since.load(Relaxed))),
1317                    ] {
1318                        j.key(k);
1319                        match v {
1320                            Some(v) => j.u64(v),
1321                            None => j.null(),
1322                        }
1323                    }
1324                });
1325            }
1326        });
1327    });
1328    json_ok(j.into_string())
1329}
1330
1331/// High-water mark of this process's resident set, in bytes.
1332///
1333/// Resident footprint is one of the four axes performance is scored on (section 11),
1334/// so a node that cannot report it can only be measured from outside with a
1335/// sampler — which is how the 64-connection run in the last sweep came back
1336/// with an implausible 26 MiB: `ps` simply missed the peak. `getrusage` cannot
1337/// miss it, because the kernel keeps the maximum rather than the instant.
1338///
1339/// The peak and not the current value because the peak is the number that has
1340/// to fit in the container's limit, and because it is one portable call:
1341/// `ru_maxrss` is bytes on macOS and kibibytes on Linux, which is the whole of
1342/// the platform difference and is why this is not inlined at the call site.
1343fn peak_rss() -> u64 {
1344    // SAFETY: `getrusage` writes the whole struct or returns -1; the zeroed
1345    // value is a valid `rusage` either way.
1346    let mut ru: libc::rusage = unsafe { std::mem::zeroed() };
1347    // The return code is not checked, because the zeroed struct is already the
1348    // answer if it failed: `getrusage(RUSAGE_SELF)` documents only EFAULT and
1349    // EINVAL, both of which are this call site being wrong rather than anything
1350    // that can happen at runtime, and a `ru_maxrss` the kernel never touched
1351    // reports 0 — which is what a "cannot measure" branch would have returned.
1352    //
1353    // SAFETY: `ru` is a live, correctly-typed `rusage` the kernel may write in
1354    // full; there is no other precondition on `RUSAGE_SELF`.
1355    unsafe { libc::getrusage(libc::RUSAGE_SELF, &mut ru) };
1356    // `#[cfg]` and not `cfg!`, which compiles both arms and runs one: the arm
1357    // for the platform this is not built for can never execute, so under `cfg!`
1358    // it is a line no test can ever reach.
1359    #[cfg(target_os = "macos")]
1360    const UNIT: u64 = 1;
1361    #[cfg(not(target_os = "macos"))]
1362    const UNIT: u64 = 1024;
1363    ru.ru_maxrss.max(0) as u64 * UNIT
1364}
1365
1366fn json_ok(body: String) -> Response {
1367    (
1368        [(axum::http::header::CONTENT_TYPE, "application/json")],
1369        body,
1370    )
1371        .into_response()
1372}
1373
1374/// Resolve on the first stop signal.
1375///
1376/// SIGTERM matters as much as SIGINT here: it is what every container
1377/// orchestrator sends, so without this arm a rolling restart kills the process
1378/// mid-block and the exporters waiting on that block see a reset.
1379///
1380/// Two `#[cfg]` bodies and not one with a `cfg!` in it: `cfg!` compiles both,
1381/// so the arm for the platform this is not built for is a line no test on this
1382/// platform can ever reach.
1383#[cfg(unix)]
1384async fn shutdown() {
1385    // `expect`, rather than falling back to ^C alone. `signal` fails only for a
1386    // signal that cannot be caught and on a runtime with no signal driver —
1387    // both of them this call site being wrong — and a silent fall-back to ^C is
1388    // a node in a container that nothing but SIGKILL can stop, which is exactly
1389    // the failure this function exists to prevent, reported nowhere.
1390    let mut term = tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate())
1391        .expect("a SIGTERM handler on the serving runtime");
1392    tokio::select! {
1393        _ = tokio::signal::ctrl_c() => {}
1394        _ = term.recv() => {}
1395    }
1396}
1397
1398/// ^C only: there is no SIGTERM to wait for.
1399#[cfg(not(unix))]
1400async fn shutdown() {
1401    let _ = tokio::signal::ctrl_c().await;
1402}
1403
1404#[cfg(test)]
1405mod tests {
1406    use super::*;
1407
1408    /// A command line, through the real tree.
1409    ///
1410    /// Whitespace-split, so no test here can pass a value with a space in it —
1411    /// which is what the `--version` charset test in `update.rs` is for.
1412    fn argv(s: &str) -> Result<ArgMatches, String> {
1413        cli()
1414            .try_get_matches_from(std::iter::once("mira").chain(s.split_whitespace()))
1415            .map_err(|e| e.to_string())
1416    }
1417
1418    /// The server's `Config` from a command line, with clap's refusals and the
1419    /// config file's flattened into the one `String` the caller asserts on.
1420    fn load(s: &str) -> Result<Config, String> {
1421        load_from(&argv(s)?)
1422    }
1423
1424    /// `mira offload <verb> …`, reached the way [`run`] reaches it.
1425    ///
1426    /// Going through the tree rather than calling [`offload_cmd`] with a verb
1427    /// name directly is what keeps the two refusals that are now clap's — a
1428    /// missing verb and an unknown one — inside the same assertion table as the
1429    /// two that are still this file's.
1430    fn offload(s: &str) -> Result<(), String> {
1431        let m = argv(&format!("offload {s}"))?;
1432        let (verb, sub) = m
1433            .subcommand_matches("offload")
1434            .and_then(ArgMatches::subcommand)
1435            .expect("subcommand_required");
1436        offload_cmd(verb, sub)
1437    }
1438
1439    fn tmp(name: &str) -> PathBuf {
1440        let d = std::env::temp_dir().join(format!("mira-{name}-{}", std::process::id()));
1441        let _ = std::fs::remove_dir_all(&d);
1442        std::fs::create_dir_all(&d).unwrap();
1443        d
1444    }
1445
1446    /// Both stop edges the tests below drive `serve_with` with, as one type.
1447    ///
1448    /// `serve_with` is generic over this future, so `ready(())` in one test and
1449    /// `pending()` in the next compile two whole servers, each running only the
1450    /// half its own callers reach — including under a coverage run, which counts
1451    /// each copy separately and so reports lines as unrun that another copy of
1452    /// the same source ran.
1453    async fn stop_edge(immediately: bool) {
1454        if !immediately {
1455            std::future::pending::<()>().await;
1456        }
1457    }
1458
1459    /// The edge that never fires is still pending once something polls it.
1460    ///
1461    /// Less circular than it looks. Three tests below hand `serve_with` this
1462    /// future to prove the server *keeps* serving, and every one of them would
1463    /// pass for the wrong reason if it resolved. And `serve_with` only polls
1464    /// its stop edge when it has nothing else to do, so whether that arm runs
1465    /// inside any given test run is otherwise a race against the request the
1466    /// test is making — which is a line of coverage that moves on its own.
1467    #[tokio::test]
1468    async fn the_stop_edge_fires_when_it_is_told_to_and_never_otherwise() {
1469        let zero = std::time::Duration::ZERO;
1470        let never = tokio::time::timeout(zero, stop_edge(false));
1471        assert!(never.await.is_err(), "the never-stop edge stopped");
1472        tokio::time::timeout(zero, stop_edge(true))
1473            .await
1474            .expect("the immediate edge did not fire");
1475    }
1476
1477    /// The probe tasks wake up and write into the statics the diagnosis reads.
1478    ///
1479    /// `start_paused` is what makes this an assertion rather than a stopwatch:
1480    /// the clock jumps to each deadline with no wall time passing, so two of
1481    /// the 50 ms periods fit in the 120 ms below with nothing left to a busy
1482    /// box, and the lag the sampler computes is `~0 - 50 ms` saturated to zero.
1483    /// `tokio::time::interval` fires its first tick immediately, so the 5 s
1484    /// dump runs once inside the same window. Mutation check: drop the
1485    /// `.record(…)` and the count stays where it started; record
1486    /// `t.elapsed()` without subtracting the period and `max_ns` is no longer
1487    /// zero, because real time did pass even though virtual time did the
1488    /// waiting.
1489    #[tokio::test(start_paused = true)]
1490    async fn the_probe_tasks_sample_the_runtime_and_dump_it() {
1491        use std::sync::atomic::Ordering::Relaxed;
1492        let lag = &mira_core::diag::RUNTIME_LAG;
1493        let before = lag.n.load(Relaxed);
1494        spawn_probes();
1495        tokio::time::sleep(std::time::Duration::from_millis(120)).await;
1496        assert_eq!(
1497            lag.n.load(Relaxed),
1498            before + 2,
1499            "the lag sampler did not run once per 50 ms period"
1500        );
1501        assert_eq!(
1502            lag.max_ns.load(Relaxed),
1503            0,
1504            "a wake that cost no real time was reported as late"
1505        );
1506    }
1507
1508    /// `mira offload list` and `mira offload restore`: a `readdir` and a copy,
1509    /// and four refusals that happen before either.
1510    ///
1511    /// The block here is a directory with the right *name* and nothing valid
1512    /// inside it, which is the point — neither verb opens a table. The name is
1513    /// the catalog entry (section 3.2), so a command that needed to read the
1514    /// bytes to list them would mean the naming scheme was not carrying its
1515    /// weight. Mutation check: make `restore` unconditional and the last call
1516    /// overwrites the block it already restored instead of reporting it
1517    /// present.
1518    #[test]
1519    fn offload_list_and_restore_read_the_store_and_nothing_else() {
1520        let dir = tmp("offload-cmd");
1521        let (store, data) = (dir.join("cold"), dir.join("data"));
1522        std::fs::create_dir_all(&data).unwrap();
1523        let uri = format!("file://{}", store.display());
1524
1525        // A missing verb, a wrong one, a missing URI and a scheme this binary
1526        // does not implement. All four are refused before anything is opened.
1527        for (args, want) in [
1528            ("", "list"),
1529            ("sync --offload file:///x", "unrecognized subcommand 'sync'"),
1530            ("list", "--offload"),
1531            ("list --offload s3://bucket", "s3://bucket"),
1532        ] {
1533            let e = offload(args).unwrap_err();
1534            assert!(e.contains(want), "`mira offload {args}` said: {e}");
1535        }
1536
1537        // An empty store is an empty catalog, not an error: there is no index
1538        // whose absence could mean something different.
1539        offload(&format!("list --offload {uri}")).unwrap();
1540
1541        let name = format!("{:020}-{:020}-{:08x}-{:012}-{:020}", 1_000, 2_000, 7, 1, 0);
1542        let block = store.join("logs").join("p=0").join(&name);
1543        std::fs::create_dir_all(&block).unwrap();
1544        std::fs::write(block.join("logs.arrow"), b"bytes").unwrap();
1545
1546        offload(&format!("list --offload {uri}")).unwrap();
1547        assert_eq!(
1548            std::fs::read_dir(&data).unwrap().count(),
1549            0,
1550            "`list` copies nothing"
1551        );
1552
1553        let restore = format!("restore --offload {uri} --data-dir {}", data.display());
1554        offload(&restore).unwrap();
1555        let local = data.join("logs").join("p=0").join(&name);
1556        assert_eq!(std::fs::read(local.join("logs.arrow")).unwrap(), b"bytes");
1557
1558        // Re-runnable, which is what makes it usable from a script that does
1559        // not track what it has already fetched.
1560        std::fs::write(local.join("logs.arrow"), b"local edit").unwrap();
1561        offload(&restore).unwrap();
1562        assert_eq!(
1563            std::fs::read(local.join("logs.arrow")).unwrap(),
1564            b"local edit",
1565            "a block already present is left alone"
1566        );
1567        let _ = std::fs::remove_dir_all(&dir);
1568    }
1569
1570    /// `mira offload push` is `restore` read backwards, and it removes nothing.
1571    ///
1572    /// The unlinking version of this verb is the one that cannot be built, and
1573    /// the assertion that the source survives is that argument rather than
1574    /// tidiness: a node reads both its WAL watermark and its next block
1575    /// sequence off the blocks it still holds, so emptying the directory walks
1576    /// both backwards and the next boot replays an absorbed log under reissued
1577    /// sequence numbers. Mutation check: make `push` unconditional and the last
1578    /// call overwrites an archived block with a volume someone has since
1579    /// edited, which is the one direction a backup verb must never go.
1580    #[test]
1581    fn offload_push_copies_out_of_the_data_dir_and_unlinks_nothing() {
1582        let dir = tmp("offload-push");
1583        let (store, data) = (dir.join("cold"), dir.join("data"));
1584        let uri = format!("file://{}", store.display());
1585
1586        let name = format!("{:020}-{:020}-{:08x}-{:012}-{:020}", 1_000, 2_000, 7, 1, 0);
1587        let local = data.join("logs").join("p=0").join(&name);
1588        std::fs::create_dir_all(&local).unwrap();
1589        std::fs::write(local.join("logs.arrow"), b"bytes").unwrap();
1590
1591        let push = format!("push --offload {uri} --data-dir {}", data.display());
1592        offload(&push).unwrap();
1593        let remote = store.join("logs").join("p=0").join(&name);
1594        assert_eq!(std::fs::read(remote.join("logs.arrow")).unwrap(), b"bytes");
1595        assert!(local.exists(), "push copies the block, it does not move it");
1596
1597        // The same block again: already archived, so a no-op rather than a
1598        // re-copy, and the verb still succeeds.
1599        offload(&push).unwrap();
1600
1601        // Different bytes under the same name is the collision, not a no-op —
1602        // reporting it as archived is what would let a scale-in delete the
1603        // volume holding the only copy.
1604        std::fs::write(local.join("logs.arrow"), b"local edit").unwrap();
1605        offload(&push).unwrap_err();
1606        assert_eq!(
1607            std::fs::read(remote.join("logs.arrow")).unwrap(),
1608            b"bytes",
1609            "a block already in the store is left alone"
1610        );
1611        let _ = std::fs::remove_dir_all(&dir);
1612    }
1613
1614    /// Flag > file > default, and every flag lands in the field it names.
1615    ///
1616    /// clap parses; [`load_from`] still decides which field each value reaches,
1617    /// and the failure that can produce is the quiet kind: a flag written into
1618    /// the wrong field starts a server that looks exactly right until someone
1619    /// reads a block from the wrong directory. It is also what holds the arg ids
1620    /// to the fields — [`opt`] answers `None` for an id no subcommand declares,
1621    /// so a typo here would be a flag that parses and then does nothing, and the
1622    /// assertions below are what catch it.
1623    #[test]
1624    fn flags_override_the_file_which_overrides_the_defaults() {
1625        let dir = tmp("load");
1626        let file = dir.join("mira.yaml");
1627        std::fs::write(
1628            &file,
1629            r#"{ "node": "from-file",
1630                 "listen": { "grpc": "127.0.0.1:1", "http": "127.0.0.1:2" },
1631                 "storage": { "dir": "/from/file", "retention": "3h" },
1632                 "ingest": { "max_request_bytes": "1MiB" } }"#,
1633        )
1634        .unwrap();
1635        let f = file.display();
1636
1637        let c = load(&format!("--config {f}")).unwrap();
1638        assert_eq!(c.node, "from-file");
1639        assert_eq!(c.data_dir, PathBuf::from("/from/file"));
1640        assert_eq!(c.retention, std::time::Duration::from_secs(3 * 3600));
1641        assert_eq!(c.max_request_bytes, 1 << 20);
1642        assert_eq!(c.http.port(), 2);
1643
1644        // The same file, every value overridden.
1645        let c = load(&format!(
1646            "--config {f} --node cli --grpc 127.0.0.1:3 --http 127.0.0.1:4 \
1647             --data-dir /from/cli --retention 30s --max-request-bytes 2MiB"
1648        ))
1649        .unwrap();
1650        assert_eq!(c.node, "cli");
1651        assert_eq!(c.grpc.port(), 3);
1652        assert_eq!(c.http.port(), 4);
1653        assert_eq!(c.data_dir, PathBuf::from("/from/cli"));
1654        assert_eq!(c.retention, std::time::Duration::from_secs(30));
1655        assert_eq!(c.max_request_bytes, 2 << 20);
1656
1657        // Everything the file above does not set, including the two that take
1658        // no value. Those two are interleaved with the rest rather than listed
1659        // apart, because a boolean flag that silently swallowed the next
1660        // argument would still pass every assertion in a block of its own.
1661        let c = load(
1662            "--queue 4096 --shards 8 --wal --alerts /from/cli.kyaml \
1663             --self-telemetry --telemetry-interval 1m",
1664        )
1665        .unwrap();
1666        assert_eq!(c.queue, 4096);
1667        assert_eq!(c.shards, 8);
1668        assert_eq!(c.alerts, Some(PathBuf::from("/from/cli.kyaml")));
1669        assert!(c.self_telemetry);
1670        assert!(c.wal);
1671        assert_eq!(c.telemetry_interval, std::time::Duration::from_secs(60));
1672
1673        // A URI is a string here; the scheme is refused where it is parsed.
1674        let c = load("--offload file:///srv/cold").unwrap();
1675        assert_eq!(c.offload.as_deref(), Some("file:///srv/cold"));
1676
1677        // No arguments at all is the shipped configuration.
1678        let d = load("").unwrap();
1679        assert_eq!(d.node, Config::default().node);
1680        assert!(!d.self_telemetry, "self-telemetry is opt-in");
1681
1682        for (args, want) in [
1683            ("--nope", "unexpected argument '--nope'"),
1684            // Deleted along with the fan-out that never existed. It is an
1685            // unknown flag now, which is the whole point of deleting it.
1686            ("--peers a:1", "unexpected argument '--peers'"),
1687            ("--node", "a value is required for '--node <NAME>'"),
1688            ("--config", "a value is required for '--config <FILE>'"),
1689            ("--grpc nope", "invalid value 'nope' for '--grpc <ADDR>'"),
1690            ("--http nope", "invalid value 'nope' for '--http <ADDR>'"),
1691            ("--retention nope", "not a duration"),
1692            ("--max-request-bytes nope", "not a size"),
1693            ("--queue nope", "not a whole number"),
1694            ("--queue 0", "at least 1"),
1695            // `--shards 0` is *not* here: zero is the documented auto value.
1696            // A negative is rejected rather than wrapped, which is what keeps
1697            // `-1` from arriving as 18 quintillion shards that `clamp` then
1698            // silently turns into 16. It is refused a step earlier than the
1699            // rest of this table — `allow_negative_numbers` is off, so `-1`
1700            // reads as a flag and never reaches `config::whole`.
1701            ("--shards nope", "not a whole number"),
1702            ("--shards -1", "unexpected argument '-1'"),
1703            ("--telemetry-interval nope", "not a duration"),
1704            ("--config /no/such/file.yaml", "/no/such/file.yaml"),
1705        ] {
1706            let e = load(args).unwrap_err();
1707            assert!(e.contains(want), "{args:?} said {e:?}");
1708        }
1709        let _ = std::fs::remove_dir_all(&dir);
1710    }
1711
1712    /// `mira mira` reads the directory the matching `mira serve` would write to,
1713    /// which is the whole reason it takes `--config` at all.
1714    #[test]
1715    fn the_tui_reads_the_directory_its_config_writes_to() {
1716        let dir = tmp("tui-src");
1717        let file = dir.join("mira.yaml");
1718        std::fs::write(&file, r#"{ "storage": { "dir": "/from/file" } }"#).unwrap();
1719        let f = file.display();
1720
1721        // Rendered rather than matched, so a wrong *variant* is a diff on the
1722        // left of the assertion instead of a panic in a `let ... else`: which
1723        // of the three answers came back is exactly what is under test.
1724        let src = |a: &str| {
1725            let out = argv(&format!("mira {a}")).and_then(|m| {
1726                tui_source(m.subcommand_matches("mira").expect("the tui subcommand"))
1727            });
1728            match out {
1729                Ok(tui::Source::Local(p)) => format!("local {}", p.display()),
1730                Ok(tui::Source::Remote(a)) => format!("remote {a}"),
1731                // First line only: clap's refusals carry the whole usage after a
1732                // blank line, which is the tree's contract to render, not this
1733                // test's to assert.
1734                Err(e) => format!("error {}", e.lines().next().unwrap_or_default()),
1735            }
1736        };
1737        let default_dir = Config::default().data_dir;
1738        for (args, want) in [
1739            (format!("--config {f}"), "local /from/file".to_owned()),
1740            (
1741                format!("--config {f} --data-dir /from/cli"),
1742                "local /from/cli".to_owned(),
1743            ),
1744            (String::new(), format!("local {}", default_dir.display())),
1745            // `--addr` wins outright: a remote source has no directory to read.
1746            ("--addr host:9999".into(), "remote host:9999".to_owned()),
1747            (
1748                "--nope".into(),
1749                "error error: unexpected argument '--nope' found".to_owned(),
1750            ),
1751            (
1752                "--data-dir".into(),
1753                "error error: a value is required for '--data-dir <PATH>' but none was supplied"
1754                    .to_owned(),
1755            ),
1756            (
1757                "--config".into(),
1758                "error error: a value is required for '--config <FILE>' but none was supplied"
1759                    .to_owned(),
1760            ),
1761        ] {
1762            assert_eq!(src(&args), want, "{args:?}");
1763        }
1764        let _ = std::fs::remove_dir_all(&dir);
1765    }
1766
1767    /// Start everything, then stop it.
1768    ///
1769    /// The assertion is that this returns at all. Shutdown is three ordered
1770    /// steps — stop accepting, await the servers so the last `Ingest` clone
1771    /// drops, then let each flusher seal what it holds — and if any link in that
1772    /// chain is wrong the drain never completes and the 15s timeout fires. It
1773    /// also proves the two listeners and the retention worker start from a
1774    /// `Config` alone, which is the one thing `e2e.rs` cannot say: it builds the
1775    /// router itself — and that the one line it logs on the way up carries what
1776    /// was resolved rather than what was asked for.
1777    #[tokio::test]
1778    async fn the_server_starts_from_a_config_and_drains_when_stopped() {
1779        let dir = tmp("serve");
1780        let cfg = Config {
1781            data_dir: dir.join("data"),
1782            grpc: "127.0.0.1:0".parse().unwrap(),
1783            http: "127.0.0.1:0".parse().unwrap(),
1784            // On, with an interval no test run reaches: this asserts that the
1785            // sampler is started and announced, not what it samples — that is
1786            // `telemetry`'s own test, and a 15-second default here would make
1787            // this one's output depend on how slow the machine is. It also makes
1788            // the elapsed-time assertion below a regression test for the sampler
1789            // holding the metrics flusher open: detached, this stop took exactly
1790            // `DRAIN_GRACE` every time.
1791            self_telemetry: true,
1792            telemetry_interval: std::time::Duration::from_secs(3600),
1793            ..Config::default()
1794        };
1795
1796        // A file, because `File` is a `MakeWriter` and writes to one land without
1797        // a flush — a buffer would need a type of its own here.
1798        let log = dir.join("start.log");
1799        // Thread-local, so it holds for this test alone — and `#[tokio::test]`
1800        // is a current-thread runtime, so it holds for everything the server
1801        // does on it too.
1802        let _logging = tracing::subscriber::set_default(
1803            tracing_subscriber::fmt()
1804                .with_writer(std::fs::File::create(&log).unwrap())
1805                .without_time()
1806                // Or every field is wrapped in the escapes that make it readable
1807                // on a terminal, which this is not.
1808                .with_ansi(false)
1809                .finish(),
1810        );
1811
1812        let t = std::time::Instant::now();
1813        serve_with(cfg.clone(), stop_edge(true)).await.unwrap();
1814        assert!(
1815            t.elapsed() < std::time::Duration::from_secs(15),
1816            "timed out"
1817        );
1818        // Created, not required to exist: an operator points `--data-dir` at a
1819        // path and expects the first start to make it.
1820        assert!(cfg.data_dir.is_dir());
1821
1822        // `--http 127.0.0.1:0` is a real thing to ask for, and this line is the
1823        // only place the port that was actually chosen is ever written down. It
1824        // used to be logged from the requested address, which reads as correct
1825        // and sends whoever pastes it at a closed port.
1826        let logged = std::fs::read_to_string(&log).unwrap();
1827        assert!(logged.contains("mira listening"), "{logged}");
1828        // No bound port is spelled `0`, in any of the three fields that carry one.
1829        assert!(!logged.contains("127.0.0.1:0"), "{logged}");
1830        assert!(logged.contains("ui=http://127.0.0.1:"), "{logged}");
1831        assert!(
1832            logged.contains("storing this node's own telemetry"),
1833            "{logged}"
1834        );
1835        // In the syntax `--retention` accepts, so the line round-trips.
1836        assert!(
1837            logged.contains(&format!("retention={}s", cfg.retention.as_secs())),
1838            "{logged}"
1839        );
1840
1841        // A port already taken is reported, not survived, and the message names
1842        // the address — on both listeners. The gRPC half is the one that used to
1843        // print `transport error` *after* logging that it was listening on it.
1844        let held = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
1845        let addr = held.local_addr().unwrap();
1846        for taken in [
1847            Config {
1848                http: addr,
1849                ..cfg.clone()
1850            },
1851            Config {
1852                grpc: addr,
1853                ..cfg.clone()
1854            },
1855        ] {
1856            let e = serve_with(taken, stop_edge(false))
1857                .await
1858                .unwrap_err()
1859                .to_string();
1860            assert!(e.contains(&addr.to_string()), "{e}");
1861            assert!(e.to_lowercase().contains("address"), "{e}");
1862        }
1863
1864        // A data directory that cannot be made says which path and why, rather
1865        // than `File exists (os error 17)`.
1866        let file = dir.join("a-file");
1867        std::fs::write(&file, b"").unwrap();
1868        let e = serve_with(
1869            Config {
1870                data_dir: file.clone(),
1871                ..cfg
1872            },
1873            stop_edge(false),
1874        )
1875        .await
1876        .unwrap_err()
1877        .to_string();
1878        assert!(e.contains(&file.display().to_string()), "{e}");
1879        let _ = std::fs::remove_dir_all(&dir);
1880    }
1881
1882    /// The two things `serve_with` does before anything is bound or mapped, and
1883    /// the order they are in.
1884    ///
1885    /// A rules file is read first *because* nothing has been created yet: a
1886    /// deployment that believes it is being paged and is not is the worst
1887    /// possible half-start, so it has to be a message and an exit rather than a
1888    /// node that is up with alerting quietly off. The log directory is opened
1889    /// next, and a failure there has to name the path — `File exists` on its
1890    /// own sends whoever reads it looking for a bug in Mira.
1891    #[tokio::test]
1892    async fn a_node_refuses_to_start_on_a_rules_file_or_a_log_it_cannot_open() {
1893        let dir = tmp("boot-guards");
1894        let rules = dir.join("alerts.kyaml");
1895        let cfg = |alerts: Option<PathBuf>, data_dir: PathBuf| Config {
1896            data_dir,
1897            grpc: "127.0.0.1:0".parse().unwrap(),
1898            http: "127.0.0.1:0".parse().unwrap(),
1899            alerts,
1900            ..Config::default()
1901        };
1902
1903        // A rules file that parses is loaded and the node comes up with it.
1904        std::fs::write(
1905            &rules,
1906            r#"{ "rules": [ { "name": "any-log", "over": "1m", "when": "count >= 1",
1907                              "query": { "signal": "logs" } } ] }"#,
1908        )
1909        .unwrap();
1910        serve_with(
1911            cfg(Some(rules.clone()), dir.join("ok")),
1912            std::future::ready(()),
1913        )
1914        .await
1915        .expect("a node with rules starts");
1916
1917        // One that does not is a refusal naming the file, before the data
1918        // directory it was given has been created.
1919        std::fs::write(&rules, "{ rules: nope }").unwrap();
1920        let never_made = dir.join("not-made");
1921        let e = serve_with(
1922            cfg(Some(rules.clone()), never_made.clone()),
1923            std::future::pending(),
1924        )
1925        .await
1926        .unwrap_err()
1927        .to_string();
1928        assert!(e.contains("alerts.kyaml"), "{e}");
1929        assert!(!never_made.exists(), "the boot got past the rules file");
1930
1931        // `.wal` occupied by a regular file: `create_dir_all` cannot make the
1932        // log directory, and an unopenable log is a start that would have
1933        // acknowledged exports it could not recover.
1934        let wal_blocked = dir.join("wal-blocked");
1935        std::fs::create_dir_all(&wal_blocked).unwrap();
1936        std::fs::write(wal_blocked.join(".wal"), b"not a directory").unwrap();
1937        let cfg = Config {
1938            wal: true,
1939            ..cfg(None, wal_blocked.clone())
1940        };
1941        let e = serve_with(cfg, std::future::pending())
1942            .await
1943            .unwrap_err()
1944            .to_string();
1945        assert!(e.contains(".wal"), "{e}");
1946        let _ = std::fs::remove_dir_all(&dir);
1947    }
1948
1949    /// A flusher that cannot start takes the process down with it.
1950    ///
1951    /// The alternative is the failure nobody notices: two signals keep working,
1952    /// the third answers every export with a 503 until someone restarts it, and
1953    /// the process stays up and green throughout. Here `logs` is a regular file,
1954    /// so the logs flusher cannot scan its directory and returns immediately.
1955    #[tokio::test]
1956    async fn a_flusher_that_cannot_start_stops_the_server() {
1957        let dir = tmp("wedged");
1958        std::fs::write(dir.join("logs"), b"not a directory").unwrap();
1959        let cfg = Config {
1960            data_dir: dir.clone(),
1961            grpc: "127.0.0.1:0".parse().unwrap(),
1962            http: "127.0.0.1:0".parse().unwrap(),
1963            // Off, or the replay reaches the same broken directory first and
1964            // this stops being a test about the flusher. That boot order is
1965            // itself correct — a log that cannot be read is a worse thing to
1966            // start over than a directory that cannot be scanned — but it is
1967            // not what is being asserted here.
1968            wal: false,
1969            ..Config::default()
1970        };
1971        // `pending`, so the only thing that can end this is the flusher.
1972        let e = serve_with(cfg, stop_edge(false))
1973            .await
1974            .unwrap_err()
1975            .to_string();
1976        assert!(e.contains("flusher"), "{e}");
1977        let _ = std::fs::remove_dir_all(&dir);
1978    }
1979
1980    /// [`drain`]'s last resort. The happy path is
1981    /// `the_server_starts_from_a_config_and_drains_when_stopped`; this is the
1982    /// branch that one can never take, because there the flushers do land.
1983    /// A real `grace` rather than a paused clock: `tokio`'s `test-util` is a
1984    /// feature the workspace does not carry, and a millisecond costs less than
1985    /// carrying it.
1986    #[tokio::test]
1987    async fn a_drain_that_never_lands_leaves_anyway() {
1988        let (stop, rx) = tokio::sync::watch::channel(());
1989        let wedged = || tokio::spawn(std::future::pending::<()>());
1990        drain(
1991            stop,
1992            wedged(),
1993            wedged(),
1994            std::array::from_fn(|_| pipeline::Flushers::wedged()),
1995            std::time::Duration::from_millis(1),
1996        )
1997        .await;
1998        // It returned, which is the assertion — an unbounded `drain` would still
1999        // be awaiting the first handle. The listeners were told to stop before
2000        // the wait began, so a caller that gave up still stopped accepting.
2001        assert!(
2002            rx.has_changed().is_err(),
2003            "drain owns the sender to the end"
2004        );
2005    }
2006
2007    async fn text(r: Response) -> (axum::http::StatusCode, String) {
2008        let (parts, body) = r.into_parts();
2009        let body = axum::body::to_bytes(body, 1 << 20).await.unwrap();
2010        (parts.status, String::from_utf8(body.to_vec()).unwrap())
2011    }
2012
2013    /// The probe answers, and it answers with the numbers an operator wants
2014    /// while ingest is unhappy — the same ones the warn! lines count.
2015    #[tokio::test]
2016    async fn health_reports_every_signals_rejections() {
2017        let (status, body) = text(health().await).await;
2018        assert_eq!(status, axum::http::StatusCode::OK);
2019        assert!(body.starts_with(r#"{"status":"ok""#), "{body}");
2020        for signal in pipeline::SIGNALS {
2021            assert!(body.contains(&format!(r#""{signal}":{{"shed":"#)), "{body}");
2022        }
2023    }
2024
2025    /// Readiness is no longer liveness under a second name.
2026    ///
2027    /// The state that broke the old argument is a node that answers every
2028    /// request and cannot store a byte: it stayed 200 and stayed in the
2029    /// Service's endpoints while NACKing 100% of exports. A 503 is what moves
2030    /// that traffic to a replica that can take it, and the body says which
2031    /// signal and for how long so the reason is in the probe's own log.
2032    #[tokio::test]
2033    async fn readiness_fails_only_once_a_signal_has_been_unable_to_store() {
2034        let (status, body) = text(ready(None)).await;
2035        assert_eq!(status, axum::http::StatusCode::OK);
2036        assert_eq!(body, r#"{"status":"ok"}"#);
2037
2038        let (status, body) = text(ready(Some(("logs", 300)))).await;
2039        assert_eq!(status, axum::http::StatusCode::SERVICE_UNAVAILABLE);
2040        assert!(body.contains(r#""signal":"logs""#), "{body}");
2041        assert!(body.contains(r#""stalled_s":300"#), "{body}");
2042
2043        // The live wiring, which is healthy in a test binary: this is the only
2044        // thing that proves `/readyz` is not still `/health`'s handler.
2045        let (status, _) = text(readyz().await).await;
2046        assert_eq!(status, axum::http::StatusCode::OK);
2047    }
2048
2049    /// The self-telemetry an agent or an operator reads instead of six numbers
2050    /// and a log stream. Every field is asserted by name because the shape is
2051    /// the API: this is what a dashboard and an MCP client bind to.
2052    #[tokio::test]
2053    async fn stats_reports_what_this_node_is_doing_with_its_disk() {
2054        let dir = tmp("stats");
2055        let (status, body) =
2056            text(stats(axum::extract::State(std::sync::Arc::new(dir.clone()))).await).await;
2057        assert_eq!(status, axum::http::StatusCode::OK);
2058        for key in [
2059            r#""uptime_s":"#,
2060            r#""free_fraction":"#,
2061            r#""queries":{"count":"#,
2062            r#""mean_ms":"#,
2063            r#""max_ms":"#,
2064        ] {
2065            assert!(body.contains(key), "{key} missing from {body}");
2066        }
2067        for signal in pipeline::SIGNALS {
2068            assert!(body.contains(&format!(r#""{signal}":{{"shed":"#)), "{body}");
2069        }
2070        for key in [
2071            "refused",
2072            "blocks_published",
2073            "rows",
2074            "bytes",
2075            "blocks_on_disk",
2076            "open_block_age_s",
2077            "stalled_s",
2078        ] {
2079            assert!(body.contains(&format!(r#""{key}":"#)), "{key}: {body}");
2080        }
2081        // An empty directory is zero blocks, not an unreadable one, and nothing
2082        // is open in a process with no flusher: `null` says so without a zero
2083        // that would read as a real measurement.
2084        assert!(body.contains(r#""blocks_on_disk":0"#), "{body}");
2085        assert!(body.contains(r#""open_block_age_s":null"#), "{body}");
2086        // A fraction, not a byte count and not a percentage — read as the
2087        // number it is rather than as the text it happened to render to, or a
2088        // volume with everything free (`"free_fraction":1`, which a fresh tmpfs
2089        // or a scratch CI disk really does report) fails a test about the
2090        // shape of the document.
2091        let free = api::parse(&body).expect("the document is KYAML")["free_fraction"]
2092            .as_f64()
2093            .expect("a readable volume reports a fraction");
2094        assert!(
2095            free > 0.0 && free <= 1.0,
2096            "free_fraction is a fraction of the volume: {free}"
2097        );
2098
2099        // A path the filesystem will not answer for — a detached volume, a
2100        // `subPath` that vanished. "I could not look" is not "the disk is
2101        // empty": a zero here reads as a volume with no room left and takes a
2102        // healthy node out of rotation, so the answer is `null` and the
2103        // endpoint still returns 200 rather than failing the whole document.
2104        let gone = std::sync::Arc::new(dir.join("no-such-volume"));
2105        let (status, body) = text(stats(axum::extract::State(gone)).await).await;
2106        assert_eq!(status, axum::http::StatusCode::OK);
2107        assert!(body.contains(r#""free_fraction":null"#), "{body}");
2108        let _ = std::fs::remove_dir_all(&dir);
2109    }
2110
2111    /// The peak resident set is one of the four axes performance is scored on,
2112    /// so it has to be a real measurement in the units the field name claims.
2113    ///
2114    /// The unit is the whole hazard: `ru_maxrss` is bytes on macOS and
2115    /// kibibytes on Linux, and getting it backwards is not a visible failure —
2116    /// it is a number 1024× out that a dashboard renders without complaint. A
2117    /// test process is comfortably inside these bounds on either platform;
2118    /// either mistake leaves it outside one of them.
2119    #[test]
2120    fn the_peak_resident_set_is_reported_in_bytes() {
2121        let rss = peak_rss();
2122        assert!(rss > 1 << 20, "{rss} bytes is below a running process");
2123        assert!(rss < 100 << 30, "{rss} bytes is a unit mistake, not an RSS");
2124    }
2125
2126    /// `mira mira --data-dir` maps blocks with no server in front of it, so it
2127    /// needs the guards the server runs or it answers the one question it exists
2128    /// for with a lie: `block::scan` reads ENOENT as an empty directory, and a
2129    /// detached volume comes out as `0/0 blocks` — the same screen a healthy
2130    /// empty store draws.
2131    #[test]
2132    fn the_tui_refuses_a_data_directory_the_server_would_have_refused() {
2133        let dir = tmp("tui-guard");
2134        let local = |p: &Path| tui::Source::Local(p.to_path_buf());
2135        // A real directory passes both guards, empty or not: an empty block
2136        // directory is a normal thing to point this at.
2137        check_source(&local(&dir), true).unwrap();
2138
2139        for bad in [dir.join("nope"), {
2140            let f = dir.join("a-file");
2141            std::fs::write(&f, b"").unwrap();
2142            f
2143        }] {
2144            let e = check_source(&local(&bad), true).unwrap_err().to_string();
2145            assert!(e.contains(&bad.display().to_string()), "{e}");
2146            assert!(e.contains("not a directory"), "{e}");
2147            // Off a terminal the same path is accepted, because `tui::run`'s
2148            // own refusal comes first and is the more useful answer: this
2149            // diagnosis is about a screen that was never going to be drawn.
2150            check_source(&local(&bad), false).unwrap();
2151            // And a remote source is never this path at all, however unusable
2152            // the same string would be as a directory: those blocks are mapped
2153            // by the server on the other end, which ran these guards itself.
2154            let remote = tui::Source::Remote(bad.display().to_string());
2155            check_source(&remote, true).unwrap();
2156        }
2157        let _ = std::fs::remove_dir_all(&dir);
2158    }
2159
2160    /// Boot recovery end to end: every frame no block claims goes back through
2161    /// its own signal's flusher, before anything is served.
2162    ///
2163    /// The three signals share one log, so a replay that read the frame header
2164    /// wrongly would hand a span to the log encoder. And a frame that passed its
2165    /// checksum and then will not decode has to be survivable, because stopping
2166    /// on it would abandon every frame behind it — one dead export instead of
2167    /// the whole log. It stays unclaimed until a later block of that signal
2168    /// covers it, which is the next export, so it does not pin the log either.
2169    #[tokio::test]
2170    async fn a_boot_replays_every_frame_no_block_claims() {
2171        use mira_core::wal::Signal;
2172        use mira_proto::collector::metrics::v1::ExportMetricsServiceRequest;
2173        use mira_proto::collector::trace::v1::ExportTraceServiceRequest;
2174        use mira_proto::metrics::v1::metric::Data;
2175        use mira_proto::metrics::v1::number_data_point::Value as NumValue;
2176        use mira_proto::metrics::v1::{
2177            Gauge, Metric, NumberDataPoint, ResourceMetrics, ScopeMetrics,
2178        };
2179        use mira_proto::trace::v1::{ResourceSpans, ScopeSpans, Span};
2180        use prost::Message as _;
2181
2182        let dir = tmp("replay");
2183        let node = mira_core::block::node_id("replaynode");
2184        let spans = ExportTraceServiceRequest {
2185            resource_spans: vec![ResourceSpans {
2186                scope_spans: vec![ScopeSpans {
2187                    spans: vec![Span {
2188                        trace_id: vec![0x11; 16].into(),
2189                        span_id: vec![0x22; 8].into(),
2190                        name: "GET /".into(),
2191                        start_time_unix_nano: 3_000,
2192                        end_time_unix_nano: 3_500,
2193                        ..Default::default()
2194                    }],
2195                    ..Default::default()
2196                }],
2197                ..Default::default()
2198            }],
2199        };
2200        let points = ExportMetricsServiceRequest {
2201            resource_metrics: vec![ResourceMetrics {
2202                scope_metrics: vec![ScopeMetrics {
2203                    metrics: vec![Metric {
2204                        name: "process.cpu".into(),
2205                        data: Some(Data::Gauge(Gauge {
2206                            data_points: vec![NumberDataPoint {
2207                                time_unix_nano: 4_000,
2208                                value: Some(NumValue::AsDouble(0.5)),
2209                                ..Default::default()
2210                            }],
2211                        })),
2212                        ..Default::default()
2213                    }],
2214                    ..Default::default()
2215                }],
2216                ..Default::default()
2217            }],
2218        };
2219
2220        // A crash: four frames appended, nothing sealed. The last is not an OTLP
2221        // export — field 1 tagged as a varint, where the schema has a message.
2222        {
2223            let wal = mira_core::wal::Wal::open(&dir, node).unwrap();
2224            let logs = e2e::logs_export("checkout", 2_000, 4).encode_to_vec();
2225            wal.append(Signal::Logs, &logs).unwrap();
2226            wal.append(Signal::Traces, &spans.encode_to_vec()).unwrap();
2227            wal.append(Signal::Metrics, &points.encode_to_vec())
2228                .unwrap();
2229            wal.append(Signal::Logs, b"\x08").unwrap();
2230        }
2231
2232        let wal = std::sync::Arc::new(mira_core::wal::Wal::open(&dir, node).unwrap());
2233        let pcfg = std::sync::Arc::new(pipeline::Config {
2234            data_dir: dir.clone(),
2235            node,
2236            wal: Some(wal),
2237            max_block_age: std::time::Duration::from_millis(50),
2238            ..Default::default()
2239        });
2240        let (logs, _ol, h_logs) = pipeline::spawn::<mira_core::logs::LogsBuilder>(&pcfg);
2241        let (traces, _ot, h_traces) = pipeline::spawn::<mira_core::traces::TracesBuilder>(&pcfg);
2242        let (metrics, _om, h_metrics) =
2243            pipeline::spawn::<mira_core::metrics::MetricsBuilder>(&pcfg);
2244
2245        replay(&dir, node, logs.clone(), traces.clone(), metrics.clone())
2246            .await
2247            .unwrap();
2248        drop((logs, traces, metrics));
2249        for h in [h_logs, h_traces, h_metrics] {
2250            h.await.unwrap();
2251        }
2252
2253        for signal in pipeline::SIGNALS {
2254            let published = mira_core::block::scan(&dir, signal).unwrap();
2255            assert_eq!(published.len(), 1, "{signal} did not store its frame");
2256        }
2257        // A block claims the first sequence of its signal that nothing covers,
2258        // not one past the frame it happens to hold — under shards the two are
2259        // different numbers, and only the first is safe to skip on the next
2260        // boot. Here nothing of any signal is left outstanding: frames 0, 1 and
2261        // 2 are in blocks, and frame 3 was retired when it failed to decode. So
2262        // all three claim the whole log, and the next boot replays nothing.
2263        //
2264        // Sequence 3 being dropped rather than pinned is the point of that
2265        // retirement: a frame that will never decode must not hold a watermark,
2266        // or every frame published behind it is replayed on every boot forever.
2267        assert_eq!(
2268            mira_core::block::wal_watermarks(&dir, node).unwrap(),
2269            [4, 4, 4]
2270        );
2271        let _ = std::fs::remove_dir_all(&dir);
2272    }
2273
2274    /// What a boot after a hard kill says out loud.
2275    ///
2276    /// Recovery is silent work on a path nobody watches, so the report is the
2277    /// only way an operator learns that this start replayed anything — and the
2278    /// torn tail is the line that distinguishes "we crashed" from "a byte on
2279    /// this volume went bad", which are different pages. Both are field
2280    /// expressions inside `tracing` macros, which means they are only ever
2281    /// *evaluated* under a subscriber: without one here, a typo in them ships.
2282    #[tokio::test]
2283    async fn a_boot_after_a_hard_kill_reports_the_torn_tail_and_what_it_recovered() {
2284        use mira_core::wal::Signal;
2285        use prost::Message as _;
2286
2287        let dir = tmp("torn-replay");
2288        let node = mira_core::block::node_id("tornnode");
2289        {
2290            let wal = mira_core::wal::Wal::open(&dir, node).unwrap();
2291            for i in 0..2 {
2292                let body = e2e::logs_export("checkout", 2_000 + i, 1).encode_to_vec();
2293                wal.append(Signal::Logs, &body).unwrap();
2294            }
2295            wal.sync().unwrap();
2296        }
2297        // Four bytes off the tail: the last frame loses its checksum, which is
2298        // exactly what a process killed mid-write leaves behind.
2299        let seg = dir
2300            .join(".wal")
2301            .join(format!("{node:08x}-{:020}.wal", 0u64));
2302        let len = std::fs::metadata(&seg).unwrap().len();
2303        std::fs::OpenOptions::new()
2304            .write(true)
2305            .open(&seg)
2306            .unwrap()
2307            .set_len(len - 4)
2308            .unwrap();
2309
2310        let pcfg = std::sync::Arc::new(pipeline::Config {
2311            data_dir: dir.clone(),
2312            node,
2313            max_block_age: std::time::Duration::from_millis(50),
2314            ..Default::default()
2315        });
2316        let (logs, _ol, h_logs) = pipeline::spawn::<mira_core::logs::LogsBuilder>(&pcfg);
2317        let (traces, _ot, h_traces) = pipeline::spawn::<mira_core::traces::TracesBuilder>(&pcfg);
2318        let (metrics, _om, h_metrics) =
2319            pipeline::spawn::<mira_core::metrics::MetricsBuilder>(&pcfg);
2320
2321        let (guard, log) = e2e::capture();
2322        replay(&dir, node, logs.clone(), traces.clone(), metrics.clone())
2323            .await
2324            .expect("a torn tail is a recovery, not a refusal");
2325        drop(guard);
2326
2327        let text = log.text();
2328        assert!(text.contains("torn frame"), "{text}");
2329        assert!(text.contains("segments=1"), "{text}");
2330        assert!(
2331            text.contains("recovered from the write-ahead log"),
2332            "{text}"
2333        );
2334        // The whole frame before the tear, and only it.
2335        assert!(text.contains("replayed=1"), "{text}");
2336        assert!(text.contains("elapsed_ms="), "{text}");
2337
2338        drop((logs, traces, metrics));
2339        for h in [h_logs, h_traces, h_metrics] {
2340            h.await.unwrap();
2341        }
2342        assert_eq!(mira_core::block::scan(&dir, "logs").unwrap().len(), 1);
2343        let _ = std::fs::remove_dir_all(&dir);
2344    }
2345
2346    /// A replay that cannot deliver stops the boot.
2347    ///
2348    /// The alternative is the quietest possible data loss: the flusher for one
2349    /// signal is gone, every frame for it is dropped on the floor, the node
2350    /// finishes starting and answers `/readyz` with a 200 — and the log those
2351    /// frames were in is truncated by the next block that gets published. So
2352    /// the first undeliverable frame ends the boot with an error naming the
2353    /// directory, and the supervisor restarts into a working process.
2354    #[tokio::test]
2355    async fn a_replay_with_nowhere_to_put_a_frame_refuses_to_finish_the_boot() {
2356        use mira_core::wal::Signal;
2357        use prost::Message as _;
2358
2359        let dir = tmp("replay-closed");
2360        let node = mira_core::block::node_id("closednode");
2361        {
2362            let wal = mira_core::wal::Wal::open(&dir, node).unwrap();
2363            wal.append(
2364                Signal::Logs,
2365                &e2e::logs_export("checkout", 2_000, 1).encode_to_vec(),
2366            )
2367            .unwrap();
2368            wal.sync().unwrap();
2369        }
2370
2371        let pcfg = std::sync::Arc::new(pipeline::Config {
2372            data_dir: dir.clone(),
2373            node,
2374            ..Default::default()
2375        });
2376        let (logs, _ol, mut h_logs) = pipeline::spawn::<mira_core::logs::LogsBuilder>(&pcfg);
2377        let (traces, _ot, _ht) = pipeline::spawn::<mira_core::traces::TracesBuilder>(&pcfg);
2378        let (metrics, _om, _hm) = pipeline::spawn::<mira_core::metrics::MetricsBuilder>(&pcfg);
2379        // The one failure mode a replay cannot route around: the receiving end
2380        // of this signal's channel is gone, so no retry and no other signal
2381        // makes the frame land.
2382        h_logs.abort();
2383        let _ = h_logs.await;
2384
2385        let e = replay(&dir, node, logs, traces, metrics)
2386            .await
2387            .expect_err("a frame with nowhere to go must stop the boot");
2388        let e = e.to_string();
2389        assert!(e.contains("flusher"), "{e}");
2390        assert!(e.contains(&dir.display().to_string()), "{e}");
2391        let _ = std::fs::remove_dir_all(&dir);
2392    }
2393}