automation-structures 0.1.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
// Bounded executable slice used by the governed-commit semantic bridge.
//
// The slice owns the mapped ResourceRegistry, Budget, PropagationPass,
// ActuationPass, AuditSink, and Sequential carriers. It fixes one
// registry key, one seat, one work item, and a unit resource charge.  Those bounds
// make the cross-tool transition relation finite without changing the transferred
// claim: capacity safety and `Committed => durable audit evidence`.
//
// Runtime boundaries that Rust does not supply are explicit in the API:
//
// - `CommitOutcome` is the external-effect adapter result.  `FailureAfterEffect`
//   records a durable recovery intent before exposing the applied effect, so a
//   retry cannot duplicate the effect.
// - `crash` clears only the volatile process flag.  The six carrier states,
//   effect receipt, audit record, and recovery intent are the modeled durable
//   store and require the registered linearizable persistence provider.
// - scheduler fairness and eventual external-service success remain deployment
//   relies.  Safety and recovery-step correspondence do not assume either.
// - attempt arithmetic is guarded before increment; Budget performs its unit
//   admission in mathematical-integer specifications and overflow-safe u64 code.

use vstd::prelude::*;

use crate::modalities::sequential::Sequential;
use crate::primitives::actuation_pass::ActuationPass;
use crate::primitives::audit_sink::AuditSink;
use crate::primitives::budget::Budget;
use crate::primitives::propagation_pass::PropagationPass;
#[expect(
    unused_imports,
    reason = "Round appears in ghost specifications erased by rustc"
)]
use crate::primitives::propagation_pass::Round;
use crate::primitives::resource_registry::ResourceRegistry;

verus! {

#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum CommitPhase {
    Pending,
    Admitted,
    Ready,
    Retryable,
    RecoveryPending,
    Committed,
    Rejected,
}

/// Frozen abstract phases for the direct source-level refinement proof.  These
/// are the same five observations used by `GovernedCommitAbstract.tla`.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum AbstractPhase {
    Pending,
    Active,
    Recovering,
    Committed,
    Failed,
}

/// One bounded integrated request.  The component fields are the actual
/// executable carriers; the remaining fields expose the external effect,
/// persistence, failure, and recovery boundary absent from the individual rows.
pub struct GovernedCommit {
    pub registry: ResourceRegistry,
    pub budget: Budget,
    pub propagation: PropagationPass,
    pub actuation: ActuationPass,
    pub audit: AuditSink,
    pub sequential: Sequential,
    pub phase: CommitPhase,
    pub attempts: u64,
    pub max_attempts: u64,
    pub effect_applied: bool,
    pub evidence_persisted: bool,
    pub recovery_intent: bool,
    pub crashed: bool,
}

impl GovernedCommit {
    pub open spec fn abstract_phase(&self) -> AbstractPhase {
        if self.phase == CommitPhase::Pending {
            AbstractPhase::Pending
        } else if self.phase == CommitPhase::Admitted
            || self.phase == CommitPhase::Ready
            || self.phase == CommitPhase::Retryable
        {
            AbstractPhase::Active
        } else if self.phase == CommitPhase::RecoveryPending {
            AbstractPhase::Recovering
        } else if self.phase == CommitPhase::Committed {
            AbstractPhase::Committed
        } else {
            AbstractPhase::Failed
        }
    }

    pub open spec fn abstract_used(&self) -> int {
        self.budget.allocated as int + self.budget.reserved as int
    }

    /// The frozen abstract initial predicate, evaluated through the executable
    /// abstraction map above.
    pub open spec fn abstract_init(&self) -> bool {
        &&& self.abstract_phase() == AbstractPhase::Pending
        &&& self.abstract_used() == 0
        &&& !self.effect_applied
        &&& !self.evidence_persisted
        &&& !self.recovery_intent
    }

    /// Direct Verus counterpart of `AbstractSystemStep`.
    pub open spec fn abstract_system_step(
        pre: &GovernedCommit,
        post: &GovernedCommit,
    ) -> bool {
        &&& post.budget.capacity == pre.budget.capacity
        &&& post.effect_applied == pre.effect_applied
        &&& post.evidence_persisted == pre.evidence_persisted
        &&& post.recovery_intent == pre.recovery_intent
        &&& ((pre.abstract_phase() == AbstractPhase::Pending
                && post.abstract_phase() == AbstractPhase::Active
                && post.abstract_used() == 1)
            || (pre.abstract_phase() == AbstractPhase::Active
                && post.abstract_phase() == AbstractPhase::Active
                && post.abstract_used() == pre.abstract_used()))
    }

    /// Direct Verus counterpart of `AbstractFailureStep`.  Rejection, retry,
    /// partial failure, and crash are exhaustive named arms.
    pub open spec fn abstract_failure_step(
        pre: &GovernedCommit,
        post: &GovernedCommit,
    ) -> bool {
        &&& post.budget.capacity == pre.budget.capacity
        &&& ((post.abstract_phase() == AbstractPhase::Failed
                && post.abstract_used() == pre.abstract_used()
                && post.effect_applied == pre.effect_applied
                && post.evidence_persisted == pre.evidence_persisted
                && post.recovery_intent == pre.recovery_intent)
            || (pre.abstract_phase() == AbstractPhase::Active
                && post.abstract_phase() == AbstractPhase::Active
                && post.abstract_used() == pre.abstract_used()
                && post.effect_applied == pre.effect_applied
                && post.evidence_persisted == pre.evidence_persisted
                && post.recovery_intent == pre.recovery_intent)
            || (pre.abstract_phase() == AbstractPhase::Active
                && post.abstract_phase() == AbstractPhase::Recovering
                && post.abstract_used() == pre.abstract_used()
                && post.effect_applied
                && !post.evidence_persisted
                && post.recovery_intent)
            || (post.abstract_phase() == pre.abstract_phase()
                && post.abstract_used() == pre.abstract_used()
                && post.effect_applied == pre.effect_applied
                && post.evidence_persisted == pre.evidence_persisted
                && post.recovery_intent == pre.recovery_intent))
    }

    /// Direct Verus counterpart of `AbstractCommitStep`.
    pub open spec fn abstract_commit_step(
        pre: &GovernedCommit,
        post: &GovernedCommit,
    ) -> bool {
        &&& (pre.abstract_phase() == AbstractPhase::Active
            || pre.abstract_phase() == AbstractPhase::Recovering)
        &&& post.abstract_phase() == AbstractPhase::Committed
        &&& post.budget.capacity == pre.budget.capacity
        &&& post.abstract_used() == 1
        &&& post.effect_applied
        &&& post.evidence_persisted
        &&& !post.recovery_intent
    }

    /// Direct Verus counterpart of the registered restart stutter.
    pub open spec fn abstract_stutter_step(
        pre: &GovernedCommit,
        post: &GovernedCommit,
    ) -> bool {
        &&& post.abstract_phase() == pre.abstract_phase()
        &&& post.budget.capacity == pre.budget.capacity
        &&& post.abstract_used() == pre.abstract_used()
        &&& post.effect_applied == pre.effect_applied
        &&& post.evidence_persisted == pre.evidence_persisted
        &&& post.recovery_intent == pre.recovery_intent
    }

    /// Concrete and abstract external observations agree by the frozen phase
    /// projection; effect and audit fields are identity-mapped.
    pub open spec fn abstract_observation_agrees(&self) -> bool {
        &&& ((self.phase == CommitPhase::Committed)
            == (self.abstract_phase() == AbstractPhase::Committed))
        &&& ((self.phase == CommitPhase::Rejected
                || self.phase == CommitPhase::RecoveryPending)
            == (self.abstract_phase() == AbstractPhase::Failed
                || self.abstract_phase() == AbstractPhase::Recovering))
    }

    pub proof fn prove_observation_agreement(&self)
        ensures self.abstract_observation_agrees(),
    {
    }

    pub open spec fn component_invariants(&self) -> bool {
        &&& self.registry.unique_mapping()
        &&& self.budget.safety_invariant()
        &&& self.propagation.inv()
        &&& self.actuation.invariant()
        &&& self.audit.inv()
        &&& self.sequential.inv()
    }

    pub open spec fn integrated_coupling(&self) -> bool {
        &&& self.max_attempts > 0
        &&& self.attempts <= self.max_attempts
        &&& self.propagation.num_nodes == 1
        &&& self.propagation.max_iterations == 1
        &&& self.propagation.max_value == 0
        &&& self.propagation.edges@.len() == 0
        &&& self.registry.contains_key(0)
        &&& self.actuation.num_seats == 1
        &&& self.actuation.allocation@.len() == 1
        &&& self.actuation.allocation@[0] is Some
        &&& self.actuation.effects@.len() == 1
        &&& self.audit.max_log_len == 1
        &&& self.sequential.steps == 3
        &&& self.sequential.value_domain_size == 4
        &&& !self.sequential.active
        &&& (self.effect_applied == (self.actuation.effects@[0] is Some))
        &&& (self.evidence_persisted == (self.audit.log@.len() == 1))
        &&& (self.phase == CommitPhase::Pending ==> self.sequential.pc == 0)
        &&& (self.phase == CommitPhase::Pending
                ==> self.budget.allocated == 0
                    && self.budget.reserved == 0
                    && !self.effect_applied
                    && !self.evidence_persisted
                    && !self.recovery_intent)
        &&& (self.phase == CommitPhase::Admitted ==> self.sequential.pc == 1)
        &&& (self.phase == CommitPhase::Ready
             || self.phase == CommitPhase::Retryable
             || self.phase == CommitPhase::RecoveryPending
                ==> self.sequential.pc == 2)
        &&& (self.phase == CommitPhase::Committed ==> self.sequential.pc == 3)
        &&& (self.phase == CommitPhase::Admitted
             || self.phase == CommitPhase::Ready
             || self.phase == CommitPhase::Retryable
             || self.phase == CommitPhase::RecoveryPending
                ==> self.budget.reserved == 1)
        &&& (self.phase == CommitPhase::Admitted
             || self.phase == CommitPhase::Ready
             || self.phase == CommitPhase::Retryable
                ==> self.budget.allocated == 0
                    && !self.effect_applied
                    && !self.evidence_persisted
                    && !self.recovery_intent)
        &&& (self.phase == CommitPhase::Rejected
                ==> !self.effect_applied && !self.evidence_persisted && !self.recovery_intent)
        &&& (self.phase == CommitPhase::RecoveryPending
                ==> self.budget.allocated == 0
                    && self.effect_applied
                    && self.recovery_intent
                    && !self.evidence_persisted)
        &&& (self.phase == CommitPhase::Committed
                ==> self.effect_applied
                    && self.evidence_persisted
                    && !self.recovery_intent
                    && self.budget.allocated == 1
                    && self.budget.reserved == 0)
    }

    pub open spec fn inv(&self) -> bool {
        self.component_invariants() && self.integrated_coupling()
    }

    /// The exact bounded guarantee transferred by the semantic bridge.
    pub open spec fn transferred_guarantee(&self) -> bool {
        &&& self.budget.used() <= self.budget.capacity as int
        &&& (self.phase == CommitPhase::Committed ==> self.evidence_persisted)
    }

    pub fn new(resource: u64, capacity: u64, max_attempts: u64) -> (s: GovernedCommit)
        requires capacity <= 1, 0 < max_attempts <= 2,
        ensures
            s.inv(),
            s.transferred_guarantee(),
            s.abstract_init(),
            s.abstract_observation_agrees(),
            s.phase == CommitPhase::Pending,
            s.attempts == 0,
            !s.effect_applied,
            !s.evidence_persisted,
            !s.recovery_intent,
            !s.crashed,
            s.budget.capacity == capacity,
            s.max_attempts == max_attempts,
    {
        let mut registry = ResourceRegistry::new();
        registry.register(0, resource);

        let budget = Budget::new(capacity);

        let edges: Vec<(usize, usize)> = Vec::new();
        let mut values: Vec<u64> = Vec::new();
        values.push(0);
        let propagation = PropagationPass::new(1, 1, 0, edges, values);

        let mut allocation: Vec<Option<u64>> = Vec::new();
        allocation.push(Some(resource));
        let actuation = ActuationPass::new(allocation, 1);

        let audit = AuditSink::new(1);
        let sequential = Sequential::new(3, 4, 0);

        GovernedCommit {
            registry,
            budget,
            propagation,
            actuation,
            audit,
            sequential,
            phase: CommitPhase::Pending,
            attempts: 0,
            max_attempts,
            effect_applied: false,
            evidence_persisted: false,
            recovery_intent: false,
            crashed: false,
        }
    }

    fn advance(sequential: &mut Sequential, next_value: u64)
        requires
            old(sequential).inv(),
            old(sequential).pc < old(sequential).steps,
            !old(sequential).active,
            next_value < old(sequential).value_domain_size,
        ensures
            final(sequential).inv(),
            final(sequential).steps == old(sequential).steps,
            final(sequential).value_domain_size == old(sequential).value_domain_size,
            final(sequential).pc == old(sequential).pc + 1,
            !final(sequential).active,
            final(sequential).value == next_value,
    {
        let began = sequential.begin_step();
        let _ = began;
        assert(began);
        let completed = sequential.complete_step(next_value);
        let _ = completed;
        assert(completed);
    }

    /// Budget admission.  Capacity rejection is an explicit terminal API result
    /// and leaves every claim-bearing carrier other than the phase unchanged.
    pub fn admit(&mut self) -> (accepted: bool)
        requires
            old(self).inv(),
            !old(self).crashed,
            old(self).phase == CommitPhase::Pending,
            old(self).sequential.pc == 0,
        ensures
            final(self).component_invariants(),
            final(self).integrated_coupling(),
            final(self).transferred_guarantee(),
            accepted ==> Self::abstract_system_step(old(self), final(self)),
            !accepted ==> Self::abstract_failure_step(old(self), final(self)),
            accepted == (old(self).budget.used() + 1 <= old(self).budget.capacity as int),
            accepted ==> final(self).phase == CommitPhase::Admitted,
            !accepted ==> final(self).phase == CommitPhase::Rejected,
            final(self).attempts == old(self).attempts,
            final(self).effect_applied == old(self).effect_applied,
            final(self).evidence_persisted == old(self).evidence_persisted,
    {
        let accepted = self.budget.reserve(1);
        if accepted {
            Self::advance(&mut self.sequential, 1);
            self.phase = CommitPhase::Admitted;
        } else {
            self.phase = CommitPhase::Rejected;
        }
        accepted
    }

    /// Run the one-node propagation witness and advance the Sequential carrier.
    /// This is the bounded readiness stage between admission and effect commit.
    pub fn propagate(&mut self)
        requires
            old(self).inv(),
            !old(self).crashed,
            old(self).phase == CommitPhase::Admitted,
            old(self).sequential.pc == 1,
            old(self).propagation.round == Round::Idle,
            old(self).propagation.changed,
            old(self).propagation.iteration == 0,
        ensures
            final(self).inv(),
            final(self).transferred_guarantee(),
            Self::abstract_system_step(old(self), final(self)),
            final(self).phase == CommitPhase::Ready,
            final(self).sequential.pc == 2,
            final(self).propagation.iteration == 1,
            final(self).propagation.round == Round::Idle,
            !final(self).propagation.changed,
    {
        self.propagation.start_round();
        self.propagation.update_node(0);
        assert(self.propagation.all_updated());
        assert(self.propagation.values@ == self.propagation.snapshot@);
        self.propagation.end_round();
        Self::advance(&mut self.sequential, 2);
        self.phase = CommitPhase::Ready;
    }

    /// Record a failed external-service attempt before any effect occurred.
    /// Calling this action again from `Retryable` is the explicit bounded retry
    /// path; the last permitted failure is a terminal rejection.
    pub fn fail_before_effect(&mut self) -> (terminal: bool)
        requires
            old(self).inv(),
            !old(self).crashed,
            old(self).phase == CommitPhase::Ready
                || old(self).phase == CommitPhase::Retryable,
            old(self).attempts < old(self).max_attempts,
            old(self).sequential.pc == 2,
            !old(self).effect_applied,
            !old(self).evidence_persisted,
        ensures
            final(self).inv(),
            final(self).transferred_guarantee(),
            Self::abstract_failure_step(old(self), final(self)),
            final(self).attempts == old(self).attempts + 1,
            final(self).effect_applied == old(self).effect_applied,
            final(self).evidence_persisted == old(self).evidence_persisted,
            final(self).recovery_intent == old(self).recovery_intent,
            final(self).attempts < final(self).max_attempts ==>
                !terminal && final(self).phase == CommitPhase::Retryable,
            final(self).attempts == final(self).max_attempts ==>
                terminal && final(self).phase == CommitPhase::Rejected,
    {
        self.attempts = self.attempts + 1;
        if self.attempts == self.max_attempts {
            self.phase = CommitPhase::Rejected;
            true
        } else {
            self.phase = CommitPhase::Retryable;
            false
        }
    }

    /// Record the external effect together with a durable recovery intent, then
    /// expose the modeled failure before the audit evidence commit. The effect must not
    /// be retried; only `recover` may complete this state.
    pub fn fail_after_effect(&mut self)
        requires
            old(self).inv(),
            !old(self).crashed,
            old(self).phase == CommitPhase::Ready
                || old(self).phase == CommitPhase::Retryable,
            old(self).attempts < old(self).max_attempts,
            old(self).sequential.pc == 2,
            !old(self).effect_applied,
            !old(self).evidence_persisted,
            old(self).audit.log@.len() == 0,
            old(self).actuation.effects@[0] is None,
        ensures
            final(self).inv(),
            final(self).transferred_guarantee(),
            Self::abstract_failure_step(old(self), final(self)),
            final(self).attempts == old(self).attempts + 1,
            final(self).phase == CommitPhase::RecoveryPending,
            final(self).effect_applied,
            !final(self).evidence_persisted,
            final(self).recovery_intent,
    {
        self.attempts = self.attempts + 1;
        // The durable intent precedes the effect receipt at this API boundary.
        self.recovery_intent = true;
        self.actuation.actuate(0);
        self.effect_applied = true;
        self.phase = CommitPhase::RecoveryPending;
    }

    /// Atomic success boundary for the bounded persistence adapter: effect
    /// receipt, unit-budget commit, audit append, and sequential closure become
    /// visible together at method return.
    pub fn commit_success(&mut self)
        requires
            old(self).inv(),
            !old(self).crashed,
            old(self).phase == CommitPhase::Ready
                || old(self).phase == CommitPhase::Retryable,
            old(self).attempts < old(self).max_attempts,
            old(self).sequential.pc == 2,
            !old(self).effect_applied,
            !old(self).evidence_persisted,
            old(self).audit.log@.len() == 0,
            old(self).actuation.effects@[0] is None,
        ensures
            final(self).inv(),
            final(self).transferred_guarantee(),
            Self::abstract_commit_step(old(self), final(self)),
            final(self).attempts == old(self).attempts + 1,
            final(self).phase == CommitPhase::Committed,
            final(self).effect_applied,
            final(self).evidence_persisted,
            !final(self).recovery_intent,
            final(self).sequential.pc == 3,
    {
        self.attempts = self.attempts + 1;
        self.actuation.actuate(0);
        self.effect_applied = true;
        self.budget.commit_reservation(1);
        let recorded = self.audit.record(0);
        let _ = recorded;
        assert(recorded);
        self.evidence_persisted = true;
        self.recovery_intent = false;
        Self::advance(&mut self.sequential, 3);
        self.phase = CommitPhase::Committed;
    }

    /// Finish a partial failure without reissuing the already applied effect.
    pub fn recover(&mut self)
        requires
            old(self).inv(),
            !old(self).crashed,
            old(self).phase == CommitPhase::RecoveryPending,
            old(self).sequential.pc == 2,
            old(self).audit.log@.len() == 0,
        ensures
            final(self).inv(),
            final(self).transferred_guarantee(),
            Self::abstract_commit_step(old(self), final(self)),
            final(self).phase == CommitPhase::Committed,
            final(self).effect_applied,
            final(self).evidence_persisted,
            !final(self).recovery_intent,
            final(self).sequential.pc == 3,
    {
        self.budget.commit_reservation(1);
        let recorded = self.audit.record(0);
        let _ = recorded;
        assert(recorded);
        self.evidence_persisted = true;
        self.recovery_intent = false;
        Self::advance(&mut self.sequential, 3);
        self.phase = CommitPhase::Committed;
    }

    /// Crash only the volatile process boundary.  All fields named by the
    /// persistence abstraction remain unchanged and therefore survive restart.
    pub fn crash(&mut self)
        requires old(self).inv(),
        ensures
            final(self).inv(),
            final(self).transferred_guarantee(),
            Self::abstract_failure_step(old(self), final(self)),
            final(self).crashed,
            final(self).phase == old(self).phase,
            final(self).effect_applied == old(self).effect_applied,
            final(self).evidence_persisted == old(self).evidence_persisted,
            final(self).recovery_intent == old(self).recovery_intent,
    {
        self.crashed = true;
    }

    pub fn restart(&mut self)
        requires old(self).inv(), old(self).crashed,
        ensures
            final(self).inv(),
            final(self).transferred_guarantee(),
            Self::abstract_stutter_step(old(self), final(self)),
            !final(self).crashed,
            final(self).phase == old(self).phase,
            final(self).effect_applied == old(self).effect_applied,
            final(self).evidence_persisted == old(self).evidence_persisted,
            final(self).recovery_intent == old(self).recovery_intent,
    {
        self.crashed = false;
    }
}

}