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_session_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    let f = &metric.family;
391    let sel = selector(metric, phase_matcher);
392    // Time-derived designations ride the `_interval_ns` / `_rate`
393    // virtual stats (per-sample active-window bookkeeping) rather
394    // than first/last timestamp arithmetic: a phase shorter than
395    // the durable write cadence leaves ONE sample behind, where
396    // `tlast - tfirst` degenerates to zero but the sample's own
397    // interval is exact.
398    let span =
399        format!("max(sum_over_time(result_success_interval_ns{sel}[{WINDOW}])) by ({by_labels})");
400    match metric.agg {
401        Min => format!("min(min_over_time({f}{sel}[{WINDOW}])) by ({by_labels})"),
402        Max => format!("max(max_over_time({f}{sel}[{WINDOW}])) by ({by_labels})"),
403        Avg => format!("avg(avg_over_time({f}{sel}[{WINDOW}])) by ({by_labels})"),
404        Last => format!("max(last_over_time({f}{sel}[{WINDOW}])) by ({by_labels})"),
405        First => format!("min(first_over_time({f}{sel}[{WINDOW}])) by ({by_labels})"),
406        Median => format!("avg(median_over_time({f}{sel}[{WINDOW}])) by ({by_labels})"),
407        Stddev => format!("avg(stddev_over_time({f}{sel}[{WINDOW}])) by ({by_labels})"),
408        Sum => format!("sum(sum_over_time({f}{sel}[{WINDOW}])) by ({by_labels})"),
409        Count => format!("sum(count_over_time({f}{sel}[{WINDOW}])) by ({by_labels})"),
410        Span => span,
411        Rate => format!("avg(avg_over_time({f}_rate{sel}[{WINDOW}])) by ({by_labels})"),
412        Delta => format!(
413            "max(last_over_time({f}{sel}[{WINDOW}])) by ({by_labels}) - \
414             min(first_over_time({f}{sel}[{WINDOW}])) by ({by_labels})"
415        ),
416    }
417}
418
419/// True when two designations measure the same thing the same way,
420/// whatever their columns are called.
421fn same_measure(a: &KeyMetric, b: &KeyMetric) -> bool {
422    a.agg == b.agg && a.family == b.family && a.matchers == b.matchers && a.samples == b.samples
423}
424
425/// One column of the spine that a phase designated: the designation
426/// and the phases that made it.
427struct SpineColumn<'a> {
428    name: String,
429    metric: &'a KeyMetric,
430    phases: Vec<&'a str>,
431}
432
433/// The spine's designated columns, in the order the phases are given
434/// and each phase's designations are written. Phases that designate
435/// the same measure under the same column name share the column; a
436/// name already taken by another measure, or by the contract, is
437/// given its phase's name in front.
438fn spine_columns<'a>(workload: &'a Workload, spine_phases: &[&'a String]) -> Vec<SpineColumn<'a>> {
439    let contract: Vec<String> = spine_contract().into_iter().map(|km| km.column).collect();
440    let mut columns: Vec<SpineColumn<'a>> = Vec::new();
441    for phase_name in spine_phases {
442        let Some(phase) = workload.phases.get(phase_name.as_str()) else {
443            continue;
444        };
445        for km in &phase.key_metrics {
446            if let Some(shared) = columns
447                .iter_mut()
448                .find(|c| c.name == km.column && same_measure(c.metric, km))
449            {
450                shared.phases.push(phase_name.as_str());
451                continue;
452            }
453            let taken =
454                contract.contains(&km.column) || columns.iter().any(|c| c.name == km.column);
455            columns.push(SpineColumn {
456                name: if taken {
457                    format!("{phase_name}_{}", km.column)
458                } else {
459                    km.column.clone()
460                },
461                metric: km,
462                phases: vec![phase_name.as_str()],
463            });
464        }
465    }
466    columns
467}
468
469/// Synthesize the report mapping for a workload with no explicit
470/// `report:` block. `Ok(None)` when the workload has an explicit
471/// block (synthesis suppressed). Errors are the SRD-109
472/// well-formedness contract.
473pub fn synthesize(workload: &Workload) -> Result<Option<serde_json::Value>, String> {
474    if !workload.report.groups.is_empty() {
475        return Ok(None);
476    }
477    synthesize_forced(workload).map(Some)
478}
479
480/// [`synthesize`] without the explicit-block suppression: the section
481/// synthesized from the structural fixtures IRRESPECTIVE of any
482/// `report:` block. This is what `nmbrs report synth` dumps and what
483/// `--synthesized` renders — the affine mirror is always inspectable,
484/// even (especially) when a hand-tuned block has diverged from it.
485pub fn synthesize_forced(workload: &Workload) -> Result<serde_json::Value, String> {
486    synthesize_forced_for(workload, None)
487}
488
489/// [`synthesize_forced`] scoped to ONE scenario when the caller knows
490/// which ran (a session records it): the walk visits only that
491/// scenario, so views carry only phases reachable in the execution —
492/// no structurally-empty column groups from sibling scenarios.
493/// `None`, or a name the workload doesn't declare, falls back to the
494/// all-scenarios union.
495pub fn synthesize_forced_for(
496    workload: &Workload,
497    scenario: Option<&str>,
498) -> Result<serde_json::Value, String> {
499    let mut walk = Walk {
500        views: BTreeMap::new(),
501        attachments: BTreeMap::new(),
502        errors: Vec::new(),
503    };
504    // Union across every scenario: anchors and attachments merge; a
505    // phase reachable both anchored and un-anchored keeps both
506    // attachments (it renders in both places). Visit order pins the
507    // first-seen phase order inside each view — and with it the
508    // table's column order — so iterate `default` first (the
509    // workload's narrative order) and the rest by name, never the
510    // scenarios HashMap's per-process ordering.
511    let mut scenario_names: Vec<&String> = workload.scenarios.keys().collect();
512    scenario_names.sort_by_key(|n| (*n != "default", (*n).clone()));
513    if let Some(sel) = scenario
514        && let Some(name) = scenario_names.iter().find(|n| n.as_str() == sel).copied()
515    {
516        scenario_names = vec![name];
517    }
518    for name in scenario_names {
519        walk.walk_nodes(&workload.scenarios[name], None, None);
520    }
521    let Walk {
522        views,
523        attachments,
524        mut errors,
525        ..
526    } = walk;
527
528    // Well-formedness: designated families must be emitted; designated
529    // phases must not silently flatten through a non-anchored sweep.
530    for (phase_name, attaches) in &attachments {
531        let Some(phase) = workload.phases.get(phase_name) else {
532            continue;
533        };
534        for km in &phase.key_metrics {
535            if km.agg != KeyAgg::Span && !family_known(phase, &km.family) {
536                errors.push(format!(
537                    "phase '{phase_name}' key_metrics.{}: family '{}' is not \
538                     emitted by this phase (declared metrics, poll timers, \
539                     SRD-91 instruments and their stat suffixes, recall_*)",
540                    km.column, km.family
541                ));
542            }
543        }
544        if !phase.key_metrics.is_empty() {
545            for a in attaches {
546                if let Attach::Flattened { via } = a {
547                    errors.push(format!(
548                        "phase '{phase_name}' designates key metrics but its \
549                         activations multiply through a non-anchored sweep \
550                         ({via}): one table row would silently aggregate many \
551                         activations. Anchor that sweep (`anchor: <view>`) or \
552                         remove the designations. There are no implied \
553                         aggregates."
554                    ));
555                }
556            }
557        }
558    }
559    if !errors.is_empty() {
560        return Err(format!(
561            "report synthesis: {} well-formedness error(s):\n  - {}",
562            errors.len(),
563            errors.join("\n  - ")
564        ));
565    }
566
567    let mut groups = serde_json::Map::new();
568
569    // ── Spine ────────────────────────────────────────────────────
570    let spine_phases: Vec<&String> = attachments
571        .iter()
572        .filter(|(_, a)| a.contains(&Attach::Spine))
573        .map(|(n, _)| n)
574        .collect();
575    let looped_unanchored: Vec<&String> = attachments
576        .iter()
577        .filter(|(_, a)| {
578            a.iter().any(|x| matches!(x, Attach::Flattened { .. }))
579                && !a
580                    .iter()
581                    .any(|x| matches!(x, Attach::View(_)) || *x == Attach::Spine)
582        })
583        .map(|(n, _)| n)
584        .collect();
585    let mut spine = String::new();
586    spine.push_str(
587        "text phases_intro as \"Workload phases — outcomes at a glance\":\n \
588         One row per workload phase, keyed by the `phase` label. Column \
589         headers carry each value's definition (aggregate over the \
590         phase's samples). Each anchored sweep in the scenario renders \
591         as its own view table below, one row per sweep iteration.\n",
592    );
593    if !looped_unanchored.is_empty() {
594        spine.push_str(&format!(
595            "text phases_unanchored as \"Not tabulated\":\n \
596             Looped phases with no anchor and no designations — activations \
597             would aggregate silently, so no rows are synthesized: {}.\n",
598            looped_unanchored
599                .iter()
600                .map(|s| s.as_str())
601                .collect::<Vec<_>>()
602                .join(", ")
603        ));
604    }
605    // Restrict to spine phases explicitly so anchored phases don't
606    // leak in through the label join. NO spine-eligible phases ⇒ no
607    // spine table at all (an empty selector would match everything,
608    // silently re-admitting exactly the phases the notes exclude).
609    if !spine_phases.is_empty() {
610        spine.push_str("table phases:\n  group_by: phase\n");
611        spine.push_str("  label \"phases — one row per workload phase\"\n");
612        let every: Vec<&str> = spine_phases.iter().map(|s| s.as_str()).collect();
613        for km in spine_contract() {
614            let q = query_for(&km, &any_phase(&every), "phase");
615            spine.push_str(&format!("  query: {}: {}\n", km.column, q));
616            spine.push_str(&format!("  header {}: {}\n", km.column, agg_desc(&km)));
617        }
618        // Each phase's own designations: a column is filled in the
619        // rows of the phases that designate it.
620        for column in spine_columns(workload, &spine_phases) {
621            let q = query_for(column.metric, &any_phase(&column.phases), "phase");
622            spine.push_str(&format!("  query: {}: {}\n", column.name, q));
623            spine.push_str(&format!(
624                "  header {}: {}\n",
625                column.name,
626                agg_desc(column.metric)
627            ));
628        }
629    }
630    groups.insert("phases".to_string(), serde_json::Value::String(spine));
631
632    // ── One group per view ──────────────────────────────────────
633    for (view_name, view) in &views {
634        let by = view.coords.join(",");
635        // Each column's header carries its definition — the declared
636        // aggregate and, when several phases contribute, the emitting
637        // phase — so the rendered table explains itself with no
638        // separate legend to cross-reference.
639        let mut table = String::new();
640        let mut seen_cols: Vec<String> = Vec::new();
641        let mut phase_names: Vec<&str> = Vec::new();
642        let contributing = view
643            .phases
644            .iter()
645            .filter(|p| {
646                workload
647                    .phases
648                    .get(p.as_str())
649                    .is_some_and(|ph| !ph.key_metrics.is_empty())
650            })
651            .count();
652        for phase_name in &view.phases {
653            let Some(phase) = workload.phases.get(phase_name) else {
654                continue;
655            };
656            if !phase.key_metrics.is_empty() {
657                phase_names.push(phase_name);
658            }
659            for km in &phase.key_metrics {
660                let col = if seen_cols.contains(&km.column) {
661                    format!("{phase_name}_{}", km.column)
662                } else {
663                    km.column.clone()
664                };
665                seen_cols.push(col.clone());
666                let q = query_for(km, &one_phase(phase_name), &by);
667                table.push_str(&format!("  query: {col}: {q}\n"));
668                let note = if contributing > 1 {
669                    format!("{} @{phase_name}", agg_desc(km))
670                } else {
671                    agg_desc(km)
672                };
673                table.push_str(&format!("  header {col}: {note}\n"));
674            }
675        }
676        // The table's own label carries the row semantics into the
677        // rendered heading and the listing.
678        let label = format!(
679            "{view_name} — one row per {by} ({})",
680            phase_names.join(", ")
681        );
682        // Direct explainer: where this figure's rows COME FROM — the
683        // comprehension definition(s) that generate them — which
684        // labels identify a row, and which phases feed the columns.
685        let defs = view
686            .defs
687            .iter()
688            .map(|d| format!("`for {d}`"))
689            .collect::<Vec<_>>()
690            .join(" and ");
691        let about = format!(
692            "text {view_name}_about as \"{view_name} — one row per {by}\":\n \
693             Rows are the iterations of {defs}; the {by} label(s) \
694             identify each row within the workload. Columns aggregate \
695             each iteration's activations of: {}. Headers carry each \
696             column's definition{}.\n",
697            phase_names.join(", "),
698            if contributing > 1 {
699                " and its @phase provenance"
700            } else {
701                ""
702            }
703        );
704        let body =
705            format!("{about}table {view_name}:\n  group_by: {by}\n  label \"{label}\"\n{table}");
706        groups.insert(format!("view_{view_name}"), serde_json::Value::String(body));
707    }
708
709    Ok(serde_json::Value::Object(groups))
710}
711
712/// Dump the synthesized section as a `report:` YAML block — the
713/// affine round-trip surface (`nmbrs report synth`): copy, paste into
714/// the workload, edit, and synthesis is suppressed in favor of the
715/// hand-tuned version.
716pub fn synthesize_yaml(workload: &Workload) -> Result<String, String> {
717    let value = synthesize_forced(workload)?;
718    let map = value.as_object().expect("synthesize emits a mapping");
719    let mut out = String::from("report:\n");
720    for (group, body) in map {
721        out.push_str(&format!("  {group}: |\n"));
722        for line in body.as_str().unwrap_or_default().lines() {
723            out.push_str(&format!("    {line}\n"));
724        }
725    }
726    Ok(out)
727}
728
729fn regex_escape(s: &str) -> String {
730    let mut out = String::with_capacity(s.len());
731    for c in s.chars() {
732        if "\\.^$|?*+()[]{}".contains(c) {
733            out.push('\\');
734        }
735        out.push(c);
736    }
737    out
738}
739
740#[cfg(test)]
741mod host_tests;
742
743#[cfg(test)]
744mod tests {
745    use super::*;
746
747    fn wl(yaml: &str) -> Workload {
748        crate::parse::parse_workload(yaml, &std::collections::HashMap::new())
749            .expect("workload parses")
750    }
751
752    const BASE: &str = r#"
753params: { adapter: testkit }
754phases:
755  tick:
756    key_metrics:
757      rows: last(result_success)
758      spd: rate(result_success)
759    ops: { t: { stmt: "X" } }
760  plain:
761    ops: { t: { stmt: "Y" } }
762"#;
763
764    #[test]
765    fn synthesizes_spine_and_anchored_view() {
766        let y = format!(
767            "{BASE}
768scenarios:
769  default:
770    - plain
771    - for: \"k in 1,2\"
772      anchor: sweep
773      phases: [tick]
774"
775        );
776        let v = synthesize(&wl(&y))
777            .expect("well-formed")
778            .expect("synthesized");
779        let m = v.as_object().unwrap();
780        assert!(m.contains_key("phases"));
781        let sweep = m.get("view_sweep").unwrap().as_str().unwrap();
782        assert!(
783            sweep.contains("group_by: k"),
784            "anchor coordinate keys the view"
785        );
786        assert!(sweep.contains("last_over_time(result_success{phase=\"tick\"}"));
787        assert!(
788            sweep.contains("query: spd:"),
789            "rate designation synthesized"
790        );
791        let spine = m.get("phases").unwrap().as_str().unwrap();
792        assert!(spine.contains("plain"), "un-looped phase rows the spine");
793        assert!(
794            !spine.contains("|tick") && !spine.contains("\"tick"),
795            "anchored phase stays out of the spine selector"
796        );
797        // Affinity: the synthesized mapping parses through the SAME
798        // grammar entry the YAML path uses.
799        crate::report::parse_report(&v).expect("synthesized section parses");
800    }
801
802    #[test]
803    fn designated_phase_under_unanchored_sweep_is_an_error() {
804        let y = format!(
805            "{BASE}
806scenarios:
807  default:
808    - for: \"k in 1,2\"
809      phases: [tick]
810"
811        );
812        let e = synthesize(&wl(&y)).unwrap_err();
813        assert!(e.contains("non-anchored sweep"), "{e}");
814        assert!(
815            e.contains("no implied") || e.contains("Anchor that sweep"),
816            "{e}"
817        );
818    }
819
820    #[test]
821    fn unknown_family_is_an_error_with_provenance() {
822        let y = "
823params: { adapter: testkit }
824phases:
825  tick:
826    key_metrics: { bogus: avg(no_such_family) }
827    ops: { t: { stmt: \"X\" } }
828scenarios:
829  default: [tick]
830";
831        let e = synthesize(&wl(y)).unwrap_err();
832        assert!(e.contains("no_such_family") && e.contains("tick"), "{e}");
833    }
834
835    #[test]
836    fn explicit_report_block_suppresses_synthesis() {
837        let y = "
838params: { adapter: testkit }
839report:
840  g: |
841    text t as \"T\":
842     body
843phases:
844  tick: { ops: { t: { stmt: \"X\" } } }
845scenarios:
846  default: [tick]
847";
848        assert!(synthesize(&wl(y)).expect("ok").is_none());
849    }
850
851    #[test]
852    fn unqualified_designation_is_a_parse_error_with_vocabulary() {
853        let y = "
854params: { adapter: testkit }
855phases:
856  tick:
857    key_metrics: { rows: result_success }
858    ops: { t: { stmt: \"X\" } }
859scenarios:
860  default: [tick]
861";
862        let e = crate::parse::parse_workload(y, &std::collections::HashMap::new())
863            .expect_err("must reject unqualified aggregate");
864        assert!(
865            e.contains("aggregate qualification required") && e.contains("min, max, avg"),
866            "{e}"
867        );
868    }
869}