use std::collections::{HashMap, HashSet};
use std::sync::Arc;
use std::time::{Duration, SystemTime};
use causa_kernel::{
CacheDirective, ContentPart, ConversationId, GenerationOptions, ToolSurface, TurnContext,
TurnId,
};
use crate::budget::WindowBudget;
use crate::config::{
RetryPolicy, ToolOutputLimits, TurnLimits, TurnRunOptions, UnknownOutcomeConfig,
};
use crate::conversation::{ConversationState, SealedResult};
use crate::driver::{ConversationOutcome, TurnResult, TurnRunner};
use crate::resume::ResumeRequest;
use super::execution::SessionCore;
use super::owner::Session;
use super::types::{
CancelReceipt, FinishedKind, SessionConfig, SessionError, WorkReceipt, WorkRef, WorkState,
};
pub const SESSION_CHECKPOINT_VERSION: u32 = 1;
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
#[non_exhaustive]
pub struct SessionCheckpoint {
pub version: u32,
pub conversation_id: ConversationId,
pub phase: CheckpointPhase,
pub works: Vec<SavedWork>,
pub next_turn: u64,
pub submit_keys: Vec<SavedSubmitKey>,
pub resume_keys: Vec<SavedResumeKey>,
pub cancel_keys: Vec<SavedCancelKey>,
pub config: SessionConfigDescription,
pub closed: bool,
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
#[serde(tag = "phase", rename_all = "snake_case")]
#[non_exhaustive]
#[allow(clippy::large_enum_variant)]
pub enum CheckpointPhase {
Idle {
state: ConversationState,
},
Paused {
outcome: ConversationOutcome,
work: WorkRef,
},
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct SavedWork {
pub work: WorkRef,
pub revision: u64,
pub state: WorkState,
pub finished: Option<FinishedKind>,
pub fault: Option<String>,
pub deadline_utc: Option<SystemTime>,
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct SavedSubmitKey {
pub key: String,
pub parts: Vec<ContentPart>,
pub receipt: WorkReceipt,
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct SavedResumeKey {
pub key: String,
pub work: WorkRef,
pub revision: u64,
pub request: ResumeRequest,
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct SavedCancelKey {
pub key: String,
pub work: WorkRef,
pub receipt: CancelReceipt,
}
#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
#[non_exhaustive]
pub struct SessionConfigDescription {
pub model: String,
pub tool_surface: ToolSurface,
pub generation: GenerationOptions,
pub cache: CacheDirective,
pub retry: RetryPolicy,
pub limits: TurnLimits,
pub attempt_timeout: Option<Duration>,
pub unknown_outcome: UnknownOutcomeConfig,
pub tool_output_limits: ToolOutputLimits,
pub tool_output_limits_overrides: HashMap<String, ToolOutputLimits>,
pub call_timeout: Option<Duration>,
pub window_budget: WindowBudget,
pub compaction_configured: bool,
pub frame_counter_configured: bool,
pub artifact_store_configured: bool,
pub truncation_counter_configured: bool,
pub session: SessionConfig,
}
impl SessionConfigDescription {
pub fn of(options: &TurnRunOptions, config: &SessionConfig) -> Self {
Self {
model: options.invocation.model.0.clone(),
tool_surface: options.invocation.tool_surface.clone(),
generation: options.invocation.generation.clone(),
cache: options.invocation.cache,
retry: options.policy.retry.clone(),
limits: options.policy.limits.clone(),
attempt_timeout: options.policy.attempt_timeout,
unknown_outcome: options.policy.unknown_outcome.clone(),
tool_output_limits: options.execution.tool_output_limits,
tool_output_limits_overrides: options.execution.tool_output_limits_overrides.clone(),
call_timeout: options.execution.call_timeout,
window_budget: options.frame.window_budget,
compaction_configured: options.frame.compaction.is_some(),
frame_counter_configured: options.frame.token_counter.is_some(),
artifact_store_configured: options.execution.artifact_store.is_some(),
truncation_counter_configured: options.execution.token_counter.is_some(),
session: config.clone(),
}
}
}
pub struct SessionRestoreRejection {
pub error: SessionError,
pub checkpoint: SessionCheckpoint,
pub runner: Arc<TurnRunner>,
pub options: TurnRunOptions,
pub config: SessionConfig,
}
pub(super) struct SavedRegistry {
pub works: Vec<SavedWork>,
pub submit_keys: Vec<SavedSubmitKey>,
pub resume_keys: Vec<SavedResumeKey>,
pub cancel_keys: Vec<SavedCancelKey>,
pub next_turn: u64,
pub closed: bool,
}
impl std::fmt::Debug for SessionRestoreRejection {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("SessionRestoreRejection")
.field("error", &self.error)
.field("checkpoint", &self.checkpoint)
.field("runner", &"Arc<TurnRunner>")
.field("options", &self.options)
.field("config", &self.config)
.finish()
}
}
impl SessionCheckpoint {
#[allow(clippy::result_large_err)]
pub fn restore(
self,
runner: Arc<TurnRunner>,
options: TurnRunOptions,
config: SessionConfig,
) -> Result<Session, SessionRestoreRejection> {
if let Err(error) = self.validate(&options, &config) {
return Err(SessionRestoreRejection {
error,
checkpoint: self,
runner,
options,
config,
});
}
let Self {
phase,
works,
next_turn,
submit_keys,
resume_keys,
cancel_keys,
closed,
..
} = self;
let registry = SavedRegistry {
works,
submit_keys,
resume_keys,
cancel_keys,
next_turn,
closed,
};
let core = match phase {
CheckpointPhase::Idle { state } => {
SessionCore::restore_idle(state, registry, runner, options, config)
}
CheckpointPhase::Paused { outcome, .. } => {
SessionCore::restore_paused(outcome, registry, runner, options, config)
}
};
Ok(Session::from_core(core))
}
fn validate(
&self,
options: &TurnRunOptions,
config: &SessionConfig,
) -> Result<(), SessionError> {
if self.version != SESSION_CHECKPOINT_VERSION {
return Err(SessionError::InvalidCheckpoint(format!(
"unsupported checkpoint version {} (this runtime writes {})",
self.version, SESSION_CHECKPOINT_VERSION
)));
}
if SessionConfigDescription::of(options, config) != self.config {
return Err(SessionError::ConfigMismatch);
}
let invalid = |reason: String| SessionError::InvalidCheckpoint(reason);
match &self.phase {
CheckpointPhase::Idle { state } => {
if *state.conversation_id() != self.conversation_id {
return Err(invalid(
"the idle state names a different conversation than the envelope".into(),
));
}
if state.active_turn().is_some() || state.sealed_result().is_some() {
return Err(invalid(
"the idle phase carries an active or sealed turn".into(),
));
}
}
CheckpointPhase::Paused { outcome, work } => {
if *outcome.state.conversation_id() != self.conversation_id {
return Err(invalid(
"the paused outcome names a different conversation than the envelope"
.into(),
));
}
if work.conversation_id != self.conversation_id {
return Err(invalid(
"the paused work names a different conversation than the envelope".into(),
));
}
let TurnResult::Paused { continuation } = &outcome.result else {
return Err(invalid(
"the paused phase does not carry a paused result".into(),
));
};
let Some(active) = outcome.state.active_turn() else {
return Err(invalid("the paused outcome has no open active turn".into()));
};
if active.turn_id() != work.turn_id {
return Err(invalid(
"the paused outcome's active turn does not match the paused work".into(),
));
}
if outcome.state.sealed_result() != Some(SealedResult::Paused) {
return Err(invalid(
"the paused outcome's active turn is not stamped Paused".into(),
));
}
crate::resume::validate_continuation_facts(continuation, active)
.map_err(invalid)?;
}
}
let history_ids: HashSet<&TurnId> = match &self.phase {
CheckpointPhase::Idle { state } => state
.history()
.iter()
.map(|entry| &entry.snapshot.turn_id)
.collect(),
CheckpointPhase::Paused { outcome, .. } => outcome
.state
.history()
.iter()
.map(|entry| &entry.snapshot.turn_id)
.collect(),
};
let prefix = format!("{}-work-", self.conversation_id.0);
let mut seen = HashSet::new();
let mut paused_works = 0usize;
for saved in &self.works {
if saved.work.conversation_id != self.conversation_id {
return Err(invalid(format!(
"work {:?} names a different conversation than the envelope",
saved.work
)));
}
if !seen.insert(saved.work.turn_id.clone()) {
return Err(invalid(format!("duplicate work identity {:?}", saved.work)));
}
let Some(index) = saved
.work
.turn_id
.0
.strip_prefix(prefix.as_str())
.and_then(|suffix| suffix.parse::<u64>().ok())
else {
return Err(invalid(format!(
"work {:?} was not allocated by this conversation's identity sequence",
saved.work
)));
};
if self.next_turn <= index {
return Err(invalid(format!(
"the allocation progress ({}) does not follow work identity {:?}",
self.next_turn, saved.work
)));
}
match &saved.finished {
Some(FinishedKind::Completed { .. })
if !history_ids.contains(&saved.work.turn_id) =>
{
return Err(invalid(format!(
"completed work {:?} has no committed history entry",
saved.work
)));
}
Some(FinishedKind::Interrupted { facts, .. }) => {
if history_ids.contains(&saved.work.turn_id) {
return Err(invalid(format!(
"interrupted work {:?} also sits in the completed history",
saved.work
)));
}
if facts.turn_id != saved.work.turn_id {
return Err(invalid(format!(
"interrupted work {:?} carries facts from another turn",
saved.work
)));
}
TurnContext::validate_blocks(&facts.turn_id, facts.blocks.as_slice())
.map_err(|error| invalid(error.to_string()))?;
}
_ => {}
}
match saved.state {
WorkState::Finished => {
if saved.finished.is_none() || saved.fault.is_some() {
return Err(invalid(format!(
"finished work {:?} carries no result or a fault",
saved.work
)));
}
}
WorkState::Paused => {
paused_works += 1;
if saved.finished.is_some() || saved.fault.is_some() {
return Err(invalid(format!(
"paused work {:?} carries a result or a fault",
saved.work
)));
}
}
WorkState::Accepted | WorkState::Running | WorkState::Faulted => {
return Err(invalid(format!(
"work {:?} is {:?}; only terminal works and the one paused work can be checkpointed",
saved.work, saved.state
)));
}
}
}
let paused_phase = matches!(&self.phase, CheckpointPhase::Paused { .. });
let expected = usize::from(paused_phase);
if paused_works != expected {
return Err(invalid(format!(
"the envelope registers {paused_works} paused works; the {} phase carries exactly one",
if paused_phase { "paused" } else { "idle" }
)));
}
if let CheckpointPhase::Paused { work, .. } = &self.phase {
let registered = self
.works
.iter()
.any(|saved| saved.work == *work && saved.state == WorkState::Paused);
if !registered {
return Err(invalid(
"the paused phase's work is not registered as a paused work".into(),
));
}
}
validate_unique_keys(
"submit",
self.submit_keys.iter().map(|saved| saved.key.as_str()),
)?;
validate_unique_keys(
"resume",
self.resume_keys.iter().map(|saved| saved.key.as_str()),
)?;
validate_unique_keys(
"cancel",
self.cancel_keys.iter().map(|saved| saved.key.as_str()),
)?;
let known: HashSet<&WorkRef> = self.works.iter().map(|saved| &saved.work).collect();
for saved in &self.submit_keys {
if !known.contains(&saved.receipt.work) {
return Err(invalid(format!(
"submit key {:?} receipts an unknown work",
saved.key
)));
}
if saved.receipt.accepted_revision != 0 {
return Err(invalid(format!(
"submit key {:?} records a non-zero acceptance revision; a live submit always accepts at revision 0",
saved.key
)));
}
if saved.parts.is_empty() {
return Err(invalid(format!(
"submit key {:?} carries no parts",
saved.key
)));
}
}
for saved in &self.resume_keys {
if !known.contains(&saved.work) {
return Err(invalid(format!(
"resume key {:?} targets an unknown work",
saved.key
)));
}
}
for saved in &self.cancel_keys {
if !known.contains(&saved.work) {
return Err(invalid(format!(
"cancel key {:?} targets an unknown work",
saved.key
)));
}
if saved.receipt.work != saved.work {
return Err(invalid(format!(
"cancel key {:?} receipts a different work than its target",
saved.key
)));
}
}
Ok(())
}
}
fn validate_unique_keys<'a>(
operation: &str,
keys: impl Iterator<Item = &'a str>,
) -> Result<(), SessionError> {
let mut seen = HashSet::new();
for key in keys {
if !seen.insert(key) {
return Err(SessionError::InvalidCheckpoint(format!(
"duplicate {operation} request key {key:?}"
)));
}
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
use crate::config::TurnRunOptions;
use crate::driver::{Continuation, PausePoint, TurnResult, TurnTrace};
use causa_kernel::{TextPayload, TurnId};
#[test]
fn envelope_roundtrips_through_json_without_shape_drift() {
let conversation_id = ConversationId("conv-c1".into());
let turn_id = TurnId::new("conv-c1-work-0");
let checkpoint = SessionCheckpoint {
version: SESSION_CHECKPOINT_VERSION,
conversation_id: conversation_id.clone(),
phase: CheckpointPhase::Paused {
outcome: paused_outcome(&conversation_id, &turn_id),
work: WorkRef {
conversation_id: conversation_id.clone(),
turn_id: turn_id.clone(),
},
},
works: vec![SavedWork {
work: WorkRef {
conversation_id: conversation_id.clone(),
turn_id,
},
revision: 1,
state: WorkState::Paused,
finished: None,
fault: None,
deadline_utc: Some(SystemTime::UNIX_EPOCH + Duration::from_secs(42)),
}],
next_turn: 1,
submit_keys: vec![SavedSubmitKey {
key: "s1".into(),
parts: vec![ContentPart::Text(TextPayload::new("hello"))],
receipt: WorkReceipt {
work: WorkRef {
conversation_id: conversation_id.clone(),
turn_id: TurnId::new("conv-c1-work-0"),
},
accepted_revision: 0,
},
}],
resume_keys: vec![],
cancel_keys: vec![],
config: SessionConfigDescription::of(
&TurnRunOptions::default(),
&SessionConfig::default(),
),
closed: false,
};
let json = serde_json::to_value(&checkpoint).expect("envelope serializes");
let back: SessionCheckpoint =
serde_json::from_value(json.clone()).expect("envelope deserializes");
assert_eq!(serde_json::to_value(&back).unwrap(), json);
assert_eq!(back.version, SESSION_CHECKPOINT_VERSION);
assert_eq!(back.next_turn, 1);
assert!(!back.closed);
let CheckpointPhase::Paused { work, .. } = &back.phase else {
panic!("the paused phase survives the roundtrip");
};
assert_eq!(work.conversation_id, conversation_id);
}
fn paused_outcome(conversation_id: &ConversationId, turn_id: &TurnId) -> ConversationOutcome {
let mut state = ConversationState::new(conversation_id.clone());
state.begin_turn(turn_id.clone()).expect("the turn admits");
state
.active_turn_mut()
.expect("begin_turn admitted an active turn")
.append_input(TextPayload::new("hi"), "user")
.expect("the input appends");
state
.seal_turn(turn_id.clone(), SealedResult::Paused)
.expect("the turn seals");
ConversationOutcome {
state,
result: TurnResult::Paused {
continuation: Continuation {
pause_point: PausePoint::PausedForSteering,
round: 0,
accounted_tool_calls: 0,
queued_inputs: Vec::new(),
},
},
trace: TurnTrace::new(),
}
}
#[test]
fn the_config_description_pins_the_options_it_was_derived_from() {
let mut options = TurnRunOptions::default();
options.invocation.model = causa_kernel::ModelRef::new("m1");
options.policy.limits.max_model_rounds = 3;
let config = SessionConfig {
retained_work_capacity: 8,
work_deadline: Some(Duration::from_secs(5)),
};
let described = SessionConfigDescription::of(&options, &config);
assert_eq!(described.model, "m1");
assert_eq!(described.limits.max_model_rounds, 3);
assert_eq!(described.session, config);
assert_eq!(described, SessionConfigDescription::of(&options, &config));
let mut swapped = options.clone();
swapped.invocation.model = causa_kernel::ModelRef::new("m2");
assert_ne!(
described,
SessionConfigDescription::of(&swapped, &config),
"a swapped model is visible to the comparison"
);
}
}