causa-runtime 0.0.1

Causa runtime — optional components: execution stack (turn loop, dispatch, streaming, pause/resume, session)
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
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
//! Slice 8 Phase C acceptance: the material-free save loop —
//! `pause → checkpoint → restore → explicit resume` — plus the export
//! guards, the replay semantics, and the validation rejections.
//!
//! C1 — an idle or paused session exports a versioned envelope (the paused
//! phase carries the complete outcome, the state saved once inside it);
//! accepted / running works refuse with `Busy`, a faulted session refuses,
//! and a closed session still exports with `closed` recorded.
//!
//! C2 — restore reloads the work refs, revisions, allocation progress,
//! request-key tables, receipts, results, and deadlines: same-key requests
//! replay their original receipts, different arguments still conflict, the
//! next submit continues the TurnId sequence, old results stay observable,
//! and a restored work resumes under its remaining — never re-granted —
//! deadline.
//!
//! C3 — restore validates version, the assembled configuration description,
//! and material consistency before registering; every rejection hands the
//! original checkpoint back; a successful restore calls no model and no
//! tool, and a restored pause still needs an explicit resume that continues
//! the original continuation.
//!
//! C4 — offline evidence for a config mismatch, a conflict identity, an
//! expired deadline, and a closed owner handover; opening from history
//! stays a different operation from restoring a checkpoint (no dedup
//! table).

mod common;

use std::sync::Arc;
use std::time::Duration;

use causa_kernel::{ContentPart, ConversationId, ModelRef, TextPayload, TurnId};
use causa_runtime::{
    CheckpointPhase, FinishedKind, PausePoint, ResumeRequest, SESSION_CHECKPOINT_VERSION, Session,
    SessionCheckpoint, SessionConfig, SessionConfigDescription, SessionError,
    SessionRestoreRejection, SubmitRequest, TurnInterruption, TurnResult, TurnRunOptions, WaitEnd,
    WorkRef, WorkState,
};
use common::{
    EchoTool, GatedGateway, RecordingGateway, approve, awaiting_echo, endturn_output, idle_session,
    pausing_session, runner_with, session_req, submit_to_pause, tooluse_output,
};
use serde_json::json;

/// A paused session plus its export: the first model call emits an `echo`
/// batch (empty arguments, so [`awaiting_echo`] matches it) that the
/// interaction pauses. The session stays owned by the caller — dropping it
/// would close the session.
async fn paused_checkpoint(
    id: &str,
    config: SessionConfig,
) -> (Session, WorkRef, u64, SessionCheckpoint) {
    let gateway =
        RecordingGateway::scripted(vec![Ok(tooluse_output("approve?", "echo", json!({})))]);
    let session = pausing_session(id, gateway, vec![Arc::new(EchoTool)], config);
    let handle = session.handle();
    let (receipt, paused) = submit_to_pause(&handle, "pause").await;
    let checkpoint = session
        .checkpoint()
        .expect("a paused session exports its envelope");
    (session, receipt.work, paused.revision, checkpoint)
}

/// Restore `checkpoint` against the same default assembly, driving the fresh
/// `gateway` afterwards.
fn restore(
    checkpoint: SessionCheckpoint,
    gateway: Arc<RecordingGateway>,
    config: SessionConfig,
) -> Session {
    SessionCheckpoint::restore(
        checkpoint,
        Arc::new(runner_with(gateway, Vec::new())),
        TurnRunOptions::default(),
        config,
    )
    .expect("the exported envelope restores against the same assembly")
}

// ---- C1: export guards --------------------------------------------------------

#[tokio::test]
async fn an_idle_session_exports_a_versioned_envelope() {
    let session = idle_session("c1-idle", RecordingGateway::scripted(vec![]));
    let checkpoint = session.checkpoint().expect("an idle session exports");

    assert_eq!(checkpoint.version, SESSION_CHECKPOINT_VERSION);
    assert_eq!(checkpoint.conversation_id, ConversationId("c1-idle".into()));
    assert!(matches!(checkpoint.phase, CheckpointPhase::Idle { .. }));
    assert!(checkpoint.works.is_empty());
    assert_eq!(checkpoint.next_turn, 0);
    assert!(checkpoint.submit_keys.is_empty());
    assert!(!checkpoint.closed);
    assert_eq!(
        checkpoint.config,
        SessionConfigDescription::of(&TurnRunOptions::default(), &SessionConfig::default()),
        "the description matches the assembled options"
    );
}

#[tokio::test]
async fn a_paused_session_exports_the_complete_outcome_once() {
    let (_, work, _, checkpoint) = paused_checkpoint("c1-paused", SessionConfig::default()).await;

    let CheckpointPhase::Paused {
        outcome,
        work: paused_ref,
    } = &checkpoint.phase
    else {
        panic!("the paused session exports the paused phase");
    };
    assert_eq!(paused_ref, &work);
    assert!(
        matches!(&outcome.result, TurnResult::Paused { .. }),
        "the outcome carries the paused result and its continuation"
    );
    // The state is saved once — inside the outcome. The works table records
    // the observation view, not a second conversation payload.
    assert_eq!(checkpoint.works.len(), 1);
    assert_eq!(checkpoint.works[0].work, work);
    assert_eq!(checkpoint.works[0].state, WorkState::Paused);
    assert!(checkpoint.works[0].finished.is_none());
    assert_eq!(
        checkpoint.submit_keys.len(),
        1,
        "the submit key is replayable"
    );
}

#[tokio::test]
async fn a_running_work_refuses_export_with_busy() {
    let gateway = GatedGateway::new("held", false);
    let session = idle_session("c1-running", gateway.clone());
    let handle = session.handle();
    let receipt = handle.submit(session_req("s1", "go")).expect("accepted");
    gateway.wait_entered().await;

    match session.checkpoint() {
        Err(SessionError::Busy { active }) => assert_eq!(active, receipt.work),
        other => panic!("expected Busy while the work runs, got {other:?}"),
    }

    gateway.release();
    let done = handle
        .wait(&receipt.work, Duration::from_secs(5))
        .await
        .unwrap();
    assert_eq!(done.observation.state, WorkState::Finished);
    // Quiescent again — the export works.
    assert!(session.checkpoint().is_ok());
}

#[test]
fn a_faulted_session_refuses_export() {
    let rt = tokio::runtime::Builder::new_current_thread()
        .enable_all()
        .build()
        .unwrap();
    let gateway = GatedGateway::new("held", true);
    let session = idle_session("c1-faulted", gateway.clone());
    let handle = session.handle();
    let receipt = rt.block_on(async {
        let receipt = handle.submit(session_req("s1", "go")).unwrap();
        gateway.wait_entered().await;
        receipt
    });
    drop(rt);

    assert_eq!(
        handle.observe(&receipt.work).unwrap().state,
        WorkState::Faulted
    );
    assert!(
        matches!(session.checkpoint(), Err(SessionError::Faulted { .. })),
        "a faulted session has no complete outcome to save"
    );
}

#[tokio::test]
async fn a_closed_session_exports_closed_and_the_restore_keeps_it() {
    let (session, _work, _revision, checkpoint) =
        paused_checkpoint("c4-closed", SessionConfig::default()).await;
    assert!(!checkpoint.closed, "an open owner exports an open envelope");

    // Shutdown keeps the paused material readable and stops acceptance; the
    // export still works and records the closed state.
    session.shutdown().await;
    let checkpoint = session
        .checkpoint()
        .expect("a closed session still exports");
    assert!(checkpoint.closed);

    let restored = restore(
        checkpoint,
        RecordingGateway::scripted(vec![]),
        SessionConfig::default(),
    );
    let handle = restored.handle();
    // The closed state is preserved, not upgraded: a new request is refused,
    // an accepted one still replays its original receipt.
    match handle.submit(session_req("after", "nope")) {
        Err(SessionError::Closed) => {}
        other => panic!("expected Closed for a new request, got {other:?}"),
    }
    let receipt = handle
        .submit(session_req("pause", "go"))
        .expect("the accepted key replays after the closed restore");
    assert_eq!(receipt.work.turn_id, TurnId::new("c4-closed-work-0"));
    assert_eq!(receipt.accepted_revision, 0);
}

// ---- C2: replay, allocation, deadlines ----------------------------------------

#[tokio::test]
async fn restore_replays_submit_receipts_and_keeps_conflicts() {
    let gateway = RecordingGateway::repeating_last(vec![Ok(endturn_output("done"))]);
    let session = idle_session("c2-submit", gateway.clone());
    let handle = session.handle();
    let receipt = handle.submit(session_req("k1", "first")).expect("accepted");
    let done = handle
        .wait(&receipt.work, Duration::from_secs(5))
        .await
        .unwrap();
    assert_eq!(done.observation.state, WorkState::Finished);

    let checkpoint = session.checkpoint().expect("exports when idle");
    let restored = restore(checkpoint, gateway.clone(), SessionConfig::default());
    let handle = restored.handle();

    // Same key, same parts: the original receipt, no second execution.
    let calls = gateway.recorded().len();
    assert_eq!(
        handle.submit(session_req("k1", "first")).expect("replays"),
        receipt
    );
    assert_eq!(
        gateway.recorded().len(),
        calls,
        "the replay executes nothing"
    );

    // Same key, different parts: a conflict, not a new work.
    let other = SubmitRequest {
        request_key: "k1".into(),
        parts: vec![ContentPart::Text(TextPayload::new("different"))],
    };
    assert!(matches!(handle.submit(other), Err(SessionError::Conflict)));

    // The allocation progress continues: the next work takes the next id,
    // and the old result stays observable under its original ref.
    let next = handle
        .submit(session_req("k2", "second"))
        .expect("accepted");
    assert_eq!(next.work.turn_id, TurnId::new("c2-submit-work-1"));
    let done = handle
        .wait(&next.work, Duration::from_secs(5))
        .await
        .unwrap();
    assert_eq!(done.observation.state, WorkState::Finished);
    let old = handle.observe(&receipt.work).unwrap();
    assert_eq!(old.state, WorkState::Finished);
    assert!(
        matches!(old.finished, Some(FinishedKind::Completed { .. })),
        "the restored result is still observable"
    );
}

#[tokio::test]
async fn restore_replays_a_resume_key_without_reexecuting() {
    let (session, work, revision, _pre_save) =
        paused_checkpoint("c2-resume", SessionConfig::default()).await;
    let handle = session.handle();
    let paused = handle.observe(&work).unwrap();
    let Some(PausePoint::AwaitingApproval { prepared, .. }) = paused.paused else {
        panic!("the work needs approval");
    };
    let request = approve(prepared.awaiting);

    // Resume before the save: the key is accepted, the work runs to
    // completion, and the session goes idle again — exportable.
    let resumed = handle
        .resume(&work, revision, "r1".into(), request.clone())
        .expect("the paused work resumes");
    let done = handle.wait(&work, Duration::from_secs(5)).await.unwrap();
    assert_eq!(done.observation.state, WorkState::Finished);

    let checkpoint = session.checkpoint().expect("exports when idle");
    let replay_gateway = RecordingGateway::scripted(vec![Ok(endturn_output("unused"))]);
    let restored = restore(checkpoint, replay_gateway.clone(), SessionConfig::default());
    let handle = restored.handle();

    // The same key with the same request replays the original resume
    // receipt without resuming anything.
    let replay = handle
        .resume(&work, revision, "r1".into(), request.clone())
        .expect("the resume key replays");
    assert_eq!(replay, resumed);
    assert!(
        replay_gateway.recorded().is_empty(),
        "the replay resumed nothing"
    );
    // The same key with a different request is a conflict.
    let conflicting = ResumeRequest {
        decision: request.decision.clone(),
        inject: vec![TextPayload::new("extra")],
    };
    assert!(matches!(
        handle.resume(&work, revision, "r1".into(), conflicting),
        Err(SessionError::Conflict)
    ));
    assert!(
        replay_gateway.recorded().is_empty(),
        "the conflict resumed nothing either"
    );
    assert_eq!(
        handle.observe(&work).unwrap().state,
        WorkState::Finished,
        "neither replay nor conflict rewrote the finished work"
    );
}

#[tokio::test]
async fn restore_executes_nothing_and_the_pause_needs_an_explicit_resume() {
    let (session, work, revision, checkpoint) =
        paused_checkpoint("c3-resume", SessionConfig::default()).await;
    let handle = session.handle();
    let paused = handle.observe(&work).unwrap();
    let Some(PausePoint::AwaitingApproval { prepared, .. }) = paused.paused else {
        panic!("the work needs approval");
    };
    let request = approve(prepared.awaiting);
    drop(session);
    drop(handle);

    let gateway2 = RecordingGateway::scripted(vec![Ok(endturn_output("resumed"))]);
    let restored = restore(checkpoint, gateway2.clone(), SessionConfig::default());
    let handle = restored.handle();

    // Restore itself is silent: no model, no tool.
    assert!(gateway2.recorded().is_empty());
    // The restored work is observable as Paused at the saved revision.
    let obs = handle.observe(&work).unwrap();
    assert_eq!(obs.state, WorkState::Paused);
    assert_eq!(obs.revision, revision);
    assert!(obs.paused.is_some(), "the pause point survives the restore");

    // The explicit resume continues the original continuation and completes
    // with exactly one further model call.
    handle
        .resume(&work, revision, "r1".into(), request)
        .expect("the restored pause resumes");
    let done = handle.wait(&work, Duration::from_secs(5)).await.unwrap();
    assert_eq!(done.end, WaitEnd::ReachedState);
    assert_eq!(done.observation.state, WorkState::Finished);
    assert_eq!(
        gateway2.recorded().len(),
        1,
        "the continuation, not a fresh turn, ran"
    );
}

#[tokio::test]
async fn restore_rederives_the_remaining_deadline_instead_of_regranting() {
    let config = SessionConfig {
        retained_work_capacity: 256,
        work_deadline: Some(Duration::from_millis(250)),
    };
    let (session, work, revision, checkpoint) =
        paused_checkpoint("c2-deadline", config.clone()).await;
    drop(session);

    // Sleep past the accept-time deadline while the work is paused.
    tokio::time::sleep(Duration::from_millis(600)).await;

    let gateway2 = RecordingGateway::scripted(vec![Ok(endturn_output("late"))]);
    let restored = restore(checkpoint, gateway2.clone(), config);
    let handle = restored.handle();

    // The resume is accepted (validation is not a deadline check), but the
    // restored remaining time is already spent: the driver stops the work
    // before dispatching anything.
    handle
        .resume(&work, revision, "r1".into(), approve(vec![awaiting_echo()]))
        .expect("a stale deadline does not reject the resume request itself");
    let done = handle.wait(&work, Duration::from_secs(5)).await.unwrap();
    assert_eq!(done.observation.state, WorkState::Finished);
    match done.observation.finished {
        Some(FinishedKind::Interrupted { cause, .. }) => assert_eq!(
            cause,
            TurnInterruption::TurnDeadlineExceeded,
            "the saved deadline still bounds the restored work"
        ),
        other => panic!("expected a deadline interruption, got {other:?}"),
    }
    assert!(
        gateway2.recorded().is_empty(),
        "the expired deadline dispatched no model call"
    );
}

// ---- C3: validation rejections -------------------------------------------------

/// An idle checkpoint of a session whose single work completed: works holds
/// the `Completed` entry, the phase state holds the committed history entry.
async fn completed_checkpoint(id: &str) -> SessionCheckpoint {
    let gateway = RecordingGateway::repeating_last(vec![Ok(endturn_output("done"))]);
    let session = idle_session(id, gateway);
    let handle = session.handle();
    let receipt = handle.submit(session_req("k1", "first")).expect("accepted");
    let _ = handle
        .wait(&receipt.work, Duration::from_secs(5))
        .await
        .unwrap();
    session.checkpoint().expect("exports when idle")
}

fn rejected(checkpoint: SessionCheckpoint) -> SessionRestoreRejection {
    SessionCheckpoint::restore(
        checkpoint,
        Arc::new(runner_with(RecordingGateway::scripted(vec![]), Vec::new())),
        TurnRunOptions::default(),
        SessionConfig::default(),
    )
    .expect_err("the forged material is rejected")
}

/// Check the persistence path and the complete by-value rejection together.
fn assert_invalid_checkpoint_returns_material(checkpoint: SessionCheckpoint) {
    let saved = serde_json::to_value(&checkpoint).unwrap();
    let checkpoint = serde_json::from_value(saved.clone()).unwrap();
    let rejection = rejected(checkpoint);
    assert!(matches!(
        rejection.error,
        SessionError::InvalidCheckpoint(_)
    ));
    assert_eq!(serde_json::to_value(rejection.checkpoint).unwrap(), saved);
}

/// Populate all three independent request-key tables using the same key.
async fn checkpoint_with_all_request_keys() -> SessionCheckpoint {
    let gateway = RecordingGateway::scripted(vec![
        Ok(tooluse_output("first pause", "echo", json!({}))),
        Ok(tooluse_output("second pause", "echo", json!({}))),
    ]);
    let session = pausing_session(
        "c-review-keys",
        gateway,
        vec![Arc::new(EchoTool)],
        SessionConfig::default(),
    );
    let handle = session.handle();
    let (receipt, paused) = submit_to_pause(&handle, "same-key").await;
    handle
        .resume(
            &receipt.work,
            paused.revision,
            "same-key".into(),
            approve(vec![awaiting_echo()]),
        )
        .unwrap();
    let paused_again = handle
        .wait(&receipt.work, Duration::from_secs(5))
        .await
        .unwrap();
    assert_eq!(paused_again.observation.state, WorkState::Paused);
    handle.cancel(&receipt.work, "same-key".into()).unwrap();
    session.checkpoint().unwrap()
}

#[tokio::test]
async fn restore_rejects_duplicate_request_keys_in_each_table() {
    let checkpoint = checkpoint_with_all_request_keys().await;
    for table in ["submit_keys", "resume_keys", "cancel_keys"] {
        let mut saved = serde_json::to_value(&checkpoint).unwrap();
        let rows = saved[table].as_array_mut().unwrap();
        rows.push(rows[0].clone());
        assert_invalid_checkpoint_returns_material(serde_json::from_value(saved).unwrap());
    }
}

#[tokio::test]
async fn restore_rejects_conflicting_submit_key_records() {
    let mut checkpoint = checkpoint_with_all_request_keys().await;
    let mut duplicate = checkpoint.submit_keys[0].clone();
    duplicate.parts = session_req("unused", "different input").parts;
    checkpoint.submit_keys.push(duplicate);
    assert_invalid_checkpoint_returns_material(checkpoint);
}

#[tokio::test]
async fn restore_preserves_same_key_across_operations_and_cancel_replay() {
    let checkpoint = checkpoint_with_all_request_keys().await;
    let submit = checkpoint.submit_keys[0].clone();
    let resume = checkpoint.resume_keys[0].clone();
    let cancel = checkpoint.cancel_keys[0].clone();
    let checkpoint = serde_json::from_value(serde_json::to_value(checkpoint).unwrap()).unwrap();
    let gateway = RecordingGateway::scripted(vec![]);
    let session = restore(checkpoint, gateway.clone(), SessionConfig::default());
    let handle = session.handle();
    assert_eq!(
        handle
            .submit(SubmitRequest {
                request_key: submit.key,
                parts: submit.parts
            })
            .unwrap(),
        submit.receipt,
    );
    let receipt = handle
        .resume(&resume.work, resume.revision, resume.key, resume.request)
        .unwrap();
    assert_eq!(receipt.work, resume.work);
    assert_eq!(receipt.accepted_revision, resume.revision);
    assert_eq!(
        handle.cancel(&cancel.work, cancel.key).unwrap(),
        cancel.receipt
    );
    assert!(gateway.recorded().is_empty());
}

#[tokio::test]
async fn restore_rejects_a_cancel_receipt_for_another_work() {
    let mut checkpoint = checkpoint_with_all_request_keys().await;
    checkpoint.cancel_keys[0].receipt.work.turn_id = TurnId::new("foreign-work");
    assert_invalid_checkpoint_returns_material(checkpoint);
}

#[tokio::test]
async fn restore_rejects_inconsistent_paused_material() {
    let (_, _, _, original) = paused_checkpoint("c-review-paused", SessionConfig::default()).await;
    for case in ["steering", "missing_call", "duplicate_call", "sealed"] {
        let mut checkpoint = original.clone();
        let CheckpointPhase::Paused { outcome, .. } = &mut checkpoint.phase else {
            unreachable!()
        };
        let TurnResult::Paused { continuation } = &mut outcome.result else {
            unreachable!()
        };
        match case {
            "steering" => continuation.pause_point = PausePoint::PausedForSteering,
            "sealed" => outcome.state.active_turn_mut().unwrap().seal(),
            _ => {
                let PausePoint::AwaitingApproval { prepared, .. } = &mut continuation.pause_point
                else {
                    unreachable!()
                };
                if case == "missing_call" {
                    prepared.awaiting.clear();
                } else {
                    prepared.awaiting.push(prepared.awaiting[0].clone());
                }
            }
        }
        assert_invalid_checkpoint_returns_material(checkpoint);
    }
}

#[tokio::test]
async fn restore_rejects_interrupted_facts_from_another_turn() {
    let mut checkpoint = checkpoint_with_all_request_keys().await;
    let Some(FinishedKind::Interrupted { facts, .. }) = &mut checkpoint.works[0].finished else {
        unreachable!()
    };
    facts.turn_id = TurnId::new("foreign-turn");
    assert_invalid_checkpoint_returns_material(checkpoint);
}

#[tokio::test]
async fn restore_rejects_invalid_blocks_in_interrupted_facts() {
    let checkpoint = checkpoint_with_all_request_keys().await;
    let mut saved = serde_json::to_value(checkpoint).unwrap();
    saved["works"][0]["finished"]["interrupted"]["facts"]["blocks"][0]["id"]["turn_id"] =
        json!("foreign-turn");
    assert_invalid_checkpoint_returns_material(serde_json::from_value(saved).unwrap());
}

#[tokio::test]
async fn a_forged_completed_work_without_history_is_rejected() {
    let checkpoint = completed_checkpoint("c3-history").await;
    let mut value = serde_json::to_value(&checkpoint).unwrap();
    // The works entry claims Completed, but its committed history entry is
    // gone — a state no live run can reach.
    value["phase"]["state"]["history"] = json!([]);
    let tampered: SessionCheckpoint = serde_json::from_value(value).unwrap();
    assert!(matches!(
        rejected(tampered).error,
        SessionError::InvalidCheckpoint(_)
    ));
}

#[tokio::test]
async fn a_rolled_back_allocation_progress_is_rejected() {
    let checkpoint = completed_checkpoint("c3-next-turn").await;
    let mut value = serde_json::to_value(&checkpoint).unwrap();
    // next_turn must follow every identity the envelope can see, or the
    // next submit would re-hand out an allocated id.
    value["next_turn"] = json!(0);
    let tampered: SessionCheckpoint = serde_json::from_value(value).unwrap();
    assert!(matches!(
        rejected(tampered).error,
        SessionError::InvalidCheckpoint(_)
    ));
}

#[tokio::test]
async fn a_forged_paused_stamp_is_rejected() {
    let (_, _, _, checkpoint) = paused_checkpoint("c3-stamp", SessionConfig::default()).await;
    let mut value = serde_json::to_value(&checkpoint).unwrap();
    // The outcome's active turn is open, so it can only be stamped Paused.
    value["phase"]["outcome"]["state"]["sealed_result"] = json!("completed");
    let tampered: SessionCheckpoint = serde_json::from_value(value).unwrap();
    assert!(matches!(
        rejected(tampered).error,
        SessionError::InvalidCheckpoint(_)
    ));
}

#[tokio::test]
async fn a_forged_submit_receipt_revision_is_rejected() {
    let checkpoint = completed_checkpoint("c3-receipt").await;
    let mut value = serde_json::to_value(&checkpoint).unwrap();
    // A live submit receipt always records revision 0.
    value["submit_keys"][0]["receipt"]["accepted_revision"] = json!(5);
    let tampered: SessionCheckpoint = serde_json::from_value(value).unwrap();
    assert!(matches!(
        rejected(tampered).error,
        SessionError::InvalidCheckpoint(_)
    ));
}

#[tokio::test]
async fn a_far_future_deadline_expiry_restores_without_failing() {
    let config = SessionConfig {
        retained_work_capacity: 256,
        work_deadline: Some(Duration::from_millis(250)),
    };
    let (_, work, revision, checkpoint) = paused_checkpoint("c3-deadline", config.clone()).await;
    let mut value = serde_json::to_value(&checkpoint).unwrap();
    // A deadline ~34,789 years out sits above the u64-nanosecond Instant on
    // macOS, where the unguarded conversion used to panic mid-restore; on
    // Linux (i64-timespec Instant) no deserializable SystemTime can
    // overflow the conversion at all. Either way the portable behavior is
    // the equivalence: such an expiry could never fire in this process, so
    // restore treats it as unbounded — no panic, no rejection.
    value["works"][0]["deadline_utc"] =
        json!({"secs_since_epoch": 1099511627776u64, "nanos_since_epoch": 0});
    let tampered: SessionCheckpoint = serde_json::from_value(value).unwrap();

    let gateway2 = RecordingGateway::scripted(vec![Ok(endturn_output("late"))]);
    let restored = SessionCheckpoint::restore(
        tampered,
        Arc::new(runner_with(gateway2.clone(), Vec::new())),
        TurnRunOptions::default(),
        config,
    )
    .expect("a far-future expiry restores as an unbounded deadline");
    let handle = restored.handle();
    handle
        .resume(&work, revision, "r1".into(), approve(vec![awaiting_echo()]))
        .expect("the restored pause resumes");
    let done = handle.wait(&work, Duration::from_secs(5)).await.unwrap();
    assert_eq!(done.observation.state, WorkState::Finished);
    assert_eq!(
        gateway2.recorded().len(),
        1,
        "the far-future deadline dispatched normally"
    );
}

#[tokio::test]
async fn restore_rejects_an_unsupported_version_and_returns_the_checkpoint() {
    let (_, _, _, checkpoint) = paused_checkpoint("c3-version", SessionConfig::default()).await;
    let mut value = serde_json::to_value(&checkpoint).unwrap();
    value["version"] = json!(99);
    let tampered: SessionCheckpoint = serde_json::from_value(value).unwrap();
    let as_saved = serde_json::to_value(&tampered).unwrap();

    let rejection = SessionCheckpoint::restore(
        tampered,
        Arc::new(runner_with(RecordingGateway::scripted(vec![]), Vec::new())),
        TurnRunOptions::default(),
        SessionConfig::default(),
    )
    .expect_err("an unsupported version is rejected");

    assert!(matches!(
        rejection.error,
        SessionError::InvalidCheckpoint(_)
    ));
    assert_eq!(
        serde_json::to_value(&rejection.checkpoint).unwrap(),
        as_saved,
        "the original materials come back untouched"
    );
    assert_eq!(rejection.config, SessionConfig::default());
}

#[tokio::test]
async fn restore_rejects_a_config_mismatch() {
    let (_, _, _, checkpoint) = paused_checkpoint("c4-config", SessionConfig::default()).await;
    let as_saved = serde_json::to_value(&checkpoint).unwrap();
    let mut swapped = TurnRunOptions::default();
    swapped.invocation.model = ModelRef::new("other-model");

    let rejection = SessionCheckpoint::restore(
        checkpoint,
        Arc::new(runner_with(RecordingGateway::scripted(vec![]), Vec::new())),
        swapped,
        SessionConfig::default(),
    )
    .expect_err("a swapped model is a configuration mismatch");

    assert!(matches!(rejection.error, SessionError::ConfigMismatch));
    assert_eq!(
        serde_json::to_value(&rejection.checkpoint).unwrap(),
        as_saved
    );

    // A mismatch away from the model is equally visible: the exported
    // envelope carries no call timeout, so restoring under one is the
    // missing-configuration case.
    let (_, _, _, checkpoint) =
        paused_checkpoint("c4-config-timeout", SessionConfig::default()).await;
    let mut timeout = TurnRunOptions::default();
    timeout.execution.call_timeout = Some(Duration::from_secs(1));
    let rejection = SessionCheckpoint::restore(
        checkpoint,
        Arc::new(runner_with(RecordingGateway::scripted(vec![]), Vec::new())),
        timeout,
        SessionConfig::default(),
    )
    .expect_err("a configuration the export never had is a mismatch");
    assert!(matches!(rejection.error, SessionError::ConfigMismatch));
}

#[tokio::test]
async fn restore_rejects_inconsistent_material_and_returns_the_checkpoint() {
    // (a) the paused work is not registered
    let (_, _, _, checkpoint) = paused_checkpoint("c4-material", SessionConfig::default()).await;
    let mut value = serde_json::to_value(&checkpoint).unwrap();
    value["works"] = json!([]);
    let as_saved = value.clone();
    let tampered: SessionCheckpoint = serde_json::from_value(value).unwrap();
    let rejection = SessionCheckpoint::restore(
        tampered,
        Arc::new(runner_with(RecordingGateway::scripted(vec![]), Vec::new())),
        TurnRunOptions::default(),
        SessionConfig::default(),
    )
    .expect_err("an unregistered paused work is inconsistent");
    assert!(matches!(
        rejection.error,
        SessionError::InvalidCheckpoint(_)
    ));
    assert_eq!(
        serde_json::to_value(&rejection.checkpoint).unwrap(),
        as_saved
    );

    // (b) a submit receipt references an unknown work
    let gateway = RecordingGateway::repeating_last(vec![Ok(endturn_output("done"))]);
    let session = idle_session("c4-material-b", gateway.clone());
    let handle = session.handle();
    let receipt = handle.submit(session_req("k1", "first")).unwrap();
    let _ = handle
        .wait(&receipt.work, Duration::from_secs(5))
        .await
        .unwrap();
    let checkpoint = session.checkpoint().unwrap();
    let mut value = serde_json::to_value(&checkpoint).unwrap();
    value["works"] = json!([]);
    let as_saved = value.clone();
    let tampered: SessionCheckpoint = serde_json::from_value(value).unwrap();
    let rejection = SessionCheckpoint::restore(
        tampered,
        Arc::new(runner_with(RecordingGateway::scripted(vec![]), Vec::new())),
        TurnRunOptions::default(),
        SessionConfig::default(),
    )
    .expect_err("a dangling receipt is inconsistent");
    assert!(matches!(
        rejection.error,
        SessionError::InvalidCheckpoint(_)
    ));
    assert_eq!(
        serde_json::to_value(&rejection.checkpoint).unwrap(),
        as_saved
    );

    // (c) the paused outcome's active turn does not match its registered work
    let (_, _, _, checkpoint) = paused_checkpoint("c4-material-c", SessionConfig::default()).await;
    let mut value = serde_json::to_value(&checkpoint).unwrap();
    value["phase"]["work"]["turn_id"] = json!("c4-material-c-work-99");
    let as_saved = value.clone();
    let tampered: SessionCheckpoint = serde_json::from_value(value).unwrap();
    let rejection = SessionCheckpoint::restore(
        tampered,
        Arc::new(runner_with(RecordingGateway::scripted(vec![]), Vec::new())),
        TurnRunOptions::default(),
        SessionConfig::default(),
    )
    .expect_err("a mismatched active turn is inconsistent");
    assert!(matches!(
        rejection.error,
        SessionError::InvalidCheckpoint(_)
    ));
    assert_eq!(
        serde_json::to_value(&rejection.checkpoint).unwrap(),
        as_saved
    );
}

// ---- C4: from-history distinction, persistence ---------------------------------

#[tokio::test]
async fn opening_from_history_rebuilds_no_dedup_table() {
    let gateway = RecordingGateway::repeating_last(vec![Ok(endturn_output("done"))]);
    let session = idle_session("c4-history", gateway.clone());
    let handle = session.handle();
    let receipt = handle.submit(session_req("k1", "first")).expect("accepted");
    let _ = handle
        .wait(&receipt.work, Duration::from_secs(5))
        .await
        .unwrap();
    let checkpoint = session.checkpoint().unwrap();

    // The restore path: the same key replays the original receipt and runs
    // nothing.
    let restored = restore(
        checkpoint.clone(),
        gateway.clone(),
        SessionConfig::default(),
    );
    let calls = gateway.recorded().len();
    assert_eq!(
        restored
            .handle()
            .submit(session_req("k1", "first"))
            .unwrap(),
        receipt
    );
    assert_eq!(gateway.recorded().len(), calls, "the restore replays");

    // The from-history path: the same history as a fresh state knows no
    // request keys and no allocation progress — the key is accepted as a
    // new work and executes again.
    let CheckpointPhase::Idle { state } = checkpoint.phase else {
        panic!("the completed session exports idle");
    };
    let reopened = Session::new(
        state,
        Arc::new(runner_with(gateway.clone(), Vec::new())),
        TurnRunOptions::default(),
        SessionConfig::default(),
    )
    .expect("a completed history is an idle session base");
    let again = reopened
        .handle()
        .submit(session_req("k1", "first"))
        .expect("no dedup table exists");
    assert_ne!(
        again, receipt,
        "the reopened session accepted the key as a new work"
    );
    assert_ne!(
        again.work.turn_id, receipt.work.turn_id,
        "the reopened session does not restore the allocation progress either"
    );
    let done = reopened
        .handle()
        .wait(&again.work, Duration::from_secs(5))
        .await
        .unwrap();
    assert_eq!(done.observation.state, WorkState::Finished);
    assert!(
        gateway.recorded().len() > calls,
        "the reopened work executed"
    );
}

#[tokio::test]
async fn the_envelope_survives_a_persistence_roundtrip() {
    let (session, work, revision, checkpoint) =
        paused_checkpoint("c2-roundtrip", SessionConfig::default()).await;
    drop(session);

    let bytes = serde_json::to_vec(&checkpoint).expect("the envelope serializes");
    let reloaded: SessionCheckpoint =
        serde_json::from_slice(&bytes).expect("the envelope deserializes");

    let gateway2 = RecordingGateway::scripted(vec![Ok(endturn_output("resumed"))]);
    let restored = restore(reloaded, gateway2.clone(), SessionConfig::default());
    let handle = restored.handle();

    // The reloaded envelope restores to the same observable pause...
    let obs = handle.observe(&work).unwrap();
    assert_eq!(obs.state, WorkState::Paused);
    assert_eq!(obs.revision, revision);
    // ...replays the saved submit key...
    assert_eq!(
        handle.submit(session_req("pause", "go")).unwrap().work,
        work
    );
    // ...and the explicit resume completes the original continuation.
    handle
        .resume(&work, revision, "r1".into(), approve(vec![awaiting_echo()]))
        .expect("the restored pause resumes");
    let done = handle.wait(&work, Duration::from_secs(5)).await.unwrap();
    assert_eq!(done.observation.state, WorkState::Finished);
    assert_eq!(gateway2.recorded().len(), 1);
}