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_host_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 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 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
435fn 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
441struct SpineColumn<'a> {
444 name: String,
445 metric: &'a KeyMetric,
446 phases: Vec<&'a str>,
447}
448
449fn 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
485pub 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
496pub fn synthesize_forced(workload: &Workload) -> Result<serde_json::Value, String> {
502 synthesize_forced_for(workload, None)
503}
504
505pub 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 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 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 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 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 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 for (view_name, view) in &views {
650 let by = view.coords.join(",");
651 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 let label = format!(
695 "{view_name} — one row per {by} ({})",
696 phase_names.join(", ")
697 );
698 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
728pub 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 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}