everruns_contracts/sandbox_checkpoint.rs
1//! Logical sandbox and authoritative workspace-checkpoint contracts.
2
3use async_trait::async_trait;
4use chrono::{DateTime, Utc};
5use serde::{Deserialize, Serialize};
6use uuid::Uuid;
7
8use crate::typed_id::SessionId;
9
10/// How a checkpoint's bytes are stored.
11#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
12#[serde(rename_all = "snake_case")]
13pub enum SandboxCheckpointKind {
14 /// A provider-managed snapshot. A fast resume path only: it dies with the
15 /// provider resource, so it cannot be the recovery path for physical loss.
16 ProviderNative,
17 /// An Everruns-owned archive of the working filesystem. The recovery path
18 /// for physical sandbox loss and provider migration.
19 PortableWorkspace,
20}
21
22impl SandboxCheckpointKind {
23 pub const fn as_str(self) -> &'static str {
24 match self {
25 Self::ProviderNative => "provider_native",
26 Self::PortableWorkspace => "portable_workspace",
27 }
28 }
29}
30
31/// Identity and fencing state of a logical sandbox.
32#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
33pub struct SandboxRef {
34 pub id: Uuid,
35 /// Current incarnation. Writes carry the generation they were issued
36 /// against so a late response from a replaced sandbox cannot advance state.
37 pub generation: i64,
38}
39
40/// A recorded workspace revision.
41#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
42pub struct SandboxCheckpoint {
43 pub id: Uuid,
44 pub sandbox_id: Uuid,
45 pub generation: i64,
46 pub source_turn_id: Option<String>,
47 pub source_tool_call_id: Option<String>,
48 pub kind: SandboxCheckpointKind,
49 pub provider_ref: Option<String>,
50 pub workspace_revision: String,
51 /// `None` while the checkpoint is uploaded but not yet authoritative.
52 pub attached_at: Option<DateTime<Utc>>,
53 pub created_at: DateTime<Utc>,
54}
55
56/// A checkpoint upload that has completed but is not yet authoritative.
57#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
58pub struct NewSandboxCheckpoint {
59 pub sandbox_id: Uuid,
60 pub generation: i64,
61 pub source_turn_id: Option<String>,
62 pub source_tool_call_id: Option<String>,
63 pub kind: SandboxCheckpointKind,
64 pub provider_ref: Option<String>,
65 pub workspace_revision: String,
66}
67
68#[derive(Debug, thiserror::Error)]
69pub enum SandboxCheckpointError {
70 #[error("sandbox checkpoint storage error: {0}")]
71 Storage(String),
72 /// The write was issued against a superseded incarnation. The caller must
73 /// not retry it against the current generation: the bytes it refers to
74 /// belong to a sandbox that no longer exists.
75 #[error("sandbox {sandbox_id} is at generation {current}, write carried {carried}")]
76 StaleGeneration {
77 sandbox_id: Uuid,
78 current: i64,
79 carried: i64,
80 },
81}
82
83/// Hard upper bound on one garbage-collection batch (TM-DOS). Caps the
84/// destructive `collect_unattached_checkpoints` regardless of caller input, so a
85/// misconfigured limit cannot request an unbounded delete; large backlogs drain
86/// over successive sweeps. Mirrors `MAX_RETENTION_PRUNE_LIMIT` in the server
87/// storage backend.
88pub const MAX_CHECKPOINT_COLLECT_LIMIT: i64 = 1000;
89
90/// Persistence for logical sandboxes and their checkpoints.
91#[async_trait]
92pub trait SandboxCheckpointStore: Send + Sync {
93 /// Resolve the logical sandbox for a session/provider pair, creating it on
94 /// first use. Idempotent.
95 async fn ensure_sandbox(
96 &self,
97 session_id: SessionId,
98 provider: &str,
99 ) -> Result<SandboxRef, SandboxCheckpointError>;
100
101 /// Record a completed upload. The checkpoint is not authoritative yet, so a
102 /// crash after this point leaves a collectable orphan rather than a pointer
103 /// to a revision no committed turn produced.
104 ///
105 /// Recording the same `workspace_revision` twice returns the existing row.
106 async fn record_checkpoint(
107 &self,
108 checkpoint: NewSandboxCheckpoint,
109 ) -> Result<SandboxCheckpoint, SandboxCheckpointError>;
110
111 /// Promote a recorded checkpoint to authoritative, fenced on `generation`.
112 /// Returns `StaleGeneration` if the sandbox has been replaced since the
113 /// upload, leaving the previous committed checkpoint in place.
114 ///
115 /// THREAT[TM-TENANT-012]: takes a bare `sandbox_id` with no org filter.
116 /// Callers MUST obtain it from [`Self::ensure_sandbox`], which scopes to the
117 /// session the tool context is executing for. Never accept a `sandbox_id`
118 /// from request input.
119 async fn attach_checkpoint(
120 &self,
121 sandbox_id: Uuid,
122 checkpoint_id: Uuid,
123 generation: i64,
124 ) -> Result<(), SandboxCheckpointError>;
125
126 /// The last checkpoint committed as authoritative, if any.
127 ///
128 /// THREAT[TM-TENANT-012]: bare `sandbox_id`, same caller obligation as
129 /// [`Self::attach_checkpoint`].
130 async fn current_checkpoint(
131 &self,
132 sandbox_id: Uuid,
133 ) -> Result<Option<SandboxCheckpoint>, SandboxCheckpointError>;
134
135 /// Reject `checkpoint_id` as authoritative and fall back to the previous
136 /// attached checkpoint, returning whatever the sandbox now points at.
137 ///
138 /// This is the reconciliation half of the crash window: a checkpoint is
139 /// attached before the tool result it belongs to is settled, so a crash in
140 /// between leaves the workspace ahead of the conversation. Rolling the
141 /// pointer back detaches the rejected revision, which returns it to the
142 /// collectable pool rather than deleting it inline.
143 ///
144 /// Fenced on `generation`, and a no-op when the sandbox no longer points at
145 /// `checkpoint_id`: in both cases something newer already decided, and this
146 /// call must not undo it. `Ok(None)` means the sandbox has no earlier
147 /// committed revision to fall back to.
148 ///
149 /// THREAT[TM-TENANT-012]: bare `sandbox_id`, same caller obligation as
150 /// [`Self::attach_checkpoint`].
151 async fn rollback_current_checkpoint(
152 &self,
153 sandbox_id: Uuid,
154 checkpoint_id: Uuid,
155 generation: i64,
156 ) -> Result<Option<SandboxCheckpoint>, SandboxCheckpointError>;
157
158 /// Delete up to `limit` uploads that were never attached and are older than
159 /// `before`. Attached checkpoints are never returned or removed. Returns the
160 /// `workspace_revision` of each collected row so the caller can drop the
161 /// matching provider-side artifact.
162 ///
163 /// `limit` bounds one destructive batch so a large backlog drains over
164 /// successive sweeps instead of issuing one unbounded delete; implementations
165 /// clamp it to [`MAX_CHECKPOINT_COLLECT_LIMIT`].
166 ///
167 /// THREAT[TM-TENANT-012]: bare `sandbox_id`, same caller obligation as
168 /// [`Self::attach_checkpoint`].
169 async fn collect_unattached_checkpoints(
170 &self,
171 sandbox_id: Uuid,
172 before: DateTime<Utc>,
173 limit: i64,
174 ) -> Result<Vec<String>, SandboxCheckpointError>;
175}
176
177/// Type-keyed wrapper installed on the tool context by hosted presets.
178///
179/// Runtime hosts install this service in the generic tool-context extension bag.
180#[derive(Clone)]
181pub struct SandboxCheckpointStoreExt(pub std::sync::Arc<dyn SandboxCheckpointStore>);