Skip to main content

nmbrs_workload/
construction.rs

1// Copyright 2024-2026 Jonathan Shook
2// SPDX-License-Identifier: Apache-2.0
3
4//! Enumerable workload-construction nodes.
5//!
6//! Every node kind of the workload grammar (workload root,
7//! phase, op, poll, scenario node, …) implements
8//! [`EnumerableNode`]: it names itself with a single
9//! discriminant, enumerates its valid sub-elements WITH their
10//! valid forms, and VALIDATES a runtime AST (partial or
11//! complete) directly. Child node kinds are held as DIRECT
12//! `&'static dyn EnumerableNode` references inside [`Form`] — no
13//! side mapping from names to nodes exists, so a dangling
14//! reference is unrepresentable: the reference graph is checked
15//! by the compiler, the same single-discriminant discipline the
16//! wrapper registry uses at the execution-context layer.
17//!
18//! These tables are the single declaration point for each
19//! element (name + forms + doc together). The flat name lists in
20//! [`crate::vocab`] are PROJECTIONS of these tables (the parser
21//! consumes those projections for its rejection checks), and the
22//! phase table is pinned against the
23//! [`crate::model::WorkloadPhase`] struct itself by a serde
24//! field probe in this module's tests.
25//!
26//! ENFORCEMENT: `parse_workload` runs [`validate_workload`] on
27//! every extends-merged document (the construction gate —
28//! docs/guide/construction_model.md). COHERENCE AXIOM: a
29//! construction that cannot be represented in the synthesizer
30//! fuzz is not yet a valid construction; the fuzzer's deferral
31//! list is the debt register against this axiom.
32//!
33//! Context sensitivity: [`EnumerableNode::elements`] receives
34//! the partial AST node (when the caller has one) and may narrow
35//! — e.g. a phase carrying `poll:` pins `concurrency` to 1, a
36//! phase with inline `ops:` loses the `tags:` selector (one
37//! source of ops, SRD-108 Part A), and an op with `abstract:`
38//! drops the statement payload.
39
40use serde_json::Value;
41
42/// A valid value form for one element. Nested node kinds are
43/// direct references — the grammar graph carries itself.
44#[derive(Clone, Copy)]
45pub enum Form {
46    /// Boolean: a YAML bool, or the string `"true"` / `"false"`
47    /// ([`crate::boolean`]).
48    Bool,
49    /// Unsigned integer (numeric strings accepted where the
50    /// element documents it).
51    U64,
52    /// Float.
53    F64,
54    /// Plain string.
55    Str,
56    /// List of strings (globs where documented).
57    StrList,
58    /// Duration: `"2.5h"`, bare seconds, or a `{param}` ref.
59    Duration,
60    /// A `{param}` / iter-var reference accepted alongside the
61    /// literal forms listed beside it.
62    ParamRef,
63    /// A polydat bindings SOURCE block (multi-line grammar).
64    GkSource,
65    /// A single polydat expression (predicates, metric values).
66    GkExpr,
67    /// A capture / result path expression (`/0/field`,
68    /// `rows[*].col` — SRD-70).
69    PathExpr,
70    /// A metric selector (`"family, label=value"`).
71    MetricSelector,
72    /// One of a closed vocabulary of literal values.
73    Vocab(&'static [&'static str]),
74    /// A nested node of the referenced kind.
75    Node(&'static dyn EnumerableNode),
76    /// A map of AUTHOR-CHOSEN names, each value a node of the
77    /// referenced kind (e.g. `phases:` → phase nodes).
78    NamedMap(&'static dyn EnumerableNode),
79    /// A list whose entries are nodes of the referenced kind.
80    ListOf(&'static dyn EnumerableNode),
81    /// A map of author-chosen names whose VALUES all take the
82    /// given form (e.g. `capture:` name → PathExpr).
83    MapOf(&'static Form),
84    /// A list whose entries all take the given form.
85    ListOfForm(&'static Form),
86    /// An open map (author-chosen keys, unmodeled values).
87    FreeMap,
88    /// An open scalar (adapter-defined or free text).
89    FreeScalar,
90}
91
92impl std::fmt::Debug for Form {
93    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
94        match self {
95            Form::Bool => write!(f, "Bool"),
96            Form::U64 => write!(f, "U64"),
97            Form::F64 => write!(f, "F64"),
98            Form::Str => write!(f, "Str"),
99            Form::StrList => write!(f, "StrList"),
100            Form::Duration => write!(f, "Duration"),
101            Form::ParamRef => write!(f, "ParamRef"),
102            Form::GkSource => write!(f, "GkSource"),
103            Form::GkExpr => write!(f, "GkExpr"),
104            Form::PathExpr => write!(f, "PathExpr"),
105            Form::MetricSelector => write!(f, "MetricSelector"),
106            Form::Vocab(v) => write!(f, "Vocab({v:?})"),
107            Form::Node(n) => write!(f, "Node({})", n.kind()),
108            Form::NamedMap(n) => write!(f, "NamedMap({})", n.kind()),
109            Form::ListOf(n) => write!(f, "ListOf({})", n.kind()),
110            Form::MapOf(inner) => write!(f, "MapOf({inner:?})"),
111            Form::ListOfForm(inner) => write!(f, "ListOfForm({inner:?})"),
112            Form::FreeMap => write!(f, "FreeMap"),
113            Form::FreeScalar => write!(f, "FreeScalar"),
114        }
115    }
116}
117
118impl PartialEq for Form {
119    fn eq(&self, other: &Self) -> bool {
120        use Form::*;
121        match (self, other) {
122            (Vocab(a), Vocab(b)) => a == b,
123            (Node(a), Node(b)) | (NamedMap(a), NamedMap(b)) | (ListOf(a), ListOf(b)) => {
124                a.kind() == b.kind()
125            }
126            (MapOf(a), MapOf(b)) | (ListOfForm(a), ListOfForm(b)) => a == b,
127            _ => std::mem::discriminant(self) == std::mem::discriminant(other),
128        }
129    }
130}
131
132/// One valid sub-element of a node: the single declaration point
133/// for its name, accepted forms, and documentation.
134#[derive(Debug, Clone, Copy)]
135pub struct ElementSpec {
136    pub name: &'static str,
137    pub forms: &'static [Form],
138    pub required: bool,
139    pub doc: &'static str,
140}
141
142const fn el(name: &'static str, forms: &'static [Form], doc: &'static str) -> ElementSpec {
143    ElementSpec {
144        name,
145        forms,
146        required: false,
147        doc,
148    }
149}
150
151/// Validation strictness: a PARTIAL model skips required-element
152/// checks (it is still being authored); a COMPLETE model does
153/// not.
154#[derive(Debug, Clone, Copy, PartialEq, Eq)]
155pub enum Mode {
156    Partial,
157    Complete,
158}
159
160/// One validation finding, with the AST path it anchors to.
161#[derive(Debug, Clone)]
162pub struct Violation {
163    pub path: String,
164    pub message: String,
165}
166
167/// An enumerable node kind of the workload construction grammar.
168pub trait EnumerableNode: Sync {
169    /// Canonical kind discriminant (`"workload"`, `"phase"`, …).
170    fn kind(&self) -> &'static str;
171    /// One-line description of the node kind.
172    fn doc(&self) -> &'static str;
173    /// Valid sub-elements. `partial` is the (possibly incomplete)
174    /// AST value AT this node when the caller has one; nodes may
175    /// narrow their element set from it. `None` yields the
176    /// unconditioned surface.
177    fn elements(&self, partial: Option<&Value>) -> Vec<ElementSpec>;
178    /// When this node also accepts keys OUTSIDE the enumerated
179    /// set, the reason (open vocabularies are declared, never
180    /// implied). `None` = closed surface.
181    fn open_surface(&self) -> Option<&'static str> {
182        None
183    }
184
185    /// Validate `value` as an instance of this node kind:
186    /// unknown keys on closed surfaces, form conformance per
187    /// element, and (in [`Mode::Complete`]) required elements —
188    /// recursing through nested node references. This is the
189    /// runtime type check of the construction grammar.
190    fn validate(&self, value: &Value, mode: Mode) -> Vec<Violation>
191    where
192        Self: Sized,
193    {
194        let mut out = Vec::new();
195        validate_node(self, value, mode, self.kind(), &mut out);
196        out
197    }
198}
199
200// ─── Node statics (single discriminants, referenced directly) ────
201
202pub static WORKLOAD: WorkloadNode = WorkloadNode;
203pub static PHASE: PhaseNode = PhaseNode;
204pub static OP: OpNode = OpNode;
205pub static POLL: PollNode = PollNode;
206pub static SCENARIO: ScenarioNode = ScenarioNode;
207pub static STOP_WHEN: StopWhenNode = StopWhenNode;
208pub static METRIC: MetricNode = MetricNode;
209pub static ABSTRACT: AbstractNode = AbstractNode;
210pub static EVALUATIONS: EvaluationsNode = EvaluationsNode;
211pub static RELEVANCY: RelevancyNode = RelevancyNode;
212pub static BINDING_CLASSES: BindingClassesNode = BindingClassesNode;
213pub static MEMO: MemoNode = MemoNode;
214pub static OP_POLL: OpPollNode = OpPollNode;
215pub static TRIES: TriesNode = TriesNode;
216pub static BACKOFF: BackoffNode = BackoffNode;
217pub static THROTTLE: ThrottleNode = ThrottleNode;
218pub static DELAY: DelayNode = DelayNode;
219pub static CONTINUE_IF: ContinueIfNode = ContinueIfNode;
220pub static CHECKPOINT: CheckpointNode = CheckpointNode;
221pub static OPTIMIZE: OptimizeNode = OptimizeNode;
222
223/// Every registered node kind — an enumeration surface for
224/// tooling (`describe`, docs). Resolution never goes through
225/// this list: forms hold their child nodes directly.
226pub static ALL_NODES: &[&dyn EnumerableNode] = &[
227    &WORKLOAD,
228    &PHASE,
229    &OP,
230    &POLL,
231    &SCENARIO,
232    &STOP_WHEN,
233    &METRIC,
234    &ABSTRACT,
235    &EVALUATIONS,
236    &RELEVANCY,
237    &BINDING_CLASSES,
238    &MEMO,
239    &OP_POLL,
240    &TRIES,
241    &BACKOFF,
242    &THROTTLE,
243    &DELAY,
244    &CONTINUE_IF,
245    &CHECKPOINT,
246    &OPTIMIZE,
247];
248
249/// Kind lookup over [`ALL_NODES`] — a convenience for external
250/// tooling only.
251pub fn node_by_kind(kind: &str) -> Option<&'static dyn EnumerableNode> {
252    ALL_NODES.iter().copied().find(|n| n.kind() == kind)
253}
254
255/// The workload root node.
256pub fn root() -> &'static dyn EnumerableNode {
257    &WORKLOAD
258}
259
260// ─── Spec tables (single declaration points) ─────────────────────
261
262const STOP_EFFECTS: &[&str] = &["stop", "fail", "abort"];
263
264pub static PHASE_ELEMENTS: &[ElementSpec] = &[
265    el(
266        "cycles",
267        &[Form::U64, Form::ParamRef, Form::Str],
268        "stanza count; string forms: {param}, extent sigils (==ops:N, ===auto) — runtime-parsed",
269    ),
270    el(
271        "concurrency",
272        &[Form::U64, Form::ParamRef, Form::Str],
273        "async fibers ({param} or bare wire name resolves in scope)",
274    ),
275    el(
276        "rate",
277        &[Form::F64, Form::ParamRef],
278        "ops/sec; {param}/iter-var resolves at the phase gather",
279    ),
280    el(
281        "daemon",
282        &[Form::Bool],
283        "runs concurrently with foreground siblings; stopped when they complete",
284    ),
285    el("adapter", &[Form::Str], "adapter override for this phase"),
286    el(
287        "errors",
288        &[Form::Str],
289        "error-routing spec (e.g. \"count,retry\", \".*:counter\")",
290    ),
291    el(
292        "tries",
293        &[Form::U64, Form::Node(&TRIES)],
294        "total attempts; map form adds backoff (carries tries_backoff)",
295    ),
296    el(
297        "interval",
298        &[Form::Duration],
299        "declarative-only today: phase re-run pacing",
300    ),
301    el("repeat", &[Form::U64], "bound for interval"),
302    el(
303        "error_rate_max",
304        &[Form::F64],
305        "opt-in error-rate circuit breaker",
306    ),
307    el(
308        "timeout",
309        &[Form::Duration, Form::ParamRef],
310        "governance bound; expiry = Interrupted+Failed (timeout)",
311    ),
312    el(
313        "stop_when",
314        &[Form::ListOf(&STOP_WHEN)],
315        "SRD-83 stop conditions",
316    ),
317    el(
318        "throttle",
319        &[Form::Bool, Form::Node(&THROTTLE)],
320        "adaptive backpressure governor: windowed attempt-failure fraction walks a dynamic control (true = defaults)",
321    ),
322    el(
323        "tags",
324        &[Form::Str],
325        "tag FILTER selecting ops from blocks (exclusive with inline ops)",
326    ),
327    el(
328        "ops",
329        &[Form::NamedMap(&OP), Form::ListOf(&OP)],
330        "inline op templates (exclusive with tags selector)",
331    ),
332    el("for_each", &[Form::Str], "phase sweep: \"var in expr\""),
333    el(
334        "continue_if",
335        &[Form::GkExpr, Form::Node(&CONTINUE_IF)],
336        "pre-entry gate bounding a for_each sweep",
337    ),
338    el(
339        "loop_scope",
340        &[Form::Vocab(&["clean", "inherit"])],
341        "loop-context seeding for for_each",
342    ),
343    el(
344        "iter_scope",
345        &[Form::Vocab(&["clean", "inherit"])],
346        "iteration seeding for for_each",
347    ),
348    el(
349        "checkpoint",
350        &[
351            Form::Vocab(&["idempotent", "none"]),
352            Form::Node(&CHECKPOINT),
353        ],
354        "skip-on-resume eligibility (SRD-44/106)",
355    ),
356    el(
357        "status_metrics",
358        &[Form::StrList],
359        "metric-name globs surfaced on the status line",
360    ),
361    el(
362        "bindings",
363        &[Form::GkSource, Form::FreeMap],
364        "phase-scope polydat bindings (map = legacy form)",
365    ),
366    el(
367        "metrics",
368        &[
369            Form::NamedMap(&METRIC),
370            Form::GkExpr,
371            Form::ListOfForm(&Form::GkExpr),
372        ],
373        "completion-time phase metrics (SRD-40b sugars: bare expr / list)",
374    ),
375    el(
376        "dimensions",
377        &[Form::FreeMap],
378        "label declarations owned by this tier",
379    ),
380    el(
381        "poll",
382        &[Form::Node(&POLL)],
383        "SRD-75 phase-poll loop (forbids concurrency > 1)",
384    ),
385    el(
386        "optimize",
387        &[Form::GkExpr, Form::Node(&OPTIMIZE)],
388        "SRD-86 optimizer dispatch (string = objective sugar)",
389    ),
390    el(
391        "key_metrics",
392        &[Form::FreeMap],
393        "SRD-113 key-metric designations: column -> agg(family), aggregate mandatory",
394    ),
395];
396
397pub static OP_MODEL_ELEMENTS: &[ElementSpec] = &[
398    el("name", &[Form::Str], "implicit — set by the op's map key"),
399    el("description", &[Form::Str], "op description"),
400    el(
401        "bindings",
402        &[Form::GkSource, Form::FreeMap],
403        "op-scope polydat bindings (map = legacy form)",
404    ),
405    el(
406        "params",
407        &[Form::FreeMap],
408        "activity-level params excised from adapter fields",
409    ),
410    el("tags", &[Form::FreeMap], "tags for filtering and metadata"),
411    el(
412        "if",
413        &[Form::GkExpr],
414        "per-cycle condition; falsy skips the op",
415    ),
416    el(
417        "delay",
418        &[Form::Str, Form::Node(&DELAY)],
419        "pre/post-op delay wire name(s)",
420    ),
421    el(
422        "evaluations",
423        &[Form::Node(&EVALUATIONS)],
424        "closed-vocab validation/scoring wrapper",
425    ),
426    el(
427        "capture",
428        &[Form::MapOf(&Form::PathExpr)],
429        "wire ← path-expression extraction map",
430    ),
431    el(
432        "metrics",
433        &[
434            Form::NamedMap(&METRIC),
435            Form::GkExpr,
436            Form::ListOfForm(&Form::GkExpr),
437        ],
438        "per-cycle synthetic metrics (SRD-40b sugars: bare expr / list)",
439    ),
440    el(
441        "result",
442        &[Form::FreeMap, Form::GkSource],
443        "SRD-66 result bindings (named paths / source)",
444    ),
445    el(
446        "traverse",
447        &[Form::FreeMap],
448        "customizes the result traversal layer",
449    ),
450    el(
451        "measure",
452        &[Form::FreeMap, Form::Str, Form::ParamRef],
453        "measurement config (string = template form)",
454    ),
455    el(
456        "abstract",
457        &[Form::Node(&ABSTRACT)],
458        "SRD-108 typed interface slot (blueprint side)",
459    ),
460    el(
461        "uses",
462        &[Form::Str],
463        "instantiate the named `op_templates:` definition",
464    ),
465    el(
466        "daemon",
467        &[Form::Bool, Form::U64],
468        "op-level daemon fiber (N = max concurrent)",
469    ),
470    el(
471        "daemon_cancel_grace_ms",
472        &[Form::U64],
473        "daemon cancel grace",
474    ),
475    el("while", &[Form::GkExpr], "op-level loop guard"),
476    el(
477        "rate",
478        &[Form::F64, Form::Str],
479        "op-level pacing (number or rate string like \"5/s\")",
480    ),
481];
482
483/// Activity-level op keys excised from adapter fields by the
484/// model layer (the parser's excision list is this table's name
485/// projection — single source).
486pub static OP_ACTIVITY_ELEMENTS: &[ElementSpec] = &[
487    el("ratio", &[Form::U64], "op dispatch ratio within the stanza"),
488    el("adapter", &[Form::Str], "adapter override for this op"),
489    el(
490        "space",
491        &[Form::Str, Form::ParamRef],
492        "adapter space selector",
493    ),
494    el("instrument", &[Form::Bool], "per-op instrumentation toggle"),
495    el("start-timers", &[Form::StrList], "timer starts"),
496    el("stop-timers", &[Form::StrList], "timer stops"),
497    el(
498        "verify",
499        &[
500            Form::ListOfForm(&Form::FreeMap),
501            Form::FreeMap,
502            Form::GkExpr,
503        ],
504        "response verification clauses (string = predicate expression)",
505    ),
506    el(
507        "relevancy",
508        &[Form::Node(&RELEVANCY)],
509        "legacy top-level shorthand for evaluations.relevancy",
510    ),
511    el("strict", &[Form::Bool], "strict verification"),
512    el(
513        "retry_advisory",
514        &[Form::Bool],
515        "per-op retry advisory (default true; false opts out)",
516    ),
517    el(
518        "poll",
519        &[Form::Node(&OP_POLL)],
520        "op-level poll loop (loops ONLY this op)",
521    ),
522    el("poll_interval_ms", &[Form::U64], "legacy op-poll interval"),
523    el("timeout_ms", &[Form::U64], "per-op timeout"),
524    el(
525        "poll_metric_name",
526        &[Form::Str],
527        "legacy op-poll metric name",
528    ),
529    el("emit", &[Form::Str], "emission override"),
530    el(
531        "batch",
532        &[Form::U64, Form::ParamRef, Form::Str],
533        "batch row cap: literal, {param}, or bare wire name",
534    ),
535    el(
536        "max_batch_size",
537        &[Form::U64, Form::GkExpr],
538        "batch byte budget (literal or GK call)",
539    ),
540    el(
541        "batchtype",
542        &[Form::Vocab(&["logged", "unlogged", "counter"])],
543        "CQL batch type",
544    ),
545    el(
546        "memo",
547        &[Form::Node(&MEMO), Form::Str],
548        "operator-facing before/after notes",
549    ),
550    el(
551        "gutter",
552        &[Form::FreeMap, Form::Str],
553        "status-gutter template (runtime-resolved)",
554    ),
555    el(
556        "readout",
557        &[Form::Vocab(&["visible", "hidden"])],
558        "SRD-63 op-level status visibility",
559    ),
560    el("errors", &[Form::Str], "per-op error-routing override"),
561    el(
562        "tries",
563        &[Form::U64, Form::Node(&TRIES)],
564        "per-op total-attempts sigil",
565    ),
566];
567
568/// The op payload keys. `op:` is the payload itself — a map of op
569/// fields, or a scalar as sugar for `op: {stmt: <scalar>}`. `stmt:`
570/// is the statement field written flat beside the op's other keys.
571pub static OP_STMT_ELEMENTS: &[ElementSpec] = &[
572    el("stmt", &[Form::FreeScalar], "statement payload field"),
573    el(
574        "op",
575        &[Form::FreeMap, Form::FreeScalar],
576        "op payload (map of op fields; scalar = statement sugar)",
577    ),
578];
579
580pub static POLL_ELEMENTS: &[ElementSpec] = &[
581    ElementSpec {
582        name: "until",
583        forms: &[Form::GkExpr],
584        required: true,
585        doc: "predicate over captures; re-evaluated per iteration",
586    },
587    el(
588        "interval_ms",
589        &[Form::U64, Form::ParamRef],
590        "sleep between iterations (default 1000)",
591    ),
592    el(
593        "timeout_ms",
594        &[Form::U64, Form::ParamRef],
595        "wall-clock cap (default 300000)",
596    ),
597    el(
598        "max_error_retries",
599        &[Form::U64, Form::ParamRef],
600        "tolerated consecutive retryable errors",
601    ),
602    el(
603        "metric_name",
604        &[Form::Str],
605        "gauge written on successful loop exit (unit from suffix)",
606    ),
607    el(
608        "on_timeout",
609        &[Form::Vocab(&["error", "abort"])],
610        "deadline disposition",
611    ),
612    el(
613        "require",
614        &[Form::MetricSelector, Form::StrList],
615        "strict-gate selectors that must resolve",
616    ),
617];
618
619pub static SCENARIO_NODE_ELEMENTS: &[ElementSpec] = &[
620    el(
621        "for_each",
622        &[Form::Str, Form::StrList],
623        "iteration: \"var in expr\" (list = union of sub-spaces)",
624    ),
625    el(
626        "for",
627        &[Form::Str, Form::StrList],
628        "alias of for_each (list = union of sub-spaces)",
629    ),
630    el(
631        "anchor",
632        &[Form::Str],
633        "SRD-113 view anchor: one synthesized table row per iteration",
634    ),
635    el("scenario", &[Form::Str], "include another scenario by name"),
636    el(
637        "scenarios",
638        &[Form::Str, Form::ListOf(&SCENARIO)],
639        "scenario include(s) — plural takes a heterogeneous list",
640    ),
641    el(
642        "for_combinations",
643        &[Form::FreeMap],
644        "cross-product map form: var → expr",
645    ),
646    el(
647        "do_while",
648        &[Form::GkExpr],
649        "run children while true (test after)",
650    ),
651    el(
652        "do_until",
653        &[Form::GkExpr],
654        "run children until true (test after)",
655    ),
656    el(
657        "bindings",
658        &[Form::GkSource, Form::FreeMap],
659        "scenario-node bindings",
660    ),
661    el("set", &[Form::FreeMap], "param shadows over the child tree"),
662    el(
663        "phases",
664        &[Form::ListOf(&SCENARIO)],
665        "child nodes under a structural key",
666    ),
667    el(
668        "counter",
669        &[Form::Str],
670        "loop counter wire for do_while / do_until",
671    ),
672];
673
674pub static STOP_WHEN_ELEMENTS: &[ElementSpec] = &[
675    ElementSpec {
676        name: "when",
677        forms: &[Form::GkExpr, Form::ParamRef],
678        required: true,
679        doc: "predicate over runtime-state wires; {param} interpolates",
680    },
681    el(
682        "effect",
683        &[Form::Vocab(STOP_EFFECTS)],
684        "disposition on fire (default fail)",
685    ),
686    el(
687        "each",
688        &[Form::StrList, Form::Str],
689        "detection scope selector(s)",
690    ),
691    el("trigger", &[Form::Str], "firing trigger"),
692    el("pulse", &[Form::FreeMap, Form::Str], "firing axis"),
693    el(
694        "at",
695        &[Form::Str],
696        "ACTION target scope — where the effect lands",
697    ),
698];
699
700pub static METRIC_ELEMENTS: &[ElementSpec] = &[
701    ElementSpec {
702        name: "value",
703        forms: &[Form::GkExpr],
704        required: true,
705        doc: "polydat expression over in-scope wires",
706    },
707    el(
708        "family",
709        &[Form::Str],
710        "family override (default: the metric's map key)",
711    ),
712    el(
713        "kind",
714        &[Form::Vocab(&["gauge", "counter", "histogram"])],
715        "instrument kind",
716    ),
717    el("unit", &[Form::Str], "unit hint"),
718    el("format", &[Form::Str], "render format hint"),
719    el(
720        "cell",
721        &[Form::FreeMap],
722        "dimension placement: label → wire (SRD coordinate cells)",
723    ),
724];
725
726pub static ABSTRACT_ELEMENTS: &[ElementSpec] = &[
727    el(
728        "needs",
729        &[Form::MapOf(&Form::FreeScalar)],
730        "wires the blueprint GUARANTEES: name → port-type keyword",
731    ),
732    el(
733        "yields",
734        &[Form::MapOf(&Form::FreeScalar)],
735        "wires the implementation must CAPTURE: name → port-type keyword",
736    ),
737    el(
738        "results",
739        &[Form::MapOf(&Form::FreeScalar)],
740        "wires delivered via result: projections: name → port-type keyword",
741    ),
742];
743
744pub static EVALUATIONS_ELEMENTS: &[ElementSpec] = &[
745    el(
746        "relevancy",
747        &[Form::Node(&RELEVANCY)],
748        "recall/ndcg scoring against ground truth",
749    ),
750    el("verify", &[Form::FreeMap], "field-equality verification"),
751];
752
753pub static RELEVANCY_ELEMENTS: &[ElementSpec] = &[
754    ElementSpec {
755        name: "actual",
756        forms: &[Form::Str],
757        required: true,
758        doc: "wire carrying retrieved values (bare wire name)",
759    },
760    ElementSpec {
761        name: "expected",
762        forms: &[Form::Str],
763        required: true,
764        doc: "wire carrying ground truth (bare wire name)",
765    },
766    el(
767        "k",
768        &[Form::U64, Form::Str],
769        "evaluation depth (literal or bare wire name)",
770    ),
771    el(
772        "r",
773        &[Form::U64, Form::Str],
774        "retrieved window (literal or bare wire name)",
775    ),
776    el(
777        "functions",
778        &[Form::ListOfForm(&Form::Vocab(&["recall", "ndcg"]))],
779        "scoring functions",
780    ),
781];
782
783pub static MEMO_ELEMENTS: &[ElementSpec] = &[
784    el(
785        "before",
786        &[Form::Str, Form::ParamRef],
787        "note before dispatch ({wire} interpolation)",
788    ),
789    el(
790        "after",
791        &[Form::Str, Form::ParamRef],
792        "note after completion ({wire} interpolation)",
793    ),
794];
795
796pub static OP_POLL_ELEMENTS: &[ElementSpec] = &[
797    el(
798        "mode",
799        &[Form::Vocab(&["await_empty"])],
800        "loop-until mode over the result body",
801    ),
802    el("until", &[Form::GkExpr], "predicate alternative to mode"),
803    el("interval_ms", &[Form::U64], "sleep between iterations"),
804    el("timeout_ms", &[Form::U64], "wall-clock cap"),
805    el(
806        "max_error_retries",
807        &[Form::U64],
808        "tolerated consecutive retryable errors",
809    ),
810    el("metric_name", &[Form::Str], "gauge on successful exit"),
811    el(
812        "memo",
813        &[Form::Str, Form::ParamRef, Form::Node(&MEMO)],
814        "per-iteration operator note ({wire} interpolation)",
815    ),
816    el(
817        "progress",
818        &[Form::Str, Form::ParamRef],
819        "derived-progress template overriding the cycle bar",
820    ),
821];
822
823pub static TRIES_ELEMENTS: &[ElementSpec] = &[
824    el("count", &[Form::U64], "total attempts"),
825    el(
826        "backoff",
827        &[Form::Node(&BACKOFF)],
828        "retry backoff overrides",
829    ),
830];
831
832pub static THROTTLE_ELEMENTS: &[ElementSpec] = &[
833    el(
834        "high",
835        &[Form::F64],
836        "windowed attempt-failure fraction that triggers back-off (default 0.05)",
837    ),
838    el("low", &[Form::F64], "recovery threshold (default high/5)"),
839    el(
840        "control",
841        &[Form::Vocab(&["concurrency", "rate"])],
842        "the dynamic control the governor walks",
843    ),
844    el(
845        "start",
846        &[Form::F64],
847        "initial offered value (slow-start seed; default = floor — declare higher only for known-robust targets)",
848    ),
849    el("floor", &[Form::F64], "never throttle below this value"),
850    el(
851        "window",
852        &[Form::Duration],
853        "evaluation window (default 2s)",
854    ),
855];
856
857pub static BACKOFF_ELEMENTS: &[ElementSpec] = &[
858    el("ratio", &[Form::F64], "growth ratio"),
859    el("min", &[Form::Duration], "floor"),
860    el("max", &[Form::Duration], "ceiling"),
861];
862
863pub static DELAY_ELEMENTS: &[ElementSpec] = &[
864    el("before", &[Form::Str], "pre-op delay wire name"),
865    el("after", &[Form::Str], "post-op delay wire name"),
866];
867
868pub static CONTINUE_IF_ELEMENTS: &[ElementSpec] = &[
869    ElementSpec {
870        name: "when",
871        forms: &[Form::GkExpr],
872        required: true,
873        doc: "pre-entry predicate (bare wires via for_iteration scope)",
874    },
875    el(
876        "each",
877        &[Form::StrList, Form::Str],
878        "evaluation scope selector(s)",
879    ),
880];
881
882pub static CHECKPOINT_ELEMENTS: &[ElementSpec] = &[
883    el("idempotent", &[Form::Bool], "prereq-class skip eligibility"),
884    el("hashed", &[Form::Bool], "provenance hashing toggle"),
885    el(
886        "verify",
887        &[Form::FreeMap],
888        "verify op-template body run before Skip",
889    ),
890];
891
892pub static OPTIMIZE_ELEMENTS: &[ElementSpec] = &[
893    el("method", &[Form::Str], "optimizer method (default sweep)"),
894    ElementSpec {
895        name: "objective",
896        forms: &[Form::GkExpr],
897        required: true,
898        doc: "objective wire expression (string sugar = whole block)",
899    },
900    el("servo", &[Form::StrList], "servo axis wires"),
901    el("max_evals", &[Form::U64], "evaluation budget"),
902    el("seed", &[Form::U64], "search seed"),
903];
904
905pub static WORKLOAD_ELEMENTS: &[ElementSpec] = &[
906    el(
907        "description",
908        &[Form::Str],
909        "workload description (required for curated catalog entries)",
910    ),
911    el(
912        "extends",
913        &[Form::Str],
914        "parent document (path or catalog name)",
915    ),
916    el(
917        "implements",
918        &[Form::Str],
919        "blueprint this implementation binds (SRD-108)",
920    ),
921    el(
922        "stick_session",
923        &[Form::Bool],
924        "SRD-106 re-attach-by-default",
925    ),
926    el("params", &[Form::FreeMap], "declared params with defaults"),
927    el(
928        "bindings",
929        &[Form::GkSource, Form::FreeMap],
930        "workload-root polydat bindings (map = legacy name→expr form)",
931    ),
932    el("phases", &[Form::NamedMap(&PHASE)], "phase definitions"),
933    el("scenarios", &[Form::NamedMap(&SCENARIO)], "scenario trees"),
934    el(
935        "ops",
936        &[Form::NamedMap(&OP), Form::ListOf(&OP)],
937        "top-level ops (legacy inline shape)",
938    ),
939    el(
940        "op",
941        &[Form::FreeScalar, Form::FreeMap],
942        "inline single-op shorthand",
943    ),
944    el(
945        "blocks",
946        &[Form::FreeMap],
947        "named op blocks for tag selection",
948    ),
949    el(
950        "op_templates",
951        &[Form::NamedMap(&OP)],
952        "reusable op definitions an op instantiates with `uses:`",
953    ),
954    el("tags", &[Form::FreeMap], "document tags"),
955    el(
956        "stop_when",
957        &[Form::ListOf(&STOP_WHEN)],
958        "workload-shell stop conditions",
959    ),
960    el(
961        "status_metrics",
962        &[Form::StrList],
963        "doc-root status-line default",
964    ),
965    el(
966        "report",
967        &[Form::FreeMap],
968        "SRD-46 report block (directive grammar: crate::report::vocab)",
969    ),
970    el("readouts", &[Form::FreeMap], "SRD-63 readout slot bindings"),
971    el(
972        "wrappers",
973        &[Form::FreeMap],
974        "SRD-32a wrapper-order override",
975    ),
976];
977
978/// GK binding declaration classes usable from workload
979/// `bindings:` blocks (the grammar itself is polydat's; the bare
980/// `name := expr` derived form has no keyword).
981pub static BINDING_CLASS_ELEMENTS: &[ElementSpec] = &[
982    el("const", &[Form::GkSource], "construction-time constant"),
983    el(
984        "cursor",
985        &[Form::GkSource],
986        "extent-driving cursor declaration",
987    ),
988    el(
989        "volatile",
990        &[Form::GkSource],
991        "re-evaluated per pull; acknowledges non-determinism",
992    ),
993    el(
994        "shared",
995        &[Form::GkSource],
996        "phase-scope shared cell (write-through across ops)",
997    ),
998    el(
999        "extern",
1000        &[Form::GkSource],
1001        "externally-written slot (captures, injected wires)",
1002    ),
1003    el(
1004        "input",
1005        &[Form::GkSource],
1006        "kernel coordinate input (kernel-plane; not workload-authored)",
1007    ),
1008];
1009
1010// ─── Node implementations ─────────────────────────────────────────
1011
1012macro_rules! simple_node {
1013    ($ty:ident, $kind:literal, $doc:literal, $table:ident) => {
1014        pub struct $ty;
1015        impl EnumerableNode for $ty {
1016            fn kind(&self) -> &'static str {
1017                $kind
1018            }
1019            fn doc(&self) -> &'static str {
1020                $doc
1021            }
1022            fn elements(&self, _partial: Option<&Value>) -> Vec<ElementSpec> {
1023                $table.to_vec()
1024            }
1025        }
1026    };
1027}
1028
1029simple_node!(
1030    WorkloadNode,
1031    "workload",
1032    "workload document root",
1033    WORKLOAD_ELEMENTS
1034);
1035simple_node!(PollNode, "poll", "SRD-75 phase-poll loop", POLL_ELEMENTS);
1036pub struct ScenarioNode;
1037impl EnumerableNode for ScenarioNode {
1038    fn kind(&self) -> &'static str {
1039        "scenario"
1040    }
1041    fn doc(&self) -> &'static str {
1042        "scenario-tree node (bare string = phase name; object = structural node)"
1043    }
1044    fn elements(&self, _partial: Option<&Value>) -> Vec<ElementSpec> {
1045        SCENARIO_NODE_ELEMENTS.to_vec()
1046    }
1047    fn open_surface(&self) -> Option<&'static str> {
1048        Some(
1049            "legacy command-string entries (`name: \"run …\"`) — string \
1050              values pass through; structural keys are closed and the \
1051              parser rejects unknown ones with non-string values",
1052        )
1053    }
1054}
1055simple_node!(
1056    StopWhenNode,
1057    "stop_when",
1058    "SRD-83 stop condition",
1059    STOP_WHEN_ELEMENTS
1060);
1061simple_node!(
1062    MetricNode,
1063    "metric",
1064    "synthetic metric declaration (SRD-40b)",
1065    METRIC_ELEMENTS
1066);
1067simple_node!(
1068    AbstractNode,
1069    "abstract",
1070    "SRD-108 typed interface slot",
1071    ABSTRACT_ELEMENTS
1072);
1073simple_node!(
1074    EvaluationsNode,
1075    "evaluations",
1076    "post-execution scoring wrapper",
1077    EVALUATIONS_ELEMENTS
1078);
1079simple_node!(
1080    RelevancyNode,
1081    "relevancy",
1082    "recall/ndcg scoring config",
1083    RELEVANCY_ELEMENTS
1084);
1085simple_node!(
1086    BindingClassesNode,
1087    "binding_classes",
1088    "GK binding declaration classes (grammar lives in polydat)",
1089    BINDING_CLASS_ELEMENTS
1090);
1091simple_node!(
1092    MemoNode,
1093    "memo",
1094    "operator-facing memo notes",
1095    MEMO_ELEMENTS
1096);
1097simple_node!(
1098    OpPollNode,
1099    "op_poll",
1100    "op-level poll loop",
1101    OP_POLL_ELEMENTS
1102);
1103simple_node!(TriesNode, "tries", "tries map form", TRIES_ELEMENTS);
1104simple_node!(
1105    BackoffNode,
1106    "backoff",
1107    "retry backoff overrides",
1108    BACKOFF_ELEMENTS
1109);
1110simple_node!(
1111    ThrottleNode,
1112    "throttle",
1113    "adaptive backpressure governor",
1114    THROTTLE_ELEMENTS
1115);
1116simple_node!(DelayNode, "delay", "pre/post-op delay", DELAY_ELEMENTS);
1117simple_node!(
1118    ContinueIfNode,
1119    "continue_if",
1120    "SRD-101 pre-entry gate",
1121    CONTINUE_IF_ELEMENTS
1122);
1123simple_node!(
1124    CheckpointNode,
1125    "checkpoint",
1126    "checkpoint declaration map form",
1127    CHECKPOINT_ELEMENTS
1128);
1129simple_node!(
1130    OptimizeNode,
1131    "optimize",
1132    "SRD-86 optimize block",
1133    OPTIMIZE_ELEMENTS
1134);
1135
1136pub struct PhaseNode;
1137impl EnumerableNode for PhaseNode {
1138    fn kind(&self) -> &'static str {
1139        "phase"
1140    }
1141    fn doc(&self) -> &'static str {
1142        "one measured phase"
1143    }
1144    fn elements(&self, partial: Option<&Value>) -> Vec<ElementSpec> {
1145        let mut out: Vec<ElementSpec> = PHASE_ELEMENTS.to_vec();
1146        if let Some(Value::Object(map)) = partial {
1147            // SRD-75: a poll phase is a serial-cycle loop —
1148            // concurrency is pinned to 1.
1149            if map.contains_key("poll") {
1150                for e in &mut out {
1151                    if e.name == "concurrency" {
1152                        e.forms = &[Form::Vocab(&["1"])];
1153                        e.doc = "pinned to 1 under poll: (SRD-75 serial-cycle loop)";
1154                    }
1155                }
1156            }
1157            // SRD-108 Part A: exactly one source of ops — inline
1158            // `ops:` and the `tags:` selector are exclusive.
1159            if map.contains_key("ops") {
1160                out.retain(|e| e.name != "tags");
1161            } else if map.contains_key("tags") {
1162                out.retain(|e| e.name != "ops");
1163            }
1164        }
1165        out
1166    }
1167}
1168
1169pub struct OpNode;
1170impl EnumerableNode for OpNode {
1171    fn kind(&self) -> &'static str {
1172        "op"
1173    }
1174    fn doc(&self) -> &'static str {
1175        "one op template"
1176    }
1177    fn elements(&self, partial: Option<&Value>) -> Vec<ElementSpec> {
1178        let mut out: Vec<ElementSpec> = OP_MODEL_ELEMENTS.to_vec();
1179        // Activity-level keys share the surface; the `tags` /
1180        // `errors` / `tries` spellings already covered by the
1181        // model table keep the model semantics.
1182        for e in OP_ACTIVITY_ELEMENTS {
1183            if !out.iter().any(|m| m.name == e.name) {
1184                out.push(*e);
1185            }
1186        }
1187        let is_abstract = matches!(partial, Some(Value::Object(m)) if m.contains_key("abstract"));
1188        if !is_abstract {
1189            // Concrete ops carry a statement payload (one of the
1190            // alias spellings); abstract slots carry none — the
1191            // bound implementation contributes it (SRD-108).
1192            out.extend_from_slice(OP_STMT_ELEMENTS);
1193        }
1194        out
1195    }
1196    fn open_surface(&self) -> Option<&'static str> {
1197        Some(
1198            "adapter op-payload fields — per-adapter surface \
1199              (closed for http/testkit via known_op_fields, open for cql)",
1200        )
1201    }
1202}
1203
1204// ─── Runtime type check (validation over any AST) ────────────────
1205
1206fn form_accepts_scalar(form: &Form, v: &Value) -> bool {
1207    match form {
1208        Form::Bool => {
1209            matches!(v, Value::Bool(_))
1210                || matches!(v, Value::String(s) if crate::boolean::is_bool_word(s))
1211        }
1212        Form::U64 => {
1213            matches!(v, Value::Number(n) if n.as_u64().is_some())
1214                || matches!(v, Value::String(s) if s.trim().parse::<u64>().is_ok())
1215        }
1216        Form::F64 => {
1217            v.is_number() || matches!(v, Value::String(s) if s.trim().parse::<f64>().is_ok())
1218        }
1219        Form::Str
1220        | Form::GkSource
1221        | Form::GkExpr
1222        | Form::PathExpr
1223        | Form::MetricSelector
1224        | Form::Duration => v.is_string() || v.is_number(),
1225        Form::ParamRef => matches!(v, Value::String(s) if s.contains('{') && s.contains('}')),
1226        Form::StrList => match v {
1227            Value::Array(items) => items.iter().all(Value::is_string),
1228            Value::String(_) => true,
1229            _ => false,
1230        },
1231        Form::Vocab(words) => {
1232            // Match by canonical rendering: strings (trimmed,
1233            // case-insensitive), numbers, and bools all compare
1234            // against the vocabulary words.
1235            let rendered = match v {
1236                Value::String(s) => s.trim().to_string(),
1237                Value::Number(n) => n.to_string(),
1238                Value::Bool(b) => b.to_string(),
1239                _ => return false,
1240            };
1241            words.iter().any(|w| w.eq_ignore_ascii_case(&rendered))
1242        }
1243        Form::FreeMap => v.is_object(),
1244        Form::FreeScalar => !v.is_object() || v.is_object(), // anything
1245        // Structural forms handled by the recursive walk.
1246        Form::Node(_)
1247        | Form::NamedMap(_)
1248        | Form::ListOf(_)
1249        | Form::MapOf(_)
1250        | Form::ListOfForm(_) => false,
1251    }
1252}
1253
1254fn validate_against_forms(
1255    forms: &[Form],
1256    value: &Value,
1257    mode: Mode,
1258    path: &str,
1259    out: &mut Vec<Violation>,
1260) {
1261    // Accept when ANY declared form matches; structural forms
1262    // recurse and report their own findings.
1263    for form in forms {
1264        match form {
1265            Form::Node(node) => {
1266                if value.is_object() {
1267                    validate_node(*node, value, mode, path, out);
1268                    return;
1269                }
1270            }
1271            Form::NamedMap(node) => {
1272                if let Value::Object(map) = value {
1273                    for (name, child) in map {
1274                        validate_node(*node, child, mode, &format!("{path}.{name}"), out);
1275                    }
1276                    return;
1277                }
1278            }
1279            Form::ListOf(node) => {
1280                if let Value::Array(items) = value {
1281                    for (i, child) in items.iter().enumerate() {
1282                        // Scenario lists accept bare-string
1283                        // shorthands (phase names); only objects
1284                        // are structural nodes.
1285                        if child.is_object() {
1286                            validate_node(*node, child, mode, &format!("{path}[{i}]"), out);
1287                        }
1288                    }
1289                    return;
1290                }
1291            }
1292            Form::MapOf(inner) => {
1293                if let Value::Object(map) = value {
1294                    for (name, child) in map {
1295                        if !form_accepts_scalar(inner, child) {
1296                            out.push(Violation {
1297                                path: format!("{path}.{name}"),
1298                                message: format!("value does not conform to {inner:?}"),
1299                            });
1300                        }
1301                    }
1302                    return;
1303                }
1304            }
1305            Form::ListOfForm(inner) => {
1306                if let Value::Array(items) = value {
1307                    for (i, child) in items.iter().enumerate() {
1308                        if !form_accepts_scalar(inner, child) && !matches!(**inner, Form::FreeMap) {
1309                            out.push(Violation {
1310                                path: format!("{path}[{i}]"),
1311                                message: format!("entry does not conform to {inner:?}"),
1312                            });
1313                        }
1314                    }
1315                    return;
1316                }
1317            }
1318            scalar => {
1319                if form_accepts_scalar(scalar, value) {
1320                    return;
1321                }
1322            }
1323        }
1324    }
1325    out.push(Violation {
1326        path: path.to_string(),
1327        message: format!("value conforms to none of the declared forms {forms:?}"),
1328    });
1329}
1330
1331fn validate_node(
1332    node: &dyn EnumerableNode,
1333    value: &Value,
1334    mode: Mode,
1335    path: &str,
1336    out: &mut Vec<Violation>,
1337) {
1338    if let Value::Array(items) = value {
1339        // A list instance of a structural kind (scenario trees,
1340        // list-form op declarations): each object entry is one
1341        // node; scalar entries are documented shorthands.
1342        for (i, item) in items.iter().enumerate() {
1343            if item.is_object() {
1344                validate_node(node, item, mode, &format!("{path}[{i}]"), out);
1345            }
1346        }
1347        return;
1348    }
1349    let Value::Object(map) = value else {
1350        // Non-object instances of structural nodes are legal for
1351        // kinds with documented scalar shorthands (scenario
1352        // strings, string sugars); the parent's form list already
1353        // vetted the scalar alternative when one exists.
1354        return;
1355    };
1356    let elements = node.elements(Some(value));
1357    for (key, child) in map {
1358        // An empty YAML section (`params:` with nothing under
1359        // it) parses as null; the parser treats it as absent —
1360        // so does the model.
1361        if child.is_null() {
1362            continue;
1363        }
1364        match elements.iter().find(|e| e.name == key.as_str()) {
1365            Some(spec) => {
1366                validate_against_forms(spec.forms, child, mode, &format!("{path}.{key}"), out);
1367            }
1368            None => {
1369                if node.open_surface().is_none() {
1370                    out.push(Violation {
1371                        path: format!("{path}.{key}"),
1372                        message: format!("unknown element on closed node kind '{}'", node.kind()),
1373                    });
1374                }
1375            }
1376        }
1377    }
1378    if mode == Mode::Complete {
1379        for spec in &elements {
1380            if spec.required && !map.contains_key(spec.name) {
1381                out.push(Violation {
1382                    path: path.to_string(),
1383                    message: format!(
1384                        "required element '{}' missing on '{}'",
1385                        spec.name,
1386                        node.kind()
1387                    ),
1388                });
1389            }
1390        }
1391    }
1392}
1393
1394/// Validate an entire (possibly partial) workload AST against
1395/// the construction grammar.
1396pub fn validate_workload(ast: &Value, mode: Mode) -> Vec<Violation> {
1397    let mut out = Vec::new();
1398    validate_node(&WORKLOAD, ast, mode, "workload", &mut out);
1399    out
1400}
1401
1402// ─── Discovery over a partial AST ─────────────────────────────────
1403
1404/// Resolve the node kind at `path` inside `partial` (a possibly
1405/// incomplete workload AST) and enumerate its valid sub-elements
1406/// there. Path segments are the YAML keys / author-chosen names
1407/// from the root; list indices are decimal. Returns `None` when
1408/// the path leaves the modeled grammar (e.g. descends into a
1409/// declared-open surface).
1410pub fn discover_at<'v>(
1411    partial: &'v Value,
1412    path: &[&str],
1413) -> Option<(&'static dyn EnumerableNode, Vec<ElementSpec>)> {
1414    let mut node: &'static dyn EnumerableNode = root();
1415    let mut value: Option<&'v Value> = Some(partial);
1416
1417    let mut segs = path.iter().peekable();
1418    while let Some(seg) = segs.next() {
1419        let elements = node.elements(value);
1420        let spec = elements.iter().find(|e| e.name == *seg)?;
1421        let child_value = value.and_then(|v| v.get(*seg));
1422        let mut next: Option<&'static dyn EnumerableNode> = None;
1423        let mut named_map = false;
1424        let mut list = false;
1425        for f in spec.forms {
1426            // When the partial AST already shows the child's
1427            // shape, the matching structural form wins; otherwise
1428            // the first structural form declared.
1429            match f {
1430                Form::Node(n) => {
1431                    next = Some(*n);
1432                }
1433                Form::NamedMap(n) => {
1434                    if next.is_none() || matches!(child_value, Some(v) if v.is_object()) {
1435                        next = Some(*n);
1436                        named_map = true;
1437                        list = false;
1438                    }
1439                }
1440                Form::ListOf(n)
1441                    if (next.is_none() || matches!(child_value, Some(v) if v.is_array())) =>
1442                {
1443                    next = Some(*n);
1444                    list = true;
1445                    named_map = false;
1446                }
1447                _ => {}
1448            }
1449        }
1450        node = next?;
1451        if named_map || list {
1452            match segs.next() {
1453                Some(name) => {
1454                    value = child_value.and_then(|v| {
1455                        if list {
1456                            name.parse::<usize>().ok().and_then(|i| v.get(i))
1457                        } else {
1458                            v.get(*name)
1459                        }
1460                    });
1461                }
1462                None => {
1463                    return Some((node, node.elements(None)));
1464                }
1465            }
1466        } else {
1467            value = child_value;
1468        }
1469    }
1470    let elements = node.elements(value);
1471    Some((node, elements))
1472}
1473
1474#[cfg(test)]
1475mod tests {
1476    use super::*;
1477
1478    fn names(specs: &[ElementSpec]) -> Vec<&'static str> {
1479        specs.iter().map(|e| e.name).collect()
1480    }
1481
1482    /// Serde field probe: capture the exact static `fields` list
1483    /// the derive passes to `deserialize_struct`, so a table can
1484    /// be pinned against the MODEL TYPE itself.
1485    fn fields_of<'de, T: serde::Deserialize<'de>>() -> Option<&'static [&'static str]> {
1486        use std::cell::Cell;
1487        struct Probe<'a>(&'a Cell<Option<&'static [&'static str]>>);
1488        impl<'de, 'a> serde::Deserializer<'de> for Probe<'a> {
1489            type Error = serde::de::value::Error;
1490            fn deserialize_struct<V>(
1491                self,
1492                _name: &'static str,
1493                fields: &'static [&'static str],
1494                _visitor: V,
1495            ) -> Result<V::Value, Self::Error>
1496            where
1497                V: serde::de::Visitor<'de>,
1498            {
1499                self.0.set(Some(fields));
1500                Err(serde::de::Error::custom("field probe"))
1501            }
1502            fn deserialize_any<V>(self, _visitor: V) -> Result<V::Value, Self::Error>
1503            where
1504                V: serde::de::Visitor<'de>,
1505            {
1506                Err(serde::de::Error::custom("field probe"))
1507            }
1508            serde::forward_to_deserialize_any! {
1509                bool i8 i16 i32 i64 i128 u8 u16 u32 u64 u128 f32 f64
1510                char str string bytes byte_buf option unit unit_struct
1511                newtype_struct seq tuple tuple_struct map enum
1512                identifier ignored_any
1513            }
1514        }
1515        let cell = Cell::new(None);
1516        let _ = T::deserialize(Probe(&cell));
1517        cell.get()
1518    }
1519
1520    /// The phase table is pinned to `WorkloadPhase` ITSELF (one
1521    /// documented nesting exception: `tries_backoff` rides
1522    /// inside `tries:`'s map form).
1523    #[test]
1524    fn phase_table_matches_the_model_struct() {
1525        let probed =
1526            fields_of::<crate::model::WorkloadPhase>().expect("WorkloadPhase is a serde struct");
1527        let mut probed: Vec<&str> = probed.to_vec();
1528        probed.retain(|f| *f != "tries_backoff");
1529        probed.sort_unstable();
1530        let mut table = names(PHASE_ELEMENTS);
1531        table.sort_unstable();
1532        assert_eq!(
1533            probed, table,
1534            "PHASE_ELEMENTS drifted from the WorkloadPhase struct — \
1535             update the spec table (and its forms/docs) in lock-step"
1536        );
1537    }
1538
1539    /// Stop-condition and continue-if tables are pinned to their
1540    /// serde structs the same way.
1541    #[test]
1542    fn serde_backed_tables_match_their_structs() {
1543        let probed = fields_of::<crate::model::StopConditionSpec>()
1544            .expect("StopConditionSpec is a serde struct");
1545        for f in probed {
1546            assert!(
1547                STOP_WHEN_ELEMENTS.iter().any(|e| e.name == *f),
1548                "STOP_WHEN_ELEMENTS missing struct field '{f}'"
1549            );
1550        }
1551        let probed =
1552            fields_of::<crate::model::ContinueIfSpec>().expect("ContinueIfSpec is a serde struct");
1553        for f in probed {
1554            assert!(
1555                CONTINUE_IF_ELEMENTS.iter().any(|e| e.name == *f),
1556                "CONTINUE_IF_ELEMENTS missing struct field '{f}'"
1557            );
1558        }
1559    }
1560
1561    #[test]
1562    fn tables_are_duplicate_free_and_nodes_registered() {
1563        let mut kinds = std::collections::BTreeSet::new();
1564        for n in ALL_NODES {
1565            assert!(kinds.insert(n.kind()), "duplicate node kind '{}'", n.kind());
1566        }
1567        for n in ALL_NODES {
1568            let mut seen = std::collections::BTreeSet::new();
1569            for e in n.elements(None) {
1570                assert!(
1571                    seen.insert(e.name),
1572                    "node '{}': duplicate element '{}'",
1573                    n.kind(),
1574                    e.name
1575                );
1576                // Every node referenced from a form is itself in
1577                // ALL_NODES — the enumeration surface is closed
1578                // over the reference graph (references are direct,
1579                // so this cannot dangle; it can only be missing
1580                // from the tooling list).
1581                for f in e.forms {
1582                    if let Form::Node(c) | Form::NamedMap(c) | Form::ListOf(c) = f {
1583                        assert!(
1584                            ALL_NODES.iter().any(|k| k.kind() == c.kind()),
1585                            "kind '{}' not in ALL_NODES",
1586                            c.kind()
1587                        );
1588                    }
1589                }
1590            }
1591        }
1592    }
1593
1594    #[test]
1595    fn discovery_walks_a_partial_ast_with_narrowing() {
1596        let partial: Value = serde_yaml::from_str(
1597            r#"
1598phases:
1599  load:
1600    poll:
1601      until: "x == 1"
1602    ops:
1603      probe:
1604        stmt: "S"
1605"#,
1606        )
1607        .expect("yaml");
1608
1609        let (node, elements) = discover_at(&partial, &[]).expect("root");
1610        assert_eq!(node.kind(), "workload");
1611        assert!(elements.iter().any(|e| e.name == "phases"));
1612
1613        let (node, elements) = discover_at(&partial, &["phases", "load"]).expect("phase");
1614        assert_eq!(node.kind(), "phase");
1615        let conc = elements
1616            .iter()
1617            .find(|e| e.name == "concurrency")
1618            .expect("concurrency");
1619        assert_eq!(conc.forms, &[Form::Vocab(&["1"])]);
1620        assert!(
1621            !elements.iter().any(|e| e.name == "tags"),
1622            "inline ops exclude the tags selector"
1623        );
1624
1625        let (node, elements) = discover_at(&partial, &["phases", "load", "poll"]).expect("poll");
1626        assert_eq!(node.kind(), "poll");
1627        assert!(elements.iter().any(|e| e.name == "until" && e.required));
1628
1629        let (node, elements) =
1630            discover_at(&partial, &["phases", "load", "ops", "probe"]).expect("op");
1631        assert_eq!(node.kind(), "op");
1632        assert!(elements.iter().any(|e| e.name == "stmt"));
1633
1634        let (node, _) = discover_at(&partial, &["phases"]).expect("phase kind");
1635        assert_eq!(node.kind(), "phase");
1636
1637        assert!(discover_at(&partial, &["phases", "load", "nope", "deeper"]).is_none());
1638    }
1639
1640    #[test]
1641    fn abstract_ops_drop_the_statement_payload() {
1642        let partial: Value = serde_yaml::from_str(
1643            r#"
1644phases:
1645  p:
1646    ops:
1647      slot:
1648        abstract:
1649          needs:
1650            q: vec_f32
1651"#,
1652        )
1653        .expect("yaml");
1654        let (_, elements) = discover_at(&partial, &["phases", "p", "ops", "slot"]).expect("op");
1655        assert!(
1656            !elements.iter().any(|e| e.name == "stmt"),
1657            "abstract slots carry no statement payload"
1658        );
1659        assert!(elements.iter().any(|e| e.name == "abstract"));
1660    }
1661
1662    #[test]
1663    fn validation_accepts_a_well_formed_document() {
1664        let ast: Value = serde_yaml::from_str(
1665            r#"
1666description: ok
1667params:
1668  p0: "3"
1669phases:
1670  load:
1671    cycles: 5
1672    concurrency: 2
1673    bindings: |
1674      const c := 1
1675    ops:
1676      ins:
1677        stmt: "X {p0}"
1678        capture:
1679          w: /0/v
1680scenarios:
1681  default:
1682    - load
1683"#,
1684        )
1685        .expect("yaml");
1686        let violations = validate_workload(&ast, Mode::Complete);
1687        assert!(
1688            violations.is_empty(),
1689            "unexpected violations: {violations:#?}"
1690        );
1691    }
1692
1693    #[test]
1694    fn validation_flags_bad_forms_and_missing_required() {
1695        let ast: Value = serde_yaml::from_str(
1696            r#"
1697phases:
1698  load:
1699    rate: "not-a-number"
1700    checkpoint: "bogus-mode"
1701    poll:
1702      interval_ms: 50
1703    metrics:
1704      m0:
1705        kind: "sideways"
1706"#,
1707        )
1708        .expect("yaml");
1709        let violations = validate_workload(&ast, Mode::Complete);
1710        let paths: Vec<&str> = violations.iter().map(|v| v.path.as_str()).collect();
1711        assert!(
1712            paths.iter().any(|p| p.ends_with("rate")),
1713            "rate form violation expected: {violations:#?}"
1714        );
1715        assert!(
1716            paths.iter().any(|p| p.ends_with("checkpoint")),
1717            "checkpoint vocab violation expected"
1718        );
1719        assert!(
1720            paths.iter().any(|p| p.ends_with("kind")),
1721            "metric kind vocab violation expected"
1722        );
1723        // poll.until is required and missing under Complete.
1724        assert!(
1725            violations.iter().any(|v| v.message.contains("'until'")),
1726            "poll.until required-missing expected: {violations:#?}"
1727        );
1728        // Partial mode: same doc, no required-missing findings.
1729        let partial = validate_workload(&ast, Mode::Partial);
1730        assert!(
1731            !partial.iter().any(|v| v.message.contains("required")),
1732            "partial mode must not demand required elements"
1733        );
1734    }
1735}