1use crate::error::InvalidError;
2use crate::limits::MAX_FORK_ID_BYTES;
3use serde::{Deserialize, Serialize};
4use std::collections::BTreeMap;
5
6#[derive(
8 Clone,
9 Copy,
10 Debug,
11 Default,
12 PartialEq,
13 Eq,
14 Serialize,
15 Deserialize,
16 strum::Display,
17 strum::EnumString,
18 strum::VariantArray,
19)]
20#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
21#[serde(rename_all = "snake_case")]
22#[strum(serialize_all = "snake_case")]
23#[non_exhaustive]
24pub enum ForkKind {
25 Severed,
28 #[default]
30 Continuous,
31}
32
33#[derive(
35 Clone,
36 Copy,
37 Debug,
38 Default,
39 PartialEq,
40 Eq,
41 Serialize,
42 Deserialize,
43 strum::Display,
44 strum::EnumString,
45 strum::VariantArray,
46)]
47#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
48#[serde(rename_all = "snake_case")]
49#[strum(serialize_all = "snake_case")]
50#[non_exhaustive]
51pub enum ForkStatus {
52 #[default]
53 Open,
54 Promoted,
55 Squashed,
56}
57
58#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
60#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
61pub struct ForkInfo {
62 pub fork_id: String,
63 #[serde(default, skip_serializing_if = "Option::is_none")]
64 pub parent: Option<String>,
65 pub kind: ForkKind,
66 pub user_id: u32,
67 pub status: ForkStatus,
68 pub created_at_micros: u64,
69 pub row_count: u64,
70}
71
72#[derive(Clone, Debug, Serialize, Deserialize)]
75#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
76pub struct ForkCreate {
77 pub v: u32,
78 pub fork_id: String,
79 #[serde(default, skip_serializing_if = "Option::is_none")]
80 pub parent: Option<String>,
81 #[serde(default)]
82 pub kind: ForkKind,
83 #[serde(default, skip_serializing_if = "Vec::is_empty")]
84 pub tables: Vec<String>,
85 #[serde(default, skip_serializing_if = "Option::is_none")]
89 pub points: Option<Vec<ForkPoint>>,
90}
91
92#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
95#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
96pub struct ForkPoint {
97 pub table: String,
98 pub partition_id: u32,
99 pub offset: u64,
100 #[serde(default, skip_serializing_if = "Option::is_none")]
102 pub source_incarnation: Option<u64>,
103}
104
105#[derive(Clone, Debug, Serialize, Deserialize)]
107#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
108pub struct ForkDelete {
109 pub v: u32,
110 pub fork_id: String,
111}
112
113#[derive(Clone, Debug, Serialize, Deserialize)]
115#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
116pub struct ForkPromote {
117 pub v: u32,
118 pub fork_id: String,
119}
120
121#[derive(Clone, Debug, Serialize, Deserialize)]
123#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
124pub struct ForkList {
125 pub v: u32,
126 #[serde(default, skip_serializing_if = "Option::is_none")]
130 pub stream: Option<String>,
131}
132
133#[derive(Clone, Debug, Serialize, Deserialize)]
136#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
137pub struct ForkPut {
138 pub v: u32,
139 pub fork_id: String,
140 pub table: String,
141 pub partition_id: u32,
142 pub offset: u64,
143 #[serde(default)]
144 pub projection_id: String,
145 #[serde(default)]
146 pub projection_version: u32,
147 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
148 pub fields: BTreeMap<String, String>,
149 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
150 pub metadata: BTreeMap<String, String>,
151 #[cfg_attr(
152 feature = "schemars",
153 schemars(schema_with = "crate::encoding::opt_bytes_schema")
154 )]
155 #[serde(
156 default,
157 skip_serializing_if = "Option::is_none",
158 with = "crate::encoding::opt_bin_bytes"
159 )]
160 pub payload: Option<Vec<u8>>,
161 #[serde(default, skip_serializing_if = "Option::is_none")]
162 pub embedding: Option<String>,
163 #[serde(default)]
164 pub tombstone: bool,
165}
166
167#[derive(Clone, Debug, Serialize, Deserialize)]
169#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
170#[non_exhaustive]
171pub enum ForkReply {
172 Ok(ForkOutcome),
173 Err(ForkError),
174}
175
176#[derive(Clone, Debug, Serialize, Deserialize)]
178#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
179#[non_exhaustive]
180pub enum ForkOutcome {
181 Created(ForkInfo),
182 Deleted(bool),
183 Promoted { rows: usize },
184 List(Vec<ForkInfo>),
185 Written,
186}
187
188#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, thiserror::Error)]
190#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
191#[non_exhaustive]
192pub enum ForkError {
193 #[error("forks not supported: {0}")]
194 Unsupported(String),
195 #[error("fork not found: {0}")]
196 NotFound(String),
197 #[error("invalid fork: {0}")]
198 InvalidFork(String),
199 #[error("fork conflict: {0}")]
200 Conflict(String),
201 #[error("fork backend error: {0}")]
202 Backend(String),
203 #[error("temporarily unavailable: {0}")]
208 Unavailable(String),
209 #[error("unsupported fork op version (expected {expected}, got {got})")]
210 Version { expected: u32, got: u32 },
211 #[error("not the partition leader for this fork")]
213 NotLeader,
214}
215
216pub fn validate_fork_id(fork_id: &str) -> Result<(), InvalidError> {
227 let Some((stream, local)) = crate::authz::split_scoped_resource(fork_id) else {
228 return crate::validate::validate_safelisted_name("fork id", fork_id, MAX_FORK_ID_BYTES);
229 };
230 if fork_id.len() > MAX_FORK_ID_BYTES {
231 return Err(InvalidError::new(format!(
232 "fork id is {}B, exceeds cap {MAX_FORK_ID_BYTES}B",
233 fork_id.len()
234 )));
235 }
236 crate::validate::validate_safelisted_name("fork id stream", stream, MAX_FORK_ID_BYTES)?;
237 crate::validate::validate_safelisted_name("fork id", local, MAX_FORK_ID_BYTES)
238}
239
240#[cfg(all(test, feature = "cbor"))]
241mod tests {
242 use super::*;
243 use crate::codes::FORK_OP_VERSION;
244 use crate::framing::{decode_named, encode_named};
245
246 #[test]
247 fn given_fork_ids_when_validated_then_should_enforce_charset_and_length() {
248 assert!(validate_fork_id("experiment-2026-q2").is_ok());
249 assert!(validate_fork_id("run_7.v2").is_ok());
250 assert!(validate_fork_id("").is_err(), "empty");
251 assert!(validate_fork_id("bad id").is_err(), "space");
252 assert!(
253 validate_fork_id("o'brien; drop table").is_err(),
254 "sql metachars rejected"
255 );
256 assert!(
257 validate_fork_id("name/../etc").is_err(),
258 "slash and dot-dot"
259 );
260 assert!(validate_fork_id(&"f".repeat(MAX_FORK_ID_BYTES)).is_ok());
261 assert!(validate_fork_id(&"f".repeat(MAX_FORK_ID_BYTES + 1)).is_err());
262 }
263
264 #[test]
265 fn given_stream_scoped_fork_ids_when_validated_then_should_safelist_both_parts() {
266 assert!(validate_fork_id("stream:acme/experiment-2026-q2").is_ok());
267 assert!(
268 validate_fork_id("stream:acme/a/b").is_err(),
269 "slash in the local part"
270 );
271 assert!(
272 validate_fork_id("stream:ac me/run").is_err(),
273 "space in the stream"
274 );
275 assert!(
276 validate_fork_id("stream:acme/").is_err(),
277 "empty local part"
278 );
279 assert!(
280 validate_fork_id("stream:acme").is_err(),
281 "the stream resource itself"
282 );
283 let local = "f".repeat(MAX_FORK_ID_BYTES - "stream:acme/".len());
284 assert!(validate_fork_id(&format!("stream:acme/{local}")).is_ok());
285 assert!(validate_fork_id(&format!("stream:acme/{local}f")).is_err());
286 }
287
288 #[test]
289 fn given_fork_create_when_round_tripped_then_should_preserve_kind() {
290 let request = ForkCreate {
291 v: FORK_OP_VERSION,
292 fork_id: "agent-run-7".to_owned(),
293 parent: None,
294 kind: ForkKind::Severed,
295 tables: vec!["readings".to_owned()],
296 points: None,
297 };
298 let bytes = encode_named(&request).expect("serializes");
299 let back: ForkCreate = decode_named(&bytes).expect("deserializes");
300 assert_eq!(back.fork_id, "agent-run-7");
301 assert_eq!(back.kind, ForkKind::Severed);
302 assert_eq!(back.points, None);
303 }
304
305 #[test]
306 fn given_fork_create_with_points_when_round_tripped_then_should_preserve_them() {
307 let points = vec![
308 ForkPoint {
309 table: "readings".to_owned(),
310 partition_id: 2,
311 offset: 41,
312 source_incarnation: Some(1_700_000_000_000_000),
313 },
314 ForkPoint {
315 table: "readings".to_owned(),
316 partition_id: 3,
317 offset: 7,
318 source_incarnation: None,
319 },
320 ];
321 let request = ForkCreate {
322 v: FORK_OP_VERSION,
323 fork_id: "agent-run-8".to_owned(),
324 parent: None,
325 kind: ForkKind::Severed,
326 tables: Vec::new(),
327 points: Some(points.clone()),
328 };
329 let bytes = encode_named(&request).expect("serializes");
330 let back: ForkCreate = decode_named(&bytes).expect("deserializes");
331 assert_eq!(back.points, Some(points));
332 }
333
334 #[test]
335 fn given_fork_reply_created_when_round_tripped_then_should_preserve_info() {
336 let reply = ForkReply::Ok(ForkOutcome::Created(ForkInfo {
337 fork_id: "f1".to_owned(),
338 parent: None,
339 kind: ForkKind::Continuous,
340 user_id: 5,
341 status: ForkStatus::Open,
342 created_at_micros: 1,
343 row_count: 0,
344 }));
345 let bytes = encode_named(&reply).expect("serializes");
346 let back: ForkReply = decode_named(&bytes).expect("deserializes");
347 let ForkReply::Ok(ForkOutcome::Created(info)) = back else {
348 panic!("expected Created");
349 };
350 assert_eq!(info.user_id, 5);
351 assert_eq!(info.kind, ForkKind::Continuous);
352 }
353
354 #[test]
355 fn given_fork_kind_when_serialized_then_should_be_snake_case() {
356 assert_eq!(
358 serde_json::to_string(&ForkKind::Severed).expect("serializes"),
359 "\"severed\""
360 );
361 assert_eq!(
362 serde_json::to_string(&ForkKind::Continuous).expect("serializes"),
363 "\"continuous\""
364 );
365 }
366}