Skip to main content

oxide_batch_plan/
late_binding.rs

1use std::error::Error;
2use std::fmt;
3
4use oxide_batch_core::{
5    ComponentRevision, DefinitionError, DefinitionTokenKind, NodeId, ParameterName,
6    ParameterValueKind, StateSchemaId, StateSchemaVersion, definition_token, validate_token,
7};
8use serde_json::{Value, json};
9
10use crate::{MissingParameterPolicy, ParameterCoercion, SelectorPath};
11
12pub use oxide_batch_core::{
13    MAX_LATE_BOUND_INPUTS, MAX_SCOPED_COMPONENTS, ScopeFrameworkSource, ScopeKind,
14    ScopedComponentId,
15};
16
17definition_token!(
18    ScopeFactoryKind,
19    DefinitionTokenKind::Component,
20    "A stable application-owned kind identifier for one scoped component factory."
21);
22
23definition_token!(
24    ScopeResolverKind,
25    DefinitionTokenKind::Component,
26    "A stable application-owned kind identifier for one scoped late-binding resolver."
27);
28
29/// One accepted source family for a scoped late-bound value.
30#[derive(Clone, Debug, Eq, PartialEq)]
31#[non_exhaustive]
32pub enum LateBoundSource {
33    /// An immutable launch parameter.
34    JobParameter(ParameterName),
35    /// A value from the committed job-execution context visible at scope creation.
36    JobContext {
37        /// Required context schema identity.
38        schema: StateSchemaId,
39        /// Required committed schema version.
40        schema_version: StateSchemaVersion,
41        /// Structured object path.
42        path: SelectorPath,
43    },
44    /// A value from the latest committed context of one logical step.
45    StepContext {
46        /// Logical step whose committed context is selected.
47        node: NodeId,
48        /// Required context schema identity.
49        schema: StateSchemaId,
50        /// Required committed schema version.
51        schema_version: StateSchemaVersion,
52        /// Structured object path.
53        path: SelectorPath,
54    },
55    /// Closed framework metadata with no ambient source access.
56    Framework(ScopeFrameworkSource),
57}
58
59impl LateBoundSource {
60    pub(crate) fn manifest_value(&self) -> Value {
61        match self {
62            Self::JobParameter(name) => json!({
63                "kind": "job_parameter",
64                "name": name.as_str()
65            }),
66            Self::JobContext {
67                schema,
68                schema_version,
69                path,
70            } => json!({
71                "kind": "job_context",
72                "path": path.manifest_value(),
73                "schema": schema.as_str(),
74                "schema_version": schema_version.get()
75            }),
76            Self::StepContext {
77                node,
78                schema,
79                schema_version,
80                path,
81            } => json!({
82                "kind": "step_context",
83                "node": node.as_str(),
84                "path": path.manifest_value(),
85                "schema": schema.as_str(),
86                "schema_version": schema_version.get()
87            }),
88            Self::Framework(source) => json!({
89                "field": source.as_str(),
90                "kind": "framework"
91            }),
92        }
93    }
94}
95
96/// One named, deterministic late-bound input to a scoped component factory.
97#[derive(Clone, Debug, Eq, PartialEq)]
98pub struct LateBoundInput {
99    name: ParameterName,
100    source: LateBoundSource,
101    expected: ParameterValueKind,
102    coercion: ParameterCoercion,
103    missing: MissingParameterPolicy,
104}
105
106impl LateBoundInput {
107    /// Declares one late-bound input.
108    #[must_use]
109    pub const fn new(
110        name: ParameterName,
111        source: LateBoundSource,
112        expected: ParameterValueKind,
113        coercion: ParameterCoercion,
114        missing: MissingParameterPolicy,
115    ) -> Self {
116        Self {
117            name,
118            source,
119            expected,
120            coercion,
121            missing,
122        }
123    }
124
125    /// Borrows the stable factory-input name.
126    #[must_use]
127    pub const fn name(&self) -> &ParameterName {
128        &self.name
129    }
130
131    /// Borrows the structured source declaration.
132    #[must_use]
133    pub const fn source(&self) -> &LateBoundSource {
134        &self.source
135    }
136
137    /// Returns the type required by the factory input.
138    #[must_use]
139    pub const fn expected_kind(&self) -> ParameterValueKind {
140        self.expected
141    }
142
143    /// Returns the deterministic coercion policy.
144    #[must_use]
145    pub const fn coercion(&self) -> ParameterCoercion {
146        self.coercion
147    }
148
149    /// Returns missing-source behavior.
150    #[must_use]
151    pub const fn missing_policy(&self) -> MissingParameterPolicy {
152        self.missing
153    }
154
155    pub(crate) fn manifest_value(&self) -> Value {
156        json!({
157            "coercion": self.coercion.as_str(),
158            "expected": self.expected.as_str(),
159            "missing": self.missing.as_str(),
160            "name": self.name.as_str(),
161            "source": self.source.manifest_value()
162        })
163    }
164}
165
166/// Restart-relevant declaration for one job- or step-scoped component.
167///
168/// Actual resolved values and application resources are deliberately absent.
169/// Declaration order cannot affect fingerprint material because inputs are
170/// canonicalized by their stable input name.
171#[derive(Clone, Debug, Eq, PartialEq)]
172pub struct ScopedComponentDefinition {
173    scope: ScopeKind,
174    id: ScopedComponentId,
175    factory_kind: ScopeFactoryKind,
176    factory_revision: ComponentRevision,
177    resolver_kind: ScopeResolverKind,
178    resolver_revision: ComponentRevision,
179    inputs: Vec<LateBoundInput>,
180}
181
182impl ScopedComponentDefinition {
183    /// Constructs a bounded, canonical scoped-component definition.
184    ///
185    /// # Errors
186    ///
187    /// Rejects more than 64 late-bound inputs or duplicate stable input names.
188    pub fn new(
189        scope: ScopeKind,
190        id: ScopedComponentId,
191        factory_kind: ScopeFactoryKind,
192        factory_revision: ComponentRevision,
193        resolver_kind: ScopeResolverKind,
194        resolver_revision: ComponentRevision,
195        mut inputs: Vec<LateBoundInput>,
196    ) -> Result<Self, LateBindingDefinitionError> {
197        if inputs.len() > MAX_LATE_BOUND_INPUTS {
198            return Err(LateBindingDefinitionError::TooManyInputs {
199                max: MAX_LATE_BOUND_INPUTS,
200            });
201        }
202        inputs.sort_by(|left, right| left.name.cmp(&right.name));
203        if inputs.windows(2).any(|pair| pair[0].name == pair[1].name) {
204            return Err(LateBindingDefinitionError::DuplicateInput);
205        }
206        Ok(Self {
207            scope,
208            id,
209            factory_kind,
210            factory_revision,
211            resolver_kind,
212            resolver_revision,
213            inputs,
214        })
215    }
216
217    /// Returns the attempt-local scope kind.
218    #[must_use]
219    pub const fn scope(&self) -> ScopeKind {
220        self.scope
221    }
222
223    /// Borrows the logical component identifier.
224    #[must_use]
225    pub const fn id(&self) -> &ScopedComponentId {
226        &self.id
227    }
228
229    /// Borrows the application-owned factory kind.
230    #[must_use]
231    pub const fn factory_kind(&self) -> &ScopeFactoryKind {
232        &self.factory_kind
233    }
234
235    /// Borrows the restart-relevant factory revision.
236    #[must_use]
237    pub const fn factory_revision(&self) -> &ComponentRevision {
238        &self.factory_revision
239    }
240
241    /// Borrows the application-owned resolver kind.
242    #[must_use]
243    pub const fn resolver_kind(&self) -> &ScopeResolverKind {
244        &self.resolver_kind
245    }
246
247    /// Borrows the restart-relevant resolver revision.
248    #[must_use]
249    pub const fn resolver_revision(&self) -> &ComponentRevision {
250        &self.resolver_revision
251    }
252
253    /// Borrows late-bound inputs in canonical input-name order.
254    #[must_use]
255    pub fn inputs(&self) -> &[LateBoundInput] {
256        &self.inputs
257    }
258
259    pub(crate) fn manifest_value(&self) -> Value {
260        json!({
261            "factory": {
262                "kind": self.factory_kind.as_str(),
263                "revision": self.factory_revision.as_str()
264            },
265            "id": self.id.as_str(),
266            "inputs": self.inputs.iter().map(LateBoundInput::manifest_value).collect::<Vec<_>>(),
267            "resolver": {
268                "kind": self.resolver_kind.as_str(),
269                "revision": self.resolver_revision.as_str()
270            },
271            "scope": self.scope.as_str()
272        })
273    }
274}
275
276/// Stable failures produced while validating a scoped-component definition.
277#[derive(Clone, Copy, Debug, Eq, PartialEq)]
278#[non_exhaustive]
279pub enum LateBindingDefinitionError {
280    /// One component declared more late-bound inputs than the accepted bound.
281    TooManyInputs {
282        /// Maximum accepted input count.
283        max: usize,
284    },
285    /// Two declarations reused one stable input name.
286    DuplicateInput,
287}
288
289impl fmt::Display for LateBindingDefinitionError {
290    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
291        match self {
292            Self::TooManyInputs { max } => {
293                write!(
294                    formatter,
295                    "scoped component exceeds the late-bound input limit of {max}"
296                )
297            }
298            Self::DuplicateInput => {
299                formatter.write_str("scoped component contains a duplicate input name")
300            }
301        }
302    }
303}
304
305impl Error for LateBindingDefinitionError {}
306
307#[cfg(test)]
308mod tests {
309    #![allow(clippy::expect_used)]
310
311    use oxide_batch_core::{
312        ComponentRevision, NodeId, ParameterName, ParameterValueKind, StateSchemaId,
313        StateSchemaVersion,
314    };
315
316    use super::*;
317
318    fn input(name: &str, source: LateBoundSource) -> LateBoundInput {
319        LateBoundInput::new(
320            ParameterName::new(name).expect("input name"),
321            source,
322            ParameterValueKind::String,
323            ParameterCoercion::Exact,
324            MissingParameterPolicy::Fail,
325        )
326    }
327
328    fn component(inputs: Vec<LateBoundInput>) -> ScopedComponentDefinition {
329        ScopedComponentDefinition::new(
330            ScopeKind::Step,
331            ScopedComponentId::new("reader").expect("component id"),
332            ScopeFactoryKind::new("postgres-reader").expect("factory kind"),
333            ComponentRevision::new("factory-v1").expect("factory revision"),
334            ScopeResolverKind::new("structured-selector").expect("resolver kind"),
335            ComponentRevision::new("resolver-v1").expect("resolver revision"),
336            inputs,
337        )
338        .expect("component definition")
339    }
340
341    #[test]
342    fn declaration_order_does_not_change_canonical_definition_material() {
343        let left = component(vec![
344            input(
345                "tenant",
346                LateBoundSource::JobParameter(ParameterName::new("tenant").expect("parameter")),
347            ),
348            input(
349                "region",
350                LateBoundSource::Framework(ScopeFrameworkSource::DefinitionRevision),
351            ),
352        ]);
353        let right = component(vec![
354            input(
355                "region",
356                LateBoundSource::Framework(ScopeFrameworkSource::DefinitionRevision),
357            ),
358            input(
359                "tenant",
360                LateBoundSource::JobParameter(ParameterName::new("tenant").expect("parameter")),
361            ),
362        ]);
363
364        assert_eq!(left.manifest_value(), right.manifest_value());
365        assert_eq!(left.inputs()[0].name().as_str(), "region");
366        assert_eq!(left.inputs()[1].name().as_str(), "tenant");
367    }
368
369    #[test]
370    fn definition_material_contains_contract_identity_but_no_resolved_value() {
371        let definition = component(vec![input(
372            "cursor",
373            LateBoundSource::StepContext {
374                node: NodeId::new("load").expect("node"),
375                schema: StateSchemaId::new("cursor.v1").expect("schema"),
376                schema_version: StateSchemaVersion::new(1).expect("schema version"),
377                path: SelectorPath::new([String::from("position")]).expect("selector"),
378            },
379        )]);
380        let encoded = serde_json::to_string(&definition.manifest_value()).expect("json");
381
382        assert!(encoded.contains("factory-v1"));
383        assert!(encoded.contains("resolver-v1"));
384        assert!(encoded.contains("cursor.v1"));
385        assert!(encoded.contains("position"));
386        assert!(!encoded.contains("resolved_value"));
387        assert!(!encoded.contains("value_digest"));
388    }
389
390    #[test]
391    fn duplicate_and_over_bound_inputs_fail_closed() {
392        let duplicate = input(
393            "tenant",
394            LateBoundSource::JobParameter(ParameterName::new("tenant").expect("parameter")),
395        );
396        let result = ScopedComponentDefinition::new(
397            ScopeKind::Job,
398            ScopedComponentId::new("service").expect("component id"),
399            ScopeFactoryKind::new("service-factory").expect("factory kind"),
400            ComponentRevision::new("factory-v1").expect("factory revision"),
401            ScopeResolverKind::new("structured-selector").expect("resolver kind"),
402            ComponentRevision::new("resolver-v1").expect("resolver revision"),
403            vec![duplicate.clone(), duplicate],
404        );
405        assert_eq!(result, Err(LateBindingDefinitionError::DuplicateInput));
406
407        let inputs = (0..=MAX_LATE_BOUND_INPUTS)
408            .map(|index| {
409                input(
410                    &format!("input-{index}"),
411                    LateBoundSource::Framework(ScopeFrameworkSource::DefinitionRevision),
412                )
413            })
414            .collect::<Vec<_>>();
415        let result = ScopedComponentDefinition::new(
416            ScopeKind::Job,
417            ScopedComponentId::new("service").expect("component id"),
418            ScopeFactoryKind::new("service-factory").expect("factory kind"),
419            ComponentRevision::new("factory-v1").expect("factory revision"),
420            ScopeResolverKind::new("structured-selector").expect("resolver kind"),
421            ComponentRevision::new("resolver-v1").expect("resolver revision"),
422            inputs,
423        );
424        assert_eq!(
425            result,
426            Err(LateBindingDefinitionError::TooManyInputs {
427                max: MAX_LATE_BOUND_INPUTS
428            })
429        );
430    }
431
432    #[test]
433    fn scoped_components_extend_format4_definition_identity() {
434        use crate::{
435            ExitPattern, FlowGraph, FlowNode, FlowTarget, FlowTransition, StepComponents, StepNode,
436        };
437        use oxide_batch_core::{
438            DefinitionRevision, JobName, MANIFEST_FORMAT_ADVANCED_FLOW, StepName, TerminalKind,
439        };
440
441        let node = NodeId::new("load").expect("node");
442        let graph = FlowGraph::new(node.clone())
443            .with_node(FlowNode::step(StepNode::new(
444                node.clone(),
445                StepName::new("load").expect("step"),
446                StepComponents::Tasklet(ComponentRevision::new("tasklet-v1").expect("revision")),
447            )))
448            .with_transition(FlowTransition::new(
449                node,
450                ExitPattern::new("*").expect("pattern"),
451                FlowTarget::Terminal(TerminalKind::Complete),
452            ))
453            .with_scoped_component(component(vec![input(
454                "tenant",
455                LateBoundSource::JobParameter(ParameterName::new("tenant").expect("parameter")),
456            )]));
457        let plan = graph
458            .compile(
459                &JobName::new("scoped").expect("job"),
460                DefinitionRevision::new("v1").expect("definition revision"),
461            )
462            .expect("compiled");
463
464        assert_eq!(plan.manifest_format(), MANIFEST_FORMAT_ADVANCED_FLOW);
465        assert_eq!(plan.scoped_components().len(), 1);
466        let encoded = String::from_utf8(plan.definition_identity().canonical_manifest().to_vec())
467            .expect("utf8 manifest");
468        assert!(encoded.contains("\"scoped_components\""));
469        assert!(encoded.contains("\"resolver-v1\""));
470        assert!(!encoded.contains("resolved_value"));
471        assert!(!encoded.contains("value_digest"));
472    }
473
474    #[test]
475    fn scoped_component_ceiling_is_enforced_per_scope_not_globally() {
476        use crate::{
477            ExitPattern, FlowGraph, FlowNode, FlowTarget, FlowTransition, StepComponents, StepNode,
478        };
479        use oxide_batch_core::{DefinitionRevision, JobName, StepName, TerminalKind};
480
481        fn empty_component(scope: ScopeKind, id: String) -> ScopedComponentDefinition {
482            ScopedComponentDefinition::new(
483                scope,
484                ScopedComponentId::new(id).expect("component id"),
485                ScopeFactoryKind::new("factory").expect("factory kind"),
486                ComponentRevision::new("factory-v1").expect("factory revision"),
487                ScopeResolverKind::new("selector").expect("resolver kind"),
488                ComponentRevision::new("resolver-v1").expect("resolver revision"),
489                Vec::new(),
490            )
491            .expect("component")
492        }
493
494        fn graph() -> FlowGraph {
495            let node = NodeId::new("load").expect("node");
496            FlowGraph::new(node.clone())
497                .with_node(FlowNode::step(StepNode::new(
498                    node.clone(),
499                    StepName::new("load").expect("step"),
500                    StepComponents::Tasklet(
501                        ComponentRevision::new("tasklet-v1").expect("revision"),
502                    ),
503                )))
504                .with_transition(FlowTransition::new(
505                    node,
506                    ExitPattern::new("*").expect("pattern"),
507                    FlowTarget::Terminal(TerminalKind::Complete),
508                ))
509        }
510
511        let mixed = (0..129).fold(graph(), |graph, index| {
512            graph.with_scoped_component(empty_component(ScopeKind::Job, format!("job-{index}")))
513        });
514        let mixed = (0..128).fold(mixed, |graph, index| {
515            graph.with_scoped_component(empty_component(ScopeKind::Step, format!("step-{index}")))
516        });
517        mixed
518            .compile(
519                &JobName::new("mixed-scope-bound").expect("job"),
520                DefinitionRevision::new("v1").expect("revision"),
521            )
522            .expect("257 total components remain legal when each scope stays below 256");
523
524        let over_one_scope = (0..=MAX_SCOPED_COMPONENTS).fold(graph(), |graph, index| {
525            graph.with_scoped_component(empty_component(ScopeKind::Job, format!("job-{index}")))
526        });
527        assert!(matches!(
528            over_one_scope.compile(
529                &JobName::new("over-scope-bound").expect("job"),
530                DefinitionRevision::new("v1").expect("revision"),
531            ),
532            Err(crate::PlanError::TooManyScopedComponents {
533                max: MAX_SCOPED_COMPONENTS
534            })
535        ));
536    }
537
538    #[test]
539    fn framework_sources_publish_stable_pre_coercion_types() {
540        for source in [
541            ScopeFrameworkSource::JobInstanceId,
542            ScopeFrameworkSource::JobExecutionId,
543            ScopeFrameworkSource::StepExecutionId,
544            ScopeFrameworkSource::Attempt,
545        ] {
546            assert_eq!(source.value_kind(), ParameterValueKind::U64);
547        }
548        for source in [
549            ScopeFrameworkSource::DefinitionRevision,
550            ScopeFrameworkSource::DefinitionFingerprint,
551            ScopeFrameworkSource::LogicalNodeId,
552            ScopeFrameworkSource::StepName,
553        ] {
554            assert_eq!(source.value_kind(), ParameterValueKind::String);
555        }
556    }
557}