1use std::collections::BTreeSet;
20
21use crate::model::{BindingsDef, ParsedOp, Workload, WorkloadPhase};
22
23pub fn bind_implementation(
29 blueprint: &mut Workload,
30 implementation: Workload,
31) -> Result<(), String> {
32 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 let slot_provided = bindings_wire_names(&slot.bindings);
93 bind_slot(slot, impl_op, &slot_key)?;
94
95 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 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 concat_bindings(&mut blueprint.bindings, implementation.bindings)
150 .map_err(|e| format!("workload-level bindings: {e}"))?;
151
152 Ok(())
153}
154
155fn bind_slot(slot: &mut ParsedOp, impl_op: ParsedOp, slot_key: &str) -> Result<(), String> {
160 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 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 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 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
307fn 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
328fn 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
404fn 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
412fn 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
446pub 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 #[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 #[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 #[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 #[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 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 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 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}