automation-structures 0.2.1

Reusable, formally specified building blocks for composing automation systems.
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
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
//! Checked public entry points for reusable execution modalities.

use crate::modalities::fork_join::ForkJoin as ForkJoinCarrier;
use crate::modalities::sequential::Sequential as SequentialCarrier;
use crate::modalities::step_graph::StepGraph as StepGraphCarrier;
use crate::modalities::stream_graph::StreamGraph as StreamGraphCarrier;
use vstd::prelude::*;

verus! {

/// Invalid sequential-execution configuration.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub enum SequentialBuildError {
    /// Sequential execution requires at least one step.
    NoSteps,
    /// The value domain must contain at least one value.
    EmptyValueDomain,
    /// The initial value is outside the configured domain.
    InitialValueOutOfRange,
}

/// A totally ordered, finite-step execution modality.
///
/// # Examples
///
/// ```rust
/// use automation_structures::Sequential;
///
/// let mut execution = Sequential::new(1, 3, 0)?;
/// assert!(execution.begin_step());
/// assert!(execution.complete_step(2));
/// assert!(execution.is_done());
/// # Ok::<(), automation_structures::SequentialBuildError>(())
/// ```
pub struct Sequential {
    inner: SequentialCarrier,
}

impl Sequential {
    #[verifier::type_invariant]
    closed spec fn well_formed(&self) -> bool { self.inner.inv() }

    /// Validate and construct an inactive sequential execution.
    ///
    /// # Errors
    ///
    /// Returns an error for zero steps, an empty value domain, or an out-of-domain
    /// initial value.
    pub fn new(steps: usize, value_domain_size: u64, initial_value: u64)
        -> (result: Result<Self, SequentialBuildError>) {
        if steps == 0 { return Err(SequentialBuildError::NoSteps); }
        if value_domain_size == 0 { return Err(SequentialBuildError::EmptyValueDomain); }
        if initial_value >= value_domain_size {
            return Err(SequentialBuildError::InitialValueOutOfRange);
        }
        Ok(Self { inner: SequentialCarrier::new(steps, value_domain_size, initial_value) })
    }

    /// Total number of steps.
    pub fn steps(&self) -> usize { self.inner.steps }

    /// Number of completed steps.
    pub fn completed(&self) -> usize { self.inner.pc }

    /// Current carried value.
    pub fn value(&self) -> u64 { self.inner.value }

    /// Whether a step is active.
    pub fn is_active(&self) -> bool { self.inner.active }

    /// Whether all steps are complete and inactive.
    pub fn is_done(&self) -> bool { self.inner.pc == self.inner.steps && !self.inner.active }

    /// Read a completed-step value by execution order.
    #[expect(clippy::indexing_slicing, reason = "the branch proves the history index is in bounds")]
    pub fn history(&self, index: usize) -> Option<u64> {
        if index < self.inner.history.len() { Some(self.inner.history[index]) } else { None }
    }

    /// Begin the next step if execution is inactive and incomplete.
    #[must_use]
    pub fn begin_step(&mut self) -> (accepted: bool) {
        proof { use_type_invariant(&*self); }
        let mut carrier = sequential_sentinel();
        core::mem::swap(&mut self.inner, &mut carrier);
        let accepted = carrier.begin_step();
        core::mem::swap(&mut self.inner, &mut carrier);
        accepted
    }

    /// Complete the active step with a value in the configured domain.
    #[must_use]
    pub fn complete_step(&mut self, next_value: u64) -> (accepted: bool) {
        proof { use_type_invariant(&*self); }
        let mut carrier = sequential_sentinel();
        core::mem::swap(&mut self.inner, &mut carrier);
        let accepted = carrier.complete_step(next_value);
        core::mem::swap(&mut self.inner, &mut carrier);
        accepted
    }
}

/// Invalid fork-join configuration.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub enum ForkJoinBuildError {
    /// The value domain must contain at least one value.
    EmptyValueDomain,
    /// The initial worker value is outside the configured domain.
    InitialValueOutOfRange,
}

/// One worker's fork-join lifecycle state.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum WorkerState {
    /// The worker may be started.
    Ready,
    /// The worker is running.
    Running,
    /// The worker has produced its value.
    Complete,
}

/// The global fork-join phase.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum ForkJoinPhase {
    /// Workers may be started and completed.
    Fork,
    /// All workers are complete and the barrier has committed.
    Join,
    /// A stable output snapshot has been produced.
    Done,
}

/// A barriered fork-join execution with a stable output snapshot.
///
/// # Examples
///
/// ```rust
/// use automation_structures::ForkJoin;
///
/// let mut execution = ForkJoin::new(1, 4, 0)?;
/// assert!(execution.start_worker(0));
/// assert!(execution.complete_worker(0, 3));
/// assert!(execution.barrier());
/// assert!(execution.produce_output());
/// assert_eq!(execution.outputs(), Some(&[3][..]));
/// # Ok::<(), automation_structures::ForkJoinBuildError>(())
/// ```
pub struct ForkJoin {
    inner: ForkJoinCarrier,
}

impl ForkJoin {
    #[verifier::type_invariant]
    closed spec fn well_formed(&self) -> bool { self.inner.inv() }

    /// Validate and construct a fork-join execution.
    ///
    /// # Errors
    ///
    /// Returns an error for an empty value domain or an out-of-domain initial value.
    pub fn new(workers: usize, value_domain_size: u64, initial_value: u64)
        -> (result: Result<Self, ForkJoinBuildError>) {
        if value_domain_size == 0 { return Err(ForkJoinBuildError::EmptyValueDomain); }
        if initial_value >= value_domain_size {
            return Err(ForkJoinBuildError::InitialValueOutOfRange);
        }
        Ok(Self { inner: ForkJoinCarrier::new(workers, value_domain_size, initial_value) })
    }

    /// Number of workers.
    pub fn len(&self) -> usize { self.inner.wstate.len() }

    /// Whether no workers are configured.
    pub fn is_empty(&self) -> bool { self.inner.wstate.is_empty() }

    /// Current global phase.
    pub fn phase(&self) -> ForkJoinPhase {
        self.inner.phase
    }

    /// Whether the output snapshot is ready.
    pub fn output_ready(&self) -> bool { self.inner.output_ready }

    /// Read one worker lifecycle state.
    #[expect(clippy::indexing_slicing, reason = "the branch proves the worker index is in bounds")]
    pub fn worker_state(&self, worker: usize) -> Option<WorkerState> {
        if worker >= self.inner.wstate.len() { return None; }
        Some(self.inner.wstate[worker])
    }

    /// Read one worker's current value.
    #[expect(clippy::indexing_slicing, reason = "the branch proves the worker index is in bounds")]
    pub fn worker_value(&self, worker: usize) -> Option<u64> {
        if worker < self.inner.wvalue.len() { Some(self.inner.wvalue[worker]) } else { None }
    }

    /// Read one stable output value after output production.
    #[expect(clippy::indexing_slicing, reason = "the branch proves the output index is in bounds")]
    pub fn output(&self, worker: usize) -> Option<u64> {
        if self.inner.output_ready && worker < self.inner.output_snapshot.len() {
            Some(self.inner.output_snapshot[worker])
        } else { None }
    }

    /// Start one ready worker during the fork phase.
    #[must_use]
    pub fn start_worker(&mut self, worker: usize) -> (accepted: bool) {
        proof { use_type_invariant(&*self); }
        let mut carrier = fork_join_sentinel();
        core::mem::swap(&mut self.inner, &mut carrier);
        let accepted = carrier.start_worker(worker);
        core::mem::swap(&mut self.inner, &mut carrier);
        accepted
    }

    /// Complete one running worker with an in-domain value.
    #[must_use]
    pub fn complete_worker(&mut self, worker: usize, value: u64) -> (accepted: bool) {
        proof { use_type_invariant(&*self); }
        let mut carrier = fork_join_sentinel();
        core::mem::swap(&mut self.inner, &mut carrier);
        let accepted = carrier.complete_worker(worker, value);
        core::mem::swap(&mut self.inner, &mut carrier);
        accepted
    }

    /// Commit the barrier when every worker is complete.
    #[must_use]
    pub fn barrier(&mut self) -> (accepted: bool) {
        proof { use_type_invariant(&*self); }
        let mut carrier = fork_join_sentinel();
        core::mem::swap(&mut self.inner, &mut carrier);
        let accepted = carrier.barrier();
        core::mem::swap(&mut self.inner, &mut carrier);
        accepted
    }

    /// Produce the immutable output snapshot from the joined worker values.
    #[must_use]
    pub fn produce_output(&mut self) -> (accepted: bool) {
        proof { use_type_invariant(&*self); }
        let mut carrier = fork_join_sentinel();
        core::mem::swap(&mut self.inner, &mut carrier);
        let accepted = carrier.produce_output();
        core::mem::swap(&mut self.inner, &mut carrier);
        accepted
    }
}

/// Invalid step-graph configuration.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub enum StepGraphBuildError {
    /// At least one edge endpoint is outside the node universe.
    EdgeEndpointOutOfRange,
    /// Duplicate edges are not admitted.
    DuplicateEdge,
}

/// One step's lifecycle state.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum StepState {
    /// A predecessor is incomplete.
    NotReady,
    /// All predecessors are complete.
    Ready,
    /// The step is running.
    Running,
    /// The step is complete.
    Complete,
}

/// A predecessor-governed directed step graph.
///
/// # Examples
///
/// ```rust
/// use automation_structures::StepGraph;
///
/// let mut graph = StepGraph::new(2, vec![(0, 1)])?;
/// assert!(graph.start(0));
/// assert!(graph.complete(0));
/// assert!(graph.become_ready(1));
/// # Ok::<(), automation_structures::StepGraphBuildError>(())
/// ```
pub struct StepGraph {
    inner: StepGraphCarrier,
}

impl StepGraph {
    #[verifier::type_invariant]
    closed spec fn well_formed(&self) -> bool { self.inner.inv() }

    /// Validate edges and construct initial readiness states.
    ///
    /// # Errors
    ///
    /// Returns an error when an endpoint is outside the node universe or an edge is duplicated.
    pub fn new(num_nodes: usize, edges: Vec<(usize, usize)>)
        -> (result: Result<Self, StepGraphBuildError>) {
        if !step_edges_valid(&edges, num_nodes) {
            return Err(StepGraphBuildError::EdgeEndpointOutOfRange);
        }
        if !step_edges_distinct(&edges) { return Err(StepGraphBuildError::DuplicateEdge); }
        Ok(Self { inner: StepGraphCarrier::new(num_nodes, edges) })
    }

    /// Number of steps.
    pub fn len(&self) -> usize { self.inner.num_nodes }

    /// Whether the graph has no steps.
    pub fn is_empty(&self) -> bool { self.inner.num_nodes == 0 }

    /// Number of directed predecessor edges.
    pub fn edge_count(&self) -> usize { self.inner.edges.len() }

    /// Read one directed predecessor edge.
    #[expect(clippy::indexing_slicing, reason = "the branch proves the edge index is in bounds")]
    pub fn edge(&self, index: usize) -> Option<(usize, usize)> {
        if index < self.inner.edges.len() { Some(self.inner.edges[index]) } else { None }
    }

    /// Read one step lifecycle state.
    #[expect(clippy::indexing_slicing, reason = "the branch proves the node index is in bounds")]
    pub fn state(&self, node: usize) -> Option<StepState> {
        if node >= self.inner.nstate.len() { return None; }
        Some(self.inner.nstate[node])
    }

    /// Promote a blocked node after every predecessor completes.
    #[must_use]
    pub fn become_ready(&mut self, node: usize) -> (accepted: bool) {
        proof { use_type_invariant(&*self); }
        let mut carrier = step_graph_sentinel();
        core::mem::swap(&mut self.inner, &mut carrier);
        let accepted = carrier.become_ready(node);
        core::mem::swap(&mut self.inner, &mut carrier);
        accepted
    }

    /// Start one ready step.
    #[must_use]
    pub fn start(&mut self, node: usize) -> (accepted: bool) {
        proof { use_type_invariant(&*self); }
        let mut carrier = step_graph_sentinel();
        core::mem::swap(&mut self.inner, &mut carrier);
        let accepted = carrier.start_running(node);
        core::mem::swap(&mut self.inner, &mut carrier);
        accepted
    }

    /// Complete one running step.
    #[must_use]
    pub fn complete(&mut self, node: usize) -> (accepted: bool) {
        proof { use_type_invariant(&*self); }
        let mut carrier = step_graph_sentinel();
        core::mem::swap(&mut self.inner, &mut carrier);
        let accepted = carrier.complete_node(node);
        core::mem::swap(&mut self.inner, &mut carrier);
        accepted
    }

    /// Whether every step is complete.
    #[expect(clippy::indexing_slicing, reason = "the loop proves the state index is in bounds")]
    #[expect(clippy::arithmetic_side_effects, reason = "the loop proves the cursor remains within the vector")]
    pub fn is_done(&self) -> bool {
        let mut index = 0;
        while index < self.inner.nstate.len()
            invariant index <= self.inner.nstate.len(),
            decreases self.inner.nstate.len() - index,
        {
            if !matches!(self.inner.nstate[index], StepState::Complete) { return false; }
            index += 1;
        }
        true
    }
}

/// Invalid stream-graph configuration.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub enum StreamGraphBuildError {
    /// Only three- and four-stage chains are currently represented.
    UnsupportedChainLength,
    /// Every inter-stage queue needs positive capacity.
    ZeroCapacity,
    /// The record value domain must be nonempty.
    EmptyRecordDomain,
}

/// A bounded three- or four-stage FIFO stream graph.
///
/// # Examples
///
/// ```rust
/// use automation_structures::StreamGraph;
///
/// let mut graph = StreamGraph::new(3, 1, 1, 4)?;
/// assert!(graph.ingest(3));
/// assert!(graph.advance_first());
/// assert_eq!(graph.consume(), Some(3));
/// assert!(graph.is_done());
/// # Ok::<(), automation_structures::StreamGraphBuildError>(())
/// ```
pub struct StreamGraph {
    inner: StreamGraphCarrier,
}

impl StreamGraph {
    #[verifier::type_invariant]
    closed spec fn well_formed(&self) -> bool { self.inner.inv() }

    /// Validate and construct an empty stream graph.
    ///
    /// # Errors
    ///
    /// Returns an error for an unsupported chain length, zero queue capacity, or an
    /// empty record domain.
    pub fn new(chain_length: usize, capacity: usize, max_inputs: usize, record_domain_size: u64)
        -> (result: Result<Self, StreamGraphBuildError>) {
        if chain_length != 3 && chain_length != 4 {
            return Err(StreamGraphBuildError::UnsupportedChainLength);
        }
        if capacity == 0 { return Err(StreamGraphBuildError::ZeroCapacity); }
        if record_domain_size == 0 { return Err(StreamGraphBuildError::EmptyRecordDomain); }
        Ok(Self { inner: StreamGraphCarrier::new(
            chain_length, capacity, max_inputs, record_domain_size,
        ) })
    }

    /// Number of execution stages.
    pub fn chain_length(&self) -> usize { self.inner.chain_length }

    /// Per-edge FIFO capacity.
    pub fn capacity(&self) -> usize { self.inner.capacity() }

    /// Records admitted at the source.
    pub fn ingested(&self) -> usize { self.inner.ingested.value() as usize }

    /// Records consumed at the sink.
    pub fn emitted(&self) -> usize { self.inner.emitted.value() as usize }

    /// Current depth of the first queue.
    pub fn first_queue_len(&self) -> usize { self.inner.q1.len() }

    /// Current depth of the second queue.
    pub fn second_queue_len(&self) -> usize { self.inner.q2.len() }

    /// Current depth of the optional third queue.
    pub fn third_queue_len(&self) -> usize { self.inner.q3.len() }

    /// Admit one source record if its value, input bound, and backpressure permit it.
    #[must_use]
    pub fn ingest(&mut self, value: u64) -> (accepted: bool) {
        proof { use_type_invariant(&*self); }
        let mut carrier = stream_graph_sentinel();
        core::mem::swap(&mut self.inner, &mut carrier);
        let accepted = carrier.source_ingest(value);
        core::mem::swap(&mut self.inner, &mut carrier);
        accepted
    }

    /// Transfer one FIFO record across the first internal stage.
    #[must_use]
    pub fn advance_first(&mut self) -> (accepted: bool) {
        proof { use_type_invariant(&*self); }
        let mut carrier = stream_graph_sentinel();
        core::mem::swap(&mut self.inner, &mut carrier);
        let accepted = carrier.middle2_fire();
        core::mem::swap(&mut self.inner, &mut carrier);
        accepted
    }

    /// Transfer one FIFO record across the optional four-stage link.
    #[must_use]
    pub fn advance_second(&mut self) -> (accepted: bool) {
        proof { use_type_invariant(&*self); }
        let mut carrier = stream_graph_sentinel();
        core::mem::swap(&mut self.inner, &mut carrier);
        let accepted = carrier.middle3_fire();
        core::mem::swap(&mut self.inner, &mut carrier);
        accepted
    }

    /// Consume and return the next FIFO record at the sink.
    #[expect(clippy::indexing_slicing, reason = "the queue guards prove the sink head is present")]
    pub fn consume(&mut self) -> (value: Option<u64>) {
        proof { use_type_invariant(&*self); }
        let value = if self.inner.chain_length == 3 {
            if self.inner.q2.is_empty() { return None; }
            self.inner.q2.values[0]
        } else {
            if self.inner.q3.is_empty() { return None; }
            self.inner.q3.values[0]
        };
        let mut carrier = stream_graph_sentinel();
        core::mem::swap(&mut self.inner, &mut carrier);
        let accepted = carrier.sink_consume();
        if !accepted {
            core::mem::swap(&mut self.inner, &mut carrier);
            return None;
        }
        core::mem::swap(&mut self.inner, &mut carrier);
        Some(value)
    }

    /// Whether the input bound is reached and every queue is drained.
    pub fn is_done(&self) -> bool {
        self.inner.ingested.value() == self.inner.max_inputs as u64
            && self.inner.q1.is_empty()
            && self.inner.q2.is_empty()
            && self.inner.q3.is_empty()
    }
}

#[expect(clippy::indexing_slicing, reason = "the loop proves the edge index is in bounds")]
#[expect(clippy::arithmetic_side_effects, reason = "the loop proves the cursor remains within the vector")]
#[expect(clippy::ptr_arg, reason = "Verus sequence-view contracts are stated over Vec in this checked boundary")]
fn step_edges_valid(edges: &Vec<(usize, usize)>, num_nodes: usize) -> (valid: bool)
    ensures valid == StepGraphCarrier::edges_valid(edges@, num_nodes),
{
    let mut index = 0;
    while index < edges.len()
        invariant
            index <= edges.len(),
            forall|i: int| 0 <= i < index ==>
                #[trigger] edges@[i].0 < num_nodes && edges@[i].1 < num_nodes,
        decreases edges.len() - index,
    {
        if edges[index].0 >= num_nodes || edges[index].1 >= num_nodes {
            assert(!StepGraphCarrier::edges_valid(edges@, num_nodes));
            return false;
        }
        index = index + 1;
    }
    true
}

#[expect(clippy::indexing_slicing, reason = "the nested loops prove both edge indices are in bounds")]
#[expect(clippy::arithmetic_side_effects, reason = "the loops prove both cursors remain within the vector")]
#[expect(clippy::ptr_arg, reason = "Verus sequence-view contracts are stated over Vec in this checked boundary")]
fn step_edges_distinct(edges: &Vec<(usize, usize)>) -> (distinct: bool)
    ensures distinct == StepGraphCarrier::edges_distinct(edges@),
{
    let mut left = 0;
    while left < edges.len()
        invariant
            left <= edges.len(),
            forall|i: int, j: int| 0 <= i < left && 0 <= j < edges.len() && i != j
                ==> #[trigger] edges@[i] != #[trigger] edges@[j],
        decreases edges.len() - left,
    {
        let mut right = left + 1;
        while right < edges.len()
            invariant
                left < edges.len(),
                left + 1 <= right <= edges.len(),
                forall|j: int| left < j < right ==> edges@[left as int] != edges@[j],
            decreases edges.len() - right,
        {
            if edges[left].0 == edges[right].0 && edges[left].1 == edges[right].1 {
                assert(!StepGraphCarrier::edges_distinct(edges@));
                return false;
            }
            right = right + 1;
        }
        left = left + 1;
    }
    true
}

fn sequential_sentinel() -> (carrier: SequentialCarrier)
    ensures carrier.inv(),
{ SequentialCarrier::new(1, 1, 0) }

fn fork_join_sentinel() -> (carrier: ForkJoinCarrier)
    ensures carrier.inv(),
{ ForkJoinCarrier::new(0, 1, 0) }

fn step_graph_sentinel() -> (carrier: StepGraphCarrier)
    ensures carrier.inv(),
{
    let edges: Vec<(usize, usize)> = Vec::new();
    StepGraphCarrier::new(0, edges)
}

fn stream_graph_sentinel() -> (carrier: StreamGraphCarrier)
    ensures carrier.inv(),
{ StreamGraphCarrier::new(3, 1, 0, 1) }

}

impl Sequential {
    /// Exclusive upper bound of carried values.
    pub fn value_domain_size(&self) -> u64 {
        self.inner.value_domain_size
    }

    /// Borrow completed-step values in execution order.
    pub fn history_values(&self) -> &[u64] {
        self.inner.history.as_slice()
    }
}

impl ForkJoin {
    /// Exclusive upper bound of worker values.
    pub fn value_domain_size(&self) -> u64 {
        self.inner.value_domain_size
    }

    /// Borrow worker lifecycle states by worker index.
    pub fn worker_states(&self) -> &[WorkerState] {
        self.inner.wstate.as_slice()
    }

    /// Borrow current worker values by worker index.
    pub fn worker_values(&self) -> &[u64] {
        self.inner.wvalue.as_slice()
    }

    /// Borrow the stable output snapshot after output production.
    pub fn outputs(&self) -> Option<&[u64]> {
        self.inner
            .output_ready
            .then_some(self.inner.output_snapshot.as_slice())
    }
}

impl StepGraph {
    /// Borrow directed predecessor edges in configured order.
    pub fn edges(&self) -> &[(usize, usize)] {
        self.inner.edges.as_slice()
    }

    /// Borrow all current step states by node index.
    pub fn states(&self) -> &[StepState] {
        self.inner.nstate.as_slice()
    }
}

impl StreamGraph {
    /// Maximum number of source records admitted by this run.
    pub fn max_inputs(&self) -> usize {
        self.inner.max_inputs
    }

    /// Exclusive upper bound of record values.
    pub fn record_domain_size(&self) -> u64 {
        self.inner.record_domain_size
    }

    /// Borrow records waiting at the first FIFO edge.
    pub fn first_queue(&self) -> &[u64] {
        self.inner.q1.values.as_slice()
    }

    /// Borrow records waiting at the second FIFO edge.
    pub fn second_queue(&self) -> &[u64] {
        self.inner.q2.values.as_slice()
    }

    /// Borrow records waiting at the optional third FIFO edge.
    pub fn third_queue(&self) -> &[u64] {
        self.inner.q3.values.as_slice()
    }
}

impl_observational_debug!(Sequential, "Sequential",
    "steps" => steps,
    "completed" => completed,
    "value" => value,
    "active" => is_active,
    "done" => is_done,
);
impl_observational_debug!(ForkJoin, "ForkJoin",
    "len" => len,
    "phase" => phase,
    "output_ready" => output_ready,
);
impl_observational_debug!(StepGraph, "StepGraph",
    "len" => len,
    "edge_count" => edge_count,
    "done" => is_done,
);
impl_observational_debug!(StreamGraph, "StreamGraph",
    "chain_length" => chain_length,
    "capacity" => capacity,
    "ingested" => ingested,
    "emitted" => emitted,
    "first_queue_len" => first_queue_len,
    "second_queue_len" => second_queue_len,
    "third_queue_len" => third_queue_len,
    "done" => is_done,
);

impl_public_error!(SequentialBuildError, {
    Self::NoSteps => "sequential execution requires at least one step",
    Self::EmptyValueDomain => "sequential value domain is empty",
    Self::InitialValueOutOfRange => "initial sequential value is outside its domain",
});
impl_public_error!(ForkJoinBuildError, {
    Self::EmptyValueDomain => "fork-join value domain is empty",
    Self::InitialValueOutOfRange => "initial worker value is outside its domain",
});
impl_public_error!(StepGraphBuildError, {
    Self::EdgeEndpointOutOfRange => "step-graph edge endpoint is outside the node universe",
    Self::DuplicateEdge => "step graph contains a duplicate edge",
});
impl_public_error!(StreamGraphBuildError, {
    Self::UnsupportedChainLength => "stream graph supports only three- or four-stage chains",
    Self::ZeroCapacity => "stream-graph queue capacity must be positive",
    Self::EmptyRecordDomain => "stream-graph record domain is empty",
});