Skip to main content

mira/
api.rs

1//! The query API.
2//!
3//! Shares the OTLP/HTTP listener rather than taking a port of its own: `/v1/*`
4//! is OTLP, `/api/v1/*` is query, `/` is the UI. One port is one thing to
5//! expose, one thing to firewall and one thing to get wrong, which is the whole
6//! argument for a single binary applied one level down.
7//!
8//! Queries are KYAML documents, and the parser is the one `config.rs` already
9//! uses. That is not a coincidence or a saving — it is the point of the
10//! KYAML-first principle. KYAML is a strict YAML 1.2 subset with explicit `{}`
11//! and `[]`, quoted strings and permitted trailing commas, which makes valid
12//! JSON valid KYAML: a browser can `JSON.stringify` a query and an agent can
13//! write one with comments in it, and both arrive at the same parser. There is
14//! no second query language and no JSON dependency.
15//!
16//! Every handler hops to `spawn_blocking` before touching a block. Reads are
17//! mmap reads, and a cold page fault stalls the OS thread it lands on with no
18//! yield point and no signal to the scheduler; run one on a tokio worker and it
19//! blocks every other connection that worker owns.
20
21use std::path::PathBuf;
22use std::sync::{Arc, LazyLock};
23
24use axum::Router;
25use axum::extract::State;
26use axum::http::{StatusCode, header};
27use axum::response::{IntoResponse, Response};
28use axum::routing::post;
29use tokio::sync::Semaphore;
30use yaml_rust2::parser::{Event, EventReceiver, Parser};
31use yaml_rust2::{Yaml, YamlLoader};
32
33use mira_core::frame::{self, Expand};
34use mira_core::query::{self, Op, Search, Signal, Target, Term, Value};
35use mira_core::series::{self, SeriesQuery};
36
37use crate::pipeline;
38
39#[derive(Clone, Default)]
40pub struct Api {
41    pub data_dir: Arc<PathBuf>,
42    /// The three flushers' open blocks, in [`pipeline::SIGNALS`] order.
43    ///
44    /// Default slots have no flusher behind them and always read empty, which is
45    /// what a unit test wanting only an `Api` gets. See
46    /// [`mira_core::signal::Open`].
47    pub open: pipeline::OpenSlots,
48    /// The alert evaluator's rules and their current state.
49    ///
50    /// Here rather than in a state of its own because three surfaces read it —
51    /// `/api/v1/alerts`, the MCP tool and the TUI pane — and the whole point of
52    /// [`crate::alert`] is that they are looking at one object. The default is
53    /// an engine with no rules, which answers "alerting is off".
54    pub alerts: Arc<crate::alert::Engine>,
55    /// The logs write handle, for the one tool that writes: `render_rca`'s
56    /// `emit` (see [`crate::rca`]). `None` means the document is rendered and
57    /// not stored, which is what a unit test's `Api` gets.
58    ///
59    /// Also `None` in the alert evaluator's copy, deliberately — see the
60    /// construction in `main`. That task never returns, so an [`pipeline::Ingest`]
61    /// clone inside it is one the logs flusher never sees dropped, and every
62    /// shutdown would sit out the full drain grace waiting on a channel that
63    /// cannot close.
64    pub logs: Option<pipeline::Ingest<mira_proto::collector::logs::v1::ExportLogsServiceRequest>>,
65}
66
67impl Api {
68    /// The open block for one signal, as the read path wants it — everything
69    /// acknowledged before this call, published or not.
70    ///
71    /// Awaited before the query rather than inside it: this is where
72    /// read-your-writes is bought, and paying for it here keeps the scan itself
73    /// synchronous and off the runtime. One entry per flusher shard, and two
74    /// from a shard whose last block is still being renamed — `search_open`
75    /// takes a list either way, which it did before a signal had more than one
76    /// open block at a time.
77    pub(crate) async fn open(&self, signal: &str) -> Vec<Arc<mira_core::signal::Open>> {
78        let Some(i) = pipeline::SIGNALS.iter().position(|s| *s == signal) else {
79            return Vec::new();
80        };
81        self.open[i].fresh().await
82    }
83
84    /// Every signal's open block, in [`pipeline::SIGNALS`] order.
85    ///
86    /// For the two frame walks that cross signals. Parallel rather than
87    /// concatenated because sequence numbers are per-signal: a flat list would
88    /// let the logs snapshot collide with a traces block on `(node, seq)`.
89    pub(crate) async fn open_all(&self) -> Vec<Vec<Arc<mira_core::signal::Open>>> {
90        let mut out = Vec::with_capacity(pipeline::SIGNALS.len());
91        for s in pipeline::SIGNALS {
92            out.push(self.open(s).await);
93        }
94        out
95    }
96}
97
98pub fn router(api: Api) -> Router {
99    Router::new()
100        .route("/api/v1/query", post(query_handler))
101        .route("/api/v1/metrics/query", post(series_handler))
102        .route("/api/v1/metrics/names", post(names_handler))
103        .route("/api/v1/correlate", post(correlate_handler))
104        .route("/api/v1/map", post(map_handler))
105        .route("/api/v1/entities", post(entities_handler))
106        .with_state(api)
107}
108
109/// Largest `limit` a caller can ask for.
110///
111/// Results are materialized into one JSON string in memory, so this is a real
112/// memory bound and not a policy. An agent asking for everything gets a lot,
113/// but not the process.
114const MAX_LIMIT: usize = 10_000;
115
116/// Log records or spans matching a filter, newest first.
117///
118/// The one read every other read is defined in terms of: an alert rule's
119/// `query`, a UI list and an agent's `query_records` are all this document.
120/// `next` in the response is the cursor to hand back as `after` for the page
121/// behind it, and `stats` says how much was scanned to answer.
122async fn query_handler(State(api): State<Api>, body: String) -> Response {
123    let q = match parse_search(&body, now_nanos()) {
124        Ok(q) => q,
125        Err(e) => return bad_request(&e),
126    };
127    let dir = api.data_dir.clone();
128    let open = api.open(q.signal.dir()).await;
129    run("rows", move || query::search_open(&dir, &q, &open)).await
130}
131
132/// One metric's series over a window, with the exemplars naming the traces
133/// behind the points.
134async fn series_handler(State(api): State<Api>, body: String) -> Response {
135    let q = match parse_series(&body, now_nanos()) {
136        Ok(q) => q,
137        Err(e) => return bad_request(&e),
138    };
139    let dir = api.data_dir.clone();
140    let open = api.open("metrics").await;
141    run("series", move || series::series_open(&dir, &q, &open)).await
142}
143
144/// Which metric names a window holds. An empty body means *right now*.
145///
146/// ```yaml
147/// { "from": "-1h", "to": "now" }
148/// ```
149async fn names_handler(State(api): State<Api>, body: String) -> Response {
150    let now = now_nanos();
151    // An empty body is a valid request for "what is there right now", which is
152    // the first thing a UI or an agent asks.
153    let doc = match window(if body.trim().is_empty() { "{}" } else { &body }, now) {
154        Ok(w) => w,
155        Err(e) => return bad_request(&e),
156    };
157    let dir = api.data_dir.clone();
158    let open = api.open("metrics").await;
159    run("names", move || {
160        series::names_open(&dir, doc.0, doc.1, &open)
161    })
162    .await
163}
164
165/// The frame around a filter: its time extent, the traces it touches and the
166/// services that took part — one round trip where a client makes three.
167///
168/// ```yaml
169/// {
170///   "signal": "logs",
171///   "from": "-15m",
172///   "where": [ { "field": "severity_number", "gte": 17 } ],
173///   "expand": [ "traces", "around:2s", "peers" ],
174/// }
175/// ```
176///
177/// One call is one investigation step: *what was going on around the thing I
178/// searched for*. The answer is a frame — a window, the traces it covers and
179/// the services that took part — and every field of it is an input to an
180/// ordinary `/api/v1/query`, which is what keeps the algebra closed.
181async fn correlate_handler(State(api): State<Api>, body: String) -> Response {
182    let now = now_nanos();
183    let (q, ops) = match parse_correlate(&body, now) {
184        Ok(v) => v,
185        Err(e) => return bad_request(&e),
186    };
187    let dir = api.data_dir.clone();
188    // Both signals, because `anchor` reads the one the search names and the
189    // span-side expanders always read traces.
190    let anchored = api.open(q.signal.dir()).await;
191    let all = api.open_all().await;
192    run("frame", move || correlate(&dir, &q, &ops, &anchored, &all)).await
193}
194
195/// Anchor, walk, label. Shared with the MCP tool of the same name, so an agent
196/// and the UI are reading one implementation rather than two.
197pub(crate) fn correlate(
198    dir: &std::path::Path,
199    q: &Search,
200    ops: &[Expand],
201    anchored: &[Arc<mira_core::signal::Open>],
202    all: &[Vec<Arc<mira_core::signal::Open>>],
203) -> mira_core::error::Result<query::Results> {
204    let (f, a) = frame::anchor(dir, q, anchored)?;
205    // The span-side expanders read traces and nothing else, so they get the
206    // traces slot rather than the whole set.
207    let traces = all.get(1).map_or(&[][..], Vec::as_slice);
208    let (f, w) = frame::expand(dir, &f, ops, traces)?;
209    let names = frame::names_of(dir, &f, all)?;
210    let mut j = mira_core::json::Json::new();
211    f.write_json(&mut j, &names);
212    Ok(query::Results {
213        json: j.into_string(),
214        stats: query::Stats {
215            blocks_total: a.blocks_total + w.blocks_total,
216            blocks_scanned: a.blocks_scanned + w.blocks_scanned,
217            rows_scanned: a.rows_scanned + w.rows_scanned,
218            rows_matched: a.rows_matched + w.rows_matched,
219            ..Default::default()
220        },
221        next: None,
222        cursors: Vec::new(),
223    })
224}
225
226/// The service map over a window.
227///
228/// ```yaml
229/// { "from": "-15m", "to": "now", "max_spans": 50000 }
230/// ```
231///
232/// `max_spans` bounds the walk rather than the answer: a map is built by
233/// reading spans and joining them by parent, so the honest limit is on how many
234/// are read, not on how many edges come back.
235async fn map_handler(State(api): State<Api>, body: String) -> Response {
236    let now = now_nanos();
237    let doc = match parse(if body.trim().is_empty() { "{}" } else { &body }) {
238        Ok(d) => d,
239        Err(e) => return bad_request(&e),
240    };
241    let (from, to, max_spans) = match map_doc(&doc, now) {
242        Ok(v) => v,
243        Err(e) => return bad_request(&e),
244    };
245    let dir = api.data_dir.clone();
246    let open = api.open("traces").await;
247    run("map", move || frame::map(&dir, from, to, max_spans, &open)).await
248}
249
250/// Every service that produced anything in a window.
251///
252/// ```yaml
253/// { "from": "-15m", "to": "now" }
254/// ```
255async fn entities_handler(State(api): State<Api>, body: String) -> Response {
256    let now = now_nanos();
257    let (from, to) = match window(if body.trim().is_empty() { "{}" } else { &body }, now) {
258        Ok(w) => w,
259        Err(e) => return bad_request(&e),
260    };
261    let dir = api.data_dir.clone();
262    let open = api.open_all().await;
263    run("entities", move || frame::entities(&dir, from, to, &open)).await
264}
265
266/// How many searches may be on the blocking pool at once.
267///
268/// The bound is the point, not the number. Every read hops to that pool — and
269/// so does every `publish` fsync, which is the ingest path's durability
270/// barrier. Unbounded, a burst of wide scans takes every thread tokio will hand
271/// out and the flusher queues behind them, so a slow query becomes an ingest
272/// stall. A permit keeps the two apart without a second runtime.
273///
274/// One per core, because a search already fans out across cores by itself
275/// (`mira_core::query::search_open`), so the (n+1)th finishes sooner waiting
276/// for a permit than time-slicing against n others. Four when the count is
277/// unavailable: enough that the UI's three panes never serialise.
278static SCANS: LazyLock<Semaphore> =
279    LazyLock::new(|| Semaphore::new(std::thread::available_parallelism().map_or(4, |n| n.get())));
280
281/// Run a search on the blocking pool, holding a permit for as long as it takes.
282///
283/// `spawn_blocking` is not optional here: reads are mmap reads, and a cold page
284/// fault stalls the OS thread with no yield point, taking every other connection
285/// that tokio worker owns down with it.
286pub(crate) async fn scan<T: Send + 'static>(
287    f: impl FnOnce() -> T + Send + 'static,
288) -> Result<T, tokio::task::JoinError> {
289    // Dropped when this returns, which is after the read has finished rather
290    // than after it has started — a permit released at `spawn_blocking` would
291    // bound nothing.
292    let _permit = SCANS.acquire().await.ok();
293    tokio::task::spawn_blocking(f).await
294}
295
296async fn run(
297    field: &'static str,
298    f: impl FnOnce() -> mira_core::error::Result<query::Results> + Send + 'static,
299) -> Response {
300    let t = std::time::Instant::now();
301    match scan(f).await {
302        Ok(Ok(r)) => json_ok(envelope(field, &r, t.elapsed())),
303        Ok(Err(e)) => (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()).into_response(),
304        Err(e) => (
305            StatusCode::INTERNAL_SERVER_ERROR,
306            format!("query task panicked: {e}"),
307        )
308            .into_response(),
309    }
310}
311
312/// The response body every read returns: the rows under their own key, and what
313/// the query cost. The cost is not decoration — it is what tells a caller its
314/// filter was too broad, and an agent has no other way to find that out.
315///
316/// `elapsed` is wall time around the read, queueing for a scan permit included.
317/// That is the number the caller actually waited, and it is the one worth
318/// showing: server time excluding the queue is a figure only the server can
319/// enjoy. Microseconds because a hot query here is single-digit milliseconds
320/// and "0 ms" is not a measurement.
321pub fn envelope(field: &str, r: &query::Results, elapsed: std::time::Duration) -> String {
322    // Absent rather than null on the last page, so `if (doc.next)` is the whole
323    // of a reader's paging logic.
324    let next = r
325        .next
326        .map(|c| format!(",\"next\":\"{c}\""))
327        .unwrap_or_default();
328    let tail = next + &cursors(&r.cursors);
329    format!(
330        "{{\"{field}\":{},\"stats\":{{\"blocks_total\":{},\"blocks_scanned\":{},\
331         \"rows_scanned\":{},\"rows_matched\":{},\"elapsed_us\":{}}}{}}}",
332        r.json,
333        r.stats.blocks_total,
334        r.stats.blocks_scanned,
335        r.stats.rows_scanned,
336        r.stats.rows_matched,
337        elapsed.as_micros(),
338        tail
339    )
340}
341
342/// `"cursors": ["…", "…"]`, index-aligned with the rows, or nothing at all.
343///
344/// Only a merging reader asks — see `proxy` — so the key is absent on every
345/// other response rather than present and empty: an empty array reads as "this
346/// page has no rows", which is what `rows` is for.
347fn cursors(cs: &[mira_core::query::Cursor]) -> String {
348    if cs.is_empty() {
349        return String::new();
350    }
351    let mut s = String::from(",\"cursors\":[");
352    for (i, c) in cs.iter().enumerate() {
353        if i > 0 {
354            s.push(',');
355        }
356        // All digits, dots and a possible leading `-`; nothing to escape.
357        s.push('"');
358        s.push_str(&c.to_string());
359        s.push('"');
360    }
361    s.push(']');
362    s
363}
364
365pub(crate) fn json_ok(body: String) -> Response {
366    (
367        StatusCode::OK,
368        [(header::CONTENT_TYPE, "application/json")],
369        body,
370    )
371        .into_response()
372}
373
374/// Errors come back as JSON too, so a caller has one thing to parse. An agent
375/// that has to distinguish a JSON success from a text/plain failure will
376/// eventually feed the failure to a JSON parser and report the parse error
377/// instead of the actual problem.
378fn bad_request(msg: &str) -> Response {
379    error(StatusCode::BAD_REQUEST, msg)
380}
381
382/// [`bad_request`] under a status the caller picks, for the proxy — whose
383/// refusals are 501 and 502 and want the same body shape.
384pub(crate) fn error(code: StatusCode, msg: &str) -> Response {
385    let mut j = mira_core::json::Json::new();
386    j.obj(|j| {
387        j.key("error");
388        j.str(msg);
389    });
390    (
391        code,
392        [(header::CONTENT_TYPE, "application/json")],
393        j.into_string(),
394    )
395        .into_response()
396}
397
398pub fn now_nanos() -> i64 {
399    std::time::SystemTime::now()
400        .duration_since(std::time::UNIX_EPOCH)
401        .unwrap_or_default()
402        .as_nanos() as i64
403}
404
405/// Parse a query document.
406///
407/// ```yaml
408/// {
409///   "signal": "logs",
410///   "from": "-15m",
411///   "to": "now",
412///   "where": [
413///     { "attr": "service.name", "eq": "checkout" },
414///     { "field": "severity_number", "gte": 17 },
415///     { "attr": "http.route", "contains": "/api" },
416///   ],
417///   "limit": 100,
418///   "after": "1757241600000000000.2718281828.7.41",
419/// }
420/// ```
421///
422/// `after` is the `next` field of a previous response, passed back verbatim, and
423/// is how you read past `limit`. There is no `offset`: on a store still being
424/// written to, a batch arriving between two pages shifts every row down, so an
425/// offset reader sees a row twice or never — and it costs the engine the whole
426/// prefix on every page.
427///
428/// A term names its target with `attr` or `field` and its operator with the
429/// other key, so `{"attr": "x", "eq": 1}` rather than
430/// `{"target": ..., "op": ..., "value": ...}`. Two keys instead of three, and
431/// the shape reads as the thing it means — which matters more than usual here,
432/// because a large share of these documents will be written by a model that has
433/// seen the schema once.
434pub fn parse_search(text: &str, now: i64) -> Result<Search, String> {
435    search_doc(&parse(text)?, now)
436}
437
438/// [`parse_search`] on an already-parsed document, for callers that received one
439/// nested inside something else — an MCP tool call, say.
440pub fn search_doc(doc: &Yaml, now: i64) -> Result<Search, String> {
441    known(
442        doc,
443        &["signal", "from", "to", "where", "limit", "after", "cursors"],
444    )?;
445    let signal = match doc["signal"].as_str() {
446        Some(s) => Signal::parse(s).ok_or(format!("unknown signal {s:?}"))?,
447        None => Signal::Logs,
448    };
449    let (from, to) = bounds(doc, now)?;
450    let limit = positive(doc, "limit", 100, MAX_LIMIT)?;
451    let after = match &doc["after"] {
452        Yaml::BadValue | Yaml::Null => None,
453        // A cursor is a string even though it is all digits and dots: KYAML
454        // quotes every scalar, and `1757241600000000000.2718281828.7.41` read
455        // as a float would come back as a different cursor entirely.
456        y => Some(
457            y.as_str()
458                .ok_or("after: quote the cursor; it is a string")?
459                .parse()?,
460        ),
461    };
462    Ok(Search {
463        signal,
464        from,
465        to,
466        terms: terms(doc)?,
467        limit,
468        after,
469        cursors: flag(doc, "cursors")?,
470    })
471}
472
473/// A boolean key, absent meaning false.
474///
475/// Both spellings, because KYAML quotes every scalar and JSON does not, and
476/// the same document has to work sent either way (principle 5).
477fn flag(doc: &Yaml, key: &str) -> Result<bool, String> {
478    match &doc[key] {
479        Yaml::BadValue | Yaml::Null => Ok(false),
480        Yaml::Boolean(b) => Ok(*b),
481        y => y
482            .as_str()
483            .and_then(|s| s.parse().ok())
484            .ok_or(format!("{key}: expected \"true\" or \"false\"")),
485    }
486}
487
488/// Parse a metrics query document.
489///
490/// ```yaml
491/// {
492///   "name": "http.server.request.duration",
493///   "from": "-1h",
494///   "where": [ { "attr": "service.name", "eq": "checkout" } ],
495///   "max_series": 50,
496/// }
497/// ```
498///
499/// Same `where` grammar as [`parse_search`], because a caller who has learned
500/// one filter syntax should not have to learn a second one to look at a chart.
501pub fn parse_series(text: &str, now: i64) -> Result<SeriesQuery, String> {
502    series_doc(&parse(text)?, now)
503}
504
505pub fn series_doc(doc: &Yaml, now: i64) -> Result<SeriesQuery, String> {
506    known(
507        doc,
508        &["name", "from", "to", "where", "max_series", "max_points"],
509    )?;
510    let (from, to) = bounds(doc, now)?;
511    Ok(SeriesQuery {
512        name: doc["name"].as_str().map(str::to_owned),
513        from,
514        to,
515        terms: terms(doc)?,
516        max_series: positive(doc, "max_series", 200, 2_000)?,
517        max_points: positive(doc, "max_points", 5_000, 100_000)?,
518    })
519}
520
521/// A correlate document: a search, plus the walk to apply to the frame it
522/// anchors.
523pub fn parse_correlate(text: &str, now: i64) -> Result<(Search, Vec<Expand>), String> {
524    correlate_doc(&parse(text)?, now)
525}
526
527/// [`parse_correlate`] on an already-parsed document, for the MCP side.
528pub fn correlate_doc(doc: &Yaml, now: i64) -> Result<(Search, Vec<Expand>), String> {
529    known(
530        doc,
531        &["signal", "from", "to", "where", "limit", "after", "expand"],
532    )?;
533    Ok((correlate_search(doc, now)?, expands(&doc["expand"])?))
534}
535
536/// The window and the span budget of a service-map request.
537pub fn map_doc(doc: &Yaml, now: i64) -> Result<(i64, i64, usize), String> {
538    known(doc, &["from", "to", "max_spans"])?;
539    let (from, to) = bounds(doc, now)?;
540    Ok((from, to, positive(doc, "max_spans", 1_000_000, 20_000_000)?))
541}
542
543/// The search half of a correlate document.
544///
545/// `search_doc` would refuse `expand` as an unknown key, and relaxing it there
546/// would let a misspelled key through on `/api/v1/query` — which is the one
547/// mistake the strictness exists to catch. Stripping the key here costs a clone
548/// of a document that is a handful of scalars.
549fn correlate_search(doc: &Yaml, now: i64) -> Result<Search, String> {
550    let mut map = doc.as_hash().cloned().unwrap_or_default();
551    map.remove(&Yaml::String("expand".into()));
552    search_doc(&Yaml::Hash(map), now)
553}
554
555/// `["traces", "around:2s", "peers"]`.
556///
557/// A list and not a set: the operations do not commute, and `around` before
558/// `traces` is overwritten by the extent `traces` measures.
559fn expands(y: &Yaml) -> Result<Vec<Expand>, String> {
560    let items = match y {
561        Yaml::BadValue | Yaml::Null => return Ok(Vec::new()),
562        Yaml::Array(a) => a,
563        _ => return Err("`expand` must be a list of steps".into()),
564    };
565    items
566        .iter()
567        .map(|s| {
568            let s = s.as_str().ok_or("each `expand` step must be a string")?;
569            match s.split_once(':') {
570                Some(("around", d)) => {
571                    Ok(Expand::Around(crate::config::duration(d)?.as_nanos() as i64))
572                }
573                None if s == "traces" => Ok(Expand::Traces),
574                None if s == "peers" => Ok(Expand::Peers),
575                _ => Err(format!(
576                    "unknown expand step {s:?}; expected traces, peers, or around:<duration>"
577                )),
578            }
579        })
580        .collect()
581}
582
583/// The `from`/`to` pair of any query document.
584pub fn window(text: &str, now: i64) -> Result<(i64, i64), String> {
585    window_doc(&parse(text)?, now)
586}
587
588/// [`window`] on an already-parsed document, for the MCP side.
589pub fn window_doc(doc: &Yaml, now: i64) -> Result<(i64, i64), String> {
590    known(doc, &["from", "to"])?;
591    bounds(doc, now)
592}
593
594/// Refuse a document that is not a mapping, or that carries a key this endpoint
595/// does not implement.
596///
597/// Every other reader here indexes by key and defaults what is missing, so a
598/// misspelled `where` is indistinguishable from no `where` at all and the answer
599/// is a confident 200 over the whole window — the one failure a caller cannot
600/// see in the response it gets. `parse_term` has always been this strict one
601/// level down; this is the same rule at the top of the document.
602pub fn known(doc: &Yaml, keys: &[&str]) -> Result<(), String> {
603    // A tool call that carries no `arguments` at all is a legal MCP request and
604    // means the same thing as an empty document.
605    if doc.is_badvalue() || doc.is_null() {
606        return Ok(());
607    }
608    let map = doc.as_hash().ok_or("a query must be a mapping")?;
609    for k in map.keys() {
610        let k = k.as_str().ok_or("query keys must be strings")?;
611        if !keys.contains(&k) {
612            return Err(format!(
613                "unknown query key {k:?}; expected one of {}",
614                keys.join(" ")
615            ));
616        }
617    }
618    Ok(())
619}
620
621/// One KYAML document, or a readable reason it is not one.
622pub fn parse(text: &str) -> Result<Yaml, String> {
623    if has_alias(text) {
624        return Err(
625            "KYAML has no anchors or aliases: write the value out instead of \
626             referring to an anchor with `*`"
627                .into(),
628        );
629    }
630    let docs = match YamlLoader::load_from_str(text) {
631        Ok(docs) => docs,
632        // JSON spells a non-BMP character as a surrogate pair and `json.dumps`
633        // does so by default, but YAML 1.2 has no surrogates and the loader
634        // refuses one — which would make an ASCII-escaping JSON client the one
635        // client principle 5 does not get for free. Retrying only a document
636        // that has already failed keeps the rewrite away from every valid one:
637        // a single-quoted `'\ud83d\ude00'` is twelve literal characters, and
638        // it parses on the first attempt.
639        Err(e) => YamlLoader::load_from_str(&fold_surrogates(text))
640            .map_err(|_| format!("not valid KYAML: {e}"))?,
641    };
642    docs.into_iter().next().ok_or("empty query".into())
643}
644
645/// Does this document use a YAML alias?
646///
647/// It has to be answered before the loader sees the text, because yaml-rust2
648/// resolves an alias by deep-cloning the anchored node into the tree. Seven
649/// levels of nine-way reuse is 356 bytes on the wire and a gigabyte of `Yaml` in
650/// the loader, nine levels is under 400 bytes and the OOM killer \u2014 and with
651/// `panic = "abort"` that takes every open block and in-flight export with it.
652/// The endpoints that route through here are unauthenticated on 4318, and
653/// neither `ingest.max_request_bytes` nor the inflate cap sees anything wrong
654/// with a body this small.
655///
656/// Bounding the expansion would be the answer if aliases were a feature Mira
657/// owed anyone. KYAML has no anchors and no aliases, so the whole mechanism is
658/// refused instead \u2014 which is also the diagnosis, rather than a limit the caller
659/// has to reverse-engineer from a truncated document.
660///
661/// The scan is a second pass over the token stream, so it is skipped for the
662/// bodies that cannot contain an alias: the token always starts with `*`, and
663/// `memchr` over the body costs a fraction of what parsing it does. A `*` inside
664/// a quoted string \u2014 a log body, a wildcard in a filter \u2014 pays for the pass and
665/// changes nothing else.
666fn has_alias(text: &str) -> bool {
667    if !text.contains('*') {
668        return false;
669    }
670    #[derive(Default)]
671    struct Spy(bool);
672    impl EventReceiver for Spy {
673        fn on_event(&mut self, ev: Event) {
674            self.0 |= matches!(ev, Event::Alias(_));
675        }
676    }
677    let mut spy = Spy::default();
678    // A syntax error is not this function's to report: the loader hits the same
679    // one and says where it is.
680    let _ = Parser::new_from_str(text).load(&mut spy, true);
681    spy.0
682}
683
684/// `\ud83d\ude00` becomes the character it encodes. Everything else is copied
685/// through untouched, an unpaired surrogate included: that is not a character,
686/// and folding it into a replacement one would turn a rejected query into a
687/// silently different one.
688fn fold_surrogates(text: &str) -> String {
689    fn hex4(s: &str) -> Option<u32> {
690        u32::from_str_radix(s.strip_prefix("\\u")?.get(..4)?, 16).ok()
691    }
692    let mut out = String::with_capacity(text.len());
693    let mut rest = text;
694    while let Some(i) = rest.find("\\u") {
695        out.push_str(&rest[..i]);
696        let folded = match (hex4(&rest[i..]), rest.get(i + 6..).and_then(hex4)) {
697            (Some(h @ 0xD800..=0xDBFF), Some(l @ 0xDC00..=0xDFFF)) => {
698                char::from_u32(0x10000 + ((h - 0xD800) << 10) + (l - 0xDC00))
699            }
700            _ => None,
701        };
702        match folded {
703            Some(c) => {
704                out.push(c);
705                rest = &rest[i + 12..];
706            }
707            None => {
708                out.push_str("\\u");
709                rest = &rest[i + 2..];
710            }
711        }
712    }
713    out.push_str(rest);
714    out
715}
716
717/// Default window is the last hour. A query with no bounds would scan the whole
718/// retention period, which is the one mistake that turns a fast engine into a
719/// slow one, and it is the mistake an agent makes first.
720pub fn bounds(doc: &Yaml, now: i64) -> Result<(i64, i64), String> {
721    let from = time_field(&doc["from"], now, now - 3_600_000_000_000)?;
722    let to = time_field(&doc["to"], now, now)?;
723    if from > to {
724        return Err(format!("from ({from}) is after to ({to})"));
725    }
726    Ok((from, to))
727}
728
729fn terms(doc: &Yaml) -> Result<Vec<Term>, String> {
730    match &doc["where"] {
731        Yaml::BadValue | Yaml::Null => Ok(Vec::new()),
732        Yaml::Array(a) => a.iter().map(parse_term).collect(),
733        _ => Err("`where` must be a list of terms".into()),
734    }
735}
736
737/// A positive integer bound, defaulted and capped rather than refused. Every
738/// one of these caps a materialization that happens in memory.
739fn positive(doc: &Yaml, key: &str, default: usize, max: usize) -> Result<usize, String> {
740    match &doc[key] {
741        Yaml::BadValue | Yaml::Null => Ok(default),
742        Yaml::Integer(n) if *n > 0 => Ok((*n as usize).min(max)),
743        other => Err(format!("{key} must be a positive integer, got {other:?}")),
744    }
745}
746
747fn parse_term(y: &Yaml) -> Result<Term, String> {
748    let map = y.as_hash().ok_or("each `where` term must be a mapping")?;
749    let mut target = None;
750    let mut opval = None;
751    for (k, v) in map {
752        let k = k.as_str().ok_or("term keys must be strings")?;
753        match k {
754            "attr" => {
755                target = Some(Target::Attr(
756                    v.as_str().ok_or("`attr` must be a string")?.to_owned(),
757                ));
758            }
759            "field" => {
760                target = Some(Target::Field(
761                    v.as_str().ok_or("`field` must be a string")?.to_owned(),
762                ));
763            }
764            other => {
765                let op = Op::parse(other).ok_or(format!(
766                    "unknown term key {other:?}; expected attr, field, or one of \
767                     eq ne lt lte gt gte contains"
768                ))?;
769                opval = Some((op, scalar(v)?));
770            }
771        }
772    }
773    let target = target.ok_or("a term needs `attr` or `field`")?;
774    let (op, value) = opval.ok_or("a term needs an operator, such as `eq`")?;
775    Ok(Term { target, op, value })
776}
777
778/// A query scalar.
779///
780/// Unlike `config.rs::scalar`, which refuses anything YAML guessed at, this
781/// keeps the guesses. The two are answering different questions: a config value
782/// of `0x1f` almost certainly meant the string, whereas a query comparing
783/// against `31` means the number, and JSON — which is where these documents come
784/// from — has already committed to that distinction in its syntax.
785fn scalar(y: &Yaml) -> Result<Value, String> {
786    Ok(match y {
787        Yaml::String(s) => Value::Str(s.clone()),
788        Yaml::Integer(i) => Value::Int(*i),
789        Yaml::Boolean(b) => Value::Bool(*b),
790        Yaml::Real(r) => Value::Double(r.parse().map_err(|_| format!("{r:?} is not a number"))?),
791        other => return Err(format!("{other:?} is not a comparable value")),
792    })
793}
794
795/// `now`, `-15m`, or absolute nanoseconds.
796///
797/// Relative is the form a UI and an agent both reach for, and it is the form
798/// that survives being pasted into a chat and run an hour later. Absolute
799/// nanoseconds are the form the API returns, so a value from a result can be
800/// fed straight back in.
801pub(crate) fn time_field(y: &Yaml, now: i64, default: i64) -> Result<i64, String> {
802    match y {
803        Yaml::BadValue | Yaml::Null => Ok(default),
804        Yaml::Integer(n) => Ok(*n),
805        Yaml::String(s) if s == "now" => Ok(now),
806        Yaml::String(s) => {
807            let (sign, rest) = match s.strip_prefix('-') {
808                Some(r) => (-1i64, r),
809                None => (1, s.strip_prefix('+').unwrap_or(s)),
810            };
811            let d = crate::config::duration(rest)?;
812            // `duration` bounds the multiply; this bounds the two steps after
813            // it. Nanoseconds are a `u128` and the window is an `i64`, so a
814            // duration well inside what `duration` accepts — `"3000000000s"`,
815            // say — still has more nanoseconds than a timestamp holds, and the
816            // `as` cast that used to be here turned that into a window on the
817            // far side of the epoch rather than into an error.
818            i64::try_from(d.as_nanos())
819                .ok()
820                .and_then(|ns| now.checked_add(sign * ns))
821                .ok_or_else(|| format!("{s:?} is further from now than a timestamp reaches"))
822        }
823        other => Err(format!("{other:?} is not a time")),
824    }
825}
826
827#[cfg(test)]
828mod tests {
829    use super::*;
830
831    /// The second half of the overflow on the unauthenticated query path.
832    /// `config::duration` bounds its own multiply, but a duration it happily
833    /// accepts can still hold more nanoseconds than an `i64` timestamp, and
834    /// then more again once `now` is added — `~292 years` is the whole budget.
835    /// The `as` cast that used to be here turned either case into a window on
836    /// the far side of the epoch and answered the query from it.
837    #[test]
838    fn a_time_further_from_now_than_a_timestamp_reaches_is_rejected() {
839        let now = 1_757_000_000_000_000_000;
840        let at = |s: &str| time_field(&Yaml::String(s.to_owned()), now, 0);
841        // Too many nanoseconds for an i64 at all; enough for an i64 but not
842        // once `now` is added; and too large for `duration` in the first place.
843        for s in ["-10000000000s", "+9000000000s", "1000000000000000000d"] {
844            assert!(at(s).is_err(), "{s:?} must not wrap");
845        }
846        assert_eq!(at("-1h").unwrap(), now - 3_600_000_000_000);
847        assert_eq!(at("now").unwrap(), now);
848        assert_eq!(time_field(&Yaml::BadValue, now, 42).unwrap(), 42);
849    }
850
851    /// The query document is written here as a browser would send it — bare
852    /// JSON — because "KYAML is a superset of JSON" is load-bearing for the API
853    /// and not something to take on faith from a spec.
854    #[test]
855    fn json_from_a_browser_parses_as_kyaml() {
856        let now = 1_000_000_000_000_000_000;
857        let q = parse_search(
858            r#"{"signal":"traces","from":"-15m","to":"now","limit":50,
859                "where":[{"attr":"service.name","eq":"checkout"},
860                         {"field":"duration_nano","gte":500000000},
861                         {"field":"name","contains":"GET"}]}"#,
862            now,
863        )
864        .unwrap();
865        assert_eq!(q.signal, Signal::Traces);
866        assert_eq!(q.to, now);
867        assert_eq!(q.from, now - 900_000_000_000);
868        assert_eq!(q.limit, 50);
869        assert_eq!(q.terms.len(), 3);
870        assert!(matches!(&q.terms[0].target, Target::Attr(k) if k == "service.name"));
871        assert_eq!(q.terms[1].op, Op::Gte);
872        assert_eq!(q.terms[1].value, Value::Int(500_000_000));
873        assert_eq!(q.terms[2].op, Op::Contains);
874    }
875
876    /// ...and the same query from a JSON client that escapes non-ASCII, which
877    /// `json.dumps` does by default. A character outside the BMP arrives as a
878    /// surrogate pair, which YAML 1.2 has no notion of, so without the fold the
879    /// one client that does not work for free is a JSON one.
880    #[test]
881    fn json_surrogate_escapes_are_folded_into_the_character() {
882        let q = parse_search(
883            r#"{"where":[{"field":"body","contains":"caf\u00e9 \ud83d\ude00"}]}"#,
884            0,
885        )
886        .unwrap();
887        assert_eq!(q.terms[0].value, Value::Str("café 😀".into()));
888        // Half a pair is not a character, so it stays the loader's error rather
889        // than becoming a replacement character in a filter that then silently
890        // matches nothing.
891        let err =
892            parse_search(r#"{"where":[{"field":"body","contains":"\ud83d"}]}"#, 0).unwrap_err();
893        assert!(err.contains("not valid KYAML"), "{err}");
894    }
895
896    /// ...and the same query in house style, with the trailing commas and the
897    /// comment that JSON cannot carry. This is what makes the format worth
898    /// having: an agent can annotate its own query.
899    #[test]
900    fn kyaml_with_comments_and_trailing_commas_parses_the_same() {
901        let q = parse_search(
902            r#"{
903              "signal": "logs",
904              # only the errors
905              "where": [
906                { "field": "severity_number", "gte": 17 },
907              ],
908            }"#,
909            0,
910        )
911        .unwrap();
912        assert_eq!(q.signal, Signal::Logs);
913        assert_eq!(q.terms.len(), 1);
914        assert_eq!(q.limit, 100);
915        // An unbounded query would scan all of retention, so the default window
916        // is an hour rather than everything.
917        assert_eq!(q.from, -3_600_000_000_000);
918    }
919
920    #[test]
921    fn malformed_queries_say_what_is_wrong() {
922        let err = |s: &str| parse_search(s, 0).unwrap_err();
923        assert!(err(r#"{"signal":"jaeger"}"#).contains("unknown signal"));
924        assert!(err(r#"{"where":[{"attr":"a","like":"b"}]}"#).contains("unknown term key"));
925        assert!(err(r#"{"where":[{"eq":"b"}]}"#).contains("needs `attr` or `field`"));
926        assert!(err(r#"{"where":[{"attr":"a"}]}"#).contains("needs an operator"));
927        assert!(err(r#"{"from":"now","to":"-1h"}"#).contains("is after"));
928        assert!(err(r#"{"limit":0}"#).contains("positive integer"));
929        // A key nothing implements is a typo, and answering a typo with a page
930        // of unfiltered rows is worse than answering it with an error: the
931        // caller has no way to tell that its filter was dropped.
932        assert!(err(r#"{"signal":"logs","filters":[]}"#).contains("unknown query key"));
933        assert!(err(r#"{"query":{"signal":"logs"}}"#).contains("unknown query key"));
934        // A whole document that is not a mapping is not a query either.
935        assert!(err("[1,2,3]").contains("must be a mapping"));
936        let step = parse_series(r#"{"name":"m","step":"1m"}"#, 0).unwrap_err();
937        assert!(step.contains("step"), "{step}");
938        let w = window(r#"{"from":0,"limit":5}"#, 0).unwrap_err();
939        assert!(w.contains("limit"), "{w}");
940        // A container is not a scalar and not a time. Both readers default what
941        // is missing, so the alternative to refusing these is comparing against
942        // whatever `unwrap_or_default` produced — a filter that matches nothing
943        // and a window that says it was honoured.
944        assert!(err(r#"{"where":[{"attr":"a","eq":[1,2]}]}"#).contains("not a comparable value"));
945        assert!(err(r#"{"where":[{"attr":"a","eq":{}}]}"#).contains("not a comparable value"));
946        assert!(err(r#"{"from":[1]}"#).contains("is not a time"));
947        assert!(err(r#"{"to":{"at":1}}"#).contains("is not a time"));
948    }
949
950    /// Unknown keys are refused, so the known set has to be exactly what the
951    /// shipped clients send — a false rejection breaks the browser UI, the
952    /// terminal UI and every MCP tool at once. The terminal UI's documents are
953    /// checked in `tui.rs` against the code that builds them; these are the
954    /// browser's and the agent's.
955    #[test]
956    fn every_document_the_clients_send_is_accepted() {
957        for d in [
958            r#"{"signal":"logs","from":"-1h","to":"now","where":[],"limit":200}"#,
959            r#"{"signal":"traces","from":0,"to":"now","limit":2000,
960                "where":[{"field":"trace_id","eq":"ab"}]}"#,
961            r#"{"signal":"logs","limit":100,"after":"1757241600000000000.2718281828.7.41"}"#,
962        ] {
963            assert!(parse_search(d, 0).is_ok(), "{d}");
964        }
965        for d in [
966            r#"{"name":"m","from":"-1h","to":"now","where":[]}"#,
967            r#"{"name":"m","from":"-1h","to":"now","max_series":64,"max_points":400,"where":[]}"#,
968        ] {
969            assert!(parse_series(d, 0).is_ok(), "{d}");
970        }
971        for d in [
972            r#"{"signal":"logs","from":"-1h","to":"now","where":[],"limit":200,
973                "expand":["traces","peers"]}"#,
974            r#"{"expand":[]}"#,
975            "{}",
976        ] {
977            assert!(parse_correlate(d, 0).is_ok(), "{d}");
978        }
979        assert!(window(r#"{"from":"-1h","to":"now"}"#, 0).is_ok());
980        assert!(window("{}", 0).is_ok());
981        // An MCP tool call is allowed to carry no `arguments` member at all.
982        assert!(search_doc(&Yaml::BadValue, 0).is_ok());
983        assert!(correlate_doc(&Yaml::BadValue, 0).is_ok());
984        assert!(map_doc(&Yaml::BadValue, 0).is_ok());
985    }
986
987    /// The walk is a list because the steps do not commute, and the wire
988    /// spelling of a step is the only place the algebra meets a string — so
989    /// both the parse and every way of getting it wrong are checked here.
990    #[test]
991    fn an_expansion_walk_parses_in_order_and_says_what_it_does_not_know() {
992        let (q, ops) = parse_correlate(
993            r#"{"signal":"traces","expand":["around:2s","traces","peers"]}"#,
994            0,
995        )
996        .unwrap();
997        assert_eq!(q.signal.dir(), "traces");
998        assert_eq!(
999            ops,
1000            [Expand::Around(2_000_000_000), Expand::Traces, Expand::Peers]
1001        );
1002        for (d, want) in [
1003            (r#"{"expand":"traces"}"#, "list of steps"),
1004            (r#"{"expand":[7]}"#, "must be a string"),
1005            (r#"{"expand":["sideways"]}"#, "sideways"),
1006            (r#"{"expand":["around:soon"]}"#, "soon"),
1007            (r#"{"expand":["peers:1"]}"#, "peers:1"),
1008            (r#"{"expanded":[]}"#, "unknown query key"),
1009        ] {
1010            assert!(parse_correlate(d, 0).unwrap_err().contains(want), "{d}");
1011        }
1012    }
1013
1014    /// A YAML alias bomb: six levels of nine-way reuse, 250 bytes on the wire,
1015    /// 531,441 leaves once expanded. It is short of the seven levels that took a
1016    /// live server to 1.02 GB on purpose — if this guard ever regresses the test
1017    /// should fail, not take the runner's memory with it.
1018    ///
1019    /// Every unauthenticated endpoint on 4318 routes through `parse`, so the
1020    /// refusal is checked here rather than once per handler.
1021    #[test]
1022    fn an_alias_bomb_is_refused_before_it_is_expanded() {
1023        let bomb = r#"{"a":&a "lol",
1024          "b":&b [*a,*a,*a,*a,*a,*a,*a,*a,*a],
1025          "c":&c [*b,*b,*b,*b,*b,*b,*b,*b,*b],
1026          "d":&d [*c,*c,*c,*c,*c,*c,*c,*c,*c],
1027          "e":&e [*d,*d,*d,*d,*d,*d,*d,*d,*d],
1028          "f":&f [*e,*e,*e,*e,*e,*e,*e,*e,*e],
1029          "g":[*f,*f,*f,*f,*f,*f,*f,*f,*f]}"#;
1030        let err = parse(bomb).unwrap_err();
1031        // The reader of this is a model as often as a person, and "invalid
1032        // document" would leave both of them editing at random.
1033        assert!(err.contains("alias"), "{err}");
1034        assert!(err.contains("KYAML"), "{err}");
1035        // Every entry point that takes a body reaches the same guard.
1036        assert!(parse_search(bomb, 0).is_err());
1037        assert!(parse_series(bomb, 0).is_err());
1038        assert!(window(bomb, 0).is_err());
1039        // An anchor nothing refers to expands to nothing, so it is only the
1040        // alias that is refused.
1041        assert!(parse(r#"{"signal":&s "logs"}"#).is_ok());
1042
1043        // The mechanism being guarded against, at a depth that is safe to load:
1044        // the loader materialises each alias as a full copy rather than sharing
1045        // it, so every level multiplies the tree by nine.
1046        let three = r#"{"a":&a "lol","b":&b [*a,*a,*a,*a,*a,*a,*a,*a,*a],
1047          "c":&c [*b,*b,*b,*b,*b,*b,*b,*b,*b],"d":[*c,*c,*c,*c,*c,*c,*c,*c,*c]}"#;
1048        let expanded = YamlLoader::load_from_str(three).unwrap().remove(0);
1049        assert_eq!(expanded["d"].as_vec().unwrap().len(), 9);
1050        assert_eq!(expanded["d"][8][8].as_vec().unwrap().len(), 9);
1051        assert_eq!(expanded["d"][8][8][8].as_str(), Some("lol"));
1052    }
1053
1054    /// The scan is skipped unless the body contains a `*`, and a `*` that is
1055    /// part of a string is not an alias — a filter looking for a wildcard in a
1056    /// log line has to keep working, and it is the one input that pays for the
1057    /// pass.
1058    #[test]
1059    fn a_star_inside_a_string_is_not_an_alias() {
1060        let q = parse_search(r#"{"where":[{"field":"body","contains":"rate *"}]}"#, 0).unwrap();
1061        assert_eq!(q.terms[0].value, Value::Str("rate *".into()));
1062    }
1063
1064    #[test]
1065    fn limit_is_capped_rather_than_refused() {
1066        let q = parse_search(r#"{"limit":9999999}"#, 0).unwrap();
1067        assert_eq!(q.limit, MAX_LIMIT);
1068    }
1069
1070    /// Status, content type and body of one handler's answer.
1071    async fn answer(res: Response) -> (StatusCode, String, String) {
1072        let status = res.status();
1073        let ct = res
1074            .headers()
1075            .get(header::CONTENT_TYPE)
1076            .and_then(|v| v.to_str().ok())
1077            .unwrap_or_default()
1078            .to_owned();
1079        let body = axum::body::to_bytes(res.into_body(), usize::MAX)
1080            .await
1081            .unwrap();
1082        (status, ct, String::from_utf8(body.to_vec()).unwrap())
1083    }
1084
1085    /// Each of the six endpoints validates its own document, and each one
1086    /// refuses with a JSON error object under a 400.
1087    ///
1088    /// Both halves are load-bearing. Skipping the check is not a crash — it is
1089    /// a confident 200 over the whole window with the caller's filter silently
1090    /// dropped, which is the one failure that does not appear in the response.
1091    /// And an error that came back as `text/plain` would be fed to a JSON
1092    /// parser by every client here, which then reports the parse error instead
1093    /// of the reason.
1094    #[tokio::test]
1095    async fn every_endpoint_refuses_a_document_it_cannot_honour_with_a_json_400() {
1096        let api = Api::default();
1097        let st = || State(api.clone());
1098        for (res, want) in [
1099            (
1100                query_handler(st(), r#"{"signal":"jaeger"}"#.into()).await,
1101                "unknown signal",
1102            ),
1103            (
1104                series_handler(st(), r#"{"max_series":0}"#.into()).await,
1105                "max_series must be a positive integer",
1106            ),
1107            (
1108                names_handler(st(), r#"{"from":"yesterday"}"#.into()).await,
1109                "yesterday",
1110            ),
1111            (
1112                correlate_handler(st(), r#"{"expand":"traces"}"#.into()).await,
1113                "`expand` must be a list of steps",
1114            ),
1115            // The service map is the one endpoint that parses and validates in
1116            // two steps, so it has two ways to answer 400.
1117            (
1118                map_handler(st(), "{not: [kyaml".into()).await,
1119                "not valid KYAML",
1120            ),
1121            (
1122                map_handler(st(), r#"{"max_spans":0}"#.into()).await,
1123                "max_spans must be a positive integer",
1124            ),
1125            (
1126                entities_handler(st(), r#"{"limit":5}"#.into()).await,
1127                "unknown query key \\\"limit\\\"",
1128            ),
1129        ] {
1130            let (status, ct, body) = answer(res).await;
1131            assert_eq!(status, StatusCode::BAD_REQUEST, "{want}: {body}");
1132            assert_eq!(ct, "application/json", "{want}");
1133            assert!(body.starts_with(r#"{"error":""#), "{want}: {body}");
1134            assert!(body.contains(want), "{body}");
1135        }
1136
1137        // The three endpoints whose document is optional treat an empty body as
1138        // "everything, now" rather than as a malformed request — it is the
1139        // first call the UI and an agent both make.
1140        let dir = std::env::temp_dir().join(format!("mira-api-empty-{}", std::process::id()));
1141        std::fs::create_dir_all(&dir).unwrap();
1142        let api = Api {
1143            data_dir: Arc::new(dir.clone()),
1144            ..Default::default()
1145        };
1146        let st = || State(api.clone());
1147        for res in [
1148            names_handler(st(), String::new()).await,
1149            map_handler(st(), "  ".into()).await,
1150            entities_handler(st(), String::new()).await,
1151        ] {
1152            let (status, ct, body) = answer(res).await;
1153            assert_eq!(status, StatusCode::OK, "{body}");
1154            assert_eq!(ct, "application/json");
1155            assert!(body.contains("\"stats\":"), "{body}");
1156        }
1157        let _ = std::fs::remove_dir_all(&dir);
1158    }
1159
1160    /// A read that fails, and a read that panics, are both a 500 with the
1161    /// reason in the body — not a dropped connection and not a dead process.
1162    ///
1163    /// `spawn_blocking` catches the unwind, so the alternative to reporting the
1164    /// `JoinError` is a request that never answers while the server carries on
1165    /// as if nothing happened. The store is broken the way a half-written data
1166    /// directory is: a plain file where a signal's directory belongs.
1167    #[tokio::test]
1168    async fn a_failed_or_panicking_scan_answers_500_with_the_reason() {
1169        let dir = std::env::temp_dir().join(format!("mira-api-broken-{}", std::process::id()));
1170        let _ = std::fs::remove_dir_all(&dir);
1171        std::fs::create_dir_all(&dir).unwrap();
1172        std::fs::write(dir.join("logs"), b"not a directory").unwrap();
1173        let api = Api {
1174            data_dir: Arc::new(dir.clone()),
1175            ..Default::default()
1176        };
1177        let (status, _, body) = answer(query_handler(State(api), "{}".into()).await).await;
1178        assert_eq!(status, StatusCode::INTERNAL_SERVER_ERROR, "{body}");
1179        assert!(!body.is_empty(), "a 500 with no reason is not a report");
1180        // The read returned an error; it did not take the process near a panic.
1181        assert!(!body.contains("panicked"), "{body}");
1182
1183        // The panic is deliberate: this is the arm that exists because a read
1184        // runs on a pool thread whose unwind tokio hands back as a `JoinError`.
1185        let (status, _, body) = answer(run("rows", || panic!("a page fault, say")).await).await;
1186        assert_eq!(status, StatusCode::INTERNAL_SERVER_ERROR);
1187        assert!(body.contains("query task panicked"), "{body}");
1188        let _ = std::fs::remove_dir_all(&dir);
1189    }
1190
1191    /// A signal name nothing implements has no open block, rather than an index
1192    /// into an array of three.
1193    ///
1194    /// Every handler reaches this with a string, and `correlate` reaches it
1195    /// with one the caller chose. Out of range would be a panic on the request
1196    /// path, and with `panic = "abort"` in the release profile that is the
1197    /// process and every in-flight export with it.
1198    ///
1199    /// Exactly one slot is served, because three empty ones cannot tell an
1200    /// unknown name apart from a known one: a lookup that answered slot 0 for
1201    /// everything it did not recognise would read identically, and it would
1202    /// serve logs to a caller asking about profiles.
1203    #[tokio::test]
1204    async fn an_unknown_signal_has_no_open_block_rather_than_an_index_out_of_range() {
1205        let dir = std::env::temp_dir().join(format!("mira-api-slots-{}", std::process::id()));
1206        let _ = std::fs::remove_dir_all(&dir);
1207        std::fs::create_dir_all(&dir).unwrap();
1208        let pcfg = Arc::new(pipeline::Config {
1209            data_dir: dir.clone(),
1210            node: 0x51,
1211            // With the log on, the acknowledgement is the frame and not the
1212            // seal — which is the only way to hold an export that is both
1213            // acknowledged and still in the builder, which is what an open
1214            // block *is*. Without it `submit` would wait out `max_block_age`
1215            // below and there would be nothing open to find.
1216            wal: Some(Arc::new(mira_core::wal::Wal::open(&dir, 0x51).unwrap())),
1217            // Long enough that nothing seals mid-test: the block has to still
1218            // be open for the slot to have anything in it.
1219            max_block_age: std::time::Duration::from_secs(3_600),
1220            ..Default::default()
1221        });
1222        let (ingest, logs_slot, flusher) = pipeline::spawn::<mira_core::logs::LogsBuilder>(&pcfg);
1223        assert!(
1224            ingest
1225                .submit(crate::e2e::logs_export("checkout", 1_000, 3))
1226                .await
1227                .is_ok()
1228        );
1229        let api = Api {
1230            data_dir: Arc::new(dir.clone()),
1231            open: [logs_slot, Default::default(), Default::default()],
1232            ..Default::default()
1233        };
1234
1235        let logs = api.open("logs").await;
1236        assert_eq!(logs.len(), 1, "the served slot answers with its open block");
1237        assert_eq!(logs[0].sealed.num_rows, 3);
1238        // Neither an unknown name nor another signal reaches into it.
1239        for absent in ["profiles", "", "traces", "metrics"] {
1240            assert!(api.open(absent).await.is_empty(), "{absent}");
1241        }
1242
1243        // One slot per signal and in signal order, not a flat concatenation:
1244        // sequence numbers are per-signal and a flat list would let logs
1245        // collide with traces on `(node, seq)`.
1246        let all = api.open_all().await;
1247        assert_eq!(all.len(), pipeline::SIGNALS.len());
1248        let i = pipeline::SIGNALS.iter().position(|s| *s == "logs").unwrap();
1249        for (j, blocks) in all.iter().enumerate() {
1250            assert_eq!(blocks.len(), usize::from(j == i), "slot {j}");
1251        }
1252
1253        drop(ingest);
1254        flusher.await.unwrap();
1255        let _ = std::fs::remove_dir_all(&dir);
1256    }
1257}