app-kit 0.0.2

Application and durable workflow composition for ai-kit
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
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
//! Preparing a run admits a durable boundary without executing its entry node.
//! These tests exercise the existing admission transaction and run owners.

use std::num::NonZeroUsize;
use std::path::{Path, PathBuf};
use std::process::{Child, Command};
use std::time::Duration;

use agents_kit::Agent;
use app_kit::workflow::{RunSelector, RunStatus, WorkflowDefinition, WorkflowState};
use app_kit::{App, AppConfig, Shutdown, WorkspaceConfig, WorkspaceId};
use serde_json::{Map, json};
use storage_kit::state::config::{LanceStateStoreConfig, StateStoreConfig};
use storage_kit::{StateStore, StateStoreBackend, StateTransactionBackend};

struct Preparation;

// This process exits after durable admission without running App/StateStore
// destructors. The parent always reaps it, including assertion/error paths.
struct PreparationProcess {
    directory: PathBuf,
    child: Option<Child>,
}

impl PreparationProcess {
    fn start() -> Self {
        Self::start_case("prepared_checkpoint_zero_survives_process_loss", None)
    }

    fn start_case(name: &str, boundary: Option<CrashBoundary>) -> Self {
        let directory = std::env::temp_dir().join(format!(
            "app-prepared-recovery-{}",
            uuid::Uuid::new_v4().simple()
        ));
        std::fs::create_dir(&directory).expect("isolated recovery directory");
        let child = Command::new(std::env::current_exe().expect("test executable"))
            .args(["--exact", name, "--nocapture"])
            .env("AI_KIT_PREPARED_RECOVERY_CHILD", &directory)
            .env(
                "AI_KIT_APP_CRASH_BOUNDARY",
                boundary.map(CrashBoundary::name).unwrap_or("prepared"),
            )
            .spawn()
            .expect("start prepared recovery child");
        Self {
            directory,
            child: Some(child),
        }
    }

    async fn wait(&mut self) {
        tokio::time::timeout(Duration::from_secs(8), async {
            loop {
                if let Some(status) = self
                    .child
                    .as_mut()
                    .expect("owned child")
                    .try_wait()
                    .expect("observe recovery child")
                {
                    self.child.take();
                    assert!(status.success(), "recovery child failed: {status}");
                    return;
                }
                tokio::time::sleep(Duration::from_millis(10)).await;
            }
        })
        .await
        .expect("recovery child exits within its bound");
    }

    async fn app(directory: &Path) -> App<StateStore, Agent> {
        let store = StateStore::connect(StateStoreConfig::Lance(LanceStateStoreConfig::directory(
            directory.join("app-state"),
        )))
        .await
        .expect("real persistent transactions");
        App::open(AppConfig::new(
            store,
            Vec::new(),
            vec![Preparation::definition()],
        ))
        .await
        .expect("open persistent App")
    }
}

impl Drop for PreparationProcess {
    fn drop(&mut self) {
        if let Some(mut child) = self.child.take() {
            let _ = child.kill();
            if let Err(error) = child.wait() {
                eprintln!(
                    "prepared recovery child reaping failed; retaining its directory: {error}"
                );
                return;
            }
        }
        let _ = std::fs::remove_dir_all(&self.directory);
    }
}

impl Preparation {
    fn definition() -> WorkflowDefinition {
        WorkflowDefinition::parse(
            &json!({
                "schema":"app-kit.workflow/v2", "id":"prepared", "revision":"r1",
                "state":{"count":0}, "required":["count"],
                "reducers":{"count":"reject_concurrent"}, "entry":"first",
                "nodes":[{"id":"first", "step":{"kind":"state", "mutations":[
                    {"kind":"assign", "target":"count", "value":{"kind":"literal", "value":99}}
                ]}}], "routes":{}
            })
            .to_string(),
        )
        .expect("state-only definition")
    }

    async fn app() -> App<StateStore, Agent> {
        let store = StateStore::connect(StateStoreConfig::Lance(LanceStateStoreConfig::memory()))
            .await
            .expect("real memory transactions");
        App::open(AppConfig::new(store, Vec::new(), vec![Self::definition()]))
            .await
            .expect("state-only App")
    }
}

#[tokio::test]
async fn prepare_keeps_checkpoint_zero_parked_through_observers_and_cancellation() {
    let mut app = Preparation::app().await;
    let workspace = app
        .create_workspace(WorkspaceConfig {
            name: None,
            root: std::env::current_dir().expect("workspace path"),
        })
        .await
        .expect("workspace");
    let workflow = workspace
        .workflow("prepared".parse().expect("id"))
        .await
        .expect("workflow");
    let run = workflow
        .prepare(
            WorkflowState::new(Map::from_iter([("count".into(), json!(7))]))
                .expect("initial patch"),
        )
        .await
        .expect("durable checkpoint zero");
    let initial = run.snapshot().await.expect("prepared snapshot");
    assert_eq!(initial.checkpoint, 0);
    assert!(matches!(initial.status, RunStatus::Paused));
    assert_eq!(initial.state.values()["count"], 7);
    let observer = workflow
        .open_run(RunSelector::Latest(run.id().clone()))
        .await
        .expect("independent observer");
    let listed = workflow
        .list_runs(None, NonZeroUsize::new(10).expect("limit"))
        .await
        .expect("list");
    assert_eq!(listed.len(), 1);
    assert_eq!(listed[0].checkpoint, 0);
    assert!(matches!(listed[0].status, RunStatus::Paused));
    let waiting = tokio::time::timeout(Duration::from_secs(3), observer.wait())
        .await
        .expect("wait exposes the parked boundary")
        .expect("parked snapshot");
    assert_eq!(waiting.checkpoint, 0);
    assert_eq!(waiting.state.values()["count"], 7);
    assert!(matches!(waiting.status, RunStatus::Paused));
    // Give already accepted background/recovery work an opportunity to run.
    // A prepared boundary must remain stable under repeated public observation.
    assert!(
        tokio::time::timeout(Duration::from_millis(150), async {
            loop {
                let snapshot = observer.snapshot().await.expect("parked readback");
                assert_eq!(snapshot.checkpoint, 0);
                assert_eq!(snapshot.state.values()["count"], 7);
                assert!(matches!(snapshot.status, RunStatus::Paused));
                tokio::task::yield_now().await;
            }
        })
        .await
        .is_err()
    );
    let accepted = run.cancel(0).await.expect("cancel prepared boundary");
    assert!(accepted.checkpoint > 0, "cancellation intent is committed");
    assert_eq!(accepted.state.values()["count"], 7);
    let cancelled = tokio::time::timeout(Duration::from_secs(3), observer.wait())
        .await
        .expect("accepted cancellation cleanup must settle")
        .expect("cancelled state");
    assert!(matches!(cancelled.status, RunStatus::Cancelled));
    assert_eq!(cancelled.state.values()["count"], 7);
    app.shutdown(Shutdown::CancelAndDrain {
        timeout: Duration::from_secs(3),
    })
    .await
    .expect("owned cancellation drains");
}

#[tokio::test]
async fn prepare_rejects_a_stale_workspace_before_allocating_a_visible_run() {
    let mut app = Preparation::app().await;
    let workspace = app
        .create_workspace(WorkspaceConfig {
            name: None,
            root: std::env::current_dir().expect("workspace path"),
        })
        .await
        .expect("workspace");
    let workflow = workspace
        .workflow("prepared".parse().expect("id"))
        .await
        .expect("workflow");
    let before = workspace
        .snapshot()
        .await
        .expect("current workspace revision");
    workspace
        .replace(
            before.revision,
            WorkspaceConfig {
                name: Some("new revision".into()),
                root: std::env::current_dir().expect("workspace path"),
            },
        )
        .await
        .expect("replace workspace");
    let result = workflow.prepare(WorkflowState::default()).await;
    assert!(matches!(result, Err(app_kit::AppError::Conflict(_))));
    let current = workspace
        .workflow("prepared".parse().expect("id"))
        .await
        .expect("current workflow");
    assert!(
        current
            .list_runs(None, NonZeroUsize::new(10).expect("limit"))
            .await
            .expect("list")
            .is_empty()
    );
    app.shutdown(Shutdown::CancelAndDrain {
        timeout: Duration::from_secs(3),
    })
    .await
    .expect("empty App drains");
}

#[tokio::test]
async fn prepared_checkpoint_zero_survives_process_loss() {
    if let Some(directory) = std::env::var_os("AI_KIT_PREPARED_RECOVERY_CHILD") {
        let directory = PathBuf::from(directory);
        let app = PreparationProcess::app(&directory).await;
        let workspace = app
            .create_workspace(WorkspaceConfig {
                name: None,
                root: directory.clone(),
            })
            .await
            .expect("durable workspace");
        let workflow = workspace
            .workflow("prepared".parse().expect("workflow id"))
            .await
            .expect("workflow");
        let run = workflow
            .prepare(
                WorkflowState::new(Map::from_iter([("count".into(), json!(7))]))
                    .expect("initial patch"),
            )
            .await
            .expect("durably prepared run");
        let snapshot = run.snapshot().await.expect("committed checkpoint zero");
        assert_eq!(snapshot.checkpoint, 0);
        assert_eq!(snapshot.state.values()["count"], 7);
        assert!(matches!(snapshot.status, RunStatus::Paused));
        std::fs::write(
            directory.join("identity.json"),
            json!({
                "workspace": workspace.id().to_string(), "run": run.id().to_string(),
                "occurrence": snapshot.occurrence,
            })
            .to_string(),
        )
        .expect("persist test-owned public identities");
        // Process loss is deliberate. Normal handle drop would signal shutdown
        // and would therefore test a different lifecycle transition.
        std::process::exit(0);
    }

    let mut process = PreparationProcess::start();
    process.wait().await;
    let identities: serde_json::Value = serde_json::from_slice(
        &std::fs::read(process.directory.join("identity.json")).expect("child identities"),
    )
    .expect("identity JSON");
    let workspace_id: WorkspaceId = identities["workspace"]
        .as_str()
        .expect("workspace id")
        .parse()
        .expect("validated workspace id");
    let run_id = identities["run"]
        .as_str()
        .expect("run id")
        .parse()
        .expect("validated run id");
    let mut app = PreparationProcess::app(&process.directory).await;
    let workspace = app
        .workspace(workspace_id)
        .await
        .expect("recovered workspace");
    let workflow = workspace
        .workflow("prepared".parse().expect("workflow id"))
        .await
        .expect("recovered workflow");
    let run = workflow
        .open_run(RunSelector::Exact {
            id: run_id,
            occurrence: identities["occurrence"]
                .as_str()
                .expect("exact occurrence")
                .to_owned(),
        })
        .await
        .expect("same durable run");
    let snapshot = run
        .wait()
        .await
        .expect("prepared recovery exposes checkpoint zero");
    assert_eq!(snapshot.checkpoint, 0);
    assert_eq!(snapshot.state.values()["count"], 7);
    assert!(matches!(snapshot.status, RunStatus::Paused));
    assert!(
        tokio::time::timeout(Duration::from_millis(150), async {
            loop {
                let snapshot = run.snapshot().await.expect("recovered parked truth");
                assert_eq!(snapshot.checkpoint, 0);
                assert_eq!(snapshot.state.values()["count"], 7);
                assert!(matches!(snapshot.status, RunStatus::Paused));
                tokio::task::yield_now().await;
            }
        })
        .await
        .is_err()
    );
    run.cancel(0)
        .await
        .expect("explicit cancellation after recovery");
    let cancelled = tokio::time::timeout(Duration::from_secs(3), run.wait())
        .await
        .expect("recovered cancellation settles")
        .expect("cancelled snapshot");
    assert!(matches!(cancelled.status, RunStatus::Cancelled));
    assert_eq!(cancelled.state.values()["count"], 7);
    app.shutdown(Shutdown::CancelAndDrain {
        timeout: Duration::from_secs(3),
    })
    .await
    .expect("reopened App drains");
    drop(run);
    drop(workflow);
    drop(workspace);
    drop(app);
}

#[derive(Clone, Copy)]
enum CrashBoundary {
    Staged,
    InputStaged,
    BeforeBarrier,
    AfterBarrier,
}

impl CrashBoundary {
    fn name(self) -> &'static str {
        match self {
            Self::Staged => "staged",
            Self::InputStaged => "input-staged",
            Self::BeforeBarrier => "before-barrier",
            Self::AfterBarrier => "after-barrier",
        }
    }

    fn selects(self, record: &storage_kit::state::record::StateRecord) -> bool {
        if !record.key.key().starts_with("history/") || record.value["workflow_id"] != "prepared" {
            return false;
        }
        match self {
            Self::Staged | Self::InputStaged => record
                .value
                .pointer("/checkpoint/staged")
                .and_then(serde_json::Value::as_array)
                .is_some_and(|staged| !staged.is_empty()),
            Self::BeforeBarrier | Self::AfterBarrier => {
                record
                    .value
                    .pointer("/checkpoint/phase/state")
                    .and_then(serde_json::Value::as_str)
                    == Some("routing")
                    && record
                        .value
                        .pointer("/checkpoint/outcomes")
                        .and_then(serde_json::Value::as_array)
                        .is_some_and(|outcomes| outcomes.len() == 1)
            }
        }
    }

    fn definition(self) -> WorkflowDefinition {
        if !matches!(self, Self::InputStaged) {
            return Preparation::definition();
        }
        WorkflowDefinition::parse(
            &json!({
                "schema":"app-kit.workflow/v2","id":"prepared","revision":"r1",
                "state":{"count":0},"required":["count"],"reducers":{"count":"reject_concurrent"},
                "entry":"input","nodes":[{"id":"input","step":{"kind":"input",
                    "message":[{"kind":"text","text":"Supply the retained input"}],
                    "schema":{"type":"integer"},"target":"count"}}],"routes":{}
            })
            .to_string(),
        )
        .unwrap()
    }

    async fn hold(self, directory: &std::path::Path) {
        use std::io::Write;
        let mut ready = std::fs::OpenOptions::new()
            .create_new(true)
            .write(true)
            .open(directory.join("crash-ready.tmp"))
            .expect("one selected native boundary");
        ready.write_all(self.name().as_bytes()).unwrap();
        ready.sync_all().unwrap();
        std::fs::rename(
            directory.join("crash-ready.tmp"),
            directory.join("crash-ready"),
        )
        .unwrap();
        // The parent force-kills this process. No synthetic commit/error or
        // graceful Drop is allowed to substitute for that native crash.
        std::future::pending::<()>().await;
    }
}

struct CrashStore {
    inner: StateStore,
    boundary: Option<CrashBoundary>,
    directory: PathBuf,
}

struct CrashTransaction {
    inner: storage_kit::StateTransaction,
    boundary: Option<CrashBoundary>,
    directory: PathBuf,
    selected: bool,
}

impl StateStoreBackend for CrashStore {
    type Transaction = CrashTransaction;

    async fn load(
        &self,
        key: storage_kit::state::record::StateKey,
    ) -> Result<Option<storage_kit::state::record::StateRecordSnapshot>, storage_kit::StateStoreError>
    {
        self.inner.load(key).await
    }

    async fn list(
        &self,
        request: storage_kit::state::record::StateListRequest,
    ) -> Result<storage_kit::state::record::StateListResponse, storage_kit::StateStoreError> {
        self.inner.list(request).await
    }

    async fn begin_transaction(&self) -> Result<Self::Transaction, storage_kit::StateStoreError> {
        Ok(CrashTransaction {
            inner: self.inner.begin_transaction().await?,
            boundary: self.boundary,
            directory: self.directory.clone(),
            selected: false,
        })
    }
}

impl StateTransactionBackend for CrashTransaction {
    async fn load(
        &mut self,
        key: storage_kit::state::record::StateKey,
    ) -> Result<Option<storage_kit::state::record::StateRecordSnapshot>, storage_kit::StateStoreError>
    {
        self.inner.load(key).await
    }

    async fn put(
        &mut self,
        record: storage_kit::state::record::StateRecord,
    ) -> Result<(), storage_kit::StateStoreError> {
        self.selected |= self
            .boundary
            .is_some_and(|boundary| boundary.selects(&record));
        self.inner.put(record).await
    }

    async fn delete(
        &mut self,
        key: storage_kit::state::record::StateKey,
    ) -> Result<(), storage_kit::StateStoreError> {
        self.inner.delete(key).await
    }

    async fn commit(self) -> Result<(), storage_kit::StateStoreError> {
        if self.selected
            && let Some(boundary @ CrashBoundary::BeforeBarrier) = self.boundary
        {
            boundary.hold(&self.directory).await;
        }
        self.inner.commit().await?;
        if self.selected
            && let Some(boundary) = self.boundary
        {
            boundary.hold(&self.directory).await;
        }
        Ok(())
    }

    async fn rollback(self) -> Result<(), storage_kit::StateStoreError> {
        self.inner.rollback().await
    }
}

struct CrashTyping {
    directory: PathBuf,
}

impl app_kit::workflow::StateTyping for CrashTyping {
    type Data = WorkflowState;

    fn construct_data(&self, state: &WorkflowState) -> Result<Self::Data, app_kit::AppError> {
        Ok(state.clone())
    }

    fn construct_state(&self, data: &Self::Data) -> Result<WorkflowState, app_kit::AppError> {
        Ok(data.clone())
    }

    fn validate_post(
        &self,
        _: &WorkflowState,
        _: &WorkflowState,
        _: &app_kit::workflow::StateChange,
    ) -> Result<(), app_kit::AppError> {
        use std::io::Write;
        let mut effects = std::fs::OpenOptions::new()
            .create(true)
            .append(true)
            .open(self.directory.join("effects"))
            .unwrap();
        writeln!(effects, "state-action").unwrap();
        effects.sync_all().unwrap();
        Ok(())
    }
}

impl PreparationProcess {
    async fn crash_app(
        directory: &std::path::Path,
        boundary: CrashBoundary,
        armed: bool,
    ) -> App<
        CrashStore,
        Agent,
        app_kit::workflow::NoActions,
        app_kit::workflow::NoConditions,
        CrashTyping,
    > {
        let config =
            StateStoreConfig::Lance(LanceStateStoreConfig::directory(directory.join("state")));
        let inner = StateStore::connect(config)
            .await
            .expect("selected real crash store");
        App::open(
            AppConfig::new(
                CrashStore {
                    inner,
                    boundary: armed.then_some(boundary),
                    directory: directory.to_owned(),
                },
                Vec::new(),
                vec![boundary.definition()],
            )
            .with_state_typing(CrashTyping {
                directory: directory.to_owned(),
            }),
        )
        .await
        .unwrap()
    }

    async fn force_at_boundary(&mut self, boundary: CrashBoundary) {
        tokio::time::timeout(Duration::from_secs(20), async {
            loop {
                assert!(
                    self.child.as_mut().unwrap().try_wait().unwrap().is_none(),
                    "crash child cannot exit before the selected native boundary"
                );
                if let Ok(ready) = std::fs::read_to_string(self.directory.join("crash-ready")) {
                    assert_eq!(ready, boundary.name());
                    break;
                }
                tokio::time::sleep(Duration::from_millis(10)).await;
            }
        })
        .await
        .expect("real transaction reaches the selected crash boundary");
        let child = self.child.as_mut().unwrap();
        child.kill().unwrap();
        let status = child.wait().unwrap();
        self.child.take();
        assert!(!status.success(), "parent actually force-kills the child");
    }
}

impl PreparationProcess {
    async fn crash_case(test_name: &str) {
        use app_kit::workflow::{CheckpointKind, ExecutionOptions};
        use futures_util::FutureExt;
        if let Some(directory) = std::env::var_os("AI_KIT_PREPARED_RECOVERY_CHILD") {
            let directory = PathBuf::from(directory);
            let boundary = match std::env::var("AI_KIT_APP_CRASH_BOUNDARY").unwrap().as_str() {
                "staged" => CrashBoundary::Staged,
                "input-staged" => CrashBoundary::InputStaged,
                "before-barrier" => CrashBoundary::BeforeBarrier,
                "after-barrier" => CrashBoundary::AfterBarrier,
                _ => panic!("unknown crash boundary"),
            };
            let app = PreparationProcess::crash_app(&directory, boundary, true).await;
            let workspace = app
                .create_workspace(WorkspaceConfig {
                    name: None,
                    root: directory.clone(),
                })
                .await
                .unwrap();
            let workflow = workspace
                .workflow("prepared".parse().unwrap())
                .await
                .unwrap();
            let mut run = workflow.prepare(WorkflowState::default()).await.unwrap();
            let prepared = run.snapshot().await.unwrap();
            std::fs::write(
                directory.join("identity.json"),
                json!({
                    "workspace": workspace.id().to_string(), "run": run.id().to_string(),
                    "occurrence": prepared.occurrence,
                })
                .to_string(),
            )
            .unwrap();
            let observer = workflow
                .open_run(RunSelector::Exact {
                    id: run.id().clone(),
                    occurrence: prepared.occurrence,
                })
                .await
                .unwrap();
            let completed = run
                .execution(ExecutionOptions::default())
                .await
                .unwrap()
                .finish()
                .await
                .unwrap();
            if matches!(boundary, CrashBoundary::InputStaged) {
                assert!(matches!(completed.status, RunStatus::Paused));
                let [
                    app_kit::workflow::Interaction::Input {
                        sequence,
                        generation,
                        ..
                    },
                ] = completed.interactions.as_slice()
                else {
                    panic!("prepared Input exposes its original target before resolution");
                };
                // Hold the actual Resolve Stage receipt after native commit.
                observer
                    .resolve(
                        *sequence,
                        *generation,
                        app_kit::workflow::Resolution::Input(json!(99)),
                    )
                    .await
                    .unwrap();
            }
            panic!("selected native boundary must remain held until force termination");
        }
        for boundary in [
            CrashBoundary::Staged,
            CrashBoundary::InputStaged,
            CrashBoundary::BeforeBarrier,
            CrashBoundary::AfterBarrier,
        ] {
            let mut process = PreparationProcess::start_case(test_name, Some(boundary));
            process.force_at_boundary(boundary).await;
            let first_effects = if matches!(boundary, CrashBoundary::InputStaged) {
                ""
            } else {
                "state-action\n"
            };
            assert_eq!(
                std::fs::read_to_string(process.directory.join("effects")).unwrap_or_default(),
                first_effects
            );
            let identity: serde_json::Value = serde_json::from_slice(
                &std::fs::read(process.directory.join("identity.json")).unwrap(),
            )
            .unwrap();
            let mut app = tokio::time::timeout(
                Duration::from_secs(10),
                PreparationProcess::crash_app(&process.directory, boundary, false),
            )
            .await
            .expect("native store and App reopen within the recovery budget");
            let observed = std::panic::AssertUnwindSafe(tokio::time::timeout(Duration::from_secs(10), async {
            let workspace = app.workspace(identity["workspace"].as_str().unwrap().parse().unwrap()).await.unwrap();
            let workflow = workspace.workflow("prepared".parse().unwrap()).await.unwrap();
            let mut run = workflow.open_run(RunSelector::Exact { id: identity["run"].as_str().unwrap().parse().unwrap(), occurrence: identity["occurrence"].as_str().unwrap().to_owned() }).await.unwrap();
            let before = run.snapshot().await.unwrap();
            assert_eq!(before.state.values()["count"], if matches!(boundary, CrashBoundary::AfterBarrier) {99} else {0});
            assert_eq!(before.last_action_ordinal, if matches!(boundary, CrashBoundary::AfterBarrier) {Some(0)} else {None});
            let complete = run.execution(ExecutionOptions::default()).await.unwrap().finish().await.unwrap();
            assert!(matches!(complete.status, RunStatus::Succeeded));
            assert_eq!(complete.state.values()["count"], 99);
            assert_eq!(complete.last_action_ordinal, Some(0));
            let history = run.history(None, NonZeroUsize::new(100).unwrap()).await.unwrap();
            assert!(history.next.is_none());
            assert_eq!(history.checkpoints.iter().filter(|row| matches!(row.kind, CheckpointKind::Action)).count(), 1,
                "head/history/receipt reconciliation cannot duplicate the committed action");
            let expected_effects = match boundary {
                CrashBoundary::InputStaged => "",
                CrashBoundary::Staged | CrashBoundary::BeforeBarrier => "state-action\nstate-action\n",
                CrashBoundary::AfterBarrier => "state-action\n",
            };
            assert_eq!(std::fs::read_to_string(process.directory.join("effects")).unwrap_or_default(), expected_effects,
                "a fresh Execution discards recomputable State stages, but committed actions never replay");
            if matches!(boundary, CrashBoundary::InputStaged) {
                assert!(complete.interactions.is_empty());
                assert_eq!(complete.outcomes.len(), 1);
                assert_eq!(complete.outcomes[0].result["value"], 99,
                    "the originally accepted answer survives without another Input resolution");
            }
        })).catch_unwind().await;
            let closed = tokio::time::timeout(
                Duration::from_secs(5),
                app.shutdown(Shutdown::CancelAndDrain {
                    timeout: Duration::from_secs(3),
                }),
            )
            .await;
            drop(app);
            match observed {
                Ok(result) => result.expect("recovered stage/barrier settles within its bound"),
                Err(panic) => std::panic::resume_unwind(panic),
            }
            closed.expect("reopened native owners join").unwrap();
        }
    }
}

#[tokio::test]
async fn staged_action_and_atomic_barrier_survive_forced_process_loss() {
    PreparationProcess::crash_case("staged_action_and_atomic_barrier_survive_forced_process_loss")
        .await;
}