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