1use yaml_rust2::Yaml;
34
35use mira_core::json::Json;
36use mira_core::query::{Op, Search, Signal, Target, Term, Value};
37
38use crate::api;
39
40const UNREADABLE: usize = usize::MAX;
43
44#[derive(Debug)]
49pub(crate) struct Rca {
50 title: String,
51 from: i64,
52 to: i64,
53 summary: String,
54 impact: Vec<String>,
55 timeline: Vec<(i64, String)>,
59 root_cause: String,
60 pub(crate) evidence: Vec<Fact>,
61 ruled_out: Vec<String>,
62 contributing: Vec<String>,
63 remediation: Vec<String>,
64 verification: Vec<String>,
65 prevention: Option<String>,
67 pub(crate) emit: bool,
68}
69
70#[derive(Debug)]
72pub(crate) struct Fact {
73 claim: String,
74 pub(crate) cite: Search,
78 shown: String,
80 pub(crate) found: Option<usize>,
83}
84
85impl Fact {
86 pub(crate) fn seen(&mut self, rows: Option<usize>) {
87 self.found = Some(rows.unwrap_or(UNREADABLE));
88 }
89}
90
91pub(crate) fn trace_query(id: &str, limit: usize) -> Result<Search, String> {
98 let id = id.trim();
99 if mira_core::query::unhex(id).is_none_or(|b| b.len() != 16) {
100 return Err(format!("{id:?} is not a 16-byte hex trace id"));
101 }
102 Ok(Search {
103 signal: Signal::Traces,
104 from: 0,
105 to: i64::MAX,
106 terms: vec![Term {
107 target: Target::Field("trace_id".into()),
108 op: Op::Eq,
109 value: Value::Str(id.to_owned()),
110 }],
111 limit,
112 after: None,
113 cursors: false,
114 })
115}
116
117pub(crate) fn doc(args: &Yaml, now: i64) -> Result<Rca, String> {
119 api::known(
120 args,
121 &[
122 "title",
123 "from",
124 "to",
125 "summary",
126 "impact",
127 "timeline",
128 "root_cause",
129 "evidence",
130 "ruled_out",
131 "contributing",
132 "remediation",
133 "verification",
134 "prevention",
135 "emit",
136 ],
137 )?;
138 let (from, to) = api::bounds(args, now)?;
139 let mut timeline = Vec::new();
140 for e in list(args, "timeline")? {
141 api::known(e, &["at", "what"])?;
142 let at = api::time_field(&e["at"], now, i64::MIN)?;
143 if at == i64::MIN {
144 return Err("each timeline entry needs `at`, as '-15m' or nanoseconds".into());
145 }
146 timeline.push((at, text(e, "what", "a timeline entry")?));
147 }
148 timeline.sort_by_key(|(at, _)| *at);
149
150 let mut evidence = Vec::new();
151 for e in list(args, "evidence")? {
152 evidence.push(fact(e, now, from, to)?);
153 }
154
155 let prevention = match &args["prevention"] {
161 Yaml::BadValue | Yaml::Null => None,
162 y => {
163 crate::alert::rule(y, &[]).map_err(|e| format!("prevention: {e}"))?;
164 Some(kyaml(y))
165 }
166 };
167
168 Ok(Rca {
169 title: text(args, "title", "an RCA")?,
170 from,
171 to,
172 summary: text(args, "summary", "an RCA")?,
173 impact: strings(args, "impact")?,
174 timeline,
175 root_cause: text(args, "root_cause", "an RCA")?,
176 evidence,
177 ruled_out: strings(args, "ruled_out")?,
178 contributing: strings(args, "contributing")?,
179 remediation: strings(args, "remediation")?,
180 verification: strings(args, "verification")?,
181 prevention,
182 emit: flag(args, "emit")?,
183 })
184}
185
186fn fact(y: &Yaml, now: i64, from: i64, to: i64) -> Result<Fact, String> {
187 api::known(y, &["claim", "trace_id", "query"])?;
188 let claim = text(y, "claim", "an evidence item")?;
189 let empty = |v: &Yaml| matches!(v, Yaml::BadValue | Yaml::Null);
190 let (mut cite, shown) = match (&y["trace_id"], &y["query"]) {
191 (t, q) if empty(t) && empty(q) => {
192 return Err(format!(
193 "evidence {claim:?} cites nothing: give it `trace_id` or `query`. \
194 A claim Mira cannot re-run is not evidence — put it in `root_cause` \
195 or `contributing` instead."
196 ));
197 }
198 (t, q) if !empty(t) && !empty(q) => {
199 return Err(format!(
200 "evidence {claim:?} cites both `trace_id` and `query`; pick one"
201 ));
202 }
203 (t, _) if !empty(t) => {
204 let id = t.as_str().ok_or("`trace_id` must be a quoted string")?;
205 (trace_query(id, 0)?, format!("trace `{}`", id.trim()))
206 }
207 (_, q) => {
208 let mut s = api::search_doc(q, now)?;
209 if empty(&q["from"]) && empty(&q["to"]) {
215 (s.from, s.to) = (from, to);
216 }
217 let shown = match filter(&s.terms) {
218 f if f.is_empty() => format!("all {}", s.signal.dir()),
219 f => format!("{} where `{f}`", s.signal.dir()),
220 };
221 (s, shown)
222 }
223 };
224 cite.limit = 0;
227 Ok(Fact {
228 claim,
229 cite,
230 shown,
231 found: None,
232 })
233}
234
235impl Rca {
236 pub(crate) fn verified(&self) -> bool {
238 self.evidence.iter().all(|f| f.found.is_some())
239 }
240
241 pub(crate) fn dead(&self) -> Option<String> {
248 let dead: Vec<&Fact> = self
249 .evidence
250 .iter()
251 .filter(|f| matches!(f.found, Some(0) | Some(UNREADABLE) | None))
252 .collect();
253 if dead.is_empty() {
254 return None;
255 }
256 let mut out = format!(
257 "nothing was rendered and nothing was stored: {} of {} citations do not \
258 hold against this store.\n",
259 dead.len(),
260 self.evidence.len()
261 );
262 for f in dead {
263 let why = match f.found {
264 Some(UNREADABLE) | None => "could not be read",
265 _ => "matches no records",
266 };
267 out.push_str(&format!(" - {} ({}) {why}\n", f.claim, f.shown));
268 }
269 out.push_str(
270 "Widen the window, fix the filter, or drop the claim — but do not publish \
271 a write-up citing evidence this node cannot produce.",
272 );
273 Some(out)
274 }
275
276 pub(crate) fn render(&self) -> String {
283 assert!(self.verified(), "render before the citations were checked");
284 let mut m = String::new();
285 m.push_str(&format!("# {}\n\n", self.title));
286 m.push_str(&format!(
287 "*{} → {} ({}). Written by an agent against Mira; every citation below was \
288 re-run at render time and returned the record count beside it.*\n\n",
289 utc(self.from),
290 utc(self.to),
291 span(self.to - self.from)
292 ));
293
294 m.push_str("## Summary\n\n");
295 m.push_str(&self.summary);
296 m.push_str("\n\n");
297 bullets(&mut m, "Impact", &self.impact);
298
299 if !self.timeline.is_empty() {
300 m.push_str("## Timeline\n\n| When (UTC) | What |\n| --- | --- |\n");
301 for (at, what) in &self.timeline {
302 m.push_str(&format!("| {} | {} |\n", utc(*at), cell(what)));
303 }
304 m.push('\n');
305 }
306
307 m.push_str("## Root cause\n\n");
308 m.push_str(&self.root_cause);
309 m.push_str("\n\n");
310
311 if !self.evidence.is_empty() {
312 m.push_str("## Evidence\n\n");
313 for f in &self.evidence {
314 m.push_str(&format!(
318 "- {} — {}, {} records\n",
319 f.claim,
320 f.shown,
321 f.found.unwrap_or_default()
322 ));
323 }
324 m.push('\n');
325 }
326
327 bullets(&mut m, "Ruled out", &self.ruled_out);
328 bullets(&mut m, "Contributing factors", &self.contributing);
329 if !self.remediation.is_empty() {
330 bullets(&mut m, "Remediation", &self.remediation);
331 m.push_str(
335 "> Mira did not apply any of this and cannot: it has no verb that \
336 changes a cluster.\n\n",
337 );
338 }
339 bullets(&mut m, "Verification", &self.verification);
340
341 if let Some(rule) = &self.prevention {
342 m.push_str(
343 "## Prevention\n\nThe rule that would have caught this, ready for \
344 `alerts.kyaml` — add your own `notify` targets:\n\n```yaml\nrules:\n - ",
345 );
346 m.push_str(&rule.replace('\n', "\n "));
350 m.push_str("\n```\n\n");
351 }
352 m
353 }
354
355 pub(crate) fn export(
363 &self,
364 md: &str,
365 now: i64,
366 ) -> mira_proto::collector::logs::v1::ExportLogsServiceRequest {
367 use mira_proto::collector::logs::v1::ExportLogsServiceRequest;
368 use mira_proto::common::v1::{AnyValue, InstrumentationScope, KeyValue, any_value};
369 use mira_proto::logs::v1::{LogRecord, ResourceLogs, ScopeLogs};
370 use mira_proto::resource::v1::Resource;
371
372 let kv = |k: &str, v: String| KeyValue {
373 key: k.into(),
374 value: Some(AnyValue {
375 value: Some(any_value::Value::StringValue(v)),
376 }),
377 };
378 ExportLogsServiceRequest {
379 resource_logs: vec![ResourceLogs {
380 resource: Some(Resource {
381 attributes: vec![kv("service.name", "mira".into())],
387 ..Default::default()
388 }),
389 scope_logs: vec![ScopeLogs {
390 scope: Some(InstrumentationScope {
391 name: "mira.rca".into(),
392 ..Default::default()
393 }),
394 log_records: vec![LogRecord {
395 time_unix_nano: now.max(0) as u64,
396 severity_number: 9,
400 severity_text: "INFO".into(),
401 event_name: "rca".into(),
402 body: Some(AnyValue {
403 value: Some(any_value::Value::StringValue(md.to_owned())),
404 }),
405 attributes: vec![
406 kv("rca.title", self.title.clone()),
407 kv("rca.window.from", utc(self.from)),
408 kv("rca.window.to", utc(self.to)),
409 ],
410 ..Default::default()
411 }],
412 ..Default::default()
413 }],
414 ..Default::default()
415 }],
416 }
417 }
418}
419
420fn bullets(m: &mut String, heading: &str, items: &[String]) {
421 if items.is_empty() {
422 return;
423 }
424 m.push_str(&format!("## {heading}\n\n"));
425 for i in items {
426 m.push_str(&format!("- {i}\n"));
427 }
428 m.push('\n');
429}
430
431fn cell(s: &str) -> String {
435 s.replace('|', "\\|").replace('\n', " ")
436}
437
438fn text(doc: &Yaml, key: &str, what: &str) -> Result<String, String> {
440 doc[key]
441 .as_str()
442 .map(str::to_owned)
443 .ok_or(format!("{what} needs a quoted `{key}`"))
444}
445
446fn strings(doc: &Yaml, key: &str) -> Result<Vec<String>, String> {
449 list(doc, key)?
450 .iter()
451 .map(|y| {
452 y.as_str()
453 .map(str::to_owned)
454 .ok_or(format!("every entry of `{key}` must be a quoted string"))
455 })
456 .collect()
457}
458
459fn list<'a>(doc: &'a Yaml, key: &str) -> Result<&'a [Yaml], String> {
460 match &doc[key] {
461 Yaml::BadValue | Yaml::Null => Ok(&[]),
462 Yaml::Array(a) => Ok(a),
463 _ => Err(format!("`{key}` must be a list")),
464 }
465}
466
467fn flag(doc: &Yaml, key: &str) -> Result<bool, String> {
468 match &doc[key] {
469 Yaml::BadValue | Yaml::Null => Ok(false),
470 Yaml::Boolean(b) => Ok(*b),
471 y => y
472 .as_str()
473 .and_then(|s| s.parse().ok())
474 .ok_or(format!("{key}: expected \"true\" or \"false\"")),
475 }
476}
477
478fn filter(terms: &[Term]) -> String {
481 crate::alert::filter_of(terms)
482}
483
484fn utc(ns: i64) -> String {
492 let secs = ns.div_euclid(1_000_000_000) as libc::time_t;
493 let mut tm: libc::tm = unsafe { std::mem::zeroed() };
498 unsafe { libc::gmtime_r(&secs, &mut tm) };
501 format!(
502 "{:04}-{:02}-{:02}T{:02}:{:02}:{:02}Z",
503 tm.tm_year + 1900,
504 tm.tm_mon + 1,
505 tm.tm_mday,
506 tm.tm_hour,
507 tm.tm_min,
508 tm.tm_sec
509 )
510}
511
512fn span(ns: i64) -> String {
514 match ns.max(0) / 1_000_000_000 {
515 s if s >= 86_400 => format!("{}d{}h", s / 86_400, s % 86_400 / 3_600),
516 s if s >= 3_600 => format!("{}h{:02}m", s / 3_600, s % 3_600 / 60),
517 s if s >= 60 => format!("{}m{:02}s", s / 60, s % 60),
518 s => format!("{s}s"),
519 }
520}
521
522fn kyaml(y: &Yaml) -> String {
530 match y.as_hash() {
531 Some(h) => h
536 .iter()
537 .map(|(k, v)| format!("{}: {}", one(k), one(v)))
538 .collect::<Vec<_>>()
539 .join("\n"),
540 None => one(y),
541 }
542}
543
544fn one(y: &Yaml) -> String {
545 let mut j = Json::new();
546 write(y, &mut j);
547 j.into_string()
548}
549
550fn write(y: &Yaml, j: &mut Json) {
551 match y {
552 Yaml::Hash(h) => j.obj(|j| {
553 for (k, v) in h {
554 j.key(k.as_str().unwrap_or_default());
555 write(v, j);
556 }
557 }),
558 Yaml::Array(a) => j.arr(|j| {
559 for v in a {
560 write(v, j);
561 }
562 }),
563 Yaml::String(s) => j.str(s),
564 Yaml::Integer(n) => j.i64(*n),
565 Yaml::Boolean(b) => j.bool(*b),
566 Yaml::Real(r) => j.f64(r.parse().unwrap_or_default()),
567 _ => j.null(),
568 }
569}
570
571#[cfg(test)]
572mod tests {
573 use super::*;
574
575 fn parse(s: &str) -> Yaml {
576 api::parse(s).unwrap()
577 }
578
579 const T: i64 = 1_789_812_000_000_000_000;
581
582 #[test]
587 fn a_claim_mira_cannot_re_run_is_not_evidence() {
588 let base = r#"{"title":"t","summary":"s","root_cause":"r","#;
589 let uncited = doc(
590 &parse(&format!(
591 r#"{base}"evidence":[{{"claim":"the pods were fine"}}]}}"#
592 )),
593 T,
594 )
595 .unwrap_err();
596 assert!(uncited.contains("cites nothing"), "{uncited}");
597 assert!(uncited.contains("the pods were fine"), "{uncited}");
598 assert!(uncited.contains("root_cause"), "{uncited}");
599
600 let both = doc(
601 &parse(&format!(
602 r#"{base}"evidence":[{{"claim":"c","query":{{}},
603 "trace_id":"4bf92f3577b34da6a3ce929d0e0e4736"}}]}}"#
604 )),
605 T,
606 )
607 .unwrap_err();
608 assert!(both.contains("pick one"), "{both}");
609
610 let mut r = doc(
614 &parse(&format!(
615 r#"{base}"evidence":[
616 {{"claim":"checkout 5xx","query":{{"where":[{{"attr":"service.name","eq":"checkout"}}]}}}},
617 {{"claim":"one bad trace","trace_id":"4bf92f3577b34da6a3ce929d0e0e4736"}}]}}"#
618 )),
619 T,
620 )
621 .unwrap();
622 assert!(!r.verified());
623 r.evidence[0].seen(Some(0));
624 r.evidence[1].seen(None);
625 assert!(r.verified());
626 let dead = r.dead().unwrap();
627 assert!(dead.contains("2 of 2"), "{dead}");
628 assert!(dead.contains("matches no records"), "{dead}");
629 assert!(dead.contains("could not be read"), "{dead}");
630 assert!(dead.contains("attr:service.name=checkout"), "{dead}");
633 assert!(dead.contains("nothing was stored"), "{dead}");
634
635 r.evidence[0].seen(Some(12));
636 r.evidence[1].seen(Some(1));
637 assert!(r.dead().is_none());
638 }
639
640 #[test]
645 fn a_citation_inherits_the_incidents_window_unless_it_names_one() {
646 let r = doc(
647 &parse(
648 r#"{"title":"t","summary":"s","root_cause":"r",
649 "from":"-6h","to":"-5h","evidence":[
650 {"claim":"a","query":{}},
651 {"claim":"b","query":{"from":"-30m"}}]}"#,
652 ),
653 T,
654 )
655 .unwrap();
656 assert_eq!(
657 (r.evidence[0].cite.from, r.evidence[0].cite.to),
658 (r.from, r.to)
659 );
660 assert_eq!(r.from, T - 6 * 3_600_000_000_000);
661 assert_eq!(r.evidence[1].cite.from, T - 30 * 60_000_000_000);
662 assert!(r.evidence.iter().all(|f| f.cite.limit == 0));
665 let t = doc(
668 &parse(
669 r#"{"title":"t","summary":"s","root_cause":"r","evidence":[
670 {"claim":"a","trace_id":" 4BF92F3577B34DA6A3CE929D0E0E4736 "}]}"#,
671 ),
672 T,
673 )
674 .unwrap();
675 assert_eq!(
676 (t.evidence[0].cite.from, t.evidence[0].cite.to),
677 (0, i64::MAX)
678 );
679 assert_eq!(t.evidence[0].cite.signal, Signal::Traces);
680
681 let bad = doc(
682 &parse(
683 r#"{"title":"t","summary":"s","root_cause":"r","evidence":[
684 {"claim":"a","trace_id":"0102030405060708"}]}"#,
685 ),
686 T,
687 )
688 .unwrap_err();
689 assert!(bad.contains("16-byte"), "{bad}");
690 }
691
692 #[test]
696 fn a_proposed_rule_is_one_the_alert_loader_accepts() {
697 let with = |rule: &str| {
698 doc(
699 &parse(&format!(
700 r#"{{"title":"t","summary":"s","root_cause":"r","prevention":{rule}}}"#
701 )),
702 T,
703 )
704 };
705 let good = with(
706 r#"{"name":"checkout-5xx","over":"5m","for":"2m","when":"count > 20",
707 "query":{"signal":"logs","where":[{"attr":"service.name","eq":"checkout"},
708 {"field":"severity_number","gte":17}]}}"#,
709 )
710 .unwrap();
711 let md = {
712 let mut g = good;
713 g.evidence.clear();
714 g.render()
715 };
716 assert!(md.contains("```yaml\nrules:\n - \"name\""), "{md}");
717 assert!(md.contains(r#""name": "checkout-5xx""#), "{md}");
721 assert!(md.contains(r#""gte":17"#), "{md}");
722
723 let windowed =
726 with(r#"{"name":"r","when":"count > 1","query":{"signal":"logs","from":"-1h"}}"#)
727 .unwrap_err();
728 assert!(windowed.contains("prevention:"), "{windowed}");
729 assert!(windowed.contains("over"), "{windowed}");
730
731 let typo =
732 with(r#"{"name":"r","when":"count > 1","query":{},"notify":["oncall"]}"#).unwrap_err();
733 assert!(typo.contains("prevention:"), "{typo}");
734 }
735
736 #[test]
740 fn the_rendered_document_is_timezone_free_ordered_and_honest_about_what_it_did() {
741 let mut r = doc(
742 &parse(
743 r#"{"title":"Checkout 5xx","summary":"Checkout returned 502 for 31 minutes.",
744 "from":1789812000000000000,"to":1789813860000000000,
745 "impact":["4,102 requests failed"],
746 "timeline":[{"at":1789813800000000000,"what":"rollback | complete"},
747 {"at":1789812060000000000,"what":"first 502"}],
748 "root_cause":"The 1.4.0 image raised the pool ceiling.",
749 "evidence":[{"claim":"the pool was exhausted",
750 "query":{"where":[{"attr":"service.name","eq":"checkout"}]}}],
751 "ruled_out":["Not the database: no slow queries."],
752 "contributing":["No alert on pool saturation."],
753 "remediation":["Roll back to 1.3.9."],
754 "verification":["502 rate back to zero."]}"#,
755 ),
756 T,
757 )
758 .unwrap();
759 r.evidence[0].seen(Some(4_102));
760 let md = r.render();
761
762 assert!(md.starts_with("# Checkout 5xx\n"), "{md}");
763 assert!(
764 md.contains("2026-09-19T10:00:00Z → 2026-09-19T10:31:00Z (31m00s)"),
765 "{md}"
766 );
767 let first = md.find("first 502").unwrap();
769 let second = md.find("rollback").unwrap();
770 assert!(first < second, "timeline out of order:\n{md}");
771 assert!(md.contains(r"rollback \| complete"), "{md}");
772 assert!(md.contains(", 4102 records"), "{md}");
775 assert!(
776 md.contains("> Mira did not apply any of this and cannot"),
777 "{md}"
778 );
779 assert!(!md.contains("## Prevention"), "{md}");
783
784 let req = r.export(&md, T);
787 let rl = &req.resource_logs[0];
788 let rec = &rl.scope_logs[0].log_records[0];
789 assert_eq!(rec.severity_number, 9);
790 assert_eq!(rec.event_name, "rca");
791 assert_eq!(rec.time_unix_nano, T as u64);
792 assert_eq!(
793 rl.resource.as_ref().unwrap().attributes[0].key,
794 "service.name"
795 );
796 assert!(rec.attributes.iter().any(|a| a.key == "rca.title"));
797 }
798
799 #[test]
803 fn a_misspelled_section_is_refused_rather_than_dropped() {
804 let bad = [
805 (r#"{"summary":"s","root_cause":"r"}"#, "`title`"),
806 (r#"{"title":"t","root_cause":"r"}"#, "`summary`"),
807 (r#"{"title":"t","summary":"s"}"#, "`root_cause`"),
808 (
809 r#"{"title":"t","summary":"s","root_cause":"r","timelines":[]}"#,
810 "unknown query key",
811 ),
812 (
813 r#"{"title":"t","summary":"s","root_cause":"r","impact":"one thing"}"#,
814 "`impact` must be a list",
815 ),
816 (
817 r#"{"title":"t","summary":"s","root_cause":"r","impact":[7]}"#,
818 "quoted string",
819 ),
820 (
821 r#"{"title":"t","summary":"s","root_cause":"r","timeline":[{"what":"x"}]}"#,
822 "needs `at`",
823 ),
824 (
825 r#"{"title":"t","summary":"s","root_cause":"r","timeline":[{"at":"-5m"}]}"#,
826 "`what`",
827 ),
828 (
829 r#"{"title":"t","summary":"s","root_cause":"r","emit":"yes"}"#,
830 "emit",
831 ),
832 (
833 r#"{"title":"t","summary":"s","root_cause":"r","from":"-1h","to":"-2h"}"#,
834 "is after",
835 ),
836 ];
837 for (args, want) in bad {
838 let e = doc(&parse(args), T).unwrap_err();
839 assert!(e.contains(want), "{args}\n wanted {want:?}, got {e:?}");
840 }
841
842 let r = doc(&parse(r#"{"title":"t","summary":"s","root_cause":"r"}"#), T).unwrap();
845 assert!(r.verified());
846 assert!(r.dead().is_none());
847 assert!(!r.emit);
848 assert!(r.render().contains("## Root cause"));
849 }
850
851 #[test]
856 fn the_rule_fence_keeps_a_number_a_number_and_one_key_per_line() {
857 let y = parse(
858 r#"{"name":"x","when":"count >= 1","query":{"where":[{"gte":17},{"on":true},
859 {"ratio":0.5},{"nil":null}]}}"#,
860 );
861 let out = kyaml(&y);
862 let lines: Vec<_> = out.lines().collect();
863 assert_eq!(lines[0], r#""name": "x""#, "{out}");
864 assert_eq!(lines.len(), 3, "one top-level key per line:\n{out}");
865 assert!(out.contains(r#"{"gte":17}"#), "{out}");
867 assert!(out.contains(r#"{"on":true}"#), "{out}");
868 assert!(out.contains(r#"{"ratio":0.5}"#), "{out}");
869 assert!(out.contains(r#"{"nil":null}"#), "{out}");
870 assert_eq!(kyaml(&parse("[1, 2]")), "[1,2]");
873 }
874}