Skip to main content

nmbrs_workload/
implements.rs

1// Copyright 2024-2026 Jonathan Shook
2// SPDX-License-Identifier: Apache-2.0
3
4//! SRD-108 Part B — the typed implementation binder.
5//!
6//! Binds an implementation workload's op bodies into a
7//! blueprint's ABSTRACT slots at load time, before any synthesis.
8//! The blueprint owns every piece of scaffolding (extents,
9//! concurrency, stop conditions, metrics, provenance classes);
10//! the implementation contributes exactly the protocol matter:
11//! op fields, adapter selection, captures, and op-level bindings.
12//!
13//! Every rule here is a LOAD error with a slot-coordinate name —
14//! nothing defers to a runtime critical section. The interface's
15//! type proof runs later, still at init: pre-map synthesis
16//! verifies `yields` against the compiled op-template program
17//! (see `nmbrs-runtime`'s SRD-108 verification hook).
18
19use std::collections::BTreeSet;
20
21use crate::model::{BindingsDef, ParsedOp, Workload, WorkloadPhase};
22
23/// Bind `implementation` into `blueprint` in place.
24///
25/// Coverage is total in both directions: every abstract slot in
26/// `blueprint` must be bound exactly once, and every op the
27/// implementation provides must land in an abstract slot.
28pub fn bind_implementation(
29    blueprint: &mut Workload,
30    implementation: Workload,
31) -> Result<(), String> {
32    // The set of wires the blueprint scaffold provides — the
33    // `needs` availability check reads this. Params + workload
34    // bindings + (per-phase) phase bindings.
35    let provided_global: BTreeSet<String> = blueprint
36        .declared_params
37        .iter()
38        .cloned()
39        .chain(bindings_wire_names(&blueprint.bindings))
40        .collect();
41
42    let unconsumed = unconsumed_blocks(&implementation);
43    if !unconsumed.is_empty() {
44        return Err(format!(
45            "implementation declares [{}], which binding does not take — an \
46             implementation provides op bodies, params, bindings, scenarios and \
47             report groups; these belong to the blueprint",
48            unconsumed.join(", ")
49        ));
50    }
51
52    let mut unbound: BTreeSet<String> = BTreeSet::new();
53    for (phase_name, phase) in &blueprint.phases {
54        for op in &phase.ops {
55            if op.abstract_interface.is_some() {
56                unbound.insert(format!("{phase_name}.{}", op.name));
57            }
58        }
59    }
60
61    for (phase_name, impl_phase) in implementation.phases {
62        let offending = scaffolding_fields_set(&impl_phase);
63        if !offending.is_empty() {
64            return Err(format!(
65                "implementation phase '{phase_name}' declares scaffolding \
66                 fields [{}] — scaffolding belongs to the blueprint; an \
67                 implementation phase carries only `ops:`",
68                offending.join(", ")
69            ));
70        }
71        let Some(blueprint_phase) = blueprint.phases.get_mut(&phase_name) else {
72            return Err(format!(
73                "implementation provides phase '{phase_name}', but the \
74                 blueprint declares no such phase"
75            ));
76        };
77        for impl_op in impl_phase.ops {
78            let slot_key = format!("{phase_name}.{}", impl_op.name);
79            let Some(slot) = blueprint_phase
80                .ops
81                .iter_mut()
82                .find(|op| op.name == impl_op.name)
83            else {
84                return Err(format!(
85                    "implementation op '{slot_key}' names no op in the \
86                     blueprint phase"
87                ));
88            };
89            if slot.abstract_interface.is_none() {
90                return Err(format!(
91                    "implementation op '{slot_key}' targets a CONCRETE \
92                     blueprint op — only abstract slots accept bindings"
93                ));
94            }
95            if !unbound.remove(&slot_key) {
96                return Err(format!("implementation binds slot '{slot_key}' twice"));
97            }
98            // The slot's own bindings as the blueprint wrote them,
99            // read before the implementation's are merged in: a
100            // need is a wire the BLUEPRINT guarantees, so one the
101            // implementation binds for itself does not meet it.
102            let slot_provided = bindings_wire_names(&slot.bindings);
103            bind_slot(slot, impl_op, &slot_key)?;
104
105            // `needs` availability: every guaranteed wire must be
106            // provided by the blueprint scaffold — params, workload
107            // bindings, this phase's bindings, or the slot's own
108            // (a wire made in the op's scope, as a fragment is:
109            // SRD-115 §5.1). (The full type proof is pre-map
110            // synthesis; this is the early named error.)
111            let mut provided = provided_global.clone();
112            provided.extend(bindings_wire_names(&blueprint_phase.bindings));
113            provided.extend(slot_provided);
114            if let Some(iface) = slot.abstract_interface.as_ref() {
115                for need in iface.needs.keys() {
116                    if !provided.contains(need) {
117                        return Err(format!(
118                            "slot '{slot_key}' declares need '{need}', but \
119                             the blueprint provides no param or binding \
120                             by that name"
121                        ));
122                    }
123                }
124            }
125        }
126    }
127
128    if !unbound.is_empty() {
129        return Err(format!(
130            "abstract slot(s) [{}] remain unbound — the implementation \
131             must cover every abstract op",
132            unbound.into_iter().collect::<Vec<_>>().join(", ")
133        ));
134    }
135
136    // Implementation params layer over the blueprint's: a NEW key
137    // adds a protocol knob; a key the blueprint already declares
138    // RE-DEFAULTS its value — the same specialization the CLI
139    // performs per invocation, made durable in a document (e.g. a
140    // turnkey variant pinning dataset and tier governance).
141    // Declaration ownership stays with the blueprint: the key is
142    // not re-declared, so consumed-param provenance and the CLI
143    // override order are unchanged. Only the YAML-DECLARED subset
144    // participates: `Workload.params` also carries every ad-hoc
145    // CLI arg (tui=, workload=, …) overlaid at parse, and those
146    // are invocation matter, not document matter.
147    let blueprint_declared: BTreeSet<String> = blueprint.declared_params.iter().cloned().collect();
148    let impl_declared: Vec<String> = implementation.declared_params;
149    for k in impl_declared {
150        if let Some(v) = implementation.params.get(&k) {
151            blueprint.params.insert(k.clone(), v.clone());
152        }
153        if !blueprint_declared.contains(&k) {
154            blueprint.declared_params.push(k);
155        }
156    }
157
158    // Workload-level bindings concatenate blueprint-first.
159    concat_bindings(&mut blueprint.bindings, implementation.bindings)
160        .map_err(|e| format!("workload-level bindings: {e}"))?;
161
162    // Scenarios: the implementation adds its own, and they may include
163    // the blueprint's. It does not redefine one.
164    let mut collisions: Vec<&String> = implementation
165        .scenarios
166        .keys()
167        .filter(|name| blueprint.scenarios.contains_key(*name))
168        .collect();
169    if !collisions.is_empty() {
170        collisions.sort();
171        return Err(format!(
172            "implementation declares scenario(s) [{}] that the blueprint already \
173             declares — an implementation adds scenarios, and runs one of its own \
174             with scenario=<name>; it does not redefine the blueprint's",
175            collisions
176                .iter()
177                .map(|s| s.as_str())
178                .collect::<Vec<_>>()
179                .join(", ")
180        ));
181    }
182    if !implementation.scenarios.is_empty() {
183        blueprint.scenarios.extend(implementation.scenarios);
184        crate::parse::resolve_scenario_includes(&mut blueprint.scenarios)
185            .map_err(|e| format!("implementation scenarios: {e}"))?;
186    }
187    blueprint
188        .scenario_parse_errors
189        .extend(implementation.scenario_parse_errors);
190
191    // Report: merged by group name, the implementation's winning.
192    blueprint
193        .report_warnings
194        .extend(implementation.report_warnings);
195    let unmatched = blueprint
196        .report
197        .merge_child(implementation.report)
198        .map_err(|e| format!("implementation report: {e}"))?;
199    blueprint.report_warnings.extend(unmatched);
200
201    Ok(())
202}
203
204/// The top-level blocks an implementation declares that binding does
205/// not take. Every input is acted on or refused, so each is an error.
206fn unconsumed_blocks(implementation: &Workload) -> Vec<&'static str> {
207    let mut blocks = Vec::new();
208    if !implementation.status_metrics.is_empty() {
209        blocks.push("status_metrics");
210    }
211    if !implementation.readouts.is_empty() {
212        blocks.push("readouts");
213    }
214    if implementation.wrappers.is_some() {
215        blocks.push("wrappers");
216    }
217    if !implementation.stop_when.is_empty() {
218        blocks.push("stop_when");
219    }
220    blocks
221}
222
223/// Bind one implementation op into one abstract slot. The slot
224/// keeps everything the blueprint declared; the implementation
225/// fills the protocol surfaces. Any overlap is a collision error
226/// — never a silent override.
227fn bind_slot(slot: &mut ParsedOp, impl_op: ParsedOp, slot_key: &str) -> Result<(), String> {
228    // Op-owned semantics the implementation may NOT set: these
229    // are measurement/scaffolding surfaces. (`result:` is NOT in
230    // this list — it is the delivery surface for the `results:`
231    // interface leg, SRD-109 Part 3.)
232    if impl_op.condition.is_some()
233        || impl_op.delay.is_some()
234        || !impl_op.metrics.is_empty()
235        || !impl_op.cell.is_empty()
236        || impl_op.traverse.is_some()
237        || impl_op.wrappers.is_some()
238        || impl_op.while_cond.is_some()
239        || impl_op.rate.is_some()
240        || !matches!(impl_op.daemon, crate::model::DaemonSpec::Disabled)
241    {
242        return Err(format!(
243            "implementation op '{slot_key}' sets op semantics \
244             (if/delay/metrics/cell/traverse/wrappers/while/rate/\
245             daemon) — those belong to the blueprint slot"
246        ));
247    }
248    if impl_op.abstract_interface.is_some() {
249        return Err(format!(
250            "implementation op '{slot_key}' declares `abstract:` — an \
251             implementation provides bodies, not interfaces"
252        ));
253    }
254
255    for (k, v) in impl_op.op {
256        if slot.op.contains_key(&k) {
257            return Err(format!(
258                "slot '{slot_key}': op field '{k}' declared by BOTH the \
259                 blueprint slot and the implementation — the blueprint \
260                 is authoritative; remove one"
261            ));
262        }
263        slot.op.insert(k, v);
264    }
265    // Op params follow the param layering rule, not the op-field
266    // collision rule: params are the system's override surface
267    // (doc → block → op cascade at parse, CLI last), and both
268    // docs materialize their workload-level params into op params
269    // — so an overlapping key here is normally a workload-level
270    // re-default seen through the cascade. The implementation
271    // (the more concrete layer) wins, mirroring the workload-level
272    // merge above; op FIELDS keep the hard collision error.
273    for (k, v) in impl_op.params {
274        slot.params.insert(k, v);
275    }
276    for (k, v) in impl_op.tags {
277        match slot.tags.get(&k) {
278            Some(existing) if existing != &v => {
279                return Err(format!(
280                    "slot '{slot_key}': tag '{k}' has conflicting values \
281                     ('{existing}' vs '{v}')"
282                ));
283            }
284            _ => {
285                slot.tags.insert(k, v);
286            }
287        }
288    }
289    if !impl_op.captures.is_empty() {
290        let existing: BTreeSet<&str> = slot.captures.iter().map(|c| c.as_name.as_str()).collect();
291        for cap in &impl_op.captures {
292            if existing.contains(cap.as_name.as_str()) {
293                return Err(format!(
294                    "slot '{slot_key}': capture '{}' declared by both \
295                     sides",
296                    cap.as_name
297                ));
298            }
299        }
300        slot.captures.extend(impl_op.captures);
301    }
302    concat_bindings(&mut slot.bindings, impl_op.bindings)
303        .map_err(|e| format!("slot '{slot_key}' bindings: {e}"))?;
304
305    // SRD-109 Part 3 — `result:` bindings deliver the `results:`
306    // interface leg. Blueprint-side entries for interface names
307    // are collisions (paths are protocol matter); impl entries
308    // colliding with blueprint entries are collisions like any
309    // other surface; the merged spec concatenates blueprint-first.
310    if let Some(iface) = slot.abstract_interface.as_ref() {
311        let blueprint_declared = result_binding_names(slot.result.as_ref());
312        for results_name in iface.results.keys() {
313            if blueprint_declared.contains(results_name.as_str()) {
314                return Err(format!(
315                    "slot '{slot_key}': `results:` wire '{results_name}' \
316                     also has a blueprint-side `result:` binding — the \
317                     projection path is protocol matter; the \
318                     implementation declares it"
319                ));
320            }
321        }
322    }
323    if let Some(impl_result) = impl_op.result {
324        let blueprint_declared = result_binding_names(slot.result.as_ref());
325        for name in result_binding_names(Some(&impl_result)) {
326            if blueprint_declared.contains(name.as_str()) {
327                return Err(format!(
328                    "slot '{slot_key}': result binding '{name}' declared \
329                     by BOTH the blueprint slot and the implementation — \
330                     remove one"
331                ));
332            }
333        }
334        slot.result = Some(match slot.result.take() {
335            None => impl_result,
336            Some(existing) => crate::model::ResultSpec::List(vec![existing, impl_result]),
337        });
338    }
339
340    // `yields` / `results` presence: every promised wire must be
341    // delivered by the bound op — a capture `as`-name for yields,
342    // a `result:` binding LHS for results. (Type equality is
343    // proven at pre-map synthesis against the compiled program.)
344    if let Some(iface) = slot.abstract_interface.as_ref() {
345        let delivered: BTreeSet<&str> = slot.captures.iter().map(|c| c.as_name.as_str()).collect();
346        for yield_name in iface.yields.keys() {
347            if !delivered.contains(yield_name.as_str()) {
348                return Err(format!(
349                    "slot '{slot_key}' promises yield '{yield_name}', \
350                     but the bound implementation captures [{}] — add a \
351                     capture (`[{yield_name}]` or `... as {yield_name}`)",
352                    delivered.into_iter().collect::<Vec<_>>().join(", ")
353                ));
354            }
355        }
356        let projected = result_binding_names(slot.result.as_ref());
357        for results_name in iface.results.keys() {
358            if !projected.contains(results_name.as_str()) {
359                return Err(format!(
360                    "slot '{slot_key}' promises results wire \
361                     '{results_name}', but the bound implementation \
362                     declares result bindings [{}] — add a `result:` \
363                     entry (`{results_name}: <path-expr>`, e.g. \
364                     `{results_name}: rows[*].column`)",
365                    projected.iter().cloned().collect::<Vec<_>>().join(", ")
366                ));
367            }
368        }
369    }
370
371    slot.interface_bound = true;
372    Ok(())
373}
374
375/// Wire names a `result:` spec declares: map-shape keys plus the
376/// `:=` LHS of string-shape source lines.
377fn result_binding_names(spec: Option<&crate::model::ResultSpec>) -> BTreeSet<String> {
378    let mut out = BTreeSet::new();
379    if let Some(spec) = spec {
380        spec.walk_fragments(|frag| match frag {
381            crate::model::ResultFragment::Named { name, .. } => {
382                out.insert(name.to_string());
383            }
384            crate::model::ResultFragment::Source(source) => {
385                for line in source.lines() {
386                    if let Some((lhs, _)) = line.trim().split_once(":=") {
387                        out.insert(lhs.trim().to_string());
388                    }
389                }
390            }
391        });
392    }
393    out
394}
395
396/// Names of scaffolding fields an implementation phase illegally
397/// sets. Only `ops:` is legal on an implementation phase.
398fn scaffolding_fields_set(phase: &WorkloadPhase) -> Vec<&'static str> {
399    let mut out = Vec::new();
400    if phase.cycles.is_some() {
401        out.push("cycles");
402    }
403    if phase.concurrency.is_some() {
404        out.push("concurrency");
405    }
406    if phase.rate.is_some() {
407        out.push("rate");
408    }
409    if phase.daemon {
410        out.push("daemon");
411    }
412    if phase.adapter.is_some() {
413        out.push("adapter");
414    }
415    if phase.errors.is_some() {
416        out.push("errors");
417    }
418    if phase.tries.is_some() {
419        out.push("tries");
420    }
421    if phase.tries_backoff.is_some() {
422        out.push("tries_backoff");
423    }
424    if phase.interval.is_some() {
425        out.push("interval");
426    }
427    if phase.repeat.is_some() {
428        out.push("repeat");
429    }
430    if phase.error_rate_max.is_some() {
431        out.push("error_rate_max");
432    }
433    if phase.timeout.is_some() {
434        out.push("timeout");
435    }
436    if !phase.stop_when.is_empty() {
437        out.push("stop_when");
438    }
439    if phase.tags.is_some() {
440        out.push("tags");
441    }
442    if phase.for_each.is_some() {
443        out.push("for_each");
444    }
445    if phase.continue_if.is_some() {
446        out.push("continue_if");
447    }
448    if phase.loop_scope.is_some() {
449        out.push("loop_scope");
450    }
451    if phase.iter_scope.is_some() {
452        out.push("iter_scope");
453    }
454    if phase.checkpoint.is_some() {
455        out.push("checkpoint");
456    }
457    if !phase.status_metrics.is_empty() {
458        out.push("status_metrics");
459    }
460    if !phase.bindings.is_empty() {
461        out.push("bindings");
462    }
463    if !phase.metrics.is_empty() {
464        out.push("metrics");
465    }
466    if !phase.dimensions.is_empty() {
467        out.push("dimensions");
468    }
469    out
470}
471
472/// Wire names a `BindingsDef` declares.
473fn bindings_wire_names(bindings: &BindingsDef) -> Vec<String> {
474    match bindings {
475        BindingsDef::PolydatSource(s) => crate::inline::binding_wire_names(s),
476        BindingsDef::Map(m) => m.keys().cloned().collect(),
477    }
478}
479
480/// Concatenate `extra` onto `base`, blueprint-first. Mixed
481/// map/source forms are rejected (no sensible concatenation) —
482/// never silently dropped.
483fn concat_bindings(base: &mut BindingsDef, extra: BindingsDef) -> Result<(), String> {
484    if extra.is_empty() {
485        return Ok(());
486    }
487    if base.is_empty() {
488        *base = extra;
489        return Ok(());
490    }
491    match (&mut *base, extra) {
492        (BindingsDef::PolydatSource(b), BindingsDef::PolydatSource(e)) => {
493            if !b.ends_with('\n') {
494                b.push('\n');
495            }
496            b.push_str(&e);
497            Ok(())
498        }
499        (BindingsDef::Map(b), BindingsDef::Map(e)) => {
500            for (k, v) in e {
501                if b.contains_key(&k) {
502                    return Err(format!("binding '{k}' declared by both sides"));
503                }
504                b.insert(k, v);
505            }
506            Ok(())
507        }
508        _ => Err("mixed bindings forms (map vs polydat source) cannot \
509                  be concatenated — use one form on both sides"
510            .into()),
511    }
512}
513
514/// Names of every unbound abstract slot in a workload — non-empty
515/// means the workload cannot run (load error at initiation).
516pub fn unbound_abstract_slots(workload: &Workload) -> Vec<String> {
517    let mut out = Vec::new();
518    for (phase_name, phase) in &workload.phases {
519        for op in &phase.ops {
520            if op.abstract_interface.is_some() && !op.interface_bound {
521                out.push(format!("{phase_name}.{}", op.name));
522            }
523        }
524    }
525    out.sort();
526    out
527}
528
529#[cfg(test)]
530mod tests {
531    use super::*;
532    use std::collections::HashMap;
533
534    fn parse(yaml: &str) -> Workload {
535        crate::parse::parse_workload(yaml, &HashMap::new()).expect("parse test workload")
536    }
537
538    const BLUEPRINT: &str = r#"
539params:
540  suite_k: "10"
541bindings: |
542  query_vector := "0.1,0.2"
543phases:
544  probe:
545    cycles: 4
546    concurrency: 2
547    ops:
548      search:
549        abstract:
550          needs:
551            query_vector: str
552            suite_k: u64
553          yields:
554            key: str
555"#;
556
557    const IMPL_OK: &str = r#"
558implements: blueprint
559phases:
560  probe:
561    ops:
562      search:
563        stmt: "SEARCH {query_vector} LIMIT {suite_k}"
564        captures: "[key]"
565"#;
566
567    /// An interface type is a polydat type keyword, resolved when
568    /// the workload is parsed; a name that is not one is refused
569    /// there, naming the interface entry.
570    #[test]
571    fn interface_types_are_polydat_keywords() {
572        let parsed = parse(BLUEPRINT);
573        let iface = parsed.phases["probe"].ops[0]
574            .abstract_interface
575            .as_ref()
576            .expect("search is an abstract slot");
577        assert_eq!(iface.needs["query_vector"], polydat::ast::PortType::Str);
578        assert_eq!(iface.needs["suite_k"], polydat::ast::PortType::U64);
579        assert_eq!(iface.yields["key"], polydat::ast::PortType::Str);
580
581        let yaml = BLUEPRINT.replace("key: str", "key: strr");
582        let err = crate::parse::parse_workload(&yaml, &HashMap::new())
583            .expect_err("an interface type that is not a keyword must be refused");
584        assert!(
585            err.contains("`abstract.yields.key:` `strr` is not a type keyword"),
586            "{err}"
587        );
588    }
589
590    #[test]
591    fn binds_and_marks_the_slot() {
592        let mut blueprint = parse(BLUEPRINT);
593        let implementation = parse(IMPL_OK);
594        bind_implementation(&mut blueprint, implementation).unwrap();
595        let op = &blueprint.phases["probe"].ops[0];
596        assert!(op.interface_bound);
597        assert!(op.op.contains_key("stmt"));
598        assert_eq!(op.captures.len(), 1);
599        assert!(unbound_abstract_slots(&blueprint).is_empty());
600    }
601
602    /// Implementation params layer over the blueprint's: a new
603    /// key adds a protocol knob (and is declared), while a key
604    /// the blueprint already declares re-defaults its value with
605    /// declaration ownership unchanged — no duplicate entry in
606    /// `declared_params`. This is what lets a turnkey variant
607    /// (extends-child of an impl) pin dataset/tier params for
608    /// single `workload=` invocation.
609    #[test]
610    fn impl_params_add_knobs_and_redefault_blueprint_params() {
611        let mut blueprint = parse(BLUEPRINT);
612        let implementation = parse(
613            r#"
614implements: blueprint
615params:
616  suite_k: "25"
617  knob: "x"
618phases:
619  probe:
620    ops:
621      search:
622        stmt: "SEARCH {query_vector} LIMIT {suite_k}"
623        captures: "[key]"
624"#,
625        );
626        bind_implementation(&mut blueprint, implementation).unwrap();
627        assert_eq!(blueprint.params["suite_k"], "25");
628        assert_eq!(blueprint.params["knob"], "x");
629        assert_eq!(
630            blueprint
631                .declared_params
632                .iter()
633                .filter(|k| k.as_str() == "suite_k")
634                .count(),
635            1,
636            "re-defaulting must not re-declare"
637        );
638        assert!(blueprint.declared_params.iter().any(|k| k == "knob"));
639    }
640
641    #[test]
642    fn missing_yield_capture_is_named() {
643        let mut blueprint = parse(BLUEPRINT);
644        let implementation = parse(
645            r#"
646implements: blueprint
647phases:
648  probe:
649    ops:
650      search:
651        stmt: "SEARCH"
652"#,
653        );
654        let err = bind_implementation(&mut blueprint, implementation).unwrap_err();
655        assert!(err.contains("yield 'key'"), "err: {err}");
656    }
657
658    #[test]
659    fn unknown_slot_and_uncovered_slot_are_errors() {
660        let mut blueprint = parse(BLUEPRINT);
661        let implementation = parse(
662            r#"
663implements: blueprint
664phases:
665  probe:
666    ops:
667      wrong_name:
668        stmt: "X"
669"#,
670        );
671        let err = bind_implementation(&mut blueprint, implementation).unwrap_err();
672        assert!(err.contains("wrong_name"), "err: {err}");
673
674        let mut blueprint = parse(BLUEPRINT);
675        let err =
676            bind_implementation(&mut blueprint, parse("implements: blueprint\n")).unwrap_err();
677        assert!(err.contains("remain unbound"), "err: {err}");
678    }
679
680    #[test]
681    fn scaffolding_on_implementation_phase_is_rejected() {
682        let mut blueprint = parse(BLUEPRINT);
683        let implementation = parse(
684            r#"
685implements: blueprint
686phases:
687  probe:
688    cycles: 99
689    ops:
690      search:
691        stmt: "X"
692        captures: "[key]"
693"#,
694        );
695        let err = bind_implementation(&mut blueprint, implementation).unwrap_err();
696        assert!(err.contains("scaffolding"), "err: {err}");
697    }
698
699    #[test]
700    fn undeclared_need_is_named() {
701        let mut blueprint = parse(
702            r#"
703phases:
704  probe:
705    cycles: 1
706    ops:
707      search:
708        abstract:
709          needs:
710            not_provided: u64
711"#,
712        );
713        let err = bind_implementation(
714            &mut blueprint,
715            parse(
716                r#"
717implements: blueprint
718phases:
719  probe:
720    ops:
721      search:
722        stmt: "X"
723"#,
724            ),
725        )
726        .unwrap_err();
727        assert!(err.contains("need 'not_provided'"), "err: {err}");
728    }
729
730    /// A need is met by a wire the blueprint slot binds for itself
731    /// (a value made in the op's own scope), and not by one the
732    /// implementation binds: the blueprint is what guarantees a need.
733    #[test]
734    fn a_need_is_met_by_the_blueprint_slots_own_binding_only() {
735        let blueprint = r#"
736phases:
737  probe:
738    cycles: 1
739    ops:
740      search:
741        bindings: |
742          made_here := cycle
743        abstract:
744          needs:
745            made_here: u64
746"#;
747        let implementation = r#"
748implements: blueprint
749phases:
750  probe:
751    ops:
752      search:
753        stmt: "X {made_here}"
754"#;
755        let mut bound = parse(blueprint);
756        bind_implementation(&mut bound, parse(implementation)).unwrap();
757        assert!(bound.phases["probe"].ops[0].interface_bound);
758
759        let mut unprovided =
760            parse(&blueprint.replace("        bindings: |\n          made_here := cycle\n", ""));
761        let err = bind_implementation(
762            &mut unprovided,
763            parse(&implementation.replace(
764                "        stmt:",
765                "        bindings: |\n          made_here := cycle\n        stmt:",
766            )),
767        )
768        .unwrap_err();
769        assert!(err.contains("need 'made_here'"), "err: {err}");
770    }
771
772    /// Where an op's measurements are placed is the blueprint's to say:
773    /// a slot keeps its `cell:`, and an implementation may not set one.
774    #[test]
775    fn a_cell_placement_belongs_to_the_blueprint_slot() {
776        let blueprint = r#"
777phases:
778  probe:
779    cycles: 1
780    dimensions:
781      tier: str
782    ops:
783      search:
784        bindings: |
785          tier_name := "a"
786        cell: { tier: tier_name }
787        abstract: {}
788"#;
789        let implementation = r#"
790implements: blueprint
791phases:
792  probe:
793    ops:
794      search:
795        stmt: "X"
796"#;
797        let mut bound = parse(blueprint);
798        bind_implementation(&mut bound, parse(implementation)).unwrap();
799        assert_eq!(bound.phases["probe"].ops[0].cell["tier"], "tier_name");
800
801        // An implementation's phase declares no dimensions, so a
802        // `cell:` written there is already refused when it is parsed.
803        // The binder refuses one however it arrived.
804        let mut plain = parse(&blueprint.replace("        cell: { tier: tier_name }\n", ""));
805        let mut placing = parse(implementation);
806        placing.phases.get_mut("probe").expect("the phase").ops[0]
807            .cell
808            .insert("tier".into(), "tier_name".into());
809        let err = bind_implementation(&mut plain, placing).unwrap_err();
810        assert!(err.contains("sets op semantics"), "err: {err}");
811    }
812
813    #[test]
814    fn op_field_collision_is_an_error() {
815        let mut blueprint = parse(
816            r#"
817phases:
818  probe:
819    cycles: 1
820    ops:
821      search:
822        stmt: "BLUEPRINT SIDE"
823        abstract:
824          yields:
825            key: str
826"#,
827        );
828        let err = bind_implementation(
829            &mut blueprint,
830            parse(
831                r#"
832implements: blueprint
833phases:
834  probe:
835    ops:
836      search:
837        stmt: "IMPL SIDE"
838        captures: "[key]"
839"#,
840            ),
841        )
842        .unwrap_err();
843        assert!(err.contains("'stmt'") && err.contains("BOTH"), "err: {err}");
844    }
845
846    #[test]
847    fn unbound_slots_are_reported() {
848        let blueprint = parse(BLUEPRINT);
849        assert_eq!(unbound_abstract_slots(&blueprint), vec!["probe.search"]);
850    }
851
852    // ── SRD-109 Part 3: the `results:` interface leg ──
853
854    const RESULTS_BLUEPRINT: &str = r#"
855phases:
856  probe:
857    cycles: 1
858    ops:
859      search:
860        abstract:
861          results:
862            keys: vec_i64
863"#;
864
865    #[test]
866    fn results_wire_delivered_by_impl_result_binding() {
867        let mut blueprint = parse(RESULTS_BLUEPRINT);
868        bind_implementation(
869            &mut blueprint,
870            parse(
871                r#"
872implements: blueprint
873phases:
874  probe:
875    ops:
876      search:
877        stmt: "SEARCH"
878        result:
879          keys: "rows[*].key"
880"#,
881            ),
882        )
883        .unwrap();
884        let op = &blueprint.phases["probe"].ops[0];
885        assert!(op.interface_bound);
886        assert!(result_binding_names(op.result.as_ref()).contains("keys"));
887    }
888
889    #[test]
890    fn missing_results_binding_is_named_with_remedy() {
891        let mut blueprint = parse(RESULTS_BLUEPRINT);
892        let err = bind_implementation(
893            &mut blueprint,
894            parse(
895                r#"
896implements: blueprint
897phases:
898  probe:
899    ops:
900      search:
901        stmt: "SEARCH"
902"#,
903            ),
904        )
905        .unwrap_err();
906        assert!(
907            err.contains("results wire") && err.contains("keys") && err.contains("path-expr"),
908            "err: {err}"
909        );
910    }
911
912    #[test]
913    fn blueprint_side_path_for_results_wire_is_a_collision() {
914        let mut blueprint = parse(
915            r#"
916phases:
917  probe:
918    cycles: 1
919    ops:
920      search:
921        result:
922          keys: "rows[*].key"
923        abstract:
924          results:
925            keys: vec_i64
926"#,
927        );
928        let err = bind_implementation(
929            &mut blueprint,
930            parse(
931                r#"
932implements: blueprint
933phases:
934  probe:
935    ops:
936      search:
937        stmt: "SEARCH"
938        result:
939          keys: "other[*].id"
940"#,
941            ),
942        )
943        .unwrap_err();
944        assert!(err.contains("protocol matter"), "err: {err}");
945    }
946
947    #[test]
948    fn result_binding_name_collision_across_sides_is_an_error() {
949        // A NON-interface result wire declared by both sides is an
950        // ordinary collision.
951        let mut blueprint = parse(
952            r#"
953phases:
954  probe:
955    cycles: 1
956    ops:
957      search:
958        result:
959          row_count: count
960        abstract:
961          results:
962            keys: vec_i64
963"#,
964        );
965        let err = bind_implementation(
966            &mut blueprint,
967            parse(
968                r#"
969implements: blueprint
970phases:
971  probe:
972    ops:
973      search:
974        stmt: "SEARCH"
975        result:
976          row_count: count
977          keys: "rows[*].key"
978"#,
979            ),
980        )
981        .unwrap_err();
982        assert!(
983            err.contains("row_count") && err.contains("BOTH"),
984            "err: {err}"
985        );
986    }
987}