1use std::collections::{BTreeMap, BTreeSet};
11use std::fmt;
12
13use rustev_contract::calibration::CalibrationArtifact;
14use rustev_contract::canonical::canonical_value_bytes;
15use rustev_contract::decimal::Decimal;
16use rustev_contract::definition::{
17 ArtifactPin, BindingChoice, CalibrationRef, Candidates, Cond, Definition, ExcessPolicy,
18 Fallback, Freshness, HandlerAction, InputDecl, ItemSource, Operation, OutcomeDecl, ParamSource,
19 ProvenanceClass, ReasonKind, ReasonSet, RequiredKind, SemanticDecl, StepBody, TypeDecl,
20 UncalibratedThreshold,
21};
22use rustev_contract::descriptor::{BackendDescriptor, InputExcess, OutputKind};
23use rustev_contract::execution::ExecutionPolicy;
24use rustev_contract::ids::{CalibrationId, DescriptorId, PlanId};
25use rustev_contract::judgment::{Derivation, Notice, NoticeKind};
26use rustev_contract::plan::{
27 BoundCalibration, Normalization, Plan, PlanExecution, PlanStep, PlanStepDetail,
28 SemanticBinding, StaticGrade,
29};
30use rustev_contract::source::SourceDescriptor;
31use rustev_contract::{Document, Identified, schema};
32use serde_json::json;
33
34use crate::calibrate;
35use crate::expr::{Ref, StepTy, TyEnv, predicate_refs, predicate_structure, type_predicate};
36use crate::ops::{self, OpArgs};
37use crate::quality;
38use crate::sem::SemKind;
39use crate::value::{Ty, Value};
40
41pub(crate) mod ranking;
42pub(crate) mod screening;
43
44pub const COMPILER: &str = concat!("rustev-core/", env!("CARGO_PKG_VERSION"));
46
47#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
49pub enum Category {
50 Parse = 1,
51 UnknownOperator = 2,
52 KindMismatch = 3,
53 Cycle = 4,
54 NoCapableBackend = 5,
55 UncalibratedThreshold = 6,
56 Budget = 7,
57 UnhandledUnresolved = 8,
58 InvalidFallback = 9,
59 CalibrationBinding = 10,
60 InvalidDefinition = 11,
61 InvalidExecution = 12,
63 GradeRequirement = 13,
66 UncorroboratedHint = 14,
69 SourceBinding = 15,
71 UncoveredProvenance = 16,
74 CallerCannotAct = 17,
77 InvalidScreening = 18,
79 UnscreenedText = 19,
81 InvalidAcquisition = 20,
82 SourceMapping = 21,
83 InvalidGeneration = 22,
84 Template = 23,
85 ModelOutputFlow = 24,
86 InvalidExtraction = 25,
87 InvalidAcceptance = 26,
88 UnacceptedModelValue = 27,
89 ExactOrderSource = 28,
90}
91
92#[derive(Debug, Clone, PartialEq, Eq)]
94pub enum ShortfallReason {
95 UnknownBackend,
96 OptionLogprobs,
97 RankMode,
98 MaxCandidates {
99 max: u64,
100 needed: u64,
101 },
102 ListwiseScores,
103 ScreenProfile,
104 ScreenTextLimit {
105 max: u64,
106 needed: u64,
107 },
108 ScreenInputExcess,
109 Operation(Operation),
110 OutputKind {
111 offered: OutputKind,
112 required: RequiredKind,
113 },
114 Options {
115 max: u64,
116 needed: u64,
117 },
118 InputLimit {
119 max: u64,
120 needed: u64,
121 },
122 Determinism {
123 offered: String,
124 required: String,
125 },
126 ArtifactPin {
127 pinned: String,
128 offered: String,
129 },
130 OutputLimit {
131 max: u64,
132 needed: u64,
133 },
134 Language {
135 required: String,
136 },
137}
138
139#[derive(Debug, Clone, PartialEq, Eq)]
140pub struct Shortfall {
141 pub backend_id: String,
142 pub reasons: Vec<ShortfallReason>,
143}
144
145#[derive(Debug, Clone, PartialEq, Eq)]
147pub struct Refusal {
148 pub category: Category,
149 pub subject: String,
151 pub detail: String,
152 pub shortfalls: Vec<Shortfall>,
154}
155
156impl fmt::Display for Refusal {
157 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
158 write!(
159 f,
160 "refused ({:?}, category {}) at {}: {}",
161 self.category, self.category as u8, self.subject, self.detail
162 )?;
163 for s in &self.shortfalls {
164 write!(f, "; {}: {:?}", s.backend_id, s.reasons)?;
165 }
166 Ok(())
167 }
168}
169
170impl std::error::Error for Refusal {}
171
172fn refuse<T>(
173 category: Category,
174 subject: impl Into<String>,
175 detail: impl Into<String>,
176) -> Result<T, Refusal> {
177 Err(Refusal {
178 category,
179 subject: subject.into(),
180 detail: detail.into(),
181 shortfalls: vec![],
182 })
183}
184
185#[derive(Debug, Clone)]
187pub(crate) enum StepInfo {
188 Ranking,
189 Generate,
190 Extract,
191 Accept(Box<rustev_contract::extraction::AcceptModelDerived>),
192 Acquisition(Box<crate::acquisition::Acquisition>),
193 Exact {
194 args: OpArgs,
195 ty: Ty,
196 },
197 Semantic {
198 decl: Box<SemanticDecl>,
199 kind: SemKind,
200 binding: Option<Box<SemanticBinding>>,
202 calibration: Option<(CalibrationArtifact, CalibrationId)>,
203 },
204 Corroborate {
206 decl: Box<rustev_contract::definition::CorroborateDecl>,
207 ty: Ty,
208 },
209}
210
211#[derive(Debug, Clone)]
212pub(crate) struct Info {
213 pub extraction_calibrations: Vec<CalibrationArtifact>,
214 pub screen_categories: BTreeMap<String, Vec<String>>,
215 pub generation: BTreeMap<String, crate::generation::Checked>,
216 pub inputs: BTreeMap<String, (Ty, InputDecl)>,
217 pub step_ids: Vec<String>,
219 pub steps: BTreeMap<String, StepInfo>,
220 pub deps: BTreeMap<String, Vec<String>>,
223 pub order: Vec<String>,
224 pub v2: bool,
226 #[allow(dead_code)] pub bound: quality::Bound,
229 #[allow(dead_code)] pub trees: BTreeMap<String, quality::Ceil>,
232 pub determinism: BTreeMap<String, rustev_contract::definition::Determinism>,
235}
236
237#[derive(Debug, Clone)]
239pub struct Compiled {
240 pub plan: Plan,
241 pub id: PlanId,
242 pub(crate) info: Info,
243}
244
245impl Compiled {
246 pub fn canonical(&self) -> Vec<u8> {
248 self.plan.canonical().unwrap_or_default()
250 }
251
252 pub fn load(
257 plan: &Plan,
258 descriptors: &[BackendDescriptor],
259 calibrations: &[CalibrationArtifact],
260 ) -> Result<Compiled, Refusal> {
261 Self::load_with_sources(plan, descriptors, calibrations, &[])
262 }
263
264 pub fn load_with_sources(
267 plan: &Plan,
268 descriptors: &[BackendDescriptor],
269 calibrations: &[CalibrationArtifact],
270 sources: &[SourceDescriptor],
271 ) -> Result<Compiled, Refusal> {
272 recompile(plan, descriptors, calibrations, sources).map_err(|e| match e {
273 Recompiled::Refused(r) => r,
274 Recompiled::Differs => Refusal {
275 category: Category::Parse,
276 subject: "plan".into(),
277 detail: "the plan document does not match its recompiled definition".into(),
278 shortfalls: vec![],
279 },
280 })
281 }
282
283 pub fn load_checked(
292 plan: &Plan,
293 descriptors: &[BackendDescriptor],
294 calibrations: &[CalibrationArtifact],
295 ) -> Result<Compiled, LoadError> {
296 Self::load_checked_with_sources(plan, descriptors, calibrations, &[])
297 }
298
299 pub fn load_checked_with_sources(
303 plan: &Plan,
304 descriptors: &[BackendDescriptor],
305 calibrations: &[CalibrationArtifact],
306 sources: &[SourceDescriptor],
307 ) -> Result<Compiled, LoadError> {
308 #[cfg(not(feature = "parameterized"))]
309 crate::unparameterized::plan(plan).map_err(|refusal| LoadError::PlanMismatch {
310 refusal: Some(refusal),
311 })?;
312 let registry_known = plan.registry == schema::EXACT_REGISTRY
315 || (plan.schema == schema::PLAN_V3 && plan.registry == schema::EXACT_REGISTRY_V2);
316 if plan.compiler != COMPILER || !registry_known {
317 return Err(LoadError::CompilerChanged {
318 recorded_compiler: plan.compiler.clone(),
319 current_compiler: COMPILER,
320 recorded_registry: plan.registry.clone(),
321 current_registry: schema::EXACT_REGISTRY,
322 });
323 }
324 let have_d: BTreeSet<DescriptorId> =
325 descriptors.iter().filter_map(|d| d.id().ok()).collect();
326 let have_c: BTreeSet<CalibrationId> =
327 calibrations.iter().filter_map(|c| c.id().ok()).collect();
328 let mut needed: Vec<(String, &DescriptorId)> = vec![];
329 for step in &plan.steps {
330 if let PlanStepDetail::Extract(b) = &step.detail {
331 needed.push((b.backend_id.clone(), &b.descriptor));
332 }
333 if let PlanStepDetail::Rank(b) = &step.detail {
334 needed.push((b.backend_id.clone(), &b.descriptor));
335 }
336 if let PlanStepDetail::Generate(b) = &step.detail {
337 needed.push((b.backend_id.clone(), &b.descriptor));
338 }
339 if let PlanStepDetail::Semantic(b) = &step.detail {
340 needed.push((b.backend_id.clone(), &b.descriptor));
341 if let BoundCalibration::Bound { id, .. } = &b.calibration
342 && !have_c.contains(id)
343 {
344 return Err(LoadError::MissingCalibration {
345 step: step.id.clone(),
346 calibration: id.clone(),
347 });
348 }
349 }
350 }
351 if let PlanExecution::Declared(d) = &plan.execution {
352 needed.extend(
353 d.fallbacks
354 .iter()
355 .map(|f| (f.backend_id.clone(), &f.descriptor)),
356 );
357 }
358 for (backend_id, descriptor) in needed {
359 if !have_d.contains(descriptor) {
360 return Err(LoadError::MissingDescriptor {
361 backend_id,
362 descriptor: descriptor.clone(),
363 });
364 }
365 }
366 recompile(plan, descriptors, calibrations, sources).map_err(|e| LoadError::PlanMismatch {
367 refusal: match e {
368 Recompiled::Refused(r) => Some(r),
369 Recompiled::Differs => None,
370 },
371 })
372 }
373}
374
375#[derive(Debug, Clone, PartialEq, Eq)]
377pub enum LoadError {
378 CompilerChanged {
380 recorded_compiler: String,
381 current_compiler: &'static str,
382 recorded_registry: String,
383 current_registry: &'static str,
384 },
385 MissingDescriptor {
387 backend_id: String,
388 descriptor: DescriptorId,
389 },
390 MissingCalibration {
392 step: String,
393 calibration: CalibrationId,
394 },
395 PlanMismatch { refusal: Option<Refusal> },
398}
399
400impl fmt::Display for LoadError {
401 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
402 match self {
403 LoadError::CompilerChanged {
404 recorded_compiler,
405 current_compiler,
406 recorded_registry,
407 current_registry,
408 } => write!(
409 f,
410 "compiler changed: recorded {recorded_compiler} ({recorded_registry}), \
411 current {current_compiler} ({current_registry})"
412 ),
413 LoadError::MissingDescriptor {
414 backend_id,
415 descriptor,
416 } => write!(f, "descriptor {descriptor} of {backend_id} not supplied"),
417 LoadError::MissingCalibration { step, calibration } => {
418 write!(f, "calibration {calibration} of step {step} not supplied")
419 }
420 LoadError::PlanMismatch { refusal: Some(r) } => {
421 write!(f, "plan does not recompile: {r}")
422 }
423 LoadError::PlanMismatch { refusal: None } => {
424 f.write_str("plan does not match its recompiled definition")
425 }
426 }
427 }
428}
429
430impl std::error::Error for LoadError {}
431
432enum Recompiled {
433 Refused(Refusal),
434 Differs,
435}
436
437fn recompile(
439 plan: &Plan,
440 descriptors: &[BackendDescriptor],
441 calibrations: &[CalibrationArtifact],
442 sources: &[SourceDescriptor],
443) -> Result<Compiled, Recompiled> {
444 let execution = match &plan.execution {
445 PlanExecution::None => None,
446 PlanExecution::Declared(d) => Some(&d.policy),
447 };
448 #[cfg(not(feature = "parameterized"))]
449 crate::unparameterized::plan(plan).map_err(Recompiled::Refused)?;
450 #[cfg(feature = "parameterized")]
451 if let Some(record) = &plan.instantiation {
452 crate::instantiate::validate_record(plan, record).map_err(|detail| {
453 Recompiled::Refused(Refusal {
454 category: Category::Parse,
455 subject: "plan".into(),
456 detail,
457 shortfalls: vec![],
458 })
459 })?;
460 }
461 let templates: Vec<_> = plan
462 .steps
463 .iter()
464 .filter_map(|s| match &s.detail {
465 PlanStepDetail::Generate(g) => Some(g.template.clone()),
466 PlanStepDetail::Extract(e) => Some(e.template.clone()),
467 _ => None,
468 })
469 .collect();
470 let programs: Vec<_> = plan
471 .steps
472 .iter()
473 .filter_map(|s| match &s.detail {
474 PlanStepDetail::Extract(e) => match &e.fallback {
475 rustev_contract::extraction_results::BoundExtractionFallback::Bound {
476 program,
477 ..
478 } => Some((**program).clone()),
479 _ => None,
480 },
481 _ => None,
482 })
483 .collect();
484 let mut c = compile_generation(
485 &plan.definition,
486 descriptors,
487 calibrations,
488 sources,
489 execution,
490 plan.instantiation.is_some(),
491 (&templates, &programs),
492 )
493 .map_err(Recompiled::Refused)?;
494 #[cfg(feature = "parameterized")]
495 {
496 c.plan.instantiation = plan.instantiation.clone();
497 }
498 c.id = c.plan.id().map_err(|e| {
499 Recompiled::Refused(Refusal {
500 category: Category::Parse,
501 subject: "plan".into(),
502 detail: e.to_string(),
503 shortfalls: vec![],
504 })
505 })?;
506 if plan.canonical().ok() != Some(c.canonical()) {
507 #[cfg(feature = "parameterized")]
508 if plan.instantiation.is_some() {
509 return Err(Recompiled::Refused(Refusal {
510 category: Category::Parse,
511 subject: "plan".into(),
512 detail: "instantiated plan differs from its recompilation".into(),
513 shortfalls: vec![],
514 }));
515 }
516 return Err(Recompiled::Differs);
517 }
518 Ok(c)
519}
520
521pub fn compile_bytes(
523 bytes: &[u8],
524 descriptors: &[BackendDescriptor],
525 calibrations: &[CalibrationArtifact],
526) -> Result<Compiled, Refusal> {
527 #[cfg(not(feature = "parameterized"))]
528 crate::unparameterized::definition(bytes)?;
529 let def = Definition::parse(bytes).map_err(|e| {
530 ranking::parse_refusal(bytes, &e).unwrap_or_else(|| Refusal {
531 category: Category::Parse,
532 subject: "definition".into(),
533 detail: e.to_string(),
534 shortfalls: vec![],
535 })
536 })?;
537 compile(&def, descriptors, calibrations)
538}
539
540fn step_ref(r: &str) -> Option<&str> {
541 r.strip_prefix("step:")
542}
543
544fn is_semver(v: &str) -> bool {
545 let parts: Vec<&str> = v.split('.').collect();
546 parts.len() == 3
547 && parts.iter().all(|p| {
548 !p.is_empty()
549 && p.bytes().all(|b| b.is_ascii_digit())
550 && (p.len() == 1 || !p.starts_with('0'))
551 })
552}
553
554fn valid_name(s: &str) -> bool {
555 !s.is_empty() && !s.contains(':') && !s.chars().any(char::is_whitespace)
556}
557
558fn check_type_decl(t: &TypeDecl) -> Result<(), String> {
559 match t {
560 TypeDecl::Text { max_bytes } if *max_bytes == 0 => {
561 Err("text max_bytes must be positive".into())
562 }
563 TypeDecl::Enum { options } => {
564 let set: BTreeSet<_> = options.iter().collect();
565 if options.is_empty()
566 || set.len() != options.len()
567 || options.iter().any(String::is_empty)
568 {
569 Err("enum options must be non-empty and unique".into())
570 } else {
571 Ok(())
572 }
573 }
574 TypeDecl::List { item, .. } => check_type_decl(item),
575 TypeDecl::Nullable { ty } => check_type_decl(ty),
576 TypeDecl::Map { value, .. } => check_type_decl(value),
577 TypeDecl::Record { fields, .. } => {
578 let set: BTreeSet<_> = fields.iter().map(|f| &f.name).collect();
579 if fields.is_empty()
580 || set.len() != fields.len()
581 || fields.iter().any(|f| f.name.is_empty())
582 {
583 return Err("record fields must be non-empty and unique".into());
584 }
585 fields.iter().try_for_each(|f| check_type_decl(&f.ty))
586 }
587 _ => Ok(()),
588 }
589}
590
591fn kind_valid_for(op: Operation, required: RequiredKind) -> bool {
593 use RequiredKind as R;
594 match op {
595 Operation::Classify => matches!(
596 required,
597 R::Label | R::Distribution | R::CalibratedProbability
598 ),
599 Operation::Proposition => matches!(
600 required,
601 R::Label | R::Distribution | R::CalibratedProbability
602 ),
603 Operation::Rubric => matches!(required, R::Label | R::OrdinalDistribution),
604 Operation::Rank => matches!(required, R::Scores),
605 Operation::Generate | Operation::Extract => false,
606 }
607}
608
609fn satisfies(output: OutputKind, required: RequiredKind) -> bool {
610 use OutputKind as O;
611 use RequiredKind as R;
612 match required {
613 R::Ranking => false,
614 R::ScreenVerdict => output == O::Screen,
615 R::TextRecord | R::TypedRecord => false,
616 R::Label => output == O::Label,
617 R::Distribution | R::CalibratedProbability | R::OrdinalDistribution => {
618 matches!(output, O::Distribution | O::Logits)
619 }
620 R::Scores => matches!(output, O::Scores | O::Logits),
621 }
622}
623
624fn sem_kind(op: Operation, required: RequiredKind) -> SemKind {
625 match (op, required) {
626 (_, RequiredKind::Ranking) => SemKind::Label,
631 (Operation::Rubric, RequiredKind::Label) => SemKind::Ordinal(false),
632 (_, RequiredKind::ScreenVerdict | RequiredKind::TextRecord | RequiredKind::TypedRecord) => {
636 SemKind::Label
637 }
638 (_, RequiredKind::Label) => SemKind::Label,
639 (_, RequiredKind::Distribution) => SemKind::Distribution,
640 (_, RequiredKind::CalibratedProbability) => SemKind::Calibrated,
641 (_, RequiredKind::OrdinalDistribution) => SemKind::Ordinal(true),
642 (_, RequiredKind::Scores) => SemKind::Scores,
643 }
644}
645
646pub(crate) fn check_candidate(
650 d: &SemanticDecl,
651 b: &BackendDescriptor,
652 required: RequiredKind,
653 options_needed: u64,
654 bound: u64,
655) -> Result<OutputKind, Vec<ShortfallReason>> {
656 let mut reasons = Vec::new();
657 let supports: Vec<_> = b
658 .operations
659 .iter()
660 .filter(|o| o.operation == d.operation)
661 .collect();
662 if supports.is_empty() {
663 reasons.push(ShortfallReason::Operation(d.operation));
664 }
665 let chosen = supports.iter().find(|o| {
666 satisfies(o.output.clone(), required)
667 && (required != RequiredKind::ScreenVerdict || d.operation == Operation::Proposition)
668 });
669 match (chosen, supports.first()) {
670 (None, Some(o)) => reasons.push(ShortfallReason::OutputKind {
671 offered: o.output.clone(),
672 required,
673 }),
674 (Some(o), _) if o.max_options < options_needed => reasons.push(ShortfallReason::Options {
675 max: o.max_options,
676 needed: options_needed,
677 }),
678 _ => {}
679 }
680 if bound > b.input_limit.max_bytes && b.input_limit.on_excess == InputExcess::Refuse {
681 reasons.push(ShortfallReason::InputLimit {
682 max: b.input_limit.max_bytes,
683 needed: bound,
684 });
685 }
686 if b.determinism < d.backend.min_determinism {
687 reasons.push(ShortfallReason::Determinism {
688 offered: format!("{:?}", b.determinism),
689 required: format!("{:?}", d.backend.min_determinism),
690 });
691 }
692 if let ArtifactPin::Pinned(a) = &d.backend.artifact
693 && a != &b.artifact
694 {
695 reasons.push(ShortfallReason::ArtifactPin {
696 pinned: a.to_string(),
697 offered: b.artifact.to_string(),
698 });
699 }
700 match chosen {
701 Some(o) if reasons.is_empty() => Ok(o.output.clone()),
702 _ => Err(reasons),
703 }
704}
705
706pub(crate) fn condition_refs(c: &Cond, out: &mut Vec<String>) {
707 match c {
708 Cond::Always => {}
709 Cond::TopLabel { step, .. }
710 | Cond::MassAtLeast { step, .. }
711 | Cond::TopMassBelow { step, .. }
712 | Cond::ExpectationAtLeast { step, .. } => out.push(format!("step:{step}")),
713 Cond::Exact(p) => predicate_refs(p, out),
714 Cond::Empty(r) | Cond::Nonempty(r) => out.push(r.clone()),
715 Cond::All(cs) | Cond::Any(cs) => cs.iter().for_each(|c| condition_refs(c, out)),
716 Cond::Not(c) => condition_refs(c, out),
717 Cond::ProvenanceWithin { reference, .. } => out.push(reference.clone()),
718 }
719}
720
721pub(crate) fn outcome_refs(o: &OutcomeDecl, out: &mut Vec<String>) {
722 match o {
723 OutcomeDecl::Propose { params, .. } => {
724 for p in params {
725 if let ParamSource::Ref(r) = &p.value {
726 out.push(r.clone());
727 }
728 }
729 }
730 OutcomeDecl::Escalate { .. } => {}
731 OutcomeDecl::MissingEvidenceFrom { step } => out.push(format!("step:{step}")),
732 OutcomeDecl::NeedsInput { .. } => {}
737 }
738}
739
740pub fn compile(
744 def: &Definition,
745 descriptors: &[BackendDescriptor],
746 calibrations: &[CalibrationArtifact],
747) -> Result<Compiled, Refusal> {
748 compile_inner(def, descriptors, calibrations, &[], None)
749}
750
751pub fn compile_with_sources(
756 def: &Definition,
757 descriptors: &[BackendDescriptor],
758 calibrations: &[CalibrationArtifact],
759 sources: &[SourceDescriptor],
760 execution: Option<&ExecutionPolicy>,
761) -> Result<Compiled, Refusal> {
762 compile_inner(def, descriptors, calibrations, sources, execution)
763}
764
765pub fn compile_with(
769 def: &Definition,
770 descriptors: &[BackendDescriptor],
771 calibrations: &[CalibrationArtifact],
772 execution: &ExecutionPolicy,
773) -> Result<Compiled, Refusal> {
774 compile_inner(def, descriptors, calibrations, &[], Some(execution))
775}
776
777fn compile_inner(
778 def: &Definition,
779 descriptors: &[BackendDescriptor],
780 calibrations: &[CalibrationArtifact],
781 sources: &[SourceDescriptor],
782 execution: Option<&ExecutionPolicy>,
783) -> Result<Compiled, Refusal> {
784 compile_instantiated(def, descriptors, calibrations, sources, execution, false)
785}
786
787pub(crate) fn compile_instantiated(
789 def: &Definition,
790 descriptors: &[BackendDescriptor],
791 calibrations: &[CalibrationArtifact],
792 sources: &[SourceDescriptor],
793 execution: Option<&ExecutionPolicy>,
794 #[cfg_attr(not(feature = "parameterized"), allow(unused_variables))] instantiated: bool,
795) -> Result<Compiled, Refusal> {
796 compile_generation(
797 def,
798 descriptors,
799 calibrations,
800 sources,
801 execution,
802 instantiated,
803 (&[], &[]),
804 )
805}
806
807pub fn compile_with_templates(
809 def: &Definition,
810 descriptors: &[BackendDescriptor],
811 calibrations: &[CalibrationArtifact],
812 sources: &[SourceDescriptor],
813 execution: Option<&ExecutionPolicy>,
814 templates: &[rustev_contract::generation::PromptTemplate],
815) -> Result<Compiled, Refusal> {
816 compile_generation(
817 def,
818 descriptors,
819 calibrations,
820 sources,
821 execution,
822 false,
823 (templates, &[]),
824 )
825}
826
827pub fn compile_with_extraction_documents(
830 def: &Definition,
831 descriptors: &[BackendDescriptor],
832 calibrations: &[CalibrationArtifact],
833 sources: &[SourceDescriptor],
834 execution: Option<&ExecutionPolicy>,
835 templates: &[rustev_contract::generation::PromptTemplate],
836 programs: &[rustev_contract::extraction_documents::ExtractRules],
837) -> Result<Compiled, Refusal> {
838 compile_generation(
839 def,
840 descriptors,
841 calibrations,
842 sources,
843 execution,
844 false,
845 (templates, programs),
846 )
847}
848
849fn compile_generation(
850 def: &Definition,
851 descriptors: &[BackendDescriptor],
852 calibrations: &[CalibrationArtifact],
853 sources: &[SourceDescriptor],
854 execution: Option<&ExecutionPolicy>,
855 instantiated: bool,
856 documents: (
857 &[rustev_contract::generation::PromptTemplate],
858 &[rustev_contract::extraction_documents::ExtractRules],
859 ),
860) -> Result<Compiled, Refusal> {
861 #[cfg(not(feature = "parameterized"))]
862 let _ = instantiated;
863 use Category as C;
864 let (templates, programs) = documents;
865
866 #[cfg(not(feature = "parameterized"))]
870 crate::unparameterized::typed_definition(def)?;
871 let v2 = def.schema == schema::DEFINITION_V2;
872 if def.schema != schema::DEFINITION && !v2 {
873 return refuse(
874 C::Parse,
875 "definition",
876 format!(
877 "schema {:?} is neither {} nor {}",
878 def.schema,
879 schema::DEFINITION,
880 schema::DEFINITION_V2
881 ),
882 );
883 }
884 let decode = if v2 { ops::decode_v2 } else { ops::decode };
885 let mut decoded: BTreeMap<String, OpArgs> = BTreeMap::new();
886 for s in &def.steps {
887 if let StepBody::Exact(e) = &s.body {
888 match decode(&e.op, e.version, &e.args) {
889 Some(Ok(a)) => {
890 decoded.insert(s.id.clone(), a);
891 }
892 Some(Err(msg)) => {
893 return refuse(
894 C::Parse,
895 format!("step:{}", s.id),
896 format!("arguments of {}@{}: {msg}", e.op, e.version),
897 );
898 }
899 None => {}
900 }
901 }
902 }
903 for d in descriptors {
904 if d.schema != schema::BACKEND {
905 return refuse(
906 C::Parse,
907 format!("backend:{}", d.backend_id),
908 "descriptor schema is not rustev.backend/1",
909 );
910 }
911 }
912 for c in calibrations {
913 if c.schema != schema::CALIBRATION {
914 return refuse(
915 C::Parse,
916 "calibration",
917 "calibration schema is not rustev.calibration/1",
918 );
919 }
920 }
921
922 if def
923 .limits
924 .acquisition
925 .as_ref()
926 .is_some_and(|b| !(1..=4096).contains(&b.max_calls))
927 {
928 return refuse(C::Parse, "limits", "acquisition.max_calls outside 1..=4096");
929 }
930 if !v2 && def.limits.acquisition.is_some() {
931 return refuse(
932 C::InvalidDefinition,
933 "limits",
934 "requires-definition-2: acquisition budget",
935 );
936 }
937 if !v2 && def.screening.is_some() {
939 return refuse(
940 C::InvalidDefinition,
941 "screening",
942 "requires-definition-2: screening needs rustev.definition/2",
943 );
944 }
945 for s in &def.steps {
947 if let StepBody::Semantic(d) = &s.body
948 && d.requires == RequiredKind::ScreenVerdict
949 {
950 return refuse(
951 C::InvalidDefinition,
952 format!("step:{}", s.id),
953 "screen_verdict is reserved for lowered screening steps",
954 );
955 }
956 }
957 for s in &def.steps {
962 if !v2
963 && matches!(
964 s.body,
965 StepBody::Acquire(_)
966 | StepBody::Widen(_)
967 | StepBody::Generate(_)
968 | StepBody::Extract(_)
969 | StepBody::AcceptModelDerived(_)
970 | StepBody::Rank(_)
971 | StepBody::Select(_)
972 )
973 {
974 return refuse(
975 C::InvalidDefinition,
976 format!("step:{}", s.id),
977 "requires-definition-2",
978 );
979 }
980 }
981 ranking::structure(def, &decoded)?;
982 for s in &def.steps {
983 crate::acquisition::structure(&s.id, &s.body)?;
984 }
985 if !v2
986 && def.policy.on_unresolved.iter().any(|h| {
987 matches!(&h.reasons,
988 ReasonSet::Only(rs) if rs.contains(&ReasonKind::Skipped))
989 })
990 {
991 return refuse(
992 C::InvalidDefinition,
993 "policy",
994 "requires-definition-2: skipped",
995 );
996 }
997 if !v2 && let Some((subject, construct)) = crate::actionable::first_construct(def) {
1000 return refuse(
1001 C::InvalidDefinition,
1002 subject,
1003 format!(
1004 "requires-definition-2: {construct} needs {}",
1005 schema::DEFINITION_V2
1006 ),
1007 );
1008 }
1009 if v2 {
1013 let decision_cache = execution
1017 .and_then(|e| e.optimization.as_ref())
1018 .is_some_and(|o| o.decision_cache.is_some());
1019 #[cfg(feature = "parameterized")]
1020 let construct_elsewhere = instantiated || decision_cache;
1021 #[cfg(not(feature = "parameterized"))]
1022 let construct_elsewhere = decision_cache;
1023 quality::structure_with_origin(def, &decoded, construct_elsewhere)?;
1024 } else if let Some((subject, construct)) = first_v2_construct(def, &decoded) {
1025 return refuse(
1026 C::InvalidDefinition,
1027 subject,
1028 format!(
1029 "requires_definition_2: {construct} needs {}",
1030 schema::DEFINITION_V2
1031 ),
1032 );
1033 }
1034 crate::generation::isolation(def, execution)?;
1035 crate::generation::structure(def)?;
1036 crate::extraction_compile::structure(def)?;
1037 let mut backend_ids = BTreeSet::new();
1039 for d in descriptors {
1040 if !backend_ids.insert(d.backend_id.as_str()) {
1041 return refuse(
1042 C::InvalidDefinition,
1043 format!("backend:{}", d.backend_id),
1044 "two descriptors share a backend id",
1045 );
1046 }
1047 }
1048 let inv = |subject: String, detail: String| -> Result<(), Refusal> {
1049 refuse(C::InvalidDefinition, subject, detail)
1050 };
1051 if def.name.is_empty() || def.package.is_empty() {
1052 inv(
1053 "definition".into(),
1054 "name and package must be non-empty".into(),
1055 )?;
1056 }
1057 if !is_semver(&def.version) {
1058 inv(
1059 "definition".into(),
1060 format!("version {:?} is not MAJOR.MINOR.PATCH", def.version),
1061 )?;
1062 }
1063 let mut inputs: BTreeMap<String, (Ty, InputDecl)> = BTreeMap::new();
1064 for i in &def.inputs {
1065 let subject = format!("input:{}", i.name);
1066 if !valid_name(&i.name) || inputs.contains_key(&i.name) {
1067 inv(
1068 subject.clone(),
1069 "input names must be unique, non-empty, without ':' or whitespace".into(),
1070 )?;
1071 }
1072 let classes: BTreeSet<_> = i.provenance.iter().collect();
1073 if i.provenance.is_empty() || classes.len() != i.provenance.len() {
1074 inv(
1075 subject.clone(),
1076 "accepted provenance classes must be non-empty and unique".into(),
1077 )?;
1078 }
1079 check_type_decl(&i.ty).or_else(|e| inv(subject, e))?;
1080 inputs.insert(i.name.clone(), (Ty::from_decl(&i.ty), i.clone()));
1081 }
1082 let ids: Vec<String> = def.steps.iter().map(|s| s.id.clone()).collect();
1083 let known = |r: &str| -> Result<(), String> {
1084 match Ref::parse(r)? {
1085 Ref::Input(n, _) if !inputs.contains_key(&n) => Err(format!("unknown input {n:?}")),
1086 Ref::Step(n) if v2 && !ids.contains(&crate::expr::split_step(&n).0) => {
1088 Err(format!("unknown step {n:?}"))
1089 }
1090 Ref::Step(n) if !v2 && !ids.contains(&n) => Err(format!("unknown step {n:?}")),
1091 _ => Ok(()),
1092 }
1093 };
1094 let ranking_kinds: BTreeSet<&str> = def
1095 .steps
1096 .iter()
1097 .filter(|s| matches!(s.body, StepBody::Rank(_) | StepBody::Select(_)))
1098 .map(|s| s.id.as_str())
1099 .collect();
1100 let mut options_of: BTreeMap<String, Vec<String>> = def
1101 .steps
1102 .iter()
1103 .filter_map(|s| {
1104 if let StepBody::Semantic(d) = &s.body {
1105 Some((s.id.clone(), d.options.clone()))
1106 } else {
1107 None
1108 }
1109 })
1110 .collect();
1111 options_of.extend(crate::extraction_compile::distribution_options(def));
1112 for (i, s) in def.steps.iter().enumerate() {
1113 let subject = format!("step:{}", s.id);
1114 if !valid_name(&s.id) || ids[..i].contains(&s.id) {
1115 inv(
1116 subject.clone(),
1117 "step ids must be unique, non-empty, without ':' or whitespace".into(),
1118 )?;
1119 }
1120 match &s.body {
1121 StepBody::Extract(_) | StepBody::AcceptModelDerived(_) => {
1122 }
1124 StepBody::Rank(_) | StepBody::Select(_) => {
1125 for r in ranking::refs(&s.body) {
1126 known(&r).or_else(|e| inv(subject.clone(), e))?;
1127 }
1128 }
1129 StepBody::Generate(_) => {}
1130 StepBody::Acquire(_) | StepBody::Widen(_) => {
1133 for r in crate::acquisition::refs(&s.body) {
1134 known(&r).or_else(|e| inv(subject.clone(), e))?;
1135 }
1136 }
1137 StepBody::Corroborate(c) => {
1138 let mut refs = vec![c.claim.clone()];
1139 c.by.iter()
1140 .for_each(|k| predicate_refs(&k.predicate, &mut refs));
1141 for r in refs {
1142 known(&r).or_else(|e| inv(subject.clone(), e))?;
1143 }
1144 }
1145 StepBody::Exact(_) => {
1146 if let Some(a) = decoded.get(&s.id) {
1147 a.structure().or_else(|e| inv(subject.clone(), e))?;
1148 for r in a.all_ref_strings() {
1149 known(&r).or_else(|e| inv(subject.clone(), e))?;
1150 }
1151 }
1152 }
1153 StepBody::Semantic(d) => {
1154 if d.task.is_empty() || d.question.is_empty() {
1155 inv(
1156 subject.clone(),
1157 "task and question must be non-empty".into(),
1158 )?;
1159 }
1160 let set: BTreeSet<_> = d.options.iter().collect();
1161 if set.len() != d.options.len() || d.options.iter().any(String::is_empty) {
1162 inv(
1163 subject.clone(),
1164 "options must be unique and non-empty".into(),
1165 )?;
1166 }
1167 match d.operation {
1168 Operation::Classify if d.options.len() < 2 => inv(
1169 subject.clone(),
1170 "classify needs at least two options".into(),
1171 )?,
1172 Operation::Proposition if d.options != ["false", "true"] => inv(
1173 subject.clone(),
1174 "proposition options must be [\"false\", \"true\"]".into(),
1175 )?,
1176 Operation::Rubric if d.options.len() < 2 => {
1177 inv(subject.clone(), "rubric needs at least two levels".into())?
1178 }
1179 Operation::Rank if !d.options.is_empty() => {
1180 inv(subject.clone(), "rank takes candidates, not options".into())?
1181 }
1182 _ => {}
1183 }
1184 match (&d.candidates, d.operation) {
1185 (Candidates::From(r), Operation::Rank) => {
1186 if step_ref(r).is_none() {
1187 inv(subject.clone(), format!("candidates {r:?} must be a step"))?;
1188 }
1189 known(r).or_else(|e| inv(subject.clone(), e))?;
1190 }
1191 (Candidates::None, Operation::Rank) => {
1192 inv(subject.clone(), "rank needs candidates".into())?
1193 }
1194 (Candidates::From(_), _) => {
1195 inv(subject.clone(), "only rank takes candidates".into())?
1196 }
1197 (Candidates::None, _) => {}
1198 }
1199 if !kind_valid_for(d.operation, d.requires) {
1200 inv(
1201 subject.clone(),
1202 format!("{:?} cannot require {:?}", d.operation, d.requires),
1203 )?;
1204 }
1205 if d.for_each.len() > 2 {
1206 inv(subject.clone(), "at most two fan-out indices".into())?;
1207 }
1208 let mut binds = BTreeSet::new();
1209 for f in &d.for_each {
1210 if !valid_name(&f.bind) || !binds.insert(f.bind.clone()) {
1211 inv(
1212 subject.clone(),
1213 format!("bind {:?} must be unique and valid", f.bind),
1214 )?;
1215 }
1216 if step_ref(&f.over).is_none() {
1217 inv(
1218 subject.clone(),
1219 format!("for_each over {:?} must be a step", f.over),
1220 )?;
1221 }
1222 known(&f.over).or_else(|e| inv(subject.clone(), e))?;
1223 if let ItemSource::List { list, .. } = &f.items {
1224 known(list).or_else(|e| inv(subject.clone(), e))?;
1225 }
1226 }
1227 for r in &d.project {
1228 match Ref::parse(r) {
1229 Ok(Ref::Bind(b)) if !binds.contains(&b) => {
1230 inv(subject.clone(), format!("unknown bind {b:?}"))?
1231 }
1232 Ok(Ref::Bind(_)) => {}
1233 Ok(Ref::Input(_, p)) if p.is_empty() => {
1234 known(r).or_else(|e| inv(subject.clone(), e))?
1235 }
1236 Ok(Ref::Step(_)) => known(r).or_else(|e| inv(subject.clone(), e))?,
1237 Ok(_) => inv(subject.clone(), format!("{r:?} cannot be projected"))?,
1238 Err(e) => inv(subject.clone(), e)?,
1239 }
1240 }
1241 if matches!(d.calibration, CalibrationRef::Id(_))
1242 && d.requires != RequiredKind::CalibratedProbability
1243 {
1244 inv(
1245 subject.clone(),
1246 "a calibration is bound only to a calibrated_probability step".into(),
1247 )?;
1248 }
1249 if let BindingChoice::Backend(b) = &d.backend.binding
1250 && b.is_empty()
1251 {
1252 inv(subject.clone(), "binding names no backend".into())?;
1253 }
1254 if let Fallback::Kind { reason, .. } = &d.fallback
1255 && reason.is_empty()
1256 {
1257 inv(subject.clone(), "a fallback states its reason".into())?;
1258 }
1259 }
1260 }
1261 }
1262 if def.limits.distribution_tolerance <= Decimal::ZERO
1263 || def.limits.distribution_tolerance > Decimal::parse("0.1").unwrap_or(Decimal::ZERO)
1264 {
1265 inv(
1266 "limits".into(),
1267 "distribution_tolerance must be in (0, 0.1]".into(),
1268 )?;
1269 }
1270 let policy = &def.policy;
1272 for (i, h) in policy.on_unresolved.iter().enumerate() {
1273 let subject = format!("policy:on_unresolved[{i}]");
1274 match Ref::parse(&h.target) {
1275 Ok(Ref::Input(_, p)) if p.is_empty() => {
1276 known(&h.target).or_else(|e| inv(subject.clone(), e))?
1277 }
1278 Ok(Ref::Step(_)) => known(&h.target).or_else(|e| inv(subject.clone(), e))?,
1279 _ => inv(
1280 subject.clone(),
1281 format!("handler target {:?} must be an input or step", h.target),
1282 )?,
1283 }
1284 if matches!(&h.reasons, ReasonSet::Only(v) if v.is_empty()) {
1285 inv(subject.clone(), "handler covers no reason".into())?;
1286 }
1287 if matches!(&h.action, HandlerAction::Escalate { reason } if reason.is_empty()) {
1288 inv(subject, "an escalation states its reason".into())?;
1289 }
1290 }
1291 let mut rule_ids = BTreeSet::new();
1292 let mut proposed_params: BTreeSet<String> = BTreeSet::new();
1293 for r in &policy.rules {
1294 let subject = format!("policy:rule:{}", r.id);
1295 if !valid_name(&r.id) || !rule_ids.insert(r.id.clone()) {
1296 inv(subject.clone(), "rule ids must be unique and valid".into())?;
1297 }
1298 cond_structure(&r.when, &options_of, &known, &ranking_kinds)
1299 .or_else(|e| inv(subject.clone(), e))?;
1300 let mut refs = Vec::new();
1301 outcome_refs(&r.then, &mut refs);
1302 for x in &refs {
1303 known(x).or_else(|e| inv(subject.clone(), e))?;
1304 }
1305 match &r.then {
1306 OutcomeDecl::Propose { action, params } => {
1307 let names: BTreeSet<_> = params.iter().map(|p| &p.name).collect();
1308 if action.is_empty()
1309 || names.len() != params.len()
1310 || params.iter().any(|p| p.name.is_empty())
1311 {
1312 inv(
1313 subject.clone(),
1314 "a proposal has an action and unique parameter names".into(),
1315 )?;
1316 }
1317 proposed_params.extend(params.iter().map(|p| p.name.clone()));
1318 }
1319 OutcomeDecl::Escalate { reason } if reason.is_empty() => {
1320 inv(subject.clone(), "an escalation states its reason".into())?
1321 }
1322 _ => {}
1323 }
1324 }
1325 match policy.rules.last() {
1326 Some(r) if r.when == Cond::Always => {}
1327 _ => inv(
1328 "policy".into(),
1329 "the last rule's condition must be `always`".into(),
1330 )?,
1331 }
1332 let mut adj_ids = BTreeSet::new();
1333 for a in &policy.adjustments {
1334 let subject = format!("policy:adjustment:{}", a.id);
1335 if !valid_name(&a.id) || !adj_ids.insert(a.id.clone()) {
1336 inv(
1337 subject.clone(),
1338 "adjustment ids must be unique and valid".into(),
1339 )?;
1340 }
1341 let scale: BTreeSet<_> = a.scale.iter().collect();
1342 if a.scale.len() < 2 || scale.len() != a.scale.len() {
1343 inv(
1344 subject.clone(),
1345 "a scale has at least two unique positions".into(),
1346 )?;
1347 }
1348 if !proposed_params.contains(&a.param) {
1349 inv(
1350 subject.clone(),
1351 format!("no proposal has parameter {:?}", a.param),
1352 )?;
1353 }
1354 cond_structure(&a.when, &options_of, &known, &ranking_kinds)
1355 .or_else(|e| inv(subject, e))?;
1356 }
1357 if v2 {
1360 let mut taken: BTreeSet<String> = ids.iter().cloned().collect();
1361 taken.extend(rule_ids.iter().cloned());
1362 taken.extend(adj_ids.iter().cloned());
1363 crate::actionable::structure(def, &inputs, &taken)?;
1364 }
1365
1366 let authored = def;
1367 let screens = screening::validate(def)?;
1368 let lowered = screening::lower(def, &screens, &mut decoded);
1369 let def = &lowered;
1370 let ids: Vec<String> = def.steps.iter().map(|s| s.id.clone()).collect();
1371
1372 let calibration_ids: Vec<(CalibrationId, &CalibrationArtifact)> = calibrations
1374 .iter()
1375 .map(|c| c.id().map(|id| (id, c)))
1376 .collect::<Result<_, _>>()
1377 .map_err(|e| Refusal {
1378 category: C::Parse,
1379 subject: "calibration".into(),
1380 detail: e.to_string(),
1381 shortfalls: vec![],
1382 })?;
1383 let mut resolved_cal: BTreeMap<String, (CalibrationArtifact, CalibrationId)> = BTreeMap::new();
1384 for s in &def.steps {
1385 let subject = format!("step:{}", s.id);
1386 match &s.body {
1387 StepBody::Extract(_) | StepBody::AcceptModelDerived(_) => {
1388 }
1390 StepBody::Rank(_) | StepBody::Select(_) => {}
1391 StepBody::Generate(_) => {}
1392 StepBody::Acquire(_) | StepBody::Widen(_) => {
1393 crate::acquisition::resolve(&s.id, &s.body, sources)?;
1394 }
1395 StepBody::Corroborate(_) => {}
1396 StepBody::Exact(e) => {
1397 let (registered, registry) = if v2 {
1398 (
1399 ops::is_registered_v2(&e.op, e.version),
1400 schema::EXACT_REGISTRY_V2,
1401 )
1402 } else {
1403 (ops::is_registered(&e.op, e.version), schema::EXACT_REGISTRY)
1404 };
1405 if !registered {
1406 return refuse(
1407 C::UnknownOperator,
1408 subject,
1409 format!("{}@{} is not in {registry}", e.op, e.version),
1410 );
1411 }
1412 }
1413 StepBody::Semantic(d) => {
1414 if d.requires != RequiredKind::CalibratedProbability {
1415 continue;
1416 }
1417 let CalibrationRef::Id(cid) = &d.calibration else {
1418 return refuse(
1419 C::CalibrationBinding,
1420 subject,
1421 "a calibrated_probability step names no calibration",
1422 );
1423 };
1424 let Some((_, art)) = calibration_ids.iter().find(|(id, _)| id == cid) else {
1425 return refuse(
1426 C::CalibrationBinding,
1427 subject,
1428 format!("calibration {cid} was not supplied"),
1429 );
1430 };
1431 calibrate::check_static(art, &d.task, &s.id, &d.options).map_err(|e| Refusal {
1432 category: C::CalibrationBinding,
1433 subject: subject.clone(),
1434 detail: e.to_string(),
1435 shortfalls: vec![],
1436 })?;
1437 resolved_cal.insert(s.id.clone(), ((*art).clone(), cid.clone()));
1438 }
1439 }
1440 }
1441
1442 let prompts = crate::generation::resolve(def, templates)?;
1443 crate::extraction_compile::resolve(def, programs)?;
1444
1445 let mut bound = if v2 {
1448 quality::bind_sources(def, sources)?
1449 } else {
1450 quality::Bound::default()
1451 };
1452
1453 let mut deps: BTreeMap<String, Vec<String>> = BTreeMap::new();
1455 for s in &def.steps {
1456 let mut refs: Vec<String> = match &s.body {
1457 StepBody::Extract(e) => e
1458 .projection
1459 .iter()
1460 .cloned()
1461 .chain(e.template.params.values().filter_map(|b| match b {
1462 rustev_contract::generation::TemplateBinding::Reference(r) => Some(r.clone()),
1463 _ => None,
1464 }))
1465 .collect(),
1466 StepBody::AcceptModelDerived(a) => crate::extraction_compile::accept_refs(a)
1467 .into_iter()
1468 .filter(|r| {
1469 let base = base_ref_v2(r);
1472 base.strip_prefix("step:")
1473 .is_none_or(|id| ids.iter().any(|s| s == id))
1474 })
1475 .collect(),
1476 StepBody::Rank(_) | StepBody::Select(_) => ranking::refs(&s.body),
1477 StepBody::Generate(g) => crate::generation::dependencies(g, def),
1478 StepBody::Acquire(_) | StepBody::Widen(_) => crate::acquisition::refs(&s.body),
1479 StepBody::Corroborate(c) => corroborate_refs(c),
1480 StepBody::Exact(_) => decoded[&s.id].refs(),
1481 StepBody::Semantic(d) => {
1482 let mut v = Vec::new();
1483 if let Candidates::From(r) = &d.candidates {
1484 v.push(r.clone());
1485 }
1486 for f in &d.for_each {
1487 v.push(f.over.clone());
1488 if let ItemSource::List { list, .. } = &f.items {
1489 v.push(list.clone());
1490 }
1491 }
1492 v.extend(
1493 d.project
1494 .iter()
1495 .filter(|r| !r.starts_with("bind:"))
1496 .cloned(),
1497 );
1498 v
1499 }
1500 };
1501 if v2 {
1502 refs = refs.iter().map(|r| base_ref_v2(r)).collect();
1504 }
1505 let mut seen = BTreeSet::new();
1506 refs.retain(|r| seen.insert(r.clone()));
1507 deps.insert(s.id.clone(), refs);
1508 }
1509 screening::dependencies(authored, &screens, &decoded, &mut deps);
1510 let order = topo_order(&ids, &deps)?;
1511
1512 let input_tys: BTreeMap<String, Ty> = inputs
1514 .iter()
1515 .map(|(k, (t, _))| (k.clone(), t.clone()))
1516 .collect();
1517 crate::extraction_compile::question_selections(def)?;
1518 crate::extraction_compile::model_gate(def)?;
1519 let mut step_tys: BTreeMap<String, StepTy> = BTreeMap::new();
1520 for (field, _) in crate::extraction_compile::distribution_options(def) {
1526 step_tys.insert(field, StepTy::Semantic(SemKind::Distribution, vec![]));
1527 }
1528 let mut infos: BTreeMap<String, StepInfo> = BTreeMap::new();
1529 let mut projection_bounds: BTreeMap<String, u64> = BTreeMap::new();
1530 let mut max_requests: BTreeMap<String, u64> = BTreeMap::new();
1531 let by_id: BTreeMap<&str, &rustev_contract::definition::StepDecl> =
1532 def.steps.iter().map(|s| (s.id.as_str(), s)).collect();
1533 let mut acquisition_derivations = BTreeMap::new();
1534 for id in &order {
1535 let s = by_id[id.as_str()];
1536 let subject = format!("step:{id}");
1537 let env = TyEnv {
1538 inputs: &input_tys,
1539 steps: &step_tys,
1540 item: None,
1541 v2,
1542 };
1543 let km = |e: String| Refusal {
1544 category: C::KindMismatch,
1545 subject: subject.clone(),
1546 detail: e,
1547 shortfalls: vec![],
1548 };
1549 match &s.body {
1550 StepBody::Extract(e) => {
1551 step_tys.insert(
1552 id.clone(),
1553 StepTy::Exact(crate::extraction_compile::record_ty(e, &input_tys)),
1554 );
1555 infos.insert(id.clone(), StepInfo::Extract);
1556 }
1557 StepBody::AcceptModelDerived(a) => {
1558 let ty = crate::extraction_compile::accept(
1559 id,
1560 a,
1561 def,
1562 &env,
1563 &acquisition_derivations,
1564 calibrations,
1565 )?;
1566 step_tys.insert(id.clone(), StepTy::Exact(ty));
1567 infos.insert(id.clone(), StepInfo::Accept(a.clone()));
1568 }
1569 StepBody::Rank(_) | StepBody::Select(_) => {
1570 let (ty, bytes) = ranking::types(id, &s.body, &env, &acquisition_derivations)?;
1571 projection_bounds.insert(id.clone(), bytes);
1572 step_tys.insert(id.clone(), ty);
1573 infos.insert(id.clone(), StepInfo::Ranking);
1574 }
1575 StepBody::Generate(_) => {
1576 infos.insert(id.clone(), StepInfo::Generate);
1577 }
1578 StepBody::Acquire(_) | StepBody::Widen(_) => {
1579 let a = crate::acquisition::compile(
1580 id,
1581 &s.body,
1582 sources,
1583 &env,
1584 &acquisition_derivations,
1585 def,
1586 )?;
1587 step_tys.insert(id.clone(), StepTy::Exact(a.ty.clone()));
1588 infos.insert(id.clone(), StepInfo::Acquisition(Box::new(a)));
1589 }
1590 StepBody::Corroborate(c) => {
1591 let ty = crate::expr::ref_ty(&c.claim, &env).map_err(km)?;
1593 for check in &c.by {
1594 type_predicate(&check.predicate, &env).map_err(km)?;
1595 }
1596 step_tys.insert(id.clone(), StepTy::Exact(ty.clone()));
1597 infos.insert(
1598 id.clone(),
1599 StepInfo::Corroborate {
1600 decl: Box::new(c.clone()),
1601 ty,
1602 },
1603 );
1604 }
1605 StepBody::Exact(_) => {
1606 let args = decoded[id].clone();
1607 if let OpArgs::MergeFields(m) = &args {
1608 let overlay = m
1610 .overlay
1611 .strip_prefix("step:")
1612 .map(|s| crate::expr::split_step(s).0);
1613 if let Some(OpArgs::JoinKeyed(j)) =
1614 overlay.as_deref().and_then(|o| decoded.get(o))
1615 && j.left != m.base
1616 {
1617 return refuse(
1618 C::InvalidDefinition,
1619 subject,
1620 format!("the overlay joins {}, not the base list {}", j.left, m.base),
1621 );
1622 }
1623 if let Some(e) = args.merge_rule_error(&env) {
1624 return refuse(C::InvalidDefinition, subject, e);
1625 }
1626 }
1627 let ty = args.type_check(&env).map_err(km)?;
1628 step_tys.insert(id.clone(), StepTy::Exact(ty.clone()));
1629 infos.insert(id.clone(), StepInfo::Exact { args, ty });
1630 }
1631 StepBody::Semantic(d) => {
1632 let mut requests: u64 = 1;
1633 let mut instance_bytes: u64 = 0;
1634 let mut bind_items = BTreeMap::new();
1635 for f in &d.for_each {
1636 let t = crate::expr::ref_ty(&f.over, &env).map_err(km)?;
1637 let (max, id_bytes) = Value::id_bounds(&t)
1638 .ok_or_else(|| km(format!("{} yields {}, not ids", f.over, t.name())))?;
1639 requests = requests.saturating_mul(max);
1640 instance_bytes = instance_bytes
1641 .saturating_add(2 + 6 * f.bind.len() as u64)
1642 .saturating_add(2 + 6 * id_bytes)
1643 .saturating_add(2);
1644 if let ItemSource::List { list, id_field } = &f.items {
1645 match crate::expr::ref_ty(list, &env).map_err(km)? {
1646 Ty::List { item, .. } => match item.as_ref() {
1647 Ty::Record(fields)
1648 if fields.iter().any(|(n, t)| {
1649 n == id_field && matches!(t, Ty::Text { .. } | Ty::Enum(_))
1650 }) =>
1651 {
1652 bind_items.insert(f.bind.clone(), (*item).clone());
1653 }
1654 _ => {
1655 return Err(km(format!(
1656 "{list} has no text id field {id_field:?}"
1657 )));
1658 }
1659 },
1660 t => return Err(km(format!("{list} is {}, not a list", t.name()))),
1661 }
1662 }
1663 }
1664 let mut candidate_bytes = 0u64;
1665 if let Candidates::From(r) = &d.candidates {
1666 let t = crate::expr::ref_ty(r, &env).map_err(km)?;
1667 let (max, id_bytes) = Value::id_bounds(&t)
1668 .ok_or_else(|| km(format!("{r} yields {}, not ids", t.name())))?;
1669 candidate_bytes = max.saturating_mul(2 + 6 * id_bytes + 1);
1670 }
1671 let mut value_bytes = 0u64;
1672 for r in &d.project {
1673 let t = match Ref::parse(r).map_err(km)? {
1674 Ref::Bind(b) if d.requires == RequiredKind::ScreenVerdict => {
1675 let (bind, field) = b
1676 .split_once('/')
1677 .ok_or_else(|| km("invalid lowered field".into()))?;
1678 match bind_items.get(bind) {
1679 Some(Ty::Record(fields)) => fields
1680 .iter()
1681 .find(|(name, _)| name == field)
1682 .map(|(_, ty)| ty.clone())
1683 .ok_or_else(|| km("unknown lowered field".into()))?,
1684 _ => return Err(km("invalid lowered item".into())),
1685 }
1686 }
1687 Ref::Bind(b) => bind_items.get(&b).cloned().ok_or_else(|| {
1688 km(format!("bind {b:?} has no item source to project"))
1689 })?,
1690 Ref::Input(n, path) => crate::expr::ref_ty(
1691 &format!("input:{}", [vec![n], path].concat().join("/")),
1692 &env,
1693 )
1694 .map_err(km)?,
1695 Ref::Step(n) => {
1696 let base = if v2 { crate::expr::split_step(&n).0 } else { n };
1697 match step_tys.get(&base) {
1698 Some(StepTy::ModelRanking(_)) => {
1699 return Err(km(format!(
1700 "{r} is a model ranking; only exact values are projected"
1701 )));
1702 }
1703 Some(StepTy::Semantic(..)) => {
1704 return Err(km(format!(
1705 "{r} is semantic; only exact values are projected"
1706 )));
1707 }
1708 Some(StepTy::Selection(_)) | Some(StepTy::Exact(_)) => {}
1709 None => return Err(km(format!("{r} is not a declared step"))),
1710 }
1711 let t = crate::expr::ref_ty(r, &env).map_err(km)?;
1712 if matches!(
1713 t,
1714 Ty::Filtered { .. } | Ty::Shortlist { .. } | Ty::Ranking { .. }
1715 ) {
1716 return Err(km(format!(
1717 "{r} is a filter, shortlist or ranking summary; project its ids through for_each instead"
1718 )));
1719 }
1720 t
1721 }
1722 _ => return Err(km(format!("{r} cannot be projected"))),
1723 };
1724 value_bytes = value_bytes
1725 .saturating_add(2 + 6 * r.len() as u64 + 1)
1726 .saturating_add(t.max_json_bytes())
1727 .saturating_add(1);
1728 }
1729 let envelope = json!({
1730 "candidates": [], "instance": {}, "operation": d.operation, "options": d.options,
1731 "question": d.question, "task": d.task, "values": {},
1732 });
1733 let base = canonical_value_bytes(&envelope)
1734 .map(|b| b.len() as u64)
1735 .unwrap_or(u64::MAX);
1736 let bound = base
1737 .saturating_add(candidate_bytes)
1738 .saturating_add(instance_bytes)
1739 .saturating_add(value_bytes);
1740 let bound = screens
1741 .iter()
1742 .find(|f| &f.step == id)
1743 .map_or(bound, |f| screening::projection_bound(f.max_bytes));
1744 projection_bounds.insert(id.clone(), bound);
1745 max_requests.insert(id.clone(), requests);
1746 let kind = sem_kind(d.operation, d.requires);
1747 let binds: Vec<String> = d.for_each.iter().map(|f| f.bind.clone()).collect();
1748 step_tys.insert(id.clone(), StepTy::Semantic(kind, binds));
1749 infos.insert(
1750 id.clone(),
1751 StepInfo::Semantic {
1752 decl: Box::new(d.clone()),
1753 kind,
1754 binding: None,
1755 calibration: resolved_cal.get(id).cloned(),
1756 },
1757 );
1758 }
1759 }
1760 acquisition_derivations = static_derivations(
1761 def,
1762 &inputs,
1763 &order[..=order.iter().position(|x| x == id).unwrap()],
1764 &deps,
1765 &infos,
1766 );
1767 }
1768
1769 crate::extraction_compile::types(def, &input_tys, &step_tys)?;
1770 crate::extraction_compile::templates(
1771 def,
1772 &prompts,
1773 &input_tys,
1774 &step_tys,
1775 &acquisition_derivations,
1776 )?;
1777 crate::extraction_compile::budget(def, &input_tys, &step_tys, execution)?;
1778 ranking::consumers(def, &deps, &step_tys, &decoded)?;
1779 screening::coverage(authored, &screens, &decoded)?;
1780 let mut generated = crate::generation::type_check(
1781 def,
1782 &prompts,
1783 &input_tys,
1784 &step_tys,
1785 &acquisition_derivations,
1786 &deps,
1787 )?;
1788
1789 crate::actionable::types(def, &input_tys, v2)?;
1791
1792 fn under_types(c: &Cond, env: &TyEnv<'_>) -> Result<(), String> {
1794 match c {
1795 Cond::Exact(p) => crate::expr::type_under(p, env),
1796 Cond::All(cs) | Cond::Any(cs) => cs.iter().try_for_each(|c| under_types(c, env)),
1797 Cond::Not(c) => under_types(c, env),
1798 _ => Ok(()),
1799 }
1800 }
1801 let env = TyEnv {
1802 inputs: &input_tys,
1803 steps: &step_tys,
1804 item: None,
1805 v2,
1806 };
1807 for (subject, cond) in quality::policy_conds(def) {
1808 under_types(cond, &env).or_else(|e| refuse(C::KindMismatch, subject, e))?;
1809 }
1810
1811 let mut trees: BTreeMap<String, quality::Ceil> = BTreeMap::new();
1815 let mut grade_table: Vec<StaticGrade> = Vec::new();
1816 if v2 {
1817 for (name, (_, decl)) in &inputs {
1818 trees.insert(
1819 format!("input:{name}"),
1820 quality::input_tree(&decl.ty, bound.inputs.get(name), None),
1821 );
1822 }
1823 for id in &order {
1824 let tree = match &infos[id] {
1825 StepInfo::Extract => {
1826 let (schema, hints) = crate::extraction_compile::hint_paths(def, id, programs);
1827 quality::extract_tree(&schema, &hints)
1828 }
1829 StepInfo::Ranking | StepInfo::Generate => {
1830 quality::Ceil::leaf(rustev_contract::grade::ValueGrade::Ungraded, false)
1831 }
1832 StepInfo::Accept(a) => quality::tree_at(&trees, &a.field, &[]),
1833 StepInfo::Acquisition(a) => a.tree.clone(),
1834 StepInfo::Exact { args, .. } => quality::step_tree(args, &trees),
1835 StepInfo::Semantic { decl, .. } => quality::semantic_tree(decl, &trees),
1836 StepInfo::Corroborate { decl, .. } => quality::corroborate_tree(decl, &trees),
1837 };
1838 trees.insert(format!("step:{id}"), tree);
1839 }
1840 for s in &def.steps {
1841 let subject = format!("step:{}", s.id);
1842 let found = match &infos[&s.id] {
1843 StepInfo::Acquisition(a) => a
1844 .reads
1845 .iter()
1846 .find_map(|r| quality::requirement_refusal(&subject, r, &trees)),
1847 StepInfo::Exact { args, .. } => quality::op_reads(args)
1848 .iter()
1849 .filter(|r| r.gate || r.require.is_some())
1850 .find_map(|r| quality::requirement_refusal(&subject, r, &trees)),
1851 StepInfo::Corroborate { decl, .. } => {
1852 quality::corroborate_refusal(&subject, decl, &trees)
1853 }
1854 StepInfo::Ranking
1855 | StepInfo::Generate
1856 | StepInfo::Extract
1857 | StepInfo::Accept(_)
1858 | StepInfo::Semantic { .. } => None,
1859 };
1860 if let Some(r) = found {
1861 return Err(r);
1862 }
1863 }
1864 for (subject, c) in quality::policy_conds(def) {
1865 let mut reads = Vec::new();
1866 quality::cond_reads(c, &mut reads);
1867 if let Some(r) = reads
1868 .iter()
1869 .find_map(|r| quality::requirement_refusal(&subject, r, &trees))
1870 {
1871 return Err(r);
1872 }
1873 }
1874 if !bound.inputs.is_empty()
1875 || infos
1876 .values()
1877 .any(|i| matches!(i, StepInfo::Acquisition(_)))
1878 {
1879 for name in inputs.keys() {
1880 let key = format!("input:{name}");
1881 trees[&key].walk(&key, &mut grade_table);
1882 }
1883 for s in &def.steps {
1884 let key = format!("step:{}", s.id);
1885 trees[&key].walk(&key, &mut grade_table);
1886 }
1887 }
1888 }
1889
1890 let mut sorted: Vec<&BackendDescriptor> = descriptors.iter().collect();
1892 sorted.sort_by(|a, b| a.backend_id.as_bytes().cmp(b.backend_id.as_bytes()));
1893
1894 let mut notices: Vec<Notice> = Vec::new();
1895 let mut details: BTreeMap<String, PlanStepDetail> = BTreeMap::new();
1896 let mut determinism = BTreeMap::new();
1897 let mut bind_ctx: BTreeMap<String, (u64, u64)> = BTreeMap::new();
1898 for s in &def.steps {
1899 let subject = format!("step:{}", s.id);
1900 let d = match &s.body {
1901 StepBody::Extract(e) => {
1902 let binding = crate::extraction_compile::bind(
1903 &s.id,
1904 e,
1905 crate::extraction_compile::needs_logprobs(def, &s.id),
1906 &prompts[&s.id],
1907 programs,
1908 &TyEnv {
1909 inputs: &input_tys,
1910 steps: &step_tys,
1911 item: None,
1912 v2,
1913 },
1914 &sorted,
1915 )?;
1916 details.insert(s.id.clone(), PlanStepDetail::Extract(Box::new(binding)));
1917 continue;
1918 }
1919 StepBody::AcceptModelDerived(a) => {
1920 details.insert(s.id.clone(), PlanStepDetail::AcceptModelDerived(a.clone()));
1921 continue;
1922 }
1923 StepBody::Rank(r) => {
1924 let StepTy::ModelRanking(pool) = step_tys[&s.id] else {
1925 unreachable!()
1926 };
1927 bind_ctx.insert(s.id.clone(), (pool, projection_bounds[&s.id]));
1928 let detail = ranking::bind(&s.id, r, pool, projection_bounds[&s.id], &sorted)?;
1929 if let PlanStepDetail::Unsupported { capability } = &detail {
1930 notices.push(Notice {
1931 screening: None,
1932 kind: NoticeKind::Fallback,
1933 subject: subject.clone(),
1934 reason: format!("unsupported: {capability}"),
1935 action: None,
1936 });
1937 }
1938 if let PlanStepDetail::Rank(binding) = &detail
1939 && let Some(backend) =
1940 sorted.iter().find(|b| b.backend_id == binding.backend_id)
1941 {
1942 determinism.insert(s.id.clone(), backend.determinism);
1943 }
1944 details.insert(s.id.clone(), detail);
1945 continue;
1946 }
1947 StepBody::Select(select) => {
1948 details.insert(s.id.clone(), PlanStepDetail::Select(select.clone()));
1949 continue;
1950 }
1951 StepBody::Generate(g) => {
1952 let binding = crate::generation::bind(&s.id, g, &generated[&s.id], &sorted)?;
1953 if let Some(checked) = generated.get_mut(&s.id) {
1954 checked.binding = binding.clone();
1955 }
1956 details.insert(s.id.clone(), PlanStepDetail::Generate(Box::new(binding)));
1957 continue;
1958 }
1959 StepBody::Semantic(d) => d,
1960 StepBody::Exact(e) => {
1961 details.insert(
1962 s.id.clone(),
1963 PlanStepDetail::Exact {
1964 op: e.op.clone(),
1965 version: e.version,
1966 },
1967 );
1968 continue;
1969 }
1970 StepBody::Acquire(_) | StepBody::Widen(_) => {
1971 details.insert(
1972 s.id.clone(),
1973 if matches!(s.body, StepBody::Acquire(_)) {
1974 PlanStepDetail::Acquire
1975 } else {
1976 PlanStepDetail::Widen
1977 },
1978 );
1979 continue;
1980 }
1981 StepBody::Corroborate(_) => {
1982 details.insert(s.id.clone(), PlanStepDetail::Corroborate);
1983 continue;
1984 }
1985 };
1986 let bound = projection_bounds[&s.id];
1987 let options_needed = match &d.candidates {
1988 Candidates::From(r) => match &step_tys[step_ref(r).unwrap_or_default()] {
1989 StepTy::Exact(t) => Value::id_bounds(t).map(|(m, _)| m).unwrap_or(0),
1990 StepTy::ModelRanking(_) | StepTy::Semantic(..) => 0,
1991 StepTy::Selection(ty) => Value::id_bounds(ty).map_or(0, |(n, _)| n),
1992 },
1993 Candidates::None => d.options.len() as u64,
1994 };
1995 bind_ctx.insert(s.id.clone(), (options_needed, bound));
1996 let candidates: Vec<&BackendDescriptor> = match &d.backend.binding {
1997 BindingChoice::Backend(b) => match sorted.iter().find(|x| &x.backend_id == b) {
1998 Some(x) => vec![*x],
1999 None => {
2000 return Err(Refusal {
2001 category: C::NoCapableBackend,
2002 subject,
2003 detail: format!("bound backend {b:?} was not supplied"),
2004 shortfalls: vec![Shortfall {
2005 backend_id: b.clone(),
2006 reasons: vec![ShortfallReason::UnknownBackend],
2007 }],
2008 });
2009 }
2010 },
2011 BindingChoice::Auto => sorted.clone(),
2012 };
2013 let consumers_ok = |k: SemKind| consumers_accept(def, &s.id, k);
2014 if let Fallback::Kind { requires, .. } = &d.fallback {
2015 if !kind_valid_for(d.operation, *requires) {
2016 return refuse(
2017 C::InvalidFallback,
2018 subject,
2019 format!("{:?} cannot fall back to {:?}", d.operation, requires),
2020 );
2021 }
2022 if *requires == RequiredKind::CalibratedProbability {
2023 return refuse(
2024 C::InvalidFallback,
2025 subject,
2026 "a fallback cannot require calibration",
2027 );
2028 }
2029 if let Err(e) = consumers_ok(sem_kind(d.operation, *requires)) {
2030 return refuse(
2031 C::InvalidFallback,
2032 subject,
2033 format!("consumers cannot accept the fallback kind: {e}"),
2034 );
2035 }
2036 }
2037 let evaluate =
2038 |required: RequiredKind| -> (Option<(&BackendDescriptor, OutputKind)>, Vec<Shortfall>) {
2039 let mut shortfalls = Vec::new();
2040 for b in &candidates {
2041 match screening::candidate(
2042 screens.iter().find(|f| f.step == s.id),
2043 d,
2044 b,
2045 required,
2046 options_needed,
2047 bound,
2048 ) {
2049 Ok(o) => return (Some((*b, o)), vec![]),
2050 Err(reasons) => shortfalls.push(Shortfall {
2051 backend_id: b.backend_id.clone(),
2052 reasons,
2053 }),
2054 }
2055 }
2056 (None, shortfalls)
2057 };
2058 let (found, shortfalls) = evaluate(d.requires);
2059 let (backend, output, requires, fallback_taken) = match (found, &d.fallback) {
2060 (Some((b, o)), _) => (b, o, d.requires, false),
2061 (None, Fallback::None) => {
2062 return Err(Refusal {
2063 category: C::NoCapableBackend,
2064 subject,
2065 detail: format!(
2066 "no backend satisfies {:?} {:?}, and no fallback is declared",
2067 d.operation, d.requires
2068 ),
2069 shortfalls,
2070 });
2071 }
2072 (None, Fallback::Unsupported) => {
2073 let capability = format!("{:?}:{:?}", d.operation, d.requires).to_lowercase();
2074 notices.push(Notice {
2075 screening: None,
2076 kind: NoticeKind::Fallback,
2077 subject: subject.clone(),
2078 reason: format!("unsupported: {capability}"),
2079 action: None,
2080 });
2081 details.insert(s.id.clone(), PlanStepDetail::Unsupported { capability });
2082 continue;
2083 }
2084 (None, Fallback::Kind { requires, reason }) => match evaluate(*requires) {
2085 (Some((b, o)), _) => {
2086 notices.push(Notice {
2087 screening: None,
2088 kind: NoticeKind::Fallback,
2089 subject: subject.clone(),
2090 reason: reason.clone(),
2091 action: None,
2092 });
2093 (b, o, *requires, true)
2094 }
2095 (None, fb_shortfalls) => {
2096 return Err(Refusal {
2097 category: C::InvalidFallback,
2098 subject,
2099 detail: format!(
2100 "neither {:?} nor the fallback {:?} is satisfied",
2101 d.requires, requires
2102 ),
2103 shortfalls: fb_shortfalls,
2104 });
2105 }
2106 },
2107 };
2108 determinism.insert(s.id.clone(), backend.determinism);
2109 let calibration = match (requires, resolved_cal.get(&s.id)) {
2110 (RequiredKind::CalibratedProbability, Some((art, cid))) => {
2111 if art.binding.artifact != backend.artifact {
2112 return refuse(
2113 C::CalibrationBinding,
2114 subject,
2115 format!(
2116 "calibration is bound to {}, the backend is {}",
2117 art.binding.artifact, backend.artifact
2118 ),
2119 );
2120 }
2121 BoundCalibration::Bound {
2122 id: cid.clone(),
2123 binding: art.binding.clone(),
2124 }
2125 }
2126 _ => BoundCalibration::None,
2127 };
2128 let normalization = match (&output, requires) {
2129 (
2130 OutputKind::Logits,
2131 RequiredKind::Distribution | RequiredKind::OrdinalDistribution,
2132 ) => Normalization::Softmax1,
2133 _ => Normalization::None,
2134 };
2135 let descriptor_id = backend.id().map_err(|e| Refusal {
2136 category: C::Parse,
2137 subject: subject.clone(),
2138 detail: e.to_string(),
2139 shortfalls: vec![],
2140 })?;
2141 let binding = SemanticBinding {
2142 backend_id: backend.backend_id.clone(),
2143 artifact: backend.artifact.clone(),
2144 descriptor: descriptor_id,
2145 output,
2146 requires,
2147 normalization,
2148 calibration,
2149 fallback_taken,
2150 max_requests: max_requests[&s.id],
2151 max_projection_bytes: bound,
2152 };
2153 if let Some(StepInfo::Semantic {
2154 binding: b,
2155 kind,
2156 calibration: cal,
2157 ..
2158 }) = infos.get_mut(&s.id)
2159 {
2160 *kind = sem_kind(d.operation, requires);
2161 if requires != RequiredKind::CalibratedProbability {
2162 *cal = None;
2163 }
2164 *b = Some(Box::new(binding.clone()));
2165 step_tys.insert(
2166 s.id.clone(),
2167 StepTy::Semantic(*kind, d.for_each.iter().map(|f| f.bind.clone()).collect()),
2168 );
2169 }
2170 details.insert(s.id.clone(), PlanStepDetail::Semantic(Box::new(binding)));
2171 }
2172
2173 crate::extraction_compile::accept_bindings(def, calibrations, &details, &mut notices)?;
2174
2175 let mut plan_execution = match execution {
2178 None => PlanExecution::None,
2179 Some(policy) => crate::execution::validate(policy, def, &sorted, &details, &bind_ctx)?,
2180 };
2181 if let PlanExecution::Declared(d) = &mut plan_execution {
2184 d.decision_cache = crate::execution::decision_cache(&d.policy, def, &order, &deps, v2)?;
2185 }
2186 crate::execution::available(&plan_execution, def)?;
2187
2188 screening::budget(authored, &screens, descriptors)?;
2190 crate::acquisition::budget(def, sources, execution)?;
2191 let mut total: u64 = crate::generation::budget(def, &details)?;
2192 total += def
2193 .steps
2194 .iter()
2195 .filter(|s| matches!(s.body, StepBody::Extract(_)))
2196 .count() as u64;
2197 for s in &def.steps {
2198 if let Some(PlanStepDetail::Extract(b)) = details.get(&s.id)
2199 && b.worst_case_request_bytes > def.limits.max_projection_bytes
2200 {
2201 return refuse(
2202 C::Budget,
2203 format!("step:{}", s.id),
2204 "extraction request exceeds max_projection_bytes",
2205 );
2206 }
2207 if let StepBody::Rank(r) = &s.body {
2208 let StepTy::ModelRanking(pool) = step_tys[&s.id] else {
2209 unreachable!()
2210 };
2211 let count = ranking::budget(&s.id, r, pool)?;
2212 if matches!(details[&s.id], PlanStepDetail::Rank(_)) {
2213 total = total.saturating_add(count);
2214 }
2215 if projection_bounds[&s.id] > def.limits.max_projection_bytes {
2216 return refuse(
2217 C::Budget,
2218 format!("step:{}", s.id),
2219 "rank projection exceeds max_projection_bytes",
2220 );
2221 }
2222 }
2223 if let Some(PlanStepDetail::Semantic(b)) = details.get(&s.id) {
2224 total = total.saturating_add(b.max_requests);
2225 if b.max_projection_bytes > def.limits.max_projection_bytes {
2226 return refuse(
2227 C::Budget,
2228 format!("step:{}", s.id),
2229 format!(
2230 "worst-case projection {} bytes exceeds max_projection_bytes {}",
2231 b.max_projection_bytes, def.limits.max_projection_bytes
2232 ),
2233 );
2234 }
2235 }
2236 }
2237 if total > def.limits.max_semantic_requests {
2238 match def.limits.on_excess {
2239 ExcessPolicy::Refuse => {
2240 return refuse(
2241 C::Budget,
2242 "limits",
2243 format!(
2244 "worst-case {total} semantic requests exceed max_semantic_requests {} without truncate_visible",
2245 def.limits.max_semantic_requests
2246 ),
2247 );
2248 }
2249 ExcessPolicy::TruncateVisible => notices.push(Notice {
2250 screening: None,
2251 kind: NoticeKind::Truncation,
2252 subject: "limits".into(),
2253 reason: format!(
2254 "worst case {total} requests; at most {} are issued",
2255 def.limits.max_semantic_requests
2256 ),
2257 action: None,
2258 }),
2259 }
2260 }
2261
2262 if v2 && let Err(detail) = quality::evidence_bound(def, &infos) {
2265 return refuse(C::Budget, "limits", format!("evidence-bound: {detail}"));
2266 }
2267
2268 let mut reasons = possible_reasons(def, &inputs, &order, &infos, &details);
2270 if v2 {
2271 extend_reasons_v2(
2272 def,
2273 &inputs,
2274 &order,
2275 &infos,
2276 &deps,
2277 &trees,
2278 &details,
2279 &mut reasons,
2280 );
2281 }
2282 check_policy(def, &input_tys, &step_tys, &reasons, &mut notices, v2)?;
2283
2284 let actionability = crate::actionable::phase_h2(def, &inputs, &deps, &reasons)?;
2287
2288 let derivations = static_derivations(def, &inputs, &order, &deps, &infos);
2290 let registry = if v2
2293 && (uses_exact_v2(def, &decoded)
2294 || def
2295 .steps
2296 .iter()
2297 .any(|s| matches!(s.body, StepBody::AcceptModelDerived(_))))
2298 {
2299 schema::EXACT_REGISTRY_V2
2300 } else {
2301 schema::EXACT_REGISTRY
2302 };
2303 let definition_id = authored.id().map_err(|e| Refusal {
2304 category: C::Parse,
2305 subject: "definition".into(),
2306 detail: e.to_string(),
2307 shortfalls: vec![],
2308 })?;
2309 let acquisitions: Vec<_> = def
2310 .steps
2311 .iter()
2312 .filter_map(|s| match &infos[&s.id] {
2313 StepInfo::Acquisition(a) => {
2314 use rustev_contract::acquisition_record::AcquisitionPossibleOutcome as O;
2315 let mut plan = a.plan.clone();
2316 for (reason, outcome) in [
2317 (ReasonKind::Skipped, O::Skipped),
2318 (ReasonKind::InsufficientGrade, O::InsufficientGrade),
2319 ] {
2320 if reasons[&format!("step:{}", s.id)].contains(&reason)
2321 && !plan.outcomes.contains(&outcome)
2322 {
2323 plan.outcomes.push(outcome);
2324 }
2325 }
2326 Some(plan)
2327 }
2328 _ => None,
2329 })
2330 .collect();
2331 for a in &acquisitions {
2332 for b in &a.sources {
2333 if !bound.sources.iter().any(|s| s.name == b.source.name) {
2334 bound.sources.push(b.source.clone());
2335 }
2336 }
2337 }
2338 bound.sources.sort_by(|a, b| a.name.cmp(&b.name));
2339 let plan = Plan {
2340 acquisitions: (!acquisitions.is_empty()).then_some(acquisitions),
2341 schema: if v2 { schema::PLAN_V3 } else { schema::PLAN }.into(),
2342 compiler: COMPILER.into(),
2343 registry: registry.into(),
2344 definition_id,
2345 definition: authored.clone(),
2346 order: order.clone(),
2347 steps: def
2348 .steps
2349 .iter()
2350 .map(|s| PlanStep {
2351 id: s.id.clone(),
2352 derivation: derivations[&s.id],
2353 detail: details[&s.id].clone(),
2354 })
2355 .collect(),
2356 notices,
2357 execution: plan_execution,
2358 sources: (!bound.sources.is_empty()).then(|| bound.sources.clone()),
2359 grades: (!grade_table.is_empty()).then_some(grade_table),
2360 actionability,
2361 instantiation: None,
2362 screening: screening::plan(authored, &screens, &details),
2363 };
2364 let id = plan.id().map_err(|e| Refusal {
2365 category: C::Parse,
2366 subject: "plan".into(),
2367 detail: e.to_string(),
2368 shortfalls: vec![],
2369 })?;
2370 Ok(Compiled {
2371 plan,
2372 id,
2373 info: Info {
2374 extraction_calibrations: calibrations.to_vec(),
2375 screen_categories: descriptors
2376 .iter()
2377 .filter_map(|d| {
2378 d.operations
2379 .iter()
2380 .find_map(|op| op.screen.as_ref())
2381 .map(|p| (d.backend_id.clone(), p.categories.clone()))
2382 })
2383 .collect(),
2384 generation: generated,
2385 inputs,
2386 step_ids: ids,
2387 steps: infos,
2388 deps,
2389 order,
2390 v2,
2391 bound,
2392 trees,
2393 determinism,
2394 },
2395 })
2396}
2397
2398fn uses_exact_v2(def: &Definition, decoded: &BTreeMap<String, OpArgs>) -> bool {
2401 decoded
2402 .values()
2403 .any(|a| matches!(a, OpArgs::JoinKeyed(_) | OpArgs::MergeFields(_)) || a.uses_v2())
2404 || def.steps.iter().any(|s| match &s.body {
2405 StepBody::Acquire(_) | StepBody::Widen(_) => true,
2406 StepBody::Corroborate(c) => {
2407 c.by.iter()
2408 .any(|k| crate::expr::predicate_uses_v2(&k.predicate))
2409 }
2410 _ => false,
2411 })
2412 || quality::policy_conds(def).any(|(_, c)| first_cond_v2(c))
2413}
2414
2415fn first_cond_v2(c: &Cond) -> bool {
2416 match c {
2417 Cond::Exact(p) => crate::expr::predicate_uses_v2(p),
2418 Cond::All(cs) | Cond::Any(cs) => cs.iter().any(first_cond_v2),
2419 Cond::Not(c) => first_cond_v2(c),
2420 _ => false,
2421 }
2422}
2423
2424fn base_ref_v2(r: &str) -> String {
2425 crate::expr::base_ref_v2(r)
2426}
2427
2428fn may_be_absent(t: &TypeDecl) -> bool {
2430 match t {
2431 TypeDecl::Nullable { .. } => true,
2432 TypeDecl::Record {
2433 present_when: Some(_),
2434 ..
2435 } => true,
2436 TypeDecl::Record { fields, .. } => fields.iter().any(|f| may_be_absent(&f.ty)),
2437 TypeDecl::List { item, .. } => may_be_absent(item),
2438 TypeDecl::Map { value, .. } => may_be_absent(value),
2439 _ => false,
2440 }
2441}
2442
2443#[allow(clippy::too_many_arguments)]
2448fn extend_reasons_v2(
2449 def: &Definition,
2450 inputs: &BTreeMap<String, (Ty, InputDecl)>,
2451 order: &[String],
2452 infos: &BTreeMap<String, StepInfo>,
2453 deps: &BTreeMap<String, Vec<String>>,
2454 trees: &BTreeMap<String, quality::Ceil>,
2455 details: &BTreeMap<String, PlanStepDetail>,
2456 reasons: &mut BTreeMap<String, BTreeSet<ReasonKind>>,
2457) {
2458 use ReasonKind as K;
2459 let graded_gate = |r: &quality::Read| {
2460 r.require.is_some() || (r.gate && quality::read_ceiling(r, trees).own.graded().is_some())
2461 };
2462 let mut absent: BTreeSet<String> = BTreeSet::new();
2463 for (name, (_, decl)) in inputs {
2464 let key = format!("input:{name}");
2465 if may_be_absent(&decl.ty) {
2466 absent.insert(key.clone());
2467 }
2468 if matches!(
2469 decl.on_disagreement,
2470 Some(rustev_contract::definition::Disagreement::Abstain)
2471 ) {
2472 reasons.entry(key).or_default().insert(K::Abstained);
2473 }
2474 }
2475 for id in order {
2476 let key = format!("step:{id}");
2477 let mut add: BTreeSet<ReasonKind> = BTreeSet::new();
2478 match &infos[id] {
2479 StepInfo::Exact { args, .. } => {
2480 let reads = quality::op_reads(args);
2481 let reads_absent = reads.iter().any(|r| absent.contains(&r.base));
2482 match args {
2483 OpArgs::JoinKeyed(_) | OpArgs::MergeFields(_) => {
2484 absent.insert(key.clone());
2485 }
2486 OpArgs::FilterWithReasons(_) | OpArgs::TopK(_) | OpArgs::FieldPresence(_) => {}
2488 _ if reads_absent => {
2489 add.insert(K::MissingEvidence);
2490 }
2491 _ => {}
2492 }
2493 if reads.iter().any(graded_gate) {
2494 add.insert(K::InsufficientGrade);
2495 }
2496 if !matches!(args, OpArgs::FieldPresence(_)) {
2497 for d in &deps[id] {
2498 let mut inherited = reasons.get(d).cloned().unwrap_or_default();
2499 if probe_only(args, d) {
2500 inherited.remove(&K::Skipped);
2501 }
2502 add.extend(inherited);
2503 }
2504 }
2505 }
2506 StepInfo::Corroborate { decl, .. } => {
2507 let (claim, _) = quality::claim_path(decl);
2508 if absent.contains(&claim) {
2509 absent.insert(key.clone());
2510 }
2511 add.extend(reasons.get(&claim).cloned().unwrap_or_default());
2512 match decl.on_contradiction {
2517 rustev_contract::definition::OnContradiction::Conflict => {
2518 add.insert(K::Conflict);
2519 }
2520 rustev_contract::definition::OnContradiction::Abstain => {
2521 add.insert(K::Abstained);
2522 }
2523 rustev_contract::definition::OnContradiction::TreatAsHint => {}
2524 }
2525 }
2526 StepInfo::Accept(a) => {
2527 add.extend(
2528 reasons
2529 .get(&base_ref_v2(&a.field))
2530 .cloned()
2531 .unwrap_or_default(),
2532 );
2533 if matches!(
2534 a.on_fail,
2535 rustev_contract::extraction::OnFail::DropField { .. }
2536 ) {
2537 absent.insert(key.clone());
2538 }
2539 }
2540 StepInfo::Ranking => {
2541 let body = &def.steps.iter().find(|s| &s.id == id).unwrap().body;
2542 let updated = ranking::reasons(body, &details[id], reasons);
2543 reasons.insert(key, updated);
2544 continue;
2545 }
2546 StepInfo::Generate | StepInfo::Extract => {}
2547 StepInfo::Acquisition(_) | StepInfo::Semantic { .. } => {
2548 for d in &deps[id] {
2549 add.extend(reasons.get(d).cloned().unwrap_or_default());
2550 }
2551 }
2552 }
2553 reasons.entry(key).or_default().extend(add);
2554 }
2555 for (_, c) in quality::policy_conds(def) {
2556 let mut reads = Vec::new();
2557 quality::cond_reads(c, &mut reads);
2558 for r in &reads {
2559 if graded_gate(r) {
2560 reasons
2561 .entry(r.base.clone())
2562 .or_default()
2563 .insert(K::InsufficientGrade);
2564 }
2565 if absent.contains(&r.base) {
2566 reasons
2567 .entry(r.base.clone())
2568 .or_default()
2569 .insert(K::MissingEvidence);
2570 }
2571 }
2572 }
2573}
2574
2575fn first_v2_construct(
2579 def: &Definition,
2580 decoded: &BTreeMap<String, OpArgs>,
2581) -> Option<(String, &'static str)> {
2582 fn type_v2(t: &TypeDecl) -> Option<&'static str> {
2583 match t {
2584 TypeDecl::Nullable { .. } => Some("a nullable type"),
2585 TypeDecl::Map { .. } => Some("a map type"),
2586 TypeDecl::Record {
2587 present_when: Some(_),
2588 ..
2589 } => Some("a presence predicate"),
2590 TypeDecl::Record { fields, .. } => fields.iter().find_map(|f| type_v2(&f.ty)),
2591 TypeDecl::List { item, .. } => type_v2(item),
2592 _ => None,
2593 }
2594 }
2595 fn cond_v2(c: &Cond) -> bool {
2596 match c {
2597 Cond::Exact(p) => crate::expr::predicate_uses_v2(p),
2598 Cond::All(cs) | Cond::Any(cs) => cs.iter().any(cond_v2),
2599 Cond::Not(c) => cond_v2(c),
2600 _ => false,
2601 }
2602 }
2603 for i in &def.inputs {
2604 let subject = format!("input:{}", i.name);
2605 if i.evidence.is_some() {
2606 return Some((subject, "an evidence declaration"));
2607 }
2608 if i.on_disagreement.is_some() {
2609 return Some((subject, "a disagreement rule"));
2610 }
2611 if let Some(c) = type_v2(&i.ty) {
2612 return Some((subject, c));
2613 }
2614 }
2615 for s in &def.steps {
2616 let subject = format!("step:{}", s.id);
2617 match &s.body {
2618 StepBody::Extract(_) => return Some((subject, "an extraction step")),
2619 StepBody::AcceptModelDerived(_) => {
2620 return Some((subject, "an accept_model_derived step"));
2621 }
2622 StepBody::Rank(_) | StepBody::Select(_) => return Some((subject, "a ranking step")),
2623 StepBody::Generate(_) => return Some((subject, "a generate step")),
2624 StepBody::Acquire(_) | StepBody::Widen(_) => {
2625 return Some((subject, "an acquisition step"));
2626 }
2627 StepBody::Corroborate(_) => return Some((subject, "a corroborate step")),
2628 StepBody::Exact(_) => {
2629 if decoded.get(&s.id).is_some_and(OpArgs::uses_v2) {
2630 return Some((subject, "a rustev.exact/2 predicate or graded reference"));
2631 }
2632 }
2633 StepBody::Semantic(_) => {}
2634 }
2635 }
2636 let policy = &def.policy;
2637 for r in &policy.rules {
2638 if cond_v2(&r.when) {
2639 return Some((
2640 format!("policy:rule:{}", r.id),
2641 "a rustev.exact/2 predicate or graded reference",
2642 ));
2643 }
2644 }
2645 for a in &policy.adjustments {
2646 if cond_v2(&a.when) {
2647 return Some((
2648 format!("policy:adjustment:{}", a.id),
2649 "a rustev.exact/2 predicate or graded reference",
2650 ));
2651 }
2652 }
2653 None
2654}
2655
2656fn corroborate_refs(c: &rustev_contract::definition::CorroborateDecl) -> Vec<String> {
2658 let mut out = vec![c.claim.clone()];
2659 for check in &c.by {
2660 predicate_refs(&check.predicate, &mut out);
2661 }
2662 out.into_iter()
2663 .filter(|r| r.starts_with("input:") || r.starts_with("step:"))
2664 .map(|r| crate::expr::base_ref(&r))
2665 .collect()
2666}
2667
2668fn cond_structure(
2669 c: &Cond,
2670 options_of: &BTreeMap<String, Vec<String>>,
2671 known: &dyn Fn(&str) -> Result<(), String>,
2672 deferred: &BTreeSet<&str>,
2673) -> Result<(), String> {
2674 let unit = Decimal::from_i64(1);
2675 if matches!(c, Cond::TopLabel { step, .. } | Cond::MassAtLeast { step, .. } | Cond::TopMassBelow { step, .. } | Cond::ExpectationAtLeast { step, .. } if deferred.contains(step.as_str()))
2676 {
2677 return Ok(());
2678 }
2679 let semantic_opts = |step: &str| -> Result<&Vec<String>, String> {
2680 known(&format!("step:{step}"))?;
2681 options_of
2682 .get(step)
2683 .ok_or_else(|| format!("{step:?} is not a semantic step"))
2684 };
2685 match c {
2686 Cond::Always => Ok(()),
2687 Cond::ProvenanceWithin { reference, .. } => known(reference),
2689 Cond::TopLabel { step, label } => {
2690 if !semantic_opts(step)?.contains(label) {
2691 return Err(format!("{label:?} is not an option of {step:?}"));
2692 }
2693 Ok(())
2694 }
2695 Cond::MassAtLeast {
2696 step,
2697 option,
2698 threshold,
2699 uncalibrated_threshold,
2700 } => {
2701 if !semantic_opts(step)?.contains(option) {
2702 return Err(format!("{option:?} is not an option of {step:?}"));
2703 }
2704 if *threshold < Decimal::ZERO || *threshold > unit {
2705 return Err("a probability threshold is in [0, 1]".into());
2706 }
2707 if matches!(uncalibrated_threshold, UncalibratedThreshold::Declared { reason } if reason.is_empty())
2708 {
2709 return Err("an uncalibrated threshold states its reason".into());
2710 }
2711 Ok(())
2712 }
2713 Cond::TopMassBelow {
2714 step,
2715 threshold,
2716 uncalibrated_threshold,
2717 } => {
2718 semantic_opts(step)?;
2719 if *threshold < Decimal::ZERO || *threshold > unit {
2720 return Err("a probability threshold is in [0, 1]".into());
2721 }
2722 if matches!(uncalibrated_threshold, UncalibratedThreshold::Declared { reason } if reason.is_empty())
2723 {
2724 return Err("an uncalibrated threshold states its reason".into());
2725 }
2726 Ok(())
2727 }
2728 Cond::ExpectationAtLeast { step, .. } => semantic_opts(step).map(|_| ()),
2729 Cond::Exact(p) => {
2730 predicate_structure(p)?;
2731 let mut refs = Vec::new();
2732 predicate_refs(p, &mut refs);
2733 refs.iter().try_for_each(|r| known(r))
2734 }
2735 Cond::Empty(r) | Cond::Nonempty(r) => known(r),
2736 Cond::All(cs) | Cond::Any(cs) => cs
2737 .iter()
2738 .try_for_each(|c| cond_structure(c, options_of, known, deferred)),
2739 Cond::Not(c) => cond_structure(c, options_of, known, deferred),
2740 }
2741}
2742
2743fn topo_order(
2746 ids: &[String],
2747 deps: &BTreeMap<String, Vec<String>>,
2748) -> Result<Vec<String>, Refusal> {
2749 let step_deps: BTreeMap<&str, BTreeSet<&str>> = ids
2750 .iter()
2751 .map(|id| {
2752 (
2753 id.as_str(),
2754 deps[id].iter().filter_map(|r| step_ref(r)).collect(),
2755 )
2756 })
2757 .collect();
2758 let mut done: BTreeSet<&str> = BTreeSet::new();
2759 let mut order = Vec::with_capacity(ids.len());
2760 loop {
2761 let next = ids.iter().find(|id| {
2762 !done.contains(id.as_str()) && step_deps[id.as_str()].iter().all(|d| done.contains(d))
2763 });
2764 match next {
2765 Some(id) => {
2766 done.insert(id);
2767 order.push(id.clone());
2768 }
2769 None => break,
2770 }
2771 }
2772 if order.len() == ids.len() {
2773 return Ok(order);
2774 }
2775 let stuck: Vec<String> = ids
2776 .iter()
2777 .filter(|id| !done.contains(id.as_str()))
2778 .cloned()
2779 .collect();
2780 refuse(
2781 Category::Cycle,
2782 format!("step:{}", stuck[0]),
2783 format!("the step graph has a cycle among {}", stuck.join(", ")),
2784 )
2785}
2786
2787fn consumers_accept(def: &Definition, step: &str, kind: SemKind) -> Result<(), String> {
2789 fn walk(c: &Cond, step: &str, kind: SemKind) -> Result<(), String> {
2790 match c {
2791 Cond::TopLabel { step: s, .. } if s == step => {
2792 if kind == SemKind::Scores {
2793 return Err("top_label needs labels".into());
2794 }
2795 Ok(())
2796 }
2797 Cond::MassAtLeast { step: s, .. } | Cond::TopMassBelow { step: s, .. } if s == step => {
2798 if kind.has_mass() {
2799 Ok(())
2800 } else {
2801 Err(format!(
2802 "a probability threshold cannot read {}",
2803 kind.name()
2804 ))
2805 }
2806 }
2807 Cond::ExpectationAtLeast { step: s, .. } if s == step => {
2808 if matches!(kind, SemKind::Ordinal(_)) {
2809 Ok(())
2810 } else {
2811 Err(format!("an expectation cannot read {}", kind.name()))
2812 }
2813 }
2814 Cond::All(cs) | Cond::Any(cs) => cs.iter().try_for_each(|c| walk(c, step, kind)),
2815 Cond::Not(c) => walk(c, step, kind),
2816 _ => Ok(()),
2817 }
2818 }
2819 for r in &def.policy.rules {
2820 walk(&r.when, step, kind)?;
2821 }
2822 for a in &def.policy.adjustments {
2823 walk(&a.when, step, kind)?;
2824 }
2825 for s in &def.steps {
2826 if let StepBody::Exact(e) = &s.body
2827 && let Some(Ok(OpArgs::WeightedRank(w))) = ops::decode(&e.op, e.version, &e.args)
2828 {
2829 for c in &w.components {
2830 match &c.source {
2831 ops::Source::PropositionMean { step: s2, .. }
2832 if step_ref(s2) == Some(step) && !kind.has_mass() =>
2833 {
2834 return Err(format!("proposition_mean cannot read {}", kind.name()));
2835 }
2836 ops::Source::RubricExpectation { step: s2 }
2837 if step_ref(s2) == Some(step) && !matches!(kind, SemKind::Ordinal(_)) =>
2838 {
2839 return Err(format!("rubric_expectation cannot read {}", kind.name()));
2840 }
2841 _ => {}
2842 }
2843 }
2844 }
2845 }
2846 Ok(())
2847}
2848
2849fn possible_reasons(
2851 def: &Definition,
2852 inputs: &BTreeMap<String, (Ty, InputDecl)>,
2853 order: &[String],
2854 infos: &BTreeMap<String, StepInfo>,
2855 details: &BTreeMap<String, PlanStepDetail>,
2856) -> BTreeMap<String, BTreeSet<ReasonKind>> {
2857 use ReasonKind as K;
2858 let mut out: BTreeMap<String, BTreeSet<ReasonKind>> = BTreeMap::new();
2859 for (name, (_, decl)) in inputs {
2860 let mut r: BTreeSet<_> = [K::MissingEvidence, K::InvalidInput, K::Conflict].into();
2861 if matches!(decl.freshness, Freshness::MaxAgeMs(_)) {
2862 r.insert(K::StaleEvidence);
2863 }
2864 out.insert(format!("input:{name}"), r);
2865 }
2866 crate::actionable::extend_reasons(def, &mut out);
2869 for id in order {
2870 let mut r = BTreeSet::new();
2871 match (&infos[id], &details[id]) {
2872 (StepInfo::Accept(a), _) => {
2873 r.extend(out.get(&base_ref_v2(&a.field)).cloned().unwrap_or_default());
2874 if matches!(a.on_fail, rustev_contract::extraction::OnFail::Unresolved) {
2875 r.extend([K::InvalidInput, K::MissingEvidence]);
2876 }
2877 }
2878 (StepInfo::Ranking, detail) => {
2879 let body = &def.steps.iter().find(|s| &s.id == id).unwrap().body;
2880 r = ranking::reasons(body, detail, &out);
2881 }
2882 (StepInfo::Generate, _) => {}
2883 (StepInfo::Extract, _) => {
2884 r.insert(K::MissingEvidence);
2885 }
2886 (StepInfo::Acquisition(a), _) => {
2887 r.extend([
2888 K::MissingEvidence,
2889 K::StaleEvidence,
2890 K::InvalidInput,
2891 K::BackendUnavailable,
2892 K::InvalidBackendOutput,
2893 K::BudgetExhausted,
2894 K::DeadlineExceeded,
2895 ]);
2896 if a.plan.outcomes.contains(
2897 &rustev_contract::acquisition_record::AcquisitionPossibleOutcome::Skipped,
2898 ) {
2899 r.insert(K::Skipped);
2900 }
2901 if a.plan.outcomes.contains(&rustev_contract::acquisition_record::AcquisitionPossibleOutcome::InsufficientGrade) { r.insert(K::InsufficientGrade); }
2902 }
2903 (_, PlanStepDetail::Unsupported { .. }) => {
2904 r.insert(K::Unsupported);
2905 }
2906 (StepInfo::Corroborate { decl, .. }, _) => {
2909 let (claim, _) = quality::claim_path(decl);
2910 r.extend(out.get(&claim).cloned().unwrap_or_default());
2911 }
2912 (StepInfo::Exact { args, .. }, _) => {
2913 if let OpArgs::FieldPresence(fp) = args {
2914 for i in &fp.inputs {
2915 let mut s = out.get(i).cloned().unwrap_or_default();
2916 s.remove(&K::MissingEvidence);
2917 r.extend(s);
2918 }
2919 } else {
2920 for d in args.refs() {
2921 let mut inherited = out.get(&d).cloned().unwrap_or_default();
2922 if probe_only(args, &d) {
2923 inherited.remove(&K::Skipped);
2924 }
2925 r.extend(inherited);
2926 }
2927 }
2928 r.extend(args.own_reasons());
2929 }
2930 (StepInfo::Semantic { decl, .. }, _) => {
2931 let mut refs: Vec<String> = decl
2932 .project
2933 .iter()
2934 .filter(|p| !p.starts_with("bind:"))
2935 .cloned()
2936 .collect();
2937 for f in &decl.for_each {
2938 refs.push(f.over.clone());
2939 if let ItemSource::List { list, .. } = &f.items {
2940 refs.push(list.clone());
2941 }
2942 }
2943 if let Candidates::From(c) = &decl.candidates {
2944 refs.push(c.clone());
2945 }
2946 for d in refs {
2947 r.extend(out.get(&d).cloned().unwrap_or_default());
2948 }
2949 if decl.for_each.is_empty() {
2950 r.extend([
2951 K::BackendUnavailable,
2952 K::InvalidBackendOutput,
2953 K::BudgetExhausted,
2954 K::DeadlineExceeded,
2955 ]);
2956 } else {
2957 r.insert(K::InvalidInput);
2959 }
2960 }
2961 }
2962 out.insert(format!("step:{id}"), r);
2963 }
2964 out
2965}
2966
2967pub(crate) fn predicate_value_refs(
2969 p: &rustev_contract::definition::Predicate,
2970 out: &mut Vec<String>,
2971) {
2972 use rustev_contract::definition::Predicate as P;
2973 match p {
2974 P::Present(_) | P::IsConstructed { .. } => {}
2975 P::All(ps) | P::Any(ps) => ps.iter().for_each(|p| predicate_value_refs(p, out)),
2976 P::Not(p) => predicate_value_refs(p, out),
2977 p => crate::expr::predicate_refs(p, out),
2978 }
2979}
2980fn condition_value_refs(c: &Cond, out: &mut Vec<String>) {
2981 match c {
2982 Cond::Exact(p) => predicate_value_refs(p, out),
2983 Cond::All(cs) | Cond::Any(cs) => cs.iter().for_each(|c| condition_value_refs(c, out)),
2984 Cond::Not(c) => condition_value_refs(c, out),
2985 c => condition_refs(c, out),
2986 }
2987}
2988pub(crate) fn probe_only(args: &OpArgs, target: &str) -> bool {
2989 if let OpArgs::Compare(c) = args {
2990 let mut values = vec![];
2991 predicate_value_refs(&c.predicate, &mut values);
2992 return !values.iter().any(|r| crate::expr::base_ref_v2(r) == target);
2993 }
2994 false
2995}
2996
2997fn cond_reads(c: &Cond, negated: bool, out: &mut Vec<(String, bool)>) {
2999 match c {
3000 Cond::Not(inner) => cond_reads(inner, !negated, out),
3001 Cond::All(cs) | Cond::Any(cs) => cs.iter().for_each(|c| cond_reads(c, negated, out)),
3002 other => {
3003 let mut refs = Vec::new();
3004 condition_refs(other, &mut refs);
3005 out.extend(refs.into_iter().map(|r| (r, negated)));
3006 }
3007 }
3008}
3009
3010fn check_policy(
3011 def: &Definition,
3012 input_tys: &BTreeMap<String, Ty>,
3013 step_tys: &BTreeMap<String, StepTy>,
3014 reasons: &BTreeMap<String, BTreeSet<ReasonKind>>,
3015 notices: &mut Vec<Notice>,
3016 v2: bool,
3017) -> Result<(), Refusal> {
3018 use Category as C;
3019 let base = |r: &str| {
3020 if v2 {
3021 crate::expr::base_ref_v2(r)
3022 } else {
3023 crate::expr::base_ref(r)
3024 }
3025 };
3026 let env = TyEnv {
3027 inputs: input_tys,
3028 steps: step_tys,
3029 item: None,
3030 v2,
3031 };
3032 let policy = &def.policy;
3033
3034 let items: Vec<(String, &Cond, Option<&OutcomeDecl>)> = policy
3036 .rules
3037 .iter()
3038 .map(|r| (format!("policy:rule:{}", r.id), &r.when, Some(&r.then)))
3039 .chain(
3040 policy
3041 .adjustments
3042 .iter()
3043 .map(|a| (format!("policy:adjustment:{}", a.id), &a.when, None)),
3044 )
3045 .collect();
3046 for (subject, cond, outcome) in &items {
3047 check_cond(cond, &env, subject, notices)?;
3048 if let Some(o) = outcome {
3049 match o {
3050 OutcomeDecl::Propose { params, .. } => {
3051 for p in params {
3052 if let ParamSource::Ref(r) = &p.value {
3053 match crate::expr::ref_ty(r, &env) {
3054 Ok(_) => {}
3055 Err(e) => {
3056 return refuse(
3057 C::KindMismatch,
3058 subject.clone(),
3059 format!("parameter {:?}: {e}", p.name),
3060 );
3061 }
3062 }
3063 }
3064 }
3065 }
3066 OutcomeDecl::MissingEvidenceFrom { step } => match step_tys.get(step) {
3067 Some(StepTy::Exact(Ty::List { item, .. }))
3068 if matches!(item.as_ref(), Ty::Text { .. }) => {}
3069 _ => {
3070 return refuse(
3071 C::KindMismatch,
3072 subject.clone(),
3073 format!("{step:?} does not list field names"),
3074 );
3075 }
3076 },
3077 OutcomeDecl::Escalate { .. } | OutcomeDecl::NeedsInput { .. } => {}
3078 }
3079 }
3080 }
3081
3082 let mut covered: BTreeMap<&str, BTreeSet<ReasonKind>> = BTreeMap::new();
3084 let mut unmet: BTreeSet<&str> = BTreeSet::new();
3085 for h in &policy.on_unresolved {
3086 let set: BTreeSet<ReasonKind> = match &h.reasons {
3087 ReasonSet::Any => ReasonKind::ALL.into_iter().collect(),
3088 ReasonSet::Only(v) => v.iter().copied().collect(),
3089 };
3090 if !matches!(
3091 h.action,
3092 HandlerAction::AsUnmet | HandlerAction::Escalate { .. }
3093 ) && set.contains(&ReasonKind::Skipped)
3094 && reasons
3095 .get(&h.target)
3096 .is_some_and(|r| r.contains(&ReasonKind::Skipped))
3097 {
3098 return refuse(
3099 C::UnhandledUnresolved,
3100 &h.target,
3101 "skipped_not_propagatable",
3102 );
3103 }
3104 if h.action == HandlerAction::AsUnmet {
3105 unmet.insert(&h.target);
3106 }
3107 covered.entry(&h.target).or_default().extend(set);
3108 }
3109 let mut reads: Vec<(String, String, bool, bool)> = Vec::new();
3110 for (subject, cond, outcome) in &items {
3111 let mut r = Vec::new();
3112 cond_reads(cond, false, &mut r);
3113 let mut values = vec![];
3114 condition_value_refs(cond, &mut values);
3115 reads.extend(
3116 r.into_iter()
3117 .filter(|(x, _)| x.starts_with("input:") || x.starts_with("step:"))
3118 .map(|(x, neg)| {
3119 let target = base(&x);
3120 let probe = !values.iter().any(|v| base(v) == target);
3121 (subject.clone(), target, neg, probe)
3122 }),
3123 );
3124 if let Some(o) = outcome {
3125 let mut refs = Vec::new();
3126 outcome_refs(o, &mut refs);
3127 reads.extend(
3128 refs.into_iter()
3129 .map(|x| (subject.clone(), base(&x), false, false)),
3130 );
3131 }
3132 }
3133 for (subject, target, negated, probe) in &reads {
3134 let mut possible = reasons.get(target).cloned().unwrap_or_default();
3135 if *probe {
3136 possible.remove(&ReasonKind::Skipped);
3137 }
3138 let have = covered.get(target.as_str()).cloned().unwrap_or_default();
3139 let missing: Vec<&str> = possible.difference(&have).map(|k| k.name()).collect();
3140 if !missing.is_empty() {
3141 return refuse(
3142 C::UnhandledUnresolved,
3143 subject.clone(),
3144 format!(
3145 "{target} can be unresolved with {} and no handler covers it",
3146 missing.join(", ")
3147 ),
3148 );
3149 }
3150 if *negated && unmet.contains(target.as_str()) {
3151 return refuse(
3152 C::UnhandledUnresolved,
3153 subject.clone(),
3154 format!("`not` over {target}, which is handled as_unmet"),
3155 );
3156 }
3157 }
3158 if let Some(last) = policy.rules.last() {
3159 let mut refs = Vec::new();
3160 outcome_refs(&last.then, &mut refs);
3161 if let Some(r) = refs
3162 .iter()
3163 .map(|r| base(r))
3164 .find(|r| unmet.contains(r.as_str()))
3165 {
3166 return refuse(
3167 C::UnhandledUnresolved,
3168 format!("policy:rule:{}", last.id),
3169 format!("the last rule reads {r}, which is handled as_unmet"),
3170 );
3171 }
3172 }
3173 Ok(())
3174}
3175
3176fn check_cond(
3177 c: &Cond,
3178 env: &TyEnv<'_>,
3179 subject: &str,
3180 notices: &mut Vec<Notice>,
3181) -> Result<(), Refusal> {
3182 use Category as C;
3183 let sem = |step: &str| -> Result<SemKind, Refusal> {
3184 match env.steps.get(step) {
3185 Some(StepTy::Semantic(k, binds)) if binds.is_empty() => Ok(*k),
3186 Some(StepTy::Semantic(..)) => refuse(
3187 C::KindMismatch,
3188 subject,
3189 format!("{step:?} fans out; the policy reads single values"),
3190 ),
3191 _ => refuse(
3192 C::KindMismatch,
3193 subject,
3194 format!("{step:?} is not a semantic step"),
3195 ),
3196 }
3197 };
3198 let threshold = |step: &str,
3199 u: &UncalibratedThreshold,
3200 notices: &mut Vec<Notice>|
3201 -> Result<(), Refusal> {
3202 match sem(step)? {
3203 SemKind::Calibrated => Ok(()),
3204 SemKind::Distribution => match u {
3205 UncalibratedThreshold::Declared { reason } => {
3206 notices.push(Notice {
3207 screening: None,
3208 kind: NoticeKind::UncalibratedThreshold,
3209 subject: subject.to_string(),
3210 reason: reason.clone(),
3211 action: None,
3212 });
3213 Ok(())
3214 }
3215 UncalibratedThreshold::NotDeclared => refuse(
3216 C::UncalibratedThreshold,
3217 subject,
3218 format!(
3219 "a probability threshold reads the uncalibrated distribution {step:?} without uncalibrated_threshold"
3220 ),
3221 ),
3222 },
3223 k => refuse(
3224 C::KindMismatch,
3225 subject,
3226 format!(
3227 "a probability threshold cannot read {} ({step:?})",
3228 k.name()
3229 ),
3230 ),
3231 }
3232 };
3233 match c {
3234 Cond::Always | Cond::ProvenanceWithin { .. } => Ok(()),
3235 Cond::TopLabel { step, .. } => match sem(step)? {
3236 SemKind::Scores => refuse(
3237 C::KindMismatch,
3238 subject,
3239 format!("top_label cannot read scores ({step:?})"),
3240 ),
3241 _ => Ok(()),
3242 },
3243 Cond::MassAtLeast {
3244 step,
3245 uncalibrated_threshold,
3246 ..
3247 }
3248 | Cond::TopMassBelow {
3249 step,
3250 uncalibrated_threshold,
3251 ..
3252 } => threshold(step, uncalibrated_threshold, notices),
3253 Cond::ExpectationAtLeast { step, .. } => match sem(step)? {
3254 SemKind::Ordinal(_) => Ok(()),
3255 k => refuse(
3256 C::KindMismatch,
3257 subject,
3258 format!("an expectation cannot read {} ({step:?})", k.name()),
3259 ),
3260 },
3261 Cond::Exact(p) => type_predicate(p, env).or_else(|e| refuse(C::KindMismatch, subject, e)),
3262 Cond::Empty(r) | Cond::Nonempty(r) => match crate::expr::ref_ty(r, env) {
3263 Ok(
3264 Ty::List { .. } | Ty::Filtered { .. } | Ty::Shortlist { .. } | Ty::Ranking { .. },
3265 ) => Ok(()),
3266 Ok(t) => refuse(C::KindMismatch, subject, format!("empty() of {}", t.name())),
3267 Err(e) => refuse(C::KindMismatch, subject, e),
3268 },
3269 Cond::All(cs) | Cond::Any(cs) => cs
3270 .iter()
3271 .try_for_each(|c| check_cond(c, env, subject, notices)),
3272 Cond::Not(c) => check_cond(c, env, subject, notices),
3273 }
3274}
3275
3276fn static_derivations(
3278 def: &Definition,
3279 inputs: &BTreeMap<String, (Ty, InputDecl)>,
3280 order: &[String],
3281 deps: &BTreeMap<String, Vec<String>>,
3282 infos: &BTreeMap<String, StepInfo>,
3283) -> BTreeMap<String, Derivation> {
3284 let semantic: BTreeSet<&str> = def
3285 .steps
3286 .iter()
3287 .filter(|s| {
3288 matches!(
3289 s.body,
3290 StepBody::Semantic(_)
3291 | StepBody::Generate(_)
3292 | StepBody::Extract(_)
3293 | StepBody::Rank(_)
3294 )
3295 })
3296 .map(|s| s.id.as_str())
3297 .collect();
3298 let mut out: BTreeMap<String, Derivation> = BTreeMap::new();
3299 for id in order {
3300 if def
3301 .steps
3302 .iter()
3303 .any(|s| &s.id == id && matches!(s.body, StepBody::Select(_)))
3304 {
3305 out.insert(id.clone(), Derivation::MixedDerived);
3306 continue;
3307 }
3308 if let Some(StepInfo::Acquisition(a)) = infos.get(id) {
3309 out.insert(id.clone(), a.plan.derivation);
3310 continue;
3311 }
3312 if let Some(StepInfo::Accept(a)) = infos.get(id) {
3313 let source = base_ref_v2(&a.field);
3314 let class = source
3315 .strip_prefix("step:")
3316 .and_then(|s| out.get(s))
3317 .copied()
3318 .unwrap_or(Derivation::ModelDerived);
3319 out.insert(id.clone(), class);
3320 continue;
3321 }
3322 if semantic.contains(id.as_str()) {
3323 out.insert(id.clone(), Derivation::ModelDerived);
3324 continue;
3325 }
3326 let claim_only;
3329 let reads: &[String] = match infos.get(id) {
3330 Some(StepInfo::Corroborate { decl, .. }) => {
3331 claim_only = vec![quality::claim_path(decl).0];
3332 &claim_only
3333 }
3334 _ => &deps[id],
3335 };
3336 let all_exact = reads.iter().all(|r| {
3337 if let Some(n) = r.strip_prefix("input:") {
3338 !inputs
3339 .get(n)
3340 .is_some_and(|(_, d)| d.provenance.contains(&ProvenanceClass::ModelDerived))
3341 } else if let Some(s) = step_ref(r) {
3342 out.get(s) == Some(&Derivation::ExactDerived)
3343 } else {
3344 true
3345 }
3346 });
3347 out.insert(
3348 id.clone(),
3349 if all_exact {
3350 Derivation::ExactDerived
3351 } else {
3352 Derivation::MixedDerived
3353 },
3354 );
3355 }
3356 out
3357}
3358
3359#[cfg(test)]
3360mod tests {
3361 use super::*;
3362
3363 #[test]
3364 fn v2_construct_describes_extraction_and_acceptance_separately() {
3365 let mut def: Definition =
3366 serde_json::from_str(include_str!("testdata/support-routing.definition.json")).unwrap();
3367 for (fixture, description) in [
3368 (
3369 include_str!("testdata/extract-step.json"),
3370 "an extraction step",
3371 ),
3372 (
3373 include_str!("testdata/accept-step.json"),
3374 "an accept_model_derived step",
3375 ),
3376 ] {
3377 def.steps = vec![serde_json::from_str(fixture).unwrap()];
3378 assert_eq!(
3379 first_v2_construct(&def, &BTreeMap::new()),
3380 Some((format!("step:{}", def.steps[0].id), description)),
3381 );
3382 }
3383 }
3384}