Skip to main content

a3s_code_core/store/
session_snapshot.rs

1use 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
11/// Schema version written by [`SessionSnapshotV1`].
12pub const SESSION_SNAPSHOT_SCHEMA_VERSION: u32 = 1;
13
14/// A complete, versioned persistence generation for one session.
15///
16/// Stores commit this value as a unit so conversation state and its related
17/// runtime records cannot be observed from different save generations.
18#[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    /// Rebind a complete snapshot to a new session and workspace.
66    ///
67    /// Session forks retain historical artifacts, traces, run ids, and child
68    /// session ids. Top-level run ownership and subagent parent ownership must
69    /// move with the new session or the aggregate would no longer be loadable.
70    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    /// Validate relationships that must hold within one persisted generation.
118    ///
119    /// Event buffers may be FIFO-trimmed, so their first sequence is allowed
120    /// to be greater than zero and `event_count` is allowed to exceed the
121    /// retained length. It must, however, remain a valid next-sequence cursor
122    /// for every retained event.
123    pub fn validate_invariants(&self) -> Result<()> {
124        self.session
125            .config
126            .tool_result_transform_policy
127            .validate()
128            .map_err(|error| {
129                anyhow::anyhow!(
130                    "session snapshot {:?} has an invalid Tool result transform policy: {error}",
131                    self.session.id
132                )
133            })?;
134        if let Some(binding) = &self.session.cognitive_package_binding {
135            binding.validate().map_err(|error| {
136                anyhow::anyhow!(
137                    "session snapshot {:?} has an invalid cognitive package binding: {error}",
138                    self.session.id
139                )
140            })?;
141        }
142        if let Some(binding) = &self.session.immutable_content_adapter_binding {
143            binding.validate().map_err(|error| {
144                anyhow::anyhow!(
145                    "session snapshot {:?} has an invalid immutable-content adapter binding: {error}",
146                    self.session.id
147                )
148            })?;
149        }
150        let mut run_ids = HashSet::with_capacity(self.run_records.len());
151
152        for (run_index, record) in self.run_records.iter().enumerate() {
153            let run_id = &record.snapshot.id;
154            if let Some(binding) = &record.snapshot.cognitive_package_binding {
155                binding.validate().map_err(|error| {
156                    anyhow::anyhow!(
157                        "run {:?} at record {} has an invalid cognitive package binding: {error}",
158                        run_id,
159                        run_index
160                    )
161                })?;
162            }
163            if let Some(binding) = &record.snapshot.capability_binding {
164                binding.validate().map_err(|error| {
165                    anyhow::anyhow!(
166                        "run {:?} at record {} has an invalid capability binding: {error}",
167                        run_id,
168                        run_index
169                    )
170                })?;
171            }
172            if !run_ids.insert(run_id.as_str()) {
173                bail!(
174                    "session snapshot {:?} contains duplicate run id {:?} at run record {}",
175                    self.session.id,
176                    run_id,
177                    run_index
178                );
179            }
180
181            if record.snapshot.session_id != self.session.id {
182                bail!(
183                    "run {:?} at record {} belongs to session {:?}, but snapshot belongs to session {:?}",
184                    run_id,
185                    run_index,
186                    record.snapshot.session_id,
187                    self.session.id
188                );
189            }
190
191            let mut previous_sequence = None;
192            // Snapshots written before Run-level binding evidence was added
193            // may still carry repeated cognitive events. Keep those loadable
194            // when the events agree with each other; new snapshots bind the
195            // value directly on RunSnapshot and no longer compare old Runs to
196            // the Session's latest catalog generation.
197            let mut legacy_event_binding = None;
198            for (event_index, event) in record.events.iter().enumerate() {
199                if let Some(previous) = previous_sequence {
200                    if event.sequence <= previous {
201                        bail!(
202                            "run {:?} event {} has sequence {}, which is not strictly greater than previous sequence {}",
203                            run_id,
204                            event_index,
205                            event.sequence,
206                            previous
207                        );
208                    }
209                }
210                previous_sequence = Some(event.sequence);
211                if let crate::agent::AgentEvent::CognitiveContextBound { binding } = &event.event {
212                    binding.validate().map_err(|error| {
213                        anyhow::anyhow!(
214                            "run {:?} event {} has an invalid cognitive package binding: {error}",
215                            run_id,
216                            event_index
217                        )
218                    })?;
219                    match &record.snapshot.cognitive_package_binding {
220                        Some(expected) if expected == binding => {}
221                        Some(_) => bail!(
222                            "run {:?} event {} carries a cognitive generation different from its admitted Run binding",
223                            run_id,
224                            event_index
225                        ),
226                        None => match &legacy_event_binding {
227                            Some(expected) if expected == binding => {}
228                            Some(_) => bail!(
229                                "legacy run {:?} event {} changes cognitive generation within one Run",
230                                run_id,
231                                event_index
232                            ),
233                            None => legacy_event_binding = Some(binding.clone()),
234                        },
235                    }
236                }
237                if let crate::agent::AgentEvent::ToolEnd { metadata, .. } = &event.event {
238                    validate_tool_result_transform_metadata(
239                        &self.session.id,
240                        run_id,
241                        event_index,
242                        metadata.as_ref(),
243                        &self.session.config.tool_result_transform_policy,
244                    )?;
245                }
246            }
247
248            if let Some(max_sequence) = previous_sequence {
249                let minimum_event_count = max_sequence.checked_add(1).ok_or_else(|| {
250                    anyhow::anyhow!(
251                        "run {:?} retained event sequence {} cannot be represented by event_count",
252                        run_id,
253                        max_sequence
254                    )
255                })?;
256                if record.snapshot.event_count < minimum_event_count {
257                    bail!(
258                        "run {:?} event_count {} does not cover retained event sequence {}; expected at least {}",
259                        run_id,
260                        record.snapshot.event_count,
261                        max_sequence,
262                        minimum_event_count
263                    );
264                }
265            }
266        }
267
268        for (task_index, task) in self.subagent_tasks.iter().enumerate() {
269            // Older snapshots can contain an empty parent when progress/end
270            // arrived before SubagentStart. A non-empty parent is authoritative
271            // and must identify the session that owns this task tracker.
272            if !task.parent_session_id.is_empty() && task.parent_session_id != self.session.id {
273                bail!(
274                    "subagent task {:?} at record {} belongs to parent session {:?}, but snapshot belongs to session {:?}",
275                    task.task_id,
276                    task_index,
277                    task.parent_session_id,
278                    self.session.id
279                );
280            }
281        }
282
283        Ok(())
284    }
285
286    /// Validate this snapshot for a load request targeting `session_id`.
287    pub fn validate_for_session(&self, session_id: &str) -> Result<()> {
288        self.ensure_loadable()?;
289        if self.session.id != session_id {
290            bail!(
291                "requested session {:?}, but snapshot payload belongs to session {:?}",
292                session_id,
293                self.session.id
294            );
295        }
296        self.validate_invariants()
297    }
298}
299
300fn validate_tool_result_transform_metadata(
301    session_id: &str,
302    run_id: &str,
303    event_index: usize,
304    metadata: Option<&serde_json::Value>,
305    policy: &crate::tools::ToolResultTransformPolicyV1,
306) -> Result<()> {
307    let Some(encoded_binding) = metadata
308        .and_then(|value| value.get(crate::tools::TOOL_RESULT_TRANSFORM_BINDING_METADATA_KEY))
309    else {
310        return Ok(());
311    };
312    let binding: crate::tools::ToolResultTransformBindingV1 =
313        serde_json::from_value(encoded_binding.clone()).map_err(|error| {
314            anyhow::anyhow!(
315                "run {:?} event {} in session {:?} has malformed Tool result transform binding: {error}",
316                run_id,
317                event_index,
318                session_id
319            )
320        })?;
321    binding.validate_for_policy(policy).map_err(|error| {
322        anyhow::anyhow!(
323            "run {:?} event {} in session {:?} has invalid Tool result transform binding: {error}",
324            run_id,
325            event_index,
326            session_id
327        )
328    })?;
329
330    let encoded_evidence = metadata
331        .and_then(|value| value.get("a3s_tool_result_evidence"))
332        .ok_or_else(|| {
333            anyhow::anyhow!(
334                "run {:?} event {} in session {:?} has a Tool result transform binding without Tool result evidence",
335                run_id,
336                event_index,
337                session_id
338            )
339        })?;
340    let evidence: crate::tools::ToolResultEvidenceV1 =
341        serde_json::from_value(encoded_evidence.clone()).map_err(|error| {
342            anyhow::anyhow!(
343                "run {:?} event {} in session {:?} has malformed Tool result evidence: {error}",
344                run_id,
345                event_index,
346                session_id
347            )
348        })?;
349    if evidence.schema != crate::tools::TOOL_RESULT_EVIDENCE_SCHEMA_V1
350        || evidence.transform_algorithm.as_deref() != Some(binding.transform_algorithm.as_str())
351    {
352        anyhow::bail!(
353            "run {:?} event {} in session {:?} has Tool result evidence that does not match its transform binding",
354            run_id,
355            event_index,
356            session_id
357        );
358    }
359    Ok(())
360}
361
362pub(super) fn artifact_store_from(artifacts: &[ToolArtifact]) -> ArtifactStore {
363    // A snapshot is an authoritative persisted generation. Rehydrating it
364    // through the default in-memory limits must not silently evict records
365    // that were accepted by a store configured with larger limits.
366    let defaults = ArtifactStoreLimits::default();
367    let requirements = artifact_store_requirements(artifacts);
368    let store = ArtifactStore::with_limits(ArtifactStoreLimits {
369        max_artifacts: defaults.max_artifacts.max(requirements.max_artifacts),
370        max_bytes: defaults.max_bytes.max(requirements.max_bytes),
371    });
372    for artifact in artifacts {
373        store.put(artifact.clone());
374    }
375    store
376}
377
378fn artifact_store_requirements(artifacts: &[ToolArtifact]) -> ArtifactStoreLimits {
379    ArtifactStoreLimits {
380        max_artifacts: artifacts.len(),
381        max_bytes: artifacts.iter().fold(0usize, |total, artifact| {
382            total.saturating_add(artifact.content.len())
383        }),
384    }
385}