causa_runtime/session/checkpoint.rs
1//! The versioned save envelope for one material-free session and the
2//! comparable description of the configuration it was produced under.
3//!
4//! The envelope is a plain data interface: [`Session`] produces it, a host
5//! persists it (harness / examples — the runtime ships no store), and
6//! [`SessionCheckpoint::restore`] consumes a re-assembled configuration plus
7//! the loaded envelope. Phase C covers only the sessions Phase A/B support —
8//! no seed, no projected materials, no per-work tool binding. When later
9//! phases extend the envelope, they must declare version compatibility or a
10//! migration rule; this format never silently guesses at unknown sections.
11//!
12//! Two trust boundaries stay with the harness, not the envelope. First,
13//! restore validates a material's *internal consistency*, not its
14//! authenticity: the works table is the sole record of an interrupted
15//! work's identity (aborted turns stay out of the completed history by
16//! design), so a hand-tampered envelope is refused only where copies inside
17//! the envelope disagree — persistence integrity is the harness's
18//! responsibility. Second, a checkpoint resumes a deliberately paused,
19//! quiescent session and promises no exactly-once across arbitrary process
20//! crashes: unsaved acceptance records, unknown external results, and a
21//! re-loaded old checkpoint gain nothing automatically.
22
23use std::collections::{HashMap, HashSet};
24use std::sync::Arc;
25use std::time::{Duration, SystemTime};
26
27use causa_kernel::{
28 CacheDirective, ContentPart, ConversationId, GenerationOptions, ToolSurface, TurnContext,
29 TurnId,
30};
31
32use crate::budget::WindowBudget;
33use crate::config::{
34 RetryPolicy, ToolOutputLimits, TurnLimits, TurnRunOptions, UnknownOutcomeConfig,
35};
36use crate::conversation::{ConversationState, SealedResult};
37use crate::driver::{ConversationOutcome, TurnResult, TurnRunner};
38use crate::resume::ResumeRequest;
39
40use super::execution::SessionCore;
41use super::owner::Session;
42use super::types::{
43 CancelReceipt, FinishedKind, SessionConfig, SessionError, WorkReceipt, WorkRef, WorkState,
44};
45
46/// The envelope format version written by [`Session::checkpoint`].
47pub const SESSION_CHECKPOINT_VERSION: u32 = 1;
48
49/// The complete save envelope of one session — everything restore needs
50/// beyond freshly assembled capabilities, at an explicit format version.
51///
52/// One phase payload only: an `Idle` envelope carries the
53/// [`ConversationState`]; a `Paused` envelope carries the **complete**
54/// [`ConversationOutcome`], whose state is the only saved active context.
55/// The envelope is never a second, drifting copy of a live session's state —
56/// it is a value the host persists and later hands back.
57#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
58#[non_exhaustive]
59pub struct SessionCheckpoint {
60 /// The envelope format version — [`SESSION_CHECKPOINT_VERSION`] for
61 /// envelopes this runtime writes. Restore rejects any version it does
62 /// not implement instead of guessing at unknown shapes.
63 pub version: u32,
64 /// The conversation the envelope belongs to. Restore registers it as-is;
65 /// collision with a still-held conversation id is the harness's check
66 /// (the session has no global instance table).
67 pub conversation_id: ConversationId,
68 /// The saved conversation phase — the Idle state or the complete paused
69 /// outcome. Exactly one is present, and the paused variant carries its
70 /// state inside the outcome.
71 pub phase: CheckpointPhase,
72 /// Every retained work: refs, revisions, terminal results, faults, and
73 /// original deadlines. Terminal results stay observable after restore;
74 /// a restored work is never a new work.
75 pub works: Vec<SavedWork>,
76 /// The session's TurnId allocation progress at save time, so restore
77 /// never hands out an identity a previous owner already used.
78 pub next_turn: u64,
79 /// The accepted submit requests, replayable by key after restore.
80 pub submit_keys: Vec<SavedSubmitKey>,
81 /// The accepted resume requests, replayable by key after restore.
82 pub resume_keys: Vec<SavedResumeKey>,
83 /// The accepted cancel requests, replayable by key after restore.
84 pub cancel_keys: Vec<SavedCancelKey>,
85 /// The comparable description of the configuration the session ran
86 /// under; restore validates it against the freshly assembled options.
87 pub config: SessionConfigDescription,
88 /// Whether the owner had closed the session at save time. Restoring a
89 /// closed envelope yields a closed session: accepted keys still replay,
90 /// new work is refused — the closed state is preserved, not upgraded.
91 pub closed: bool,
92}
93
94/// The saved conversation phase: the idle state, or the complete paused
95/// outcome plus the work ref it belongs to.
96///
97/// The `Paused` arm is deliberately the complete outcome (the same shape the
98/// in-memory slot holds), so the enum is as large as that outcome. Boxing it
99/// would add indirection for a value there is exactly one of, matching the
100/// accepted trade-off on the session's `Slot`.
101#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
102#[serde(tag = "phase", rename_all = "snake_case")]
103#[non_exhaustive]
104#[allow(clippy::large_enum_variant)]
105pub enum CheckpointPhase {
106 /// The session was idle: the state (with its committed history) is the
107 /// whole conversation payload; its active slot is empty.
108 Idle {
109 /// The idle conversation state.
110 state: ConversationState,
111 },
112 /// The session held a paused work: the complete outcome (its own state,
113 /// the paused result, and the continuation) is the whole payload. No
114 /// second state copy is saved beside it.
115 Paused {
116 /// The complete paused outcome, including its state and continuation.
117 outcome: ConversationOutcome,
118 /// The paused work the outcome belongs to.
119 work: WorkRef,
120 },
121}
122
123/// One retained work's saved view: everything `observe` reported plus the
124/// absolute deadline.
125#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
126pub struct SavedWork {
127 /// The work's identity (conversation + assigned turn id).
128 pub work: WorkRef,
129 /// The work's revision at save time; restore continues the sequence
130 /// from here, so a caller's pre-save revision stays meaningful.
131 pub revision: u64,
132 /// The work's state at save time — `Paused` only for the paused phase
133 /// payload's work. `Accepted` / `Running` / `Faulted` cannot be
134 /// checkpointed (their slots refuse to export), so a legitimate
135 /// envelope carries only terminal states and the one paused work.
136 pub state: WorkState,
137 /// The terminal result when the work is `Finished`.
138 pub finished: Option<FinishedKind>,
139 /// The fault reason when the work is `Faulted`.
140 pub fault: Option<String>,
141 /// The work's deadline as an absolute UTC expiry. Monotonic deadlines
142 /// have no wall-clock meaning across processes, so the remaining time is
143 /// re-derived at restore — never re-granted in full.
144 pub deadline_utc: Option<SystemTime>,
145}
146
147/// One accepted submit under its request key, saved for replay.
148#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
149pub struct SavedSubmitKey {
150 /// The caller's idempotency key.
151 pub key: String,
152 /// The parts the request was accepted for; a same-key retry with
153 /// different parts is a conflict after restore, exactly as before it.
154 pub parts: Vec<ContentPart>,
155 /// The original acceptance receipt.
156 pub receipt: WorkReceipt,
157}
158
159/// One accepted resume under its request key, saved for replay.
160#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
161pub struct SavedResumeKey {
162 /// The caller's idempotency key.
163 pub key: String,
164 /// The work the resume targeted.
165 pub work: WorkRef,
166 /// The paused revision the resume named.
167 pub revision: u64,
168 /// The request it was accepted for (decision + injected inputs).
169 pub request: ResumeRequest,
170}
171
172/// One accepted cancel under its request key, saved for replay.
173#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
174pub struct SavedCancelKey {
175 /// The caller's idempotency key.
176 pub key: String,
177 /// The work the cancel targeted.
178 pub work: WorkRef,
179 /// The original cancel receipt.
180 pub receipt: CancelReceipt,
181}
182
183/// The comparable description of one assembled configuration: the plain-data
184/// projection of [`TurnRunOptions`] plus the session coordination config.
185///
186/// Restore re-derives the description from the newly assembled options and
187/// rejects a mismatch — the same model ref, tool surface, and execution
188/// options must be in force, so a checkpoint cannot silently resume under a
189/// swapped model or narrowed surface. Ports the description cannot compare
190/// by value (the interaction seam, the gateway, the executor, the concrete
191/// compaction / counter implementations behind the presence flags) stay the
192/// harness's assembly responsibility: this description pins *what was
193/// configured*, not the identity of behavior objects behind it.
194#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
195#[non_exhaustive]
196pub struct SessionConfigDescription {
197 /// The model the runs invoke (`ModelRef` as its raw string).
198 pub model: String,
199 /// The tool surface advertised on the first model phase.
200 pub tool_surface: ToolSurface,
201 /// Sampling parameters sent with every attempt.
202 pub generation: GenerationOptions,
203 /// Prompt-cache instruction.
204 pub cache: CacheDirective,
205 /// Retry schedule for failed model attempts.
206 pub retry: RetryPolicy,
207 /// Per-turn loop bounds.
208 pub limits: TurnLimits,
209 /// Per-model-attempt budget.
210 pub attempt_timeout: Option<Duration>,
211 /// Unknown-outcome continuation configuration.
212 pub unknown_outcome: UnknownOutcomeConfig,
213 /// Fallback tool-output truncation limit.
214 pub tool_output_limits: ToolOutputLimits,
215 /// Per-tool-name truncation-limit overrides.
216 pub tool_output_limits_overrides: HashMap<String, ToolOutputLimits>,
217 /// Per-tool-call deadline.
218 pub call_timeout: Option<Duration>,
219 /// Frame-compaction trigger thresholds.
220 pub window_budget: WindowBudget,
221 /// Whether a compaction implementation is configured.
222 pub compaction_configured: bool,
223 /// Whether a frame token counter is configured.
224 pub frame_counter_configured: bool,
225 /// Whether a tool-output artifact store is configured.
226 pub artifact_store_configured: bool,
227 /// Whether a truncation-estimation counter is configured.
228 pub truncation_counter_configured: bool,
229 /// The session coordination config (retention capacity, work deadline).
230 pub session: SessionConfig,
231}
232
233impl SessionConfigDescription {
234 /// Describe an assembled configuration — the projection restore compares
235 /// against, and the description [`Session::checkpoint`] records.
236 pub fn of(options: &TurnRunOptions, config: &SessionConfig) -> Self {
237 Self {
238 model: options.invocation.model.0.clone(),
239 tool_surface: options.invocation.tool_surface.clone(),
240 generation: options.invocation.generation.clone(),
241 cache: options.invocation.cache,
242 retry: options.policy.retry.clone(),
243 limits: options.policy.limits.clone(),
244 attempt_timeout: options.policy.attempt_timeout,
245 unknown_outcome: options.policy.unknown_outcome.clone(),
246 tool_output_limits: options.execution.tool_output_limits,
247 tool_output_limits_overrides: options.execution.tool_output_limits_overrides.clone(),
248 call_timeout: options.execution.call_timeout,
249 window_budget: options.frame.window_budget,
250 compaction_configured: options.frame.compaction.is_some(),
251 frame_counter_configured: options.frame.token_counter.is_some(),
252 artifact_store_configured: options.execution.artifact_store.is_some(),
253 truncation_counter_configured: options.execution.token_counter.is_some(),
254 session: config.clone(),
255 }
256 }
257}
258
259/// A rejected restore: the reason plus everything the caller handed in,
260/// returned untouched — the original checkpoint included. Nothing was
261/// registered; correcting the input and retrying costs nothing.
262pub struct SessionRestoreRejection {
263 /// Why the restore was rejected.
264 pub error: SessionError,
265 /// The original checkpoint, exactly as received.
266 pub checkpoint: SessionCheckpoint,
267 /// The assembled runner, returned by value.
268 pub runner: Arc<TurnRunner>,
269 /// The assembled run options, returned by value.
270 pub options: TurnRunOptions,
271 /// The session configuration, returned by value.
272 pub config: SessionConfig,
273}
274
275/// The validated checkpoint's registry parts — the works table, the three
276/// request-key replay tables, the allocation progress, and the closed
277/// state — ready for the execution core to assemble.
278pub(super) struct SavedRegistry {
279 /// Every retained work's saved view.
280 pub works: Vec<SavedWork>,
281 /// The accepted submit requests.
282 pub submit_keys: Vec<SavedSubmitKey>,
283 /// The accepted resume requests.
284 pub resume_keys: Vec<SavedResumeKey>,
285 /// The accepted cancel requests.
286 pub cancel_keys: Vec<SavedCancelKey>,
287 /// The TurnId allocation progress.
288 pub next_turn: u64,
289 /// Whether the owner had closed the session at save time.
290 pub closed: bool,
291}
292
293impl std::fmt::Debug for SessionRestoreRejection {
294 /// `TurnRunner` carries no `Debug` impl (it holds gateway / executor
295 /// trait objects), so the rejection renders it as an opaque handle and
296 /// prints the rest.
297 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
298 f.debug_struct("SessionRestoreRejection")
299 .field("error", &self.error)
300 .field("checkpoint", &self.checkpoint)
301 .field("runner", &"Arc<TurnRunner>")
302 .field("options", &self.options)
303 .field("config", &self.config)
304 .finish()
305 }
306}
307
308impl SessionCheckpoint {
309 /// Register this checkpoint as a live session, against a freshly
310 /// assembled configuration.
311 ///
312 /// Validation runs first and completely — the envelope version, the
313 /// configuration description against the assembled options, and the
314 /// material's internal consistency — so a rejection returns everything
315 /// by value ([`SessionRestoreRejection`]) and leaves nothing behind. A
316 /// successful restore calls no model and no tool: an idle envelope
317 /// registers as an idle session, a paused envelope registers with the
318 /// work paused on its original continuation, still requiring an explicit
319 /// [`SessionHandle::resume`](super::SessionHandle::resume). The request
320 /// keys replay their original receipts after restore; a different
321 /// work's claim on a saved key is a conflict, exactly as before the
322 /// save. Identity allocation continues from the saved progress, and
323 /// each work's remaining deadline is re-derived from its saved absolute
324 /// expiry — never re-granted in full.
325 ///
326 /// Two constructors loading the same checkpoint are the harness's
327 /// problem to avoid: the session has no global instance table, so it
328 /// cannot refuse a second owner on its own.
329 // The rejection carries the whole checkpoint plus the assembled
330 // runner / options / config back by value, which is the point of the
331 // contract — the same by-value shape `Session::new` returns.
332 #[allow(clippy::result_large_err)]
333 pub fn restore(
334 self,
335 runner: Arc<TurnRunner>,
336 options: TurnRunOptions,
337 config: SessionConfig,
338 ) -> Result<Session, SessionRestoreRejection> {
339 if let Err(error) = self.validate(&options, &config) {
340 return Err(SessionRestoreRejection {
341 error,
342 checkpoint: self,
343 runner,
344 options,
345 config,
346 });
347 }
348 let Self {
349 phase,
350 works,
351 next_turn,
352 submit_keys,
353 resume_keys,
354 cancel_keys,
355 closed,
356 ..
357 } = self;
358 let registry = SavedRegistry {
359 works,
360 submit_keys,
361 resume_keys,
362 cancel_keys,
363 next_turn,
364 closed,
365 };
366 let core = match phase {
367 CheckpointPhase::Idle { state } => {
368 SessionCore::restore_idle(state, registry, runner, options, config)
369 }
370 CheckpointPhase::Paused { outcome, .. } => {
371 SessionCore::restore_paused(outcome, registry, runner, options, config)
372 }
373 };
374 Ok(Session::from_core(core))
375 }
376
377 /// Validate the envelope completely before anything registers: version,
378 /// configuration description, and the material's internal consistency.
379 fn validate(
380 &self,
381 options: &TurnRunOptions,
382 config: &SessionConfig,
383 ) -> Result<(), SessionError> {
384 if self.version != SESSION_CHECKPOINT_VERSION {
385 return Err(SessionError::InvalidCheckpoint(format!(
386 "unsupported checkpoint version {} (this runtime writes {})",
387 self.version, SESSION_CHECKPOINT_VERSION
388 )));
389 }
390 if SessionConfigDescription::of(options, config) != self.config {
391 return Err(SessionError::ConfigMismatch);
392 }
393 let invalid = |reason: String| SessionError::InvalidCheckpoint(reason);
394 match &self.phase {
395 CheckpointPhase::Idle { state } => {
396 if *state.conversation_id() != self.conversation_id {
397 return Err(invalid(
398 "the idle state names a different conversation than the envelope".into(),
399 ));
400 }
401 if state.active_turn().is_some() || state.sealed_result().is_some() {
402 return Err(invalid(
403 "the idle phase carries an active or sealed turn".into(),
404 ));
405 }
406 }
407 CheckpointPhase::Paused { outcome, work } => {
408 if *outcome.state.conversation_id() != self.conversation_id {
409 return Err(invalid(
410 "the paused outcome names a different conversation than the envelope"
411 .into(),
412 ));
413 }
414 if work.conversation_id != self.conversation_id {
415 return Err(invalid(
416 "the paused work names a different conversation than the envelope".into(),
417 ));
418 }
419 let TurnResult::Paused { continuation } = &outcome.result else {
420 return Err(invalid(
421 "the paused phase does not carry a paused result".into(),
422 ));
423 };
424 let Some(active) = outcome.state.active_turn() else {
425 return Err(invalid("the paused outcome has no open active turn".into()));
426 };
427 if active.turn_id() != work.turn_id {
428 return Err(invalid(
429 "the paused outcome's active turn does not match the paused work".into(),
430 ));
431 }
432 if outcome.state.sealed_result() != Some(SealedResult::Paused) {
433 return Err(invalid(
434 "the paused outcome's active turn is not stamped Paused".into(),
435 ));
436 }
437 crate::resume::validate_continuation_facts(continuation, active)
438 .map_err(invalid)?;
439 }
440 }
441 // The committed history is the second copy of every completed turn:
442 // a Completed works entry without its history entry (or an
443 // Interrupted one with a history entry — the completed-only history
444 // can never hold an aborted turn) is a state no live run reaches.
445 let history_ids: HashSet<&TurnId> = match &self.phase {
446 CheckpointPhase::Idle { state } => state
447 .history()
448 .iter()
449 .map(|entry| &entry.snapshot.turn_id)
450 .collect(),
451 CheckpointPhase::Paused { outcome, .. } => outcome
452 .state
453 .history()
454 .iter()
455 .map(|entry| &entry.snapshot.turn_id)
456 .collect(),
457 };
458 // Works: one identity each, terminal except the single paused work
459 // of the paused phase. Accepted / Running / Faulted entries cannot
460 // come from a legitimate export (their slot refuses to export), so
461 // they are inconsistencies rather than states to preserve. Every
462 // identity must follow the conversation's allocation sequence, and
463 // the progress must sit past it — restore re-registers, it does not
464 // re-derive, and a rolled-back progress would re-hand out an
465 // allocated turn id.
466 let prefix = format!("{}-work-", self.conversation_id.0);
467 let mut seen = HashSet::new();
468 let mut paused_works = 0usize;
469 for saved in &self.works {
470 if saved.work.conversation_id != self.conversation_id {
471 return Err(invalid(format!(
472 "work {:?} names a different conversation than the envelope",
473 saved.work
474 )));
475 }
476 if !seen.insert(saved.work.turn_id.clone()) {
477 return Err(invalid(format!("duplicate work identity {:?}", saved.work)));
478 }
479 let Some(index) = saved
480 .work
481 .turn_id
482 .0
483 .strip_prefix(prefix.as_str())
484 .and_then(|suffix| suffix.parse::<u64>().ok())
485 else {
486 return Err(invalid(format!(
487 "work {:?} was not allocated by this conversation's identity sequence",
488 saved.work
489 )));
490 };
491 if self.next_turn <= index {
492 return Err(invalid(format!(
493 "the allocation progress ({}) does not follow work identity {:?}",
494 self.next_turn, saved.work
495 )));
496 }
497 match &saved.finished {
498 Some(FinishedKind::Completed { .. })
499 if !history_ids.contains(&saved.work.turn_id) =>
500 {
501 return Err(invalid(format!(
502 "completed work {:?} has no committed history entry",
503 saved.work
504 )));
505 }
506 Some(FinishedKind::Interrupted { facts, .. }) => {
507 if history_ids.contains(&saved.work.turn_id) {
508 return Err(invalid(format!(
509 "interrupted work {:?} also sits in the completed history",
510 saved.work
511 )));
512 }
513 if facts.turn_id != saved.work.turn_id {
514 return Err(invalid(format!(
515 "interrupted work {:?} carries facts from another turn",
516 saved.work
517 )));
518 }
519 TurnContext::validate_blocks(&facts.turn_id, facts.blocks.as_slice())
520 .map_err(|error| invalid(error.to_string()))?;
521 }
522 _ => {}
523 }
524 match saved.state {
525 WorkState::Finished => {
526 if saved.finished.is_none() || saved.fault.is_some() {
527 return Err(invalid(format!(
528 "finished work {:?} carries no result or a fault",
529 saved.work
530 )));
531 }
532 }
533 WorkState::Paused => {
534 paused_works += 1;
535 if saved.finished.is_some() || saved.fault.is_some() {
536 return Err(invalid(format!(
537 "paused work {:?} carries a result or a fault",
538 saved.work
539 )));
540 }
541 }
542 WorkState::Accepted | WorkState::Running | WorkState::Faulted => {
543 return Err(invalid(format!(
544 "work {:?} is {:?}; only terminal works and the one paused work can be checkpointed",
545 saved.work, saved.state
546 )));
547 }
548 }
549 }
550 let paused_phase = matches!(&self.phase, CheckpointPhase::Paused { .. });
551 let expected = usize::from(paused_phase);
552 if paused_works != expected {
553 return Err(invalid(format!(
554 "the envelope registers {paused_works} paused works; the {} phase carries exactly one",
555 if paused_phase { "paused" } else { "idle" }
556 )));
557 }
558 if let CheckpointPhase::Paused { work, .. } = &self.phase {
559 let registered = self
560 .works
561 .iter()
562 .any(|saved| saved.work == *work && saved.state == WorkState::Paused);
563 if !registered {
564 return Err(invalid(
565 "the paused phase's work is not registered as a paused work".into(),
566 ));
567 }
568 }
569 // Key tables: every receipt and target must reference a registered
570 // work, so replay after restore never invents a work.
571 validate_unique_keys(
572 "submit",
573 self.submit_keys.iter().map(|saved| saved.key.as_str()),
574 )?;
575 validate_unique_keys(
576 "resume",
577 self.resume_keys.iter().map(|saved| saved.key.as_str()),
578 )?;
579 validate_unique_keys(
580 "cancel",
581 self.cancel_keys.iter().map(|saved| saved.key.as_str()),
582 )?;
583 let known: HashSet<&WorkRef> = self.works.iter().map(|saved| &saved.work).collect();
584 for saved in &self.submit_keys {
585 if !known.contains(&saved.receipt.work) {
586 return Err(invalid(format!(
587 "submit key {:?} receipts an unknown work",
588 saved.key
589 )));
590 }
591 if saved.receipt.accepted_revision != 0 {
592 return Err(invalid(format!(
593 "submit key {:?} records a non-zero acceptance revision; a live submit always accepts at revision 0",
594 saved.key
595 )));
596 }
597 if saved.parts.is_empty() {
598 return Err(invalid(format!(
599 "submit key {:?} carries no parts",
600 saved.key
601 )));
602 }
603 }
604 for saved in &self.resume_keys {
605 if !known.contains(&saved.work) {
606 return Err(invalid(format!(
607 "resume key {:?} targets an unknown work",
608 saved.key
609 )));
610 }
611 }
612 for saved in &self.cancel_keys {
613 if !known.contains(&saved.work) {
614 return Err(invalid(format!(
615 "cancel key {:?} targets an unknown work",
616 saved.key
617 )));
618 }
619 if saved.receipt.work != saved.work {
620 return Err(invalid(format!(
621 "cancel key {:?} receipts a different work than its target",
622 saved.key
623 )));
624 }
625 }
626 Ok(())
627 }
628}
629
630/// Each operation has its own key namespace, with one saved record per key.
631fn validate_unique_keys<'a>(
632 operation: &str,
633 keys: impl Iterator<Item = &'a str>,
634) -> Result<(), SessionError> {
635 let mut seen = HashSet::new();
636 for key in keys {
637 if !seen.insert(key) {
638 return Err(SessionError::InvalidCheckpoint(format!(
639 "duplicate {operation} request key {key:?}"
640 )));
641 }
642 }
643 Ok(())
644}
645
646#[cfg(test)]
647mod tests {
648 use super::*;
649 use crate::config::TurnRunOptions;
650 use crate::driver::{Continuation, PausePoint, TurnResult, TurnTrace};
651 use causa_kernel::{TextPayload, TurnId};
652
653 #[test]
654 fn envelope_roundtrips_through_json_without_shape_drift() {
655 let conversation_id = ConversationId("conv-c1".into());
656 let turn_id = TurnId::new("conv-c1-work-0");
657 let checkpoint = SessionCheckpoint {
658 version: SESSION_CHECKPOINT_VERSION,
659 conversation_id: conversation_id.clone(),
660 phase: CheckpointPhase::Paused {
661 outcome: paused_outcome(&conversation_id, &turn_id),
662 work: WorkRef {
663 conversation_id: conversation_id.clone(),
664 turn_id: turn_id.clone(),
665 },
666 },
667 works: vec![SavedWork {
668 work: WorkRef {
669 conversation_id: conversation_id.clone(),
670 turn_id,
671 },
672 revision: 1,
673 state: WorkState::Paused,
674 finished: None,
675 fault: None,
676 deadline_utc: Some(SystemTime::UNIX_EPOCH + Duration::from_secs(42)),
677 }],
678 next_turn: 1,
679 submit_keys: vec![SavedSubmitKey {
680 key: "s1".into(),
681 parts: vec![ContentPart::Text(TextPayload::new("hello"))],
682 receipt: WorkReceipt {
683 work: WorkRef {
684 conversation_id: conversation_id.clone(),
685 turn_id: TurnId::new("conv-c1-work-0"),
686 },
687 accepted_revision: 0,
688 },
689 }],
690 resume_keys: vec![],
691 cancel_keys: vec![],
692 config: SessionConfigDescription::of(
693 &TurnRunOptions::default(),
694 &SessionConfig::default(),
695 ),
696 closed: false,
697 };
698
699 let json = serde_json::to_value(&checkpoint).expect("envelope serializes");
700 let back: SessionCheckpoint =
701 serde_json::from_value(json.clone()).expect("envelope deserializes");
702 assert_eq!(serde_json::to_value(&back).unwrap(), json);
703 assert_eq!(back.version, SESSION_CHECKPOINT_VERSION);
704 assert_eq!(back.next_turn, 1);
705 assert!(!back.closed);
706 let CheckpointPhase::Paused { work, .. } = &back.phase else {
707 panic!("the paused phase survives the roundtrip");
708 };
709 assert_eq!(work.conversation_id, conversation_id);
710 }
711
712 /// A minimal paused outcome: one open turn, sealed and stamped `Paused`,
713 /// with a steering continuation and no saved batches.
714 fn paused_outcome(conversation_id: &ConversationId, turn_id: &TurnId) -> ConversationOutcome {
715 let mut state = ConversationState::new(conversation_id.clone());
716 state.begin_turn(turn_id.clone()).expect("the turn admits");
717 state
718 .active_turn_mut()
719 .expect("begin_turn admitted an active turn")
720 .append_input(TextPayload::new("hi"), "user")
721 .expect("the input appends");
722 state
723 .seal_turn(turn_id.clone(), SealedResult::Paused)
724 .expect("the turn seals");
725 ConversationOutcome {
726 state,
727 result: TurnResult::Paused {
728 continuation: Continuation {
729 pause_point: PausePoint::PausedForSteering,
730 round: 0,
731 accounted_tool_calls: 0,
732 queued_inputs: Vec::new(),
733 },
734 },
735 trace: TurnTrace::new(),
736 }
737 }
738
739 #[test]
740 fn the_config_description_pins_the_options_it_was_derived_from() {
741 let mut options = TurnRunOptions::default();
742 options.invocation.model = causa_kernel::ModelRef::new("m1");
743 options.policy.limits.max_model_rounds = 3;
744 let config = SessionConfig {
745 retained_work_capacity: 8,
746 work_deadline: Some(Duration::from_secs(5)),
747 };
748
749 let described = SessionConfigDescription::of(&options, &config);
750 assert_eq!(described.model, "m1");
751 assert_eq!(described.limits.max_model_rounds, 3);
752 assert_eq!(described.session, config);
753 assert_eq!(described, SessionConfigDescription::of(&options, &config));
754
755 let mut swapped = options.clone();
756 swapped.invocation.model = causa_kernel::ModelRef::new("m2");
757 assert_ne!(
758 described,
759 SessionConfigDescription::of(&swapped, &config),
760 "a swapped model is visible to the comparison"
761 );
762 }
763}