tandem-plan-compiler 0.4.42

Mission and plan compiler boundary for Tandem
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
// Copyright (c) 2026 Frumu LTD
// Licensed under the Business Source License 1.1

use std::collections::{BTreeMap, BTreeSet, VecDeque};

use serde::{Deserialize, Serialize};

use crate::plan_package::{
    DependencyResolutionStrategy, PartialFailureMode, ReentryPoint, RoutinePackage,
};

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct RoutineExecutionBatch {
    pub step_ids: Vec<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct RoutineExecutionPlan {
    pub routine_id: String,
    pub strategy: DependencyResolutionStrategy,
    pub partial_failure_mode: PartialFailureMode,
    pub reentry_point: ReentryPoint,
    #[serde(default)]
    pub external_prerequisites: Vec<String>,
    #[serde(default)]
    pub batches: Vec<RoutineExecutionBatch>,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum DependencyPlanningError {
    MissingStepDependency { step_id: String, dependency: String },
    CyclicStepDependencies { remaining_step_ids: Vec<String> },
}

pub fn plan_routine_execution(
    routine: &RoutinePackage,
) -> Result<RoutineExecutionPlan, DependencyPlanningError> {
    let step_ids = routine
        .steps
        .iter()
        .map(|step| step.step_id.clone())
        .collect::<Vec<_>>();
    let step_id_set = step_ids.iter().cloned().collect::<BTreeSet<_>>();
    let routine_dependency_ids = routine
        .dependencies
        .iter()
        .map(|dependency| dependency.routine_id.clone())
        .collect::<BTreeSet<_>>();

    let mut adjacency = BTreeMap::<String, Vec<String>>::new();
    let mut indegree = BTreeMap::<String, usize>::new();
    let mut declared_index = BTreeMap::<String, usize>::new();
    let mut external_prerequisites = BTreeSet::<String>::new();

    for (index, step) in routine.steps.iter().enumerate() {
        adjacency.entry(step.step_id.clone()).or_default();
        indegree.entry(step.step_id.clone()).or_insert(0);
        declared_index.insert(step.step_id.clone(), index);
    }

    for step in &routine.steps {
        for dependency in &step.dependencies {
            if step_id_set.contains(dependency) {
                adjacency
                    .entry(dependency.clone())
                    .or_default()
                    .push(step.step_id.clone());
                *indegree.entry(step.step_id.clone()).or_insert(0) += 1;
            } else if routine_dependency_ids.contains(dependency) {
                external_prerequisites.insert(dependency.clone());
            } else {
                return Err(DependencyPlanningError::MissingStepDependency {
                    step_id: step.step_id.clone(),
                    dependency: dependency.clone(),
                });
            }
        }
    }

    let mut ready = indegree
        .iter()
        .filter_map(|(step_id, degree)| (*degree == 0).then_some(step_id.clone()))
        .collect::<Vec<_>>();
    ready.sort_by_key(|step_id| declared_index.get(step_id).copied().unwrap_or(usize::MAX));
    let mut ready = VecDeque::from(ready);
    let mut planned = Vec::<String>::new();
    let mut batches = Vec::<RoutineExecutionBatch>::new();

    match routine.dependency_resolution.strategy {
        DependencyResolutionStrategy::StrictSequential => {
            batches = step_ids
                .iter()
                .map(|step_id| RoutineExecutionBatch {
                    step_ids: vec![step_id.clone()],
                })
                .collect();
            planned = step_ids.clone();
        }
        DependencyResolutionStrategy::TopologicalSequential => {
            while let Some(step_id) = ready.pop_front() {
                planned.push(step_id.clone());
                batches.push(RoutineExecutionBatch {
                    step_ids: vec![step_id.clone()],
                });
                release_dependents(
                    &step_id,
                    &adjacency,
                    &mut indegree,
                    &declared_index,
                    &mut ready,
                );
            }
        }
        DependencyResolutionStrategy::TopologicalParallel => {
            while !ready.is_empty() {
                let current_batch = ready.drain(..).collect::<Vec<_>>();
                for step_id in &current_batch {
                    planned.push(step_id.clone());
                }
                batches.push(RoutineExecutionBatch {
                    step_ids: current_batch.clone(),
                });

                let mut next_ready = Vec::<String>::new();
                for step_id in &current_batch {
                    collect_released_dependents(
                        step_id,
                        &adjacency,
                        &mut indegree,
                        &mut next_ready,
                    );
                }
                next_ready.sort_by_key(|step_id| {
                    declared_index.get(step_id).copied().unwrap_or(usize::MAX)
                });
                ready = VecDeque::from(next_ready);
            }
        }
    }

    if planned.len() != step_ids.len() {
        let remaining_step_ids = step_ids
            .into_iter()
            .filter(|step_id| !planned.contains(step_id))
            .collect::<Vec<_>>();
        return Err(DependencyPlanningError::CyclicStepDependencies { remaining_step_ids });
    }

    Ok(RoutineExecutionPlan {
        routine_id: routine.routine_id.clone(),
        strategy: routine.dependency_resolution.strategy.clone(),
        partial_failure_mode: routine.dependency_resolution.partial_failure_mode.clone(),
        reentry_point: routine.dependency_resolution.reentry_point.clone(),
        external_prerequisites: external_prerequisites.into_iter().collect(),
        batches,
    })
}

fn release_dependents(
    step_id: &str,
    adjacency: &BTreeMap<String, Vec<String>>,
    indegree: &mut BTreeMap<String, usize>,
    declared_index: &BTreeMap<String, usize>,
    ready: &mut VecDeque<String>,
) {
    let mut released = Vec::<String>::new();
    collect_released_dependents(step_id, adjacency, indegree, &mut released);
    released.sort_by_key(|candidate| declared_index.get(candidate).copied().unwrap_or(usize::MAX));
    for candidate in released {
        ready.push_back(candidate);
    }
}

fn collect_released_dependents(
    step_id: &str,
    adjacency: &BTreeMap<String, Vec<String>>,
    indegree: &mut BTreeMap<String, usize>,
    released: &mut Vec<String>,
) {
    if let Some(dependents) = adjacency.get(step_id) {
        for dependent in dependents {
            if let Some(entry) = indegree.get_mut(dependent) {
                *entry -= 1;
                if *entry == 0 {
                    released.push(dependent.clone());
                }
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::plan_package::{
        ApprovalMode, AuditScope, CrossRoutineVisibility, DataScope, DependencyResolution,
        DependencyResolutionStrategy, FinalArtifactVisibility, IntermediateArtifactVisibility,
        MidRoutineConnectorFailureMode, MissionContextScope, PartialFailureMode, ReentryPoint,
        RoutineConnectorResolution, RoutineDependency, RoutineSemanticKind, RunHistoryVisibility,
        StepPackage, SuccessCriteria, TriggerDefinition, TriggerKind,
    };

    fn sample_routine(strategy: DependencyResolutionStrategy) -> RoutinePackage {
        RoutinePackage {
            routine_id: "routine_a".to_string(),
            semantic_kind: RoutineSemanticKind::Mixed,
            trigger: TriggerDefinition {
                trigger_type: TriggerKind::Manual,
                schedule: None,
                timezone: None,
            },
            dependencies: vec![RoutineDependency {
                dependency_type: "routine".to_string(),
                routine_id: "upstream_routine".to_string(),
                mode: crate::plan_package::DependencyMode::Hard,
            }],
            dependency_resolution: DependencyResolution {
                strategy,
                partial_failure_mode: PartialFailureMode::PauseDownstreamOnly,
                reentry_point: ReentryPoint::FailedStep,
                mid_routine_connector_failure: MidRoutineConnectorFailureMode::SurfaceAndPause,
            },
            connector_resolution: RoutineConnectorResolution::default(),
            data_scope: DataScope {
                readable_paths: vec!["mission.goal".to_string()],
                writable_paths: vec!["knowledge/workflows/drafts/routine_a/**".to_string()],
                denied_paths: vec!["credentials/**".to_string()],
                cross_routine_visibility: CrossRoutineVisibility::None,
                mission_context_scope: MissionContextScope::GoalAndOwnRoutine,
                mission_context_justification: None,
            },
            audit_scope: AuditScope {
                run_history_visibility: RunHistoryVisibility::PlanOwner,
                named_audit_roles: Vec::new(),
                intermediate_artifact_visibility: IntermediateArtifactVisibility::RoutineOnly,
                final_artifact_visibility: FinalArtifactVisibility::PlanOwner,
            },
            success_criteria: SuccessCriteria::default(),
            steps: vec![
                StepPackage {
                    step_id: "step_a".to_string(),
                    label: "A".to_string(),
                    kind: "analysis".to_string(),
                    action: "A".to_string(),
                    inputs: Vec::new(),
                    outputs: Vec::new(),
                    dependencies: vec!["upstream_routine".to_string()],
                    context_reads: Vec::new(),
                    context_writes: Vec::new(),
                    connector_requirements: Vec::new(),
                    model_policy: Default::default(),
                    approval_policy: ApprovalMode::InternalOnly,
                    success_criteria: SuccessCriteria::default(),
                    failure_policy: Default::default(),
                    retry_policy: Default::default(),
                    artifacts: Vec::new(),
                    provenance: None,
                    notes: None,
                },
                StepPackage {
                    step_id: "step_b".to_string(),
                    label: "B".to_string(),
                    kind: "analysis".to_string(),
                    action: "B".to_string(),
                    inputs: Vec::new(),
                    outputs: Vec::new(),
                    dependencies: vec!["step_a".to_string()],
                    context_reads: Vec::new(),
                    context_writes: Vec::new(),
                    connector_requirements: Vec::new(),
                    model_policy: Default::default(),
                    approval_policy: ApprovalMode::InternalOnly,
                    success_criteria: SuccessCriteria::default(),
                    failure_policy: Default::default(),
                    retry_policy: Default::default(),
                    artifacts: Vec::new(),
                    provenance: None,
                    notes: None,
                },
                StepPackage {
                    step_id: "step_c".to_string(),
                    label: "C".to_string(),
                    kind: "analysis".to_string(),
                    action: "C".to_string(),
                    inputs: Vec::new(),
                    outputs: Vec::new(),
                    dependencies: vec!["step_a".to_string()],
                    context_reads: Vec::new(),
                    context_writes: Vec::new(),
                    connector_requirements: Vec::new(),
                    model_policy: Default::default(),
                    approval_policy: ApprovalMode::InternalOnly,
                    success_criteria: SuccessCriteria::default(),
                    failure_policy: Default::default(),
                    retry_policy: Default::default(),
                    artifacts: Vec::new(),
                    provenance: None,
                    notes: None,
                },
                StepPackage {
                    step_id: "step_d".to_string(),
                    label: "D".to_string(),
                    kind: "analysis".to_string(),
                    action: "D".to_string(),
                    inputs: Vec::new(),
                    outputs: Vec::new(),
                    dependencies: vec!["step_b".to_string(), "step_c".to_string()],
                    context_reads: Vec::new(),
                    context_writes: Vec::new(),
                    connector_requirements: Vec::new(),
                    model_policy: Default::default(),
                    approval_policy: ApprovalMode::InternalOnly,
                    success_criteria: SuccessCriteria::default(),
                    failure_policy: Default::default(),
                    retry_policy: Default::default(),
                    artifacts: Vec::new(),
                    provenance: None,
                    notes: None,
                },
            ],
        }
    }

    #[test]
    fn topological_parallel_groups_ready_steps() {
        let routine = sample_routine(DependencyResolutionStrategy::TopologicalParallel);

        let plan = plan_routine_execution(&routine).expect("plan");

        assert_eq!(
            plan.external_prerequisites,
            vec!["upstream_routine".to_string()]
        );
        assert_eq!(
            plan.batches,
            vec![
                RoutineExecutionBatch {
                    step_ids: vec!["step_a".to_string()]
                },
                RoutineExecutionBatch {
                    step_ids: vec!["step_b".to_string(), "step_c".to_string()]
                },
                RoutineExecutionBatch {
                    step_ids: vec!["step_d".to_string()]
                }
            ]
        );
    }

    #[test]
    fn topological_sequential_emits_single_step_batches() {
        let routine = sample_routine(DependencyResolutionStrategy::TopologicalSequential);

        let plan = plan_routine_execution(&routine).expect("plan");

        assert_eq!(
            plan.batches,
            vec![
                RoutineExecutionBatch {
                    step_ids: vec!["step_a".to_string()]
                },
                RoutineExecutionBatch {
                    step_ids: vec!["step_b".to_string()]
                },
                RoutineExecutionBatch {
                    step_ids: vec!["step_c".to_string()]
                },
                RoutineExecutionBatch {
                    step_ids: vec!["step_d".to_string()]
                }
            ]
        );
    }

    #[test]
    fn strict_sequential_uses_declared_order() {
        let mut routine = sample_routine(DependencyResolutionStrategy::StrictSequential);
        routine.steps.swap(1, 2);

        let plan = plan_routine_execution(&routine).expect("plan");

        assert_eq!(
            plan.batches,
            vec![
                RoutineExecutionBatch {
                    step_ids: vec!["step_a".to_string()]
                },
                RoutineExecutionBatch {
                    step_ids: vec!["step_c".to_string()]
                },
                RoutineExecutionBatch {
                    step_ids: vec!["step_b".to_string()]
                },
                RoutineExecutionBatch {
                    step_ids: vec!["step_d".to_string()]
                }
            ]
        );
    }

    #[test]
    fn missing_step_dependency_returns_error() {
        let mut routine = sample_routine(DependencyResolutionStrategy::TopologicalParallel);
        routine.steps[1].dependencies = vec!["missing_step".to_string()];

        let error = plan_routine_execution(&routine).expect_err("missing dependency error");

        assert_eq!(
            error,
            DependencyPlanningError::MissingStepDependency {
                step_id: "step_b".to_string(),
                dependency: "missing_step".to_string(),
            }
        );
    }

    #[test]
    fn cyclic_dependencies_return_error() {
        let mut routine = sample_routine(DependencyResolutionStrategy::TopologicalParallel);
        routine.steps[0].dependencies.push("step_d".to_string());

        let error = plan_routine_execution(&routine).expect_err("cycle error");

        match error {
            DependencyPlanningError::CyclicStepDependencies { remaining_step_ids } => {
                assert!(remaining_step_ids.contains(&"step_a".to_string()));
                assert!(remaining_step_ids.contains(&"step_d".to_string()));
            }
            other => panic!("unexpected error: {other:?}"),
        }
    }
}