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