a3s_code_core/store/
session_snapshot.rs1use super::SessionData;
2use crate::run::RunRecord;
3use crate::subagent_task_tracker::SubagentTaskSnapshot;
4use crate::tools::{ArtifactStore, ArtifactStoreLimits, ToolArtifact};
5use crate::trace::TraceEvent;
6use crate::verification::VerificationReport;
7use anyhow::{bail, Result};
8use serde::{Deserialize, Serialize};
9use std::collections::HashSet;
10
11pub const SESSION_SNAPSHOT_SCHEMA_VERSION: u32 = 1;
13
14#[derive(Debug, Clone, Serialize, Deserialize)]
19pub struct SessionSnapshotV1 {
20 pub schema_version: u32,
21 pub session: SessionData,
22 #[serde(default)]
23 pub artifacts: Vec<ToolArtifact>,
24 #[serde(default)]
25 pub trace_events: Vec<TraceEvent>,
26 #[serde(default)]
27 pub run_records: Vec<RunRecord>,
28 #[serde(default)]
29 pub verification_reports: Vec<VerificationReport>,
30 #[serde(default)]
31 pub subagent_tasks: Vec<SubagentTaskSnapshot>,
32}
33
34impl SessionSnapshotV1 {
35 pub fn new(
36 session: SessionData,
37 artifacts: &ArtifactStore,
38 trace_events: Vec<TraceEvent>,
39 run_records: Vec<RunRecord>,
40 verification_reports: Vec<VerificationReport>,
41 subagent_tasks: Vec<SubagentTaskSnapshot>,
42 ) -> Self {
43 Self {
44 schema_version: SESSION_SNAPSHOT_SCHEMA_VERSION,
45 session,
46 artifacts: artifacts.artifacts(),
47 trace_events,
48 run_records,
49 verification_reports,
50 subagent_tasks,
51 }
52 }
53
54 pub fn session_only(session: SessionData) -> Self {
55 Self::new(
56 session,
57 &ArtifactStore::new(),
58 Vec::new(),
59 Vec::new(),
60 Vec::new(),
61 Vec::new(),
62 )
63 }
64
65 pub fn fork_for_session(
71 mut self,
72 session_id: impl Into<String>,
73 workspace: impl Into<String>,
74 ) -> Result<Self> {
75 let source_session_id = self.session.id.clone();
76 self.validate_for_session(&source_session_id)?;
77
78 let session_id = session_id.into();
79 if session_id.trim().is_empty() {
80 bail!("forked session id cannot be empty");
81 }
82
83 self.session.id = session_id.clone();
84 self.session.config.workspace = workspace.into();
85 for record in &mut self.run_records {
86 record.snapshot.session_id.clone_from(&session_id);
87 }
88 for task in &mut self.subagent_tasks {
89 if !task.parent_session_id.is_empty() {
90 task.parent_session_id.clone_from(&session_id);
91 }
92 }
93
94 self.validate_for_session(&session_id)?;
95 Ok(self)
96 }
97
98 pub fn artifact_store(&self) -> ArtifactStore {
99 artifact_store_from(&self.artifacts)
100 }
101
102 pub(crate) fn artifact_store_requirements(&self) -> ArtifactStoreLimits {
103 artifact_store_requirements(&self.artifacts)
104 }
105
106 pub fn ensure_loadable(&self) -> Result<()> {
107 if self.schema_version != SESSION_SNAPSHOT_SCHEMA_VERSION {
108 bail!(
109 "unsupported session snapshot schema version {}; expected {}",
110 self.schema_version,
111 SESSION_SNAPSHOT_SCHEMA_VERSION
112 );
113 }
114 Ok(())
115 }
116
117 pub fn validate_invariants(&self) -> Result<()> {
124 let mut run_ids = HashSet::with_capacity(self.run_records.len());
125
126 for (run_index, record) in self.run_records.iter().enumerate() {
127 let run_id = &record.snapshot.id;
128 if !run_ids.insert(run_id.as_str()) {
129 bail!(
130 "session snapshot {:?} contains duplicate run id {:?} at run record {}",
131 self.session.id,
132 run_id,
133 run_index
134 );
135 }
136
137 if record.snapshot.session_id != self.session.id {
138 bail!(
139 "run {:?} at record {} belongs to session {:?}, but snapshot belongs to session {:?}",
140 run_id,
141 run_index,
142 record.snapshot.session_id,
143 self.session.id
144 );
145 }
146
147 let mut previous_sequence = None;
148 for (event_index, event) in record.events.iter().enumerate() {
149 if let Some(previous) = previous_sequence {
150 if event.sequence <= previous {
151 bail!(
152 "run {:?} event {} has sequence {}, which is not strictly greater than previous sequence {}",
153 run_id,
154 event_index,
155 event.sequence,
156 previous
157 );
158 }
159 }
160 previous_sequence = Some(event.sequence);
161 }
162
163 if let Some(max_sequence) = previous_sequence {
164 let minimum_event_count = max_sequence.checked_add(1).ok_or_else(|| {
165 anyhow::anyhow!(
166 "run {:?} retained event sequence {} cannot be represented by event_count",
167 run_id,
168 max_sequence
169 )
170 })?;
171 if record.snapshot.event_count < minimum_event_count {
172 bail!(
173 "run {:?} event_count {} does not cover retained event sequence {}; expected at least {}",
174 run_id,
175 record.snapshot.event_count,
176 max_sequence,
177 minimum_event_count
178 );
179 }
180 }
181 }
182
183 for (task_index, task) in self.subagent_tasks.iter().enumerate() {
184 if !task.parent_session_id.is_empty() && task.parent_session_id != self.session.id {
188 bail!(
189 "subagent task {:?} at record {} belongs to parent session {:?}, but snapshot belongs to session {:?}",
190 task.task_id,
191 task_index,
192 task.parent_session_id,
193 self.session.id
194 );
195 }
196 }
197
198 Ok(())
199 }
200
201 pub fn validate_for_session(&self, session_id: &str) -> Result<()> {
203 self.ensure_loadable()?;
204 if self.session.id != session_id {
205 bail!(
206 "requested session {:?}, but snapshot payload belongs to session {:?}",
207 session_id,
208 self.session.id
209 );
210 }
211 self.validate_invariants()
212 }
213}
214
215pub(super) fn artifact_store_from(artifacts: &[ToolArtifact]) -> ArtifactStore {
216 let defaults = ArtifactStoreLimits::default();
220 let requirements = artifact_store_requirements(artifacts);
221 let store = ArtifactStore::with_limits(ArtifactStoreLimits {
222 max_artifacts: defaults.max_artifacts.max(requirements.max_artifacts),
223 max_bytes: defaults.max_bytes.max(requirements.max_bytes),
224 });
225 for artifact in artifacts {
226 store.put(artifact.clone());
227 }
228 store
229}
230
231fn artifact_store_requirements(artifacts: &[ToolArtifact]) -> ArtifactStoreLimits {
232 ArtifactStoreLimits {
233 max_artifacts: artifacts.len(),
234 max_bytes: artifacts.iter().fold(0usize, |total, artifact| {
235 total.saturating_add(artifact.content.len())
236 }),
237 }
238}