1use std::collections::BTreeMap;
39
40use crate::model::{KeyAgg, KeyMetric, ScenarioNode, Workload, WorkloadPhase};
41
42const WINDOW: &str = "30d";
46
47fn 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#[derive(Debug, Default)]
87struct View {
88 coords: Vec<String>,
91 phases: Vec<String>,
93 defs: Vec<String>,
97}
98
99#[derive(Debug, Clone, PartialEq)]
101enum Attach {
102 Spine,
103 View(String),
104 Flattened {
108 via: String,
109 },
110}
111
112struct Walk {
113 views: BTreeMap<String, View>,
114 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 self.walk_nodes(children, Some(view_name), None);
179 }
180 None => {
181 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 self.walk_nodes(children, anchor, flattened_via);
197 }
198 }
199 }
200 }
201}
202
203fn 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 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
266fn 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
282fn 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
352fn 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
367fn one_phase(phase: &str) -> String {
369 format!("phase=\"{phase}\"")
370}
371
372fn 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
384fn 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 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
419fn 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
425struct SpineColumn<'a> {
428 name: String,
429 metric: &'a KeyMetric,
430 phases: Vec<&'a str>,
431}
432
433fn 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
469pub 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
480pub fn synthesize_forced(workload: &Workload) -> Result<serde_json::Value, String> {
486 synthesize_forced_for(workload, None)
487}
488
489pub 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 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 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 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 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 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 for (view_name, view) in &views {
634 let by = view.coords.join(",");
635 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 let label = format!(
679 "{view_name} — one row per {by} ({})",
680 phase_names.join(", ")
681 );
682 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
712pub 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 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}