Skip to main content

nmbrs_workload/
report_synth.rs

1// Copyright 2024-2026 Jonathan Shook
2// SPDX-License-Identifier: Apache-2.0
3
4//! SRD-109 — report synthesis: the workload's structure IS the report
5//! definition.
6//!
7//! When a workload carries no explicit `report:` block, this module
8//! synthesizes one from the structural fixtures — `key_metrics`
9//! designations on phases and `anchor` cues on scenario sweeps — and
10//! the result is a `serde_json` mapping fed through the SAME
11//! [`crate::report::parse_report`] entry the YAML path uses. That is
12//! the affine contract made literal: everything synthesized is
13//! expressible by hand in the SRD-46 grammar, and `nmbrs report synth`
14//! dumps exactly what would be hand-written.
15//!
16//! Well-formedness is enforced here, at synthesis (= report) time:
17//! a designated family that no op emits, and a designated phase whose
18//! activations multiply through a NON-anchored sweep (a silent
19//! flatten), are hard errors carrying the fix in the message. There
20//! are no implied aggregates anywhere: designations carry their
21//! aggregate by grammar (enforced at workload parse), the SRD-91
22//! spine columns carry contract-level defaults declared in this
23//! module, and everything else is an error.
24//!
25//! MVP scope decisions (documented, revisitable):
26//! - The spine table rows are phases with activation cardinality 1
27//!   (not under any sweep). Its columns are the SRD-91 contract's and
28//!   then each of those phases' own designations, a column holding a
29//!   value in the rows of the phases that designate it. View-attached
30//!   phases live in their view's table; un-anchored looped phases
31//!   WITHOUT designations are listed in a text note instead of
32//!   silently aggregated.
33//! - View tables carry designation columns only (no auto spine
34//!   columns), keyed by the anchor sweep's coordinate label(s).
35//! - The rollup window is a fixed generous lookback (`WINDOW`); the
36//!   execution selection narrows actual sample ranges.
37
38use std::collections::BTreeMap;
39
40use crate::model::{KeyAgg, KeyMetric, ScenarioNode, Workload, WorkloadPhase};
41
42/// Rollup lookback for every synthesized query. Must outlast any
43/// session; the metricsql evaluation window (latest-sample span)
44/// bounds what it actually reads.
45const WINDOW: &str = "30d";
46
47/// SRD-109 §"The spine contract" — the contract-level default
48/// designations every phase carries through its SRD-91 outcome
49/// instruments. Declared HERE (once) so the spine is not an implied
50/// aggregate.
51fn spine_contract() -> Vec<KeyMetric> {
52    use KeyAgg::*;
53    vec![
54        KeyMetric {
55            column: "count".into(),
56            agg: Last,
57            family: "result_success".into(),
58            matchers: String::new(),
59            samples: None,
60        },
61        KeyMetric {
62            column: "failures".into(),
63            agg: Last,
64            family: "result_failure".into(),
65            matchers: String::new(),
66            samples: None,
67        },
68        KeyMetric {
69            column: "wall".into(),
70            agg: Span,
71            family: String::new(),
72            matchers: String::new(),
73            samples: None,
74        },
75        KeyMetric {
76            column: "p99".into(),
77            agg: Max,
78            family: "result_success_p99".into(),
79            matchers: String::new(),
80            samples: None,
81        },
82    ]
83}
84
85/// One view (anchored table) discovered in the scenario walk.
86#[derive(Debug, Default)]
87struct View {
88    /// Coordinate labels of the anchoring sweep(s). All anchors
89    /// sharing this view name must agree (SRD-109 §Anchors).
90    coords: Vec<String>,
91    /// Phases attached beneath this view, in first-seen order.
92    phases: Vec<String>,
93    /// Human renderings of the anchoring comprehension(s) — the
94    /// definitions that generate this view's rows, for the
95    /// per-figure explainer. Unique, first-seen order.
96    defs: Vec<String>,
97}
98
99/// Where a phase's designations land.
100#[derive(Debug, Clone, PartialEq)]
101enum Attach {
102    Spine,
103    View(String),
104    /// Beneath a non-anchored sweep (relative to its nearest anchor):
105    /// designations here are the silent-flatten error; undesignated
106    /// phases are merely noted.
107    Flattened {
108        via: String,
109    },
110}
111
112struct Walk {
113    views: BTreeMap<String, View>,
114    /// phase name -> attachments (a phase may appear in several
115    /// scenarios / positions; every distinct attachment is kept).
116    attachments: BTreeMap<String, Vec<Attach>>,
117    errors: Vec<String>,
118}
119
120impl Walk {
121    fn walk_nodes(
122        &mut self,
123        nodes: &[ScenarioNode],
124        anchor: Option<&str>,
125        flattened_via: Option<&str>,
126    ) {
127        for node in nodes {
128            match node {
129                ScenarioNode::Phase(name) => {
130                    let attach = match (flattened_via, anchor) {
131                        (Some(via), _) => Attach::Flattened {
132                            via: via.to_string(),
133                        },
134                        (None, Some(v)) => Attach::View(v.to_string()),
135                        (None, None) => Attach::Spine,
136                    };
137                    let entry = self.attachments.entry(name.clone()).or_default();
138                    if !entry.contains(&attach) {
139                        entry.push(attach.clone());
140                    }
141                    if let Attach::View(v) = &attach {
142                        let view = self
143                            .views
144                            .get_mut(v)
145                            .expect("view registered before descent");
146                        if !view.phases.contains(name) {
147                            view.phases.push(name.clone());
148                        }
149                    }
150                }
151                ScenarioNode::Comprehension {
152                    comprehension,
153                    children,
154                    anchor: node_anchor,
155                    ..
156                } => {
157                    let coords = comprehension.coordinate_names();
158                    match node_anchor {
159                        Some(view_name) => {
160                            let view = self.views.entry(view_name.clone()).or_default();
161                            let def = describe_comprehension(comprehension);
162                            if !view.defs.contains(&def) {
163                                view.defs.push(def);
164                            }
165                            if view.coords.is_empty() {
166                                view.coords = coords.clone();
167                            } else if view.coords != coords {
168                                self.errors.push(format!(
169                                    "anchor view '{view_name}': coordinate label sets \
170                                     disagree across anchors ({:?} vs {:?}) — views \
171                                     sharing a name must share coordinates",
172                                    view.coords, coords
173                                ));
174                            }
175                            // An anchor RESETS the flatten state: rows exist
176                            // at this altitude, so activations below are 1:1
177                            // with rows until another sweep intervenes.
178                            self.walk_nodes(children, Some(view_name), None);
179                        }
180                        None => {
181                            // Non-anchored sweep: everything beneath
182                            // multiplies relative to the current row space.
183                            let via = format!("for {}", coords.join(","));
184                            self.walk_nodes(children, anchor, Some(&via));
185                        }
186                    }
187                }
188                ScenarioNode::IncludedScenario { children, .. }
189                | ScenarioNode::Bindings { children, .. }
190                | ScenarioNode::DoWhile { children, .. }
191                | ScenarioNode::DoUntil { children, .. } => {
192                    // Transparent for attachment purposes (do_while /
193                    // do_until are unbounded sweeps and SHOULD flatten,
194                    // but none of our workloads designate beneath one
195                    // yet — revisit with breakouts).
196                    self.walk_nodes(children, anchor, flattened_via);
197                }
198            }
199        }
200    }
201}
202
203/// Families a phase is known to emit: declared phase/op `metrics:`
204/// keys, the poll wrapper's `metric_name`, the SRD-91 outcome
205/// instruments (with their stat suffixes), and the validation
206/// observer's `recall_*` families for ANN ops with ground truth.
207fn known_families(phase: &WorkloadPhase) -> Vec<String> {
208    let mut out: Vec<String> = Vec::new();
209    for name in phase.metrics.keys() {
210        out.push(name.clone());
211    }
212    for op in &phase.ops {
213        for name in op.metrics.keys() {
214            out.push(name.clone());
215        }
216        // Op-level poll wrappers: `poll` is a RESERVED op key, so the
217        // parser routes it into `op.params` (the runtime reads it from
218        // there too — see scope.rs template_poll_until). Its
219        // `metric_name` is a duration family the wrapper emits.
220        for source in [&op.params, &op.op] {
221            if let Some(m) = source
222                .get("poll")
223                .and_then(|v| v.as_object())
224                .and_then(|p| p.get("metric_name"))
225                .and_then(|v| v.as_str())
226            {
227                out.push(m.to_string());
228            }
229        }
230    }
231    if let Some(poll) = &phase.poll
232        && let Some(m) = &poll.metric_name
233    {
234        out.push(m.clone());
235    }
236    const INSTRUMENTS: &[&str] = &[
237        "result_success",
238        "result_failure",
239        "result_total",
240        "attempt_total",
241        "attempt_success",
242        "attempt_failure",
243        "result_bytes",
244        "result_elements",
245        "cycles_total",
246        "cycles_servicetime",
247    ];
248    const SUFFIXES: &[&str] = &[
249        "", "_p50", "_p75", "_p90", "_p95", "_p99", "_p999", "_mean", "_min", "_max", "_stddev",
250        "_rate", "_count",
251    ];
252    for i in INSTRUMENTS {
253        for sfx in SUFFIXES {
254            out.push(format!("{i}{sfx}"));
255        }
256    }
257    out
258}
259
260fn family_known(phase: &WorkloadPhase, family: &str) -> bool {
261    family.starts_with("recall_")
262        || KeyMetric::is_host_family(family)
263        || known_families(phase).iter().any(|f| f == family)
264}
265
266/// Human form of a designation's aggregate — the legend spelling
267/// (`avg(load_weight)`, `rate(result_success)`, `span()`).
268fn agg_desc(km: &KeyMetric) -> String {
269    if km.agg == KeyAgg::Span {
270        return "span()".to_string();
271    }
272    let mut measure = km.family.clone();
273    if !km.matchers.is_empty() {
274        measure.push_str(&format!("{{{}}}", km.matchers));
275    }
276    if let Some(mode) = &km.samples {
277        measure.push_str(&format!(", {mode}"));
278    }
279    format!("{}({measure})", format!("{:?}", km.agg).to_lowercase())
280}
281
282/// Human rendering of a comprehension — the `var in source` form an
283/// operator wrote, reconstructed from the AST for figure explainers.
284fn describe_comprehension(c: &polydat::iteration::comprehension::Comprehension) -> String {
285    use polydat::iteration::comprehension::Comprehension as C;
286    match c {
287        C::Clause { name, source } => format!("{name} in {}", describe_source(source)),
288        C::Cartesian { children } => children
289            .iter()
290            .map(describe_comprehension)
291            .collect::<Vec<_>>()
292            .join(", "),
293        C::Zip { children, .. } => format!(
294            "zip({})",
295            children
296                .iter()
297                .map(describe_comprehension)
298                .collect::<Vec<_>>()
299                .join(", ")
300        ),
301        C::Union { children } => children
302            .iter()
303            .map(describe_comprehension)
304            .collect::<Vec<_>>()
305            .join(" | "),
306        C::Filter { child, predicate } => {
307            format!("{} if {predicate}", describe_comprehension(child))
308        }
309        C::Order {
310            child,
311            strategy,
312            truncation,
313            seed,
314        } => {
315            let mut text = format!("{} ordered {strategy:?}", describe_comprehension(child));
316            if let Some(n) = truncation {
317                text.push_str(&format!(" take {n}"));
318            }
319            if let Some(s) = seed {
320                text.push_str(&format!(" seed {s}"));
321            }
322            text
323        }
324    }
325}
326
327fn describe_source(s: &polydat::iteration::comprehension::Source) -> String {
328    use polydat::iteration::comprehension::Source;
329    use polydat::iteration::comprehension::source::LiteralValue;
330    match s {
331        Source::Literal { values } => values
332            .iter()
333            .map(|v| match v {
334                LiteralValue::Int(i) => i.to_string(),
335                LiteralValue::UInt(u) => u.to_string(),
336                LiteralValue::Float(f) => f.to_string(),
337                LiteralValue::String(st) => st.clone(),
338                LiteralValue::Bool(b) => b.to_string(),
339                LiteralValue::Json(j) => j.to_string(),
340            })
341            .collect::<Vec<_>>()
342            .join(","),
343        Source::IntRange { lo, hi, step } if *step == 1 => format!("{lo}..{hi}"),
344        Source::IntRange { lo, hi, step } => format!("{lo}..{hi} step {step}"),
345        Source::Generator { expr, .. } => expr.clone(),
346        Source::WorkloadParamList { name, .. } => format!("{{{name}}}"),
347        Source::ContinuousInterval { .. } => "<continuous interval>".to_string(),
348        Source::Distribution { distribution, .. } => format!("{distribution:?}(…)"),
349    }
350}
351
352/// The selector of one designation over the phases `phase_matcher`
353/// picks (`phase="load"`, `phase=~"load|settle"`): the phases, the
354/// designation's own matchers, and for a family of the session
355/// sampler the mode its samples are counted by (SRD-118 §5.1).
356fn selector(metric: &KeyMetric, phase_matcher: &str) -> String {
357    let mut parts = vec![phase_matcher.to_string()];
358    if !metric.matchers.is_empty() {
359        parts.push(metric.matchers.clone());
360    }
361    if let Some(mode) = metric.sample_mode() {
362        parts.push(format!("phase_samples=\"{mode}\""));
363    }
364    format!("{{{}}}", parts.join(","))
365}
366
367/// The matcher that picks one phase.
368fn one_phase(phase: &str) -> String {
369    format!("phase=\"{phase}\"")
370}
371
372/// The matcher that picks any of `phases`.
373fn any_phase(phases: &[&str]) -> String {
374    format!(
375        "phase=~\"{}\"",
376        phases
377            .iter()
378            .map(|s| regex_escape(s))
379            .collect::<Vec<_>>()
380            .join("|")
381    )
382}
383
384/// The metricsql expression for one designation, over the phases
385/// `phase_matcher` picks and grouped by `by_labels`. This is the ONE
386/// place the aggregate vocabulary maps to query text — every mapping
387/// explicit, none implied (SRD-109 §Well-formedness).
388fn query_for(metric: &KeyMetric, phase_matcher: &str, by_labels: &str) -> String {
389    use KeyAgg::*;
390    // A host measure is a gauge stored with the least, the greatest
391    // and the mean of its window's readings beside the last (SRD-42):
392    // the session's once per long window, a phase's own once for the
393    // phase. The least of a phase is the least of those, and likewise
394    // the greatest and the mean; the last value alone would miss a
395    // peak between two stored samples.
396    let windowed = match metric.agg {
397        Min => "_min",
398        Max => "_max",
399        Avg => "_mean",
400        _ => "",
401    };
402    let f = &if KeyMetric::is_host_family(&metric.family) {
403        format!("{}{windowed}", metric.family)
404    } else {
405        metric.family.clone()
406    };
407    let sel = selector(metric, phase_matcher);
408    // Time-derived designations ride the `_interval_ns` / `_rate`
409    // virtual stats (per-sample active-window bookkeeping) rather
410    // than first/last timestamp arithmetic: a phase shorter than
411    // the durable write cadence leaves ONE sample behind, where
412    // `tlast - tfirst` degenerates to zero but the sample's own
413    // interval is exact.
414    let span =
415        format!("max(sum_over_time(result_success_interval_ns{sel}[{WINDOW}])) by ({by_labels})");
416    match metric.agg {
417        Min => format!("min(min_over_time({f}{sel}[{WINDOW}])) by ({by_labels})"),
418        Max => format!("max(max_over_time({f}{sel}[{WINDOW}])) by ({by_labels})"),
419        Avg => format!("avg(avg_over_time({f}{sel}[{WINDOW}])) by ({by_labels})"),
420        Last => format!("max(last_over_time({f}{sel}[{WINDOW}])) by ({by_labels})"),
421        First => format!("min(first_over_time({f}{sel}[{WINDOW}])) by ({by_labels})"),
422        Median => format!("avg(median_over_time({f}{sel}[{WINDOW}])) by ({by_labels})"),
423        Stddev => format!("avg(stddev_over_time({f}{sel}[{WINDOW}])) by ({by_labels})"),
424        Sum => format!("sum(sum_over_time({f}{sel}[{WINDOW}])) by ({by_labels})"),
425        Count => format!("sum(count_over_time({f}{sel}[{WINDOW}])) by ({by_labels})"),
426        Span => span,
427        Rate => format!("avg(avg_over_time({f}_rate{sel}[{WINDOW}])) by ({by_labels})"),
428        Delta => format!(
429            "max(last_over_time({f}{sel}[{WINDOW}])) by ({by_labels}) - \
430             min(first_over_time({f}{sel}[{WINDOW}])) by ({by_labels})"
431        ),
432    }
433}
434
435/// True when two designations measure the same thing the same way,
436/// whatever their columns are called.
437fn same_measure(a: &KeyMetric, b: &KeyMetric) -> bool {
438    a.agg == b.agg && a.family == b.family && a.matchers == b.matchers && a.samples == b.samples
439}
440
441/// One column of the spine that a phase designated: the designation
442/// and the phases that made it.
443struct SpineColumn<'a> {
444    name: String,
445    metric: &'a KeyMetric,
446    phases: Vec<&'a str>,
447}
448
449/// The spine's designated columns, in the order the phases are given
450/// and each phase's designations are written. Phases that designate
451/// the same measure under the same column name share the column; a
452/// name already taken by another measure, or by the contract, is
453/// given its phase's name in front.
454fn spine_columns<'a>(workload: &'a Workload, spine_phases: &[&'a String]) -> Vec<SpineColumn<'a>> {
455    let contract: Vec<String> = spine_contract().into_iter().map(|km| km.column).collect();
456    let mut columns: Vec<SpineColumn<'a>> = Vec::new();
457    for phase_name in spine_phases {
458        let Some(phase) = workload.phases.get(phase_name.as_str()) else {
459            continue;
460        };
461        for km in &phase.key_metrics {
462            if let Some(shared) = columns
463                .iter_mut()
464                .find(|c| c.name == km.column && same_measure(c.metric, km))
465            {
466                shared.phases.push(phase_name.as_str());
467                continue;
468            }
469            let taken =
470                contract.contains(&km.column) || columns.iter().any(|c| c.name == km.column);
471            columns.push(SpineColumn {
472                name: if taken {
473                    format!("{phase_name}_{}", km.column)
474                } else {
475                    km.column.clone()
476                },
477                metric: km,
478                phases: vec![phase_name.as_str()],
479            });
480        }
481    }
482    columns
483}
484
485/// Synthesize the report mapping for a workload with no explicit
486/// `report:` block. `Ok(None)` when the workload has an explicit
487/// block (synthesis suppressed). Errors are the SRD-109
488/// well-formedness contract.
489pub fn synthesize(workload: &Workload) -> Result<Option<serde_json::Value>, String> {
490    if !workload.report.groups.is_empty() {
491        return Ok(None);
492    }
493    synthesize_forced(workload).map(Some)
494}
495
496/// [`synthesize`] without the explicit-block suppression: the section
497/// synthesized from the structural fixtures IRRESPECTIVE of any
498/// `report:` block. This is what `nmbrs report synth` dumps and what
499/// `--synthesized` renders — the affine mirror is always inspectable,
500/// even (especially) when a hand-tuned block has diverged from it.
501pub fn synthesize_forced(workload: &Workload) -> Result<serde_json::Value, String> {
502    synthesize_forced_for(workload, None)
503}
504
505/// [`synthesize_forced`] scoped to ONE scenario when the caller knows
506/// which ran (a session records it): the walk visits only that
507/// scenario, so views carry only phases reachable in the execution —
508/// no structurally-empty column groups from sibling scenarios.
509/// `None`, or a name the workload doesn't declare, falls back to the
510/// all-scenarios union.
511pub fn synthesize_forced_for(
512    workload: &Workload,
513    scenario: Option<&str>,
514) -> Result<serde_json::Value, String> {
515    let mut walk = Walk {
516        views: BTreeMap::new(),
517        attachments: BTreeMap::new(),
518        errors: Vec::new(),
519    };
520    // Union across every scenario: anchors and attachments merge; a
521    // phase reachable both anchored and un-anchored keeps both
522    // attachments (it renders in both places). Visit order pins the
523    // first-seen phase order inside each view — and with it the
524    // table's column order — so iterate `default` first (the
525    // workload's narrative order) and the rest by name, never the
526    // scenarios HashMap's per-process ordering.
527    let mut scenario_names: Vec<&String> = workload.scenarios.keys().collect();
528    scenario_names.sort_by_key(|n| (*n != "default", (*n).clone()));
529    if let Some(sel) = scenario
530        && let Some(name) = scenario_names.iter().find(|n| n.as_str() == sel).copied()
531    {
532        scenario_names = vec![name];
533    }
534    for name in scenario_names {
535        walk.walk_nodes(&workload.scenarios[name], None, None);
536    }
537    let Walk {
538        views,
539        attachments,
540        mut errors,
541        ..
542    } = walk;
543
544    // Well-formedness: designated families must be emitted; designated
545    // phases must not silently flatten through a non-anchored sweep.
546    for (phase_name, attaches) in &attachments {
547        let Some(phase) = workload.phases.get(phase_name) else {
548            continue;
549        };
550        for km in &phase.key_metrics {
551            if km.agg != KeyAgg::Span && !family_known(phase, &km.family) {
552                errors.push(format!(
553                    "phase '{phase_name}' key_metrics.{}: family '{}' is not \
554                     emitted by this phase (declared metrics, poll timers, \
555                     SRD-91 instruments and their stat suffixes, recall_*)",
556                    km.column, km.family
557                ));
558            }
559        }
560        if !phase.key_metrics.is_empty() {
561            for a in attaches {
562                if let Attach::Flattened { via } = a {
563                    errors.push(format!(
564                        "phase '{phase_name}' designates key metrics but its \
565                         activations multiply through a non-anchored sweep \
566                         ({via}): one table row would silently aggregate many \
567                         activations. Anchor that sweep (`anchor: <view>`) or \
568                         remove the designations. There are no implied \
569                         aggregates."
570                    ));
571                }
572            }
573        }
574    }
575    if !errors.is_empty() {
576        return Err(format!(
577            "report synthesis: {} well-formedness error(s):\n  - {}",
578            errors.len(),
579            errors.join("\n  - ")
580        ));
581    }
582
583    let mut groups = serde_json::Map::new();
584
585    // ── Spine ────────────────────────────────────────────────────
586    let spine_phases: Vec<&String> = attachments
587        .iter()
588        .filter(|(_, a)| a.contains(&Attach::Spine))
589        .map(|(n, _)| n)
590        .collect();
591    let looped_unanchored: Vec<&String> = attachments
592        .iter()
593        .filter(|(_, a)| {
594            a.iter().any(|x| matches!(x, Attach::Flattened { .. }))
595                && !a
596                    .iter()
597                    .any(|x| matches!(x, Attach::View(_)) || *x == Attach::Spine)
598        })
599        .map(|(n, _)| n)
600        .collect();
601    let mut spine = String::new();
602    spine.push_str(
603        "text phases_intro as \"Workload phases — outcomes at a glance\":\n \
604         One row per workload phase, keyed by the `phase` label. Column \
605         headers carry each value's definition (aggregate over the \
606         phase's samples). Each anchored sweep in the scenario renders \
607         as its own view table below, one row per sweep iteration.\n",
608    );
609    if !looped_unanchored.is_empty() {
610        spine.push_str(&format!(
611            "text phases_unanchored as \"Not tabulated\":\n \
612             Looped phases with no anchor and no designations — activations \
613             would aggregate silently, so no rows are synthesized: {}.\n",
614            looped_unanchored
615                .iter()
616                .map(|s| s.as_str())
617                .collect::<Vec<_>>()
618                .join(", ")
619        ));
620    }
621    // Restrict to spine phases explicitly so anchored phases don't
622    // leak in through the label join. NO spine-eligible phases ⇒ no
623    // spine table at all (an empty selector would match everything,
624    // silently re-admitting exactly the phases the notes exclude).
625    if !spine_phases.is_empty() {
626        spine.push_str("table phases:\n  group_by: phase\n");
627        spine.push_str("  label \"phases — one row per workload phase\"\n");
628        let every: Vec<&str> = spine_phases.iter().map(|s| s.as_str()).collect();
629        for km in spine_contract() {
630            let q = query_for(&km, &any_phase(&every), "phase");
631            spine.push_str(&format!("  query: {}: {}\n", km.column, q));
632            spine.push_str(&format!("  header {}: {}\n", km.column, agg_desc(&km)));
633        }
634        // Each phase's own designations: a column is filled in the
635        // rows of the phases that designate it.
636        for column in spine_columns(workload, &spine_phases) {
637            let q = query_for(column.metric, &any_phase(&column.phases), "phase");
638            spine.push_str(&format!("  query: {}: {}\n", column.name, q));
639            spine.push_str(&format!(
640                "  header {}: {}\n",
641                column.name,
642                agg_desc(column.metric)
643            ));
644        }
645    }
646    groups.insert("phases".to_string(), serde_json::Value::String(spine));
647
648    // ── One group per view ──────────────────────────────────────
649    for (view_name, view) in &views {
650        let by = view.coords.join(",");
651        // Each column's header carries its definition — the declared
652        // aggregate and, when several phases contribute, the emitting
653        // phase — so the rendered table explains itself with no
654        // separate legend to cross-reference.
655        let mut table = String::new();
656        let mut seen_cols: Vec<String> = Vec::new();
657        let mut phase_names: Vec<&str> = Vec::new();
658        let contributing = view
659            .phases
660            .iter()
661            .filter(|p| {
662                workload
663                    .phases
664                    .get(p.as_str())
665                    .is_some_and(|ph| !ph.key_metrics.is_empty())
666            })
667            .count();
668        for phase_name in &view.phases {
669            let Some(phase) = workload.phases.get(phase_name) else {
670                continue;
671            };
672            if !phase.key_metrics.is_empty() {
673                phase_names.push(phase_name);
674            }
675            for km in &phase.key_metrics {
676                let col = if seen_cols.contains(&km.column) {
677                    format!("{phase_name}_{}", km.column)
678                } else {
679                    km.column.clone()
680                };
681                seen_cols.push(col.clone());
682                let q = query_for(km, &one_phase(phase_name), &by);
683                table.push_str(&format!("  query: {col}: {q}\n"));
684                let note = if contributing > 1 {
685                    format!("{} @{phase_name}", agg_desc(km))
686                } else {
687                    agg_desc(km)
688                };
689                table.push_str(&format!("  header {col}: {note}\n"));
690            }
691        }
692        // The table's own label carries the row semantics into the
693        // rendered heading and the listing.
694        let label = format!(
695            "{view_name} — one row per {by} ({})",
696            phase_names.join(", ")
697        );
698        // Direct explainer: where this figure's rows COME FROM — the
699        // comprehension definition(s) that generate them — which
700        // labels identify a row, and which phases feed the columns.
701        let defs = view
702            .defs
703            .iter()
704            .map(|d| format!("`for {d}`"))
705            .collect::<Vec<_>>()
706            .join(" and ");
707        let about = format!(
708            "text {view_name}_about as \"{view_name} — one row per {by}\":\n \
709             Rows are the iterations of {defs}; the {by} label(s) \
710             identify each row within the workload. Columns aggregate \
711             each iteration's activations of: {}. Headers carry each \
712             column's definition{}.\n",
713            phase_names.join(", "),
714            if contributing > 1 {
715                " and its @phase provenance"
716            } else {
717                ""
718            }
719        );
720        let body =
721            format!("{about}table {view_name}:\n  group_by: {by}\n  label \"{label}\"\n{table}");
722        groups.insert(format!("view_{view_name}"), serde_json::Value::String(body));
723    }
724
725    Ok(serde_json::Value::Object(groups))
726}
727
728/// Dump the synthesized section as a `report:` YAML block — the
729/// affine round-trip surface (`nmbrs report synth`): copy, paste into
730/// the workload, edit, and synthesis is suppressed in favor of the
731/// hand-tuned version.
732pub fn synthesize_yaml(workload: &Workload) -> Result<String, String> {
733    let value = synthesize_forced(workload)?;
734    let map = value.as_object().expect("synthesize emits a mapping");
735    let mut out = String::from("report:\n");
736    for (group, body) in map {
737        out.push_str(&format!("  {group}: |\n"));
738        for line in body.as_str().unwrap_or_default().lines() {
739            out.push_str(&format!("    {line}\n"));
740        }
741    }
742    Ok(out)
743}
744
745fn regex_escape(s: &str) -> String {
746    let mut out = String::with_capacity(s.len());
747    for c in s.chars() {
748        if "\\.^$|?*+()[]{}".contains(c) {
749            out.push('\\');
750        }
751        out.push(c);
752    }
753    out
754}
755
756#[cfg(test)]
757mod host_tests;
758
759#[cfg(test)]
760mod tests {
761    use super::*;
762
763    fn wl(yaml: &str) -> Workload {
764        crate::parse::parse_workload(yaml, &std::collections::HashMap::new())
765            .expect("workload parses")
766    }
767
768    const BASE: &str = r#"
769params: { adapter: testkit }
770phases:
771  tick:
772    key_metrics:
773      rows: last(result_success)
774      spd: rate(result_success)
775    ops: { t: { stmt: "X" } }
776  plain:
777    ops: { t: { stmt: "Y" } }
778"#;
779
780    #[test]
781    fn synthesizes_spine_and_anchored_view() {
782        let y = format!(
783            "{BASE}
784scenarios:
785  default:
786    - plain
787    - for: \"k in 1,2\"
788      anchor: sweep
789      phases: [tick]
790"
791        );
792        let v = synthesize(&wl(&y))
793            .expect("well-formed")
794            .expect("synthesized");
795        let m = v.as_object().unwrap();
796        assert!(m.contains_key("phases"));
797        let sweep = m.get("view_sweep").unwrap().as_str().unwrap();
798        assert!(
799            sweep.contains("group_by: k"),
800            "anchor coordinate keys the view"
801        );
802        assert!(sweep.contains("last_over_time(result_success{phase=\"tick\"}"));
803        assert!(
804            sweep.contains("query: spd:"),
805            "rate designation synthesized"
806        );
807        let spine = m.get("phases").unwrap().as_str().unwrap();
808        assert!(spine.contains("plain"), "un-looped phase rows the spine");
809        assert!(
810            !spine.contains("|tick") && !spine.contains("\"tick"),
811            "anchored phase stays out of the spine selector"
812        );
813        // Affinity: the synthesized mapping parses through the SAME
814        // grammar entry the YAML path uses.
815        crate::report::parse_report(&v).expect("synthesized section parses");
816    }
817
818    #[test]
819    fn designated_phase_under_unanchored_sweep_is_an_error() {
820        let y = format!(
821            "{BASE}
822scenarios:
823  default:
824    - for: \"k in 1,2\"
825      phases: [tick]
826"
827        );
828        let e = synthesize(&wl(&y)).unwrap_err();
829        assert!(e.contains("non-anchored sweep"), "{e}");
830        assert!(
831            e.contains("no implied") || e.contains("Anchor that sweep"),
832            "{e}"
833        );
834    }
835
836    #[test]
837    fn unknown_family_is_an_error_with_provenance() {
838        let y = "
839params: { adapter: testkit }
840phases:
841  tick:
842    key_metrics: { bogus: avg(no_such_family) }
843    ops: { t: { stmt: \"X\" } }
844scenarios:
845  default: [tick]
846";
847        let e = synthesize(&wl(y)).unwrap_err();
848        assert!(e.contains("no_such_family") && e.contains("tick"), "{e}");
849    }
850
851    #[test]
852    fn explicit_report_block_suppresses_synthesis() {
853        let y = "
854params: { adapter: testkit }
855report:
856  g: |
857    text t as \"T\":
858     body
859phases:
860  tick: { ops: { t: { stmt: \"X\" } } }
861scenarios:
862  default: [tick]
863";
864        assert!(synthesize(&wl(y)).expect("ok").is_none());
865    }
866
867    #[test]
868    fn unqualified_designation_is_a_parse_error_with_vocabulary() {
869        let y = "
870params: { adapter: testkit }
871phases:
872  tick:
873    key_metrics: { rows: result_success }
874    ops: { t: { stmt: \"X\" } }
875scenarios:
876  default: [tick]
877";
878        let e = crate::parse::parse_workload(y, &std::collections::HashMap::new())
879            .expect_err("must reject unqualified aggregate");
880        assert!(
881            e.contains("aggregate qualification required") && e.contains("min, max, avg"),
882            "{e}"
883        );
884    }
885}