behavior-contracts 0.5.0

Language-neutral IR runtime core (expression evaluation, template rendering, execution plan, canonical serialization) shared across DSL implementations. Passes the dsl-contracts conformance vectors byte-for-byte.
Documentation
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
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
//! plan — execution-plan.md reference implementation.
//!
//! run_plan(plan, ops, exec): execute stage groups sequentially, interpret
//! null-binding skip, Skip propagation, and Error Policy Kind (fail/retry/continue)
//! to produce a deterministic result tree. Node execution is delegated to `exec`.
//!
//! Bounded parallel stage execution (bc#23, execution-plan.md §4.1):
//! [`run_plan_parallel`] additionally dispatches the members of a stage on scoped
//! worker threads, bounded by `plan.concurrency`, while COMMITTING interpretation
//! (Skip / Policy Kind / Failure) in ascending index order — the observed result
//! (tree / executed / skipped / failure code+message) is byte-identical to
//! [`run_plan`]. It requires `exec: Fn + Sync` (callable from multiple threads),
//! which is why it is a separate, additive entry point: [`run_plan`] keeps the
//! `FnMut` seam (and stays sequential — a conforming §4.1 fallback) so existing
//! consumers, including [`crate::behavior::run_behavior`]'s stateful exec closure,
//! are untouched.

use crate::value::Value;

#[derive(Debug, Clone)]
pub struct ExecutionPlanSpec {
    pub groups: Vec<Vec<usize>>,
    pub concurrency: i64,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PolicyKind {
    Fail,
    Retry,
    Continue,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RelationKind {
    Single,
    Connection,
}

#[derive(Debug, Clone)]
pub struct OpSpec {
    pub id: String,
    pub parent: Option<usize>,
    pub bind_field: Option<String>,
    pub relation_kind: Option<RelationKind>,
    /// Raw policy string from the vector (validated at run time so unknown
    /// policies fail closed with UNKNOWN_POLICY rather than at parse time).
    pub policy: Option<String>,
}

/// consumer-supplied node execution outcome (mock).
#[derive(Debug, Clone)]
pub enum ExecOutcome {
    Ok(Value),
    Error(String),
}

#[derive(Debug, Clone)]
enum OpState {
    Ok(Value),
    Skipped,
    // Failed is never stored: fail policy raises immediately.
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PlanFailureCode {
    OpFailed,
    UnknownPolicy,
    InvalidPlan,
}

impl PlanFailureCode {
    pub fn as_str(self) -> &'static str {
        match self {
            PlanFailureCode::OpFailed => "OP_FAILED",
            PlanFailureCode::UnknownPolicy => "UNKNOWN_POLICY",
            PlanFailureCode::InvalidPlan => "INVALID_PLAN",
        }
    }
}

#[derive(Debug, Clone)]
pub struct PlanFailure {
    pub code: PlanFailureCode,
    pub message: String,
}

impl std::fmt::Display for PlanFailure {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}: {}", self.code.as_str(), self.message)
    }
}
impl std::error::Error for PlanFailure {}

fn fail<T>(code: PlanFailureCode, message: impl Into<String>) -> Result<T, PlanFailure> {
    Err(PlanFailure {
        code,
        message: message.into(),
    })
}

#[derive(Debug)]
pub struct RunResult {
    states: Vec<Option<OpState>>,
    pub executed: Vec<String>,
    pub skipped: Vec<String>,
    ops_ref: Vec<(String, Option<RelationKind>)>,
}

impl RunResult {
    /// Build the observed result tree (opId → value; Skip → unproduced form).
    pub fn final_tree(&self) -> Vec<(String, Value)> {
        let mut tree = Vec::new();
        for (i, st) in self.states.iter().enumerate() {
            match st {
                Some(OpState::Ok(v)) => tree.push((self.ops_ref[i].0.clone(), v.clone())),
                Some(OpState::Skipped) => tree.push((
                    self.ops_ref[i].0.clone(),
                    unproduced_value(self.ops_ref[i].1),
                )),
                None => {}
            }
        }
        tree
    }
}

fn unproduced_value(kind: Option<RelationKind>) -> Value {
    if kind == Some(RelationKind::Connection) {
        Value::Obj(vec![
            ("items".into(), Value::Arr(vec![])),
            ("cursor".into(), Value::Null),
        ])
    } else {
        Value::Null
    }
}

fn parse_policy(raw: &Option<String>) -> Result<PolicyKind, PlanFailure> {
    match raw.as_deref() {
        None | Some("fail") => Ok(PolicyKind::Fail),
        Some("retry") => Ok(PolicyKind::Retry),
        Some("continue") => Ok(PolicyKind::Continue),
        Some(other) => fail(
            PlanFailureCode::UnknownPolicy,
            format!("unknown policy kind: {other}"),
        ),
    }
}

/// Run the plan. `exec(op, bound_value)` returns the node outcome (mock).
pub fn run_plan<F>(
    plan: Option<&ExecutionPlanSpec>,
    ops: &[OpSpec],
    mut exec: F,
) -> Result<RunResult, PlanFailure>
where
    F: FnMut(&OpSpec, Option<&Value>) -> ExecOutcome,
{
    let n = ops.len();
    let mut states: Vec<Option<OpState>> = vec![None; n];
    let mut executed_idx: Vec<usize> = Vec::new();
    let mut skipped_idx: Vec<usize> = Vec::new();

    let stages: Vec<Vec<usize>> = match plan {
        Some(p) => p.groups.clone(),
        None => (0..n).map(|i| vec![i]).collect(),
    };

    validate_coverage(&stages, n)?;

    for stage in &stages {
        let mut ordered = stage.clone();
        ordered.sort_unstable(); // determinism: concurrency does not change results
        for &i in &ordered {
            let st = run_op(
                i,
                &ops[i],
                &states,
                &mut exec,
                &mut executed_idx,
                &mut skipped_idx,
            )?;
            states[i] = Some(st);
        }
    }

    executed_idx.sort_unstable();
    skipped_idx.sort_unstable();

    Ok(RunResult {
        executed: executed_idx.iter().map(|&i| ops[i].id.clone()).collect(),
        skipped: skipped_idx.iter().map(|&i| ops[i].id.clone()).collect(),
        ops_ref: ops
            .iter()
            .map(|o| (o.id.clone(), o.relation_kind))
            .collect(),
        states,
    })
}

/// Bounded parallel variant of [`run_plan`] (bc#23).
///
/// Deterministic commit protocol (execution-plan.md §4.1), per stage:
/// 1. preflight (ascending index): policy validation, skip decision, and bindField
///    binding are derived from the settled prior-stage states (stage members are
///    mutually independent — §1).
/// 2. dispatch (ascending index, bounded): exec of runnable members runs on scoped
///    worker threads, at most `plan.concurrency` in flight.
/// 3. commit (ascending index): outcomes are interpreted in declaration order, so
///    the failure identity (code + message) matches [`run_plan`] exactly.
///
/// The only observable difference from [`run_plan`] is speculative dispatch: when a
/// member's interpretation fails, later members of the same stage may already have
/// been executed (same allowance as graphddb's historical thread-overlap).
///
/// A consumer shipping a plan with `concurrency > 1` declares that `exec` may be
/// invoked from that many threads concurrently (ship `concurrency: 1` otherwise —
/// that, single-member stages, and intra-stage parent/child dependencies all fall
/// back to sequential dispatch with unchanged results).
pub fn run_plan_parallel<F>(
    plan: Option<&ExecutionPlanSpec>,
    ops: &[OpSpec],
    exec: F,
) -> Result<RunResult, PlanFailure>
where
    F: Fn(&OpSpec, Option<&Value>) -> ExecOutcome + Sync,
{
    let n = ops.len();
    let mut states: Vec<Option<OpState>> = vec![None; n];
    let mut executed_idx: Vec<usize> = Vec::new();
    let mut skipped_idx: Vec<usize> = Vec::new();

    let stages: Vec<Vec<usize>> = match plan {
        Some(p) => p.groups.clone(),
        None => (0..n).map(|i| vec![i]).collect(),
    };
    let concurrency = plan.map(|p| p.concurrency).unwrap_or(1);

    validate_coverage(&stages, n)?;

    for stage in &stages {
        let mut ordered = stage.clone();
        ordered.sort_unstable();

        let has_intra_deps = ordered
            .iter()
            .any(|&i| matches!(ops[i].parent, Some(p) if ordered.contains(&p)));

        if concurrency <= 1 || ordered.len() <= 1 || has_intra_deps {
            // Sequential fallback (§4.1) — identical per-op flow to run_plan.
            for &i in &ordered {
                let st = run_op(
                    i,
                    &ops[i],
                    &states,
                    &mut |op: &OpSpec, b: Option<&Value>| exec(op, b),
                    &mut executed_idx,
                    &mut skipped_idx,
                )?;
                states[i] = Some(st);
            }
            continue;
        }

        // ── parallel path ────────────────────────────────────────────────────
        let pres: Vec<Preflight> = ordered
            .iter()
            .map(|&i| preflight_op(&ops[i], &states))
            .collect();

        // Jobs = runnable members in declaration order; a shared cursor hands them
        // out in that order to at most `concurrency` scoped worker threads.
        let jobs: Vec<usize> = (0..ordered.len())
            .filter(|&k| matches!(pres[k], Preflight::Exec { .. }))
            .collect();
        let workers = (concurrency.max(1) as usize).min(jobs.len());
        let cursor = std::sync::atomic::AtomicUsize::new(0);
        let slots: Vec<std::sync::Mutex<Option<ExecOutcome>>> = (0..ordered.len())
            .map(|_| std::sync::Mutex::new(None))
            .collect();

        std::thread::scope(|scope| {
            for _ in 0..workers {
                scope.spawn(|| loop {
                    let j = cursor.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
                    if j >= jobs.len() {
                        break;
                    }
                    let k = jobs[j];
                    let i = ordered[k];
                    let bound = match &pres[k] {
                        Preflight::Exec { bound, .. } => bound.as_ref(),
                        _ => unreachable!(),
                    };
                    let outcome = exec(&ops[i], bound);
                    *slots[k].lock().unwrap() = Some(outcome);
                });
            }
        }); // worker panics propagate here (like sequential exec panics)

        // Commit (ascending index): declaration-order interpretation.
        for (k, &i) in ordered.iter().enumerate() {
            match &pres[k] {
                Preflight::InvalidPolicy(msg) => {
                    return fail(PlanFailureCode::UnknownPolicy, msg.clone())
                }
                Preflight::Skip => {
                    skipped_idx.push(i);
                    states[i] = Some(OpState::Skipped);
                }
                Preflight::Exec { policy, .. } => {
                    let outcome = slots[k]
                        .lock()
                        .unwrap()
                        .take()
                        .expect("dispatched op must have an outcome");
                    let st = interpret_outcome(
                        i,
                        &ops[i],
                        *policy,
                        outcome,
                        &mut executed_idx,
                        &mut skipped_idx,
                    )?;
                    states[i] = Some(st);
                }
            }
        }
    }

    executed_idx.sort_unstable();
    skipped_idx.sort_unstable();

    Ok(RunResult {
        executed: executed_idx.iter().map(|&i| ops[i].id.clone()).collect(),
        skipped: skipped_idx.iter().map(|&i| ops[i].id.clone()).collect(),
        ops_ref: ops
            .iter()
            .map(|o| (o.id.clone(), o.relation_kind))
            .collect(),
        states,
    })
}

/// Pure pre-exec decision for one op (policy validation → skip decision →
/// bindField binding), shared by the sequential and parallel paths. The order
/// mirrors the sequential run_op exactly: the policy check precedes the skip
/// decision (UNKNOWN_POLICY fires even for ops that would be skipped).
enum Preflight {
    InvalidPolicy(String),
    Skip,
    Exec {
        policy: PolicyKind,
        bound: Option<Value>,
    },
}

fn preflight_op(op: &OpSpec, states: &[Option<OpState>]) -> Preflight {
    let policy = match parse_policy(&op.policy) {
        Ok(p) => p,
        Err(e) => return Preflight::InvalidPolicy(e.message), // fail-closed on unknown
    };

    let mut bound_value: Option<Value> = None;
    if let Some(pidx) = op.parent {
        match states.get(pidx).and_then(|s| s.as_ref()) {
            Some(OpState::Ok(pv)) => {
                if let Some(field) = &op.bind_field {
                    let bound = pv.obj_get(field);
                    match bound {
                        None | Some(Value::Null) => return Preflight::Skip,
                        Some(b) => bound_value = Some(b.clone()),
                    }
                }
            }
            _ => {
                // parent skipped / failed / not produced → skip (chain)
                return Preflight::Skip;
            }
        }
    }
    Preflight::Exec {
        policy,
        bound: bound_value,
    }
}

/// Post-exec interpretation (executed bookkeeping → Policy Kind), shared by both
/// paths so failure messages stay identical.
fn interpret_outcome(
    i: usize,
    op: &OpSpec,
    policy: PolicyKind,
    outcome: ExecOutcome,
    executed_idx: &mut Vec<usize>,
    skipped_idx: &mut Vec<usize>,
) -> Result<OpState, PlanFailure> {
    executed_idx.push(i);

    match outcome {
        ExecOutcome::Ok(v) => Ok(OpState::Ok(v)),
        ExecOutcome::Error(e) => match policy {
            PolicyKind::Fail => fail(
                PlanFailureCode::OpFailed,
                format!("operation '{}' failed under 'fail' policy: {e}", op.id),
            ),
            PolicyKind::Retry => fail(
                PlanFailureCode::OpFailed,
                format!(
                    "operation '{}' failed under 'retry' policy (exhausted): {e}",
                    op.id
                ),
            ),
            PolicyKind::Continue => {
                // failed op produces no Port → treat as unproduced/skip downstream.
                skipped_idx.push(i);
                executed_idx.pop(); // ran but produced no Port
                Ok(OpState::Skipped)
            }
        },
    }
}

fn run_op<F>(
    i: usize,
    op: &OpSpec,
    states: &[Option<OpState>],
    exec: &mut F,
    executed_idx: &mut Vec<usize>,
    skipped_idx: &mut Vec<usize>,
) -> Result<OpState, PlanFailure>
where
    F: FnMut(&OpSpec, Option<&Value>) -> ExecOutcome,
{
    let (policy, bound_value) = match preflight_op(op, states) {
        Preflight::InvalidPolicy(msg) => return fail(PlanFailureCode::UnknownPolicy, msg),
        Preflight::Skip => {
            skipped_idx.push(i);
            return Ok(OpState::Skipped);
        }
        Preflight::Exec { policy, bound } => (policy, bound),
    };

    let outcome = exec(op, bound_value.as_ref());
    interpret_outcome(i, op, policy, outcome, executed_idx, skipped_idx)
}

fn validate_coverage(stages: &[Vec<usize>], n: usize) -> Result<(), PlanFailure> {
    let mut seen = std::collections::HashSet::new();
    for stage in stages {
        for &i in stage {
            if i >= n {
                return fail(
                    PlanFailureCode::InvalidPlan,
                    format!("stage index {i} out of range [0,{n})"),
                );
            }
            if !seen.insert(i) {
                return fail(
                    PlanFailureCode::InvalidPlan,
                    format!("operation {i} appears in more than one stage"),
                );
            }
        }
    }
    if seen.len() != n {
        return fail(
            PlanFailureCode::InvalidPlan,
            format!(
                "plan does not cover all {n} operations (covered {})",
                seen.len()
            ),
        );
    }
    Ok(())
}