flint_store/lib.rs
1//! The object store behind a trait — L2 step 4 (design review A13,
2//! with A6's conditional-publish contract baked into the signatures).
3//!
4//! Only generation ASSEMBLY is backend-specific; everything above this
5//! trait (interval log, flush pipeline, eviction, hydration, epoch
6//! state machine) is backend-neutral. Backends:
7//!
8//! - `memory` — the in-process test double, implementing the FULL
9//! conditional semantics (412/409, stamps, CRC validation, MPU
10//! state, epoch CAS). Every backend-neutral tier test runs here.
11//! - `s3` — MPU + UploadPartCopy + conditional PUT/Complete per A6/A8.
12//! - Azure Blob (second, per A13): Put Block List with committed-block
13//! reuse and NATIVE leases for the epoch. GCS later.
14//!
15//! Contract points the signatures enforce:
16//!
17//! - **No unconditional publish exists.** Every write carries either
18//! `IfMatch` (update of a known generation) or `IfNoneMatchAny`
19//! (first generation of a new key). A caller that wants an unguarded
20//! overwrite has made a design error upstream (A6).
21//! - **The multipart ETag is NOT a content hash** and never appears in
22//! any integrity role; content identity is the full-object
23//! CRC-64/NVME, computed by the flusher from LOCAL truth and
24//! validated server-side at publish (a mismatch fails the publish,
25//! it does not warn).
26//! - **Assembly failure aborts the assembly** (A9): no backend may
27//! leave a partial MPU behind on an error path it can reach.
28//!
29//! Extracted from `spdk-csi-driver/src/tier/store/` (2026-08-25) so
30//! flint-lean can depend on the store WITHOUT the hub crate's build
31//! (13 binaries, the aws/kube/nfs dep trees). The hub crate re-exports
32//! this crate at its old path (`crate::tier::store::*`), so every
33//! existing import keeps working. The `s3` backend is feature-gated —
34//! test loops that only need the memory double never build the AWS
35//! SDK.
36
37pub mod counters;
38pub mod gate;
39
40pub use counters::{RequestCounter, RequestCounts, RequestKind};
41pub mod layout;
42pub mod memory;
43pub mod probe;
44pub mod readonly;
45
46pub use readonly::ReadOnly;
47#[cfg(feature = "s3")]
48pub mod s3;
49#[cfg(feature = "s3")]
50pub mod rawread;
51
52use async_trait::async_trait;
53use bytes::Bytes;
54use std::collections::HashMap;
55
56// ── CRC-64/NVME ──────────────────────────────────────────────────────
57//
58// The tier's one content-identity algorithm (A6): linearly combinable
59// (so S3 can compute it FULL_OBJECT across multipart, copied parts
60// included) and supported end-to-end by both S3 and the local flusher.
61// Hand-rolled table CRC — 30 lines beats a dependency; the test pins
62// the catalog check value.
63
64/// Reflected form of the CRC-64/NVME polynomial 0xAD93D23594C935A9.
65const CRC64_NVME_POLY: u64 = 0x9A6C_9329_AC4B_C9B5;
66
67/// Slice-by-8: eight tables, so `update` consumes a u64 word per round
68/// instead of a byte. Table 0 is the classic byte table; table k is
69/// table k-1 advanced one more zero byte. Same polynomial, same digest
70/// — the catalog check value and the split-update property both pin it.
71///
72/// This is the checkout resume path's inner loop: a restarted container
73/// re-CRCs every present file before it can serve, so the byte-at-a-time
74/// form put a full tree re-hash on the agent-blocking path.
75fn crc64_tables8() -> &'static [[u64; 256]; 8] {
76 static TABLES: std::sync::OnceLock<[[u64; 256]; 8]> = std::sync::OnceLock::new();
77 TABLES.get_or_init(|| {
78 let mut t = [[0u64; 256]; 8];
79 t[0] = *crc64_table();
80 let mut i = 0usize;
81 while i < 256 {
82 let mut k = 1usize;
83 while k < 8 {
84 let prev = t[k - 1][i];
85 t[k][i] = (prev >> 8) ^ t[0][(prev & 0xFF) as usize];
86 k += 1;
87 }
88 i += 1;
89 }
90 t
91 })
92}
93
94fn crc64_table() -> &'static [u64; 256] {
95 static TABLE: std::sync::OnceLock<[u64; 256]> = std::sync::OnceLock::new();
96 TABLE.get_or_init(|| {
97 let mut t = [0u64; 256];
98 let mut i = 0usize;
99 while i < 256 {
100 let mut crc = i as u64;
101 let mut b = 0;
102 while b < 8 {
103 crc = if crc & 1 == 1 { (crc >> 1) ^ CRC64_NVME_POLY } else { crc >> 1 };
104 b += 1;
105 }
106 t[i] = crc;
107 i += 1;
108 }
109 t
110 })
111}
112
113/// Streaming CRC-64/NVME (the flusher feeds file ranges through this).
114#[derive(Clone)]
115pub struct Crc64Nvme(u64);
116
117impl Default for Crc64Nvme {
118 fn default() -> Self {
119 Self::new()
120 }
121}
122
123impl Crc64Nvme {
124 pub fn new() -> Self {
125 Crc64Nvme(u64::MAX)
126 }
127 pub fn update(&mut self, data: &[u8]) {
128 let t = crc64_tables8();
129 let mut crc = self.0;
130 let mut rest = data;
131 // Eight bytes per round off the aligned body...
132 while let Some((head, tail)) = rest.split_first_chunk::<8>() {
133 let w = u64::from_le_bytes(*head) ^ crc;
134 crc = t[7][(w & 0xFF) as usize]
135 ^ t[6][((w >> 8) & 0xFF) as usize]
136 ^ t[5][((w >> 16) & 0xFF) as usize]
137 ^ t[4][((w >> 24) & 0xFF) as usize]
138 ^ t[3][((w >> 32) & 0xFF) as usize]
139 ^ t[2][((w >> 40) & 0xFF) as usize]
140 ^ t[1][((w >> 48) & 0xFF) as usize]
141 ^ t[0][((w >> 56) & 0xFF) as usize];
142 rest = tail;
143 }
144 // ...then the <8-byte tail, byte-at-a-time as before. `update`
145 // is a STREAMING call: the tail runs per chunk, so an arbitrary
146 // split must give the same digest as one pass. The test pins it.
147 for &b in rest {
148 crc = t[0][((crc ^ b as u64) & 0xFF) as usize] ^ (crc >> 8);
149 }
150 self.0 = crc;
151 }
152 pub fn finalize(self) -> u64 {
153 self.0 ^ u64::MAX
154 }
155}
156
157/// One column of the GF(2) operator applied to a register.
158fn gf2_times(mat: &[u64; 64], mut v: u64) -> u64 {
159 let mut sum = 0u64;
160 let mut i = 0usize;
161 while v != 0 {
162 if v & 1 == 1 {
163 sum ^= mat[i];
164 }
165 v >>= 1;
166 i += 1;
167 }
168 sum
169}
170
171/// `out` becomes the operator that applies `mat` twice.
172fn gf2_square(out: &mut [u64; 64], mat: &[u64; 64]) {
173 for n in 0..64 {
174 out[n] = gf2_times(mat, mat[n]);
175 }
176}
177
178/// CRC-64/NVME of `A || B`, from the CRCs of `A` and `B` and the LENGTH
179/// of `B`. Bytes are never re-read.
180///
181/// This exists so a full-object checksum can be assembled from parts
182/// computed INDEPENDENTLY — and therefore concurrently. Without it a
183/// caller that wants the store to compute the checksum has to hand it
184/// the parts in order, one at a time, because a CRC taken out of order
185/// is a different number; the alternative was a whole extra pass over
186/// the file before the upload. Now it is neither.
187///
188/// The identity it rests on: for a reflected CRC whose init and xorout
189/// are both all-ones, appending `n` zero bytes is a LINEAR operator `Z`
190/// on the register, and `F(A||B) = Z_n(F(A)) ^ F(B)` — the init and
191/// xorout terms cancel because `Z(X) ^ Z(I) = Z(X ^ I) = Z(0) = 0`.
192/// Structure follows zlib's `crc32_combine`, widened to 64 bits.
193pub fn crc64_combine(crc_a: u64, crc_b: u64, len_b: u64) -> u64 {
194 if len_b == 0 {
195 return crc_a;
196 }
197 let mut odd = [0u64; 64];
198 let mut even = [0u64; 64];
199 // One zero BIT.
200 odd[0] = CRC64_NVME_POLY;
201 let mut row = 1u64;
202 for n in 1..64 {
203 odd[n] = row;
204 row <<= 1;
205 }
206 gf2_square(&mut even, &odd); // two bits
207 gf2_square(&mut odd, &even); // four bits
208 let mut crc = crc_a;
209 let mut len = len_b;
210 loop {
211 gf2_square(&mut even, &odd); // eight bits == one zero BYTE
212 if len & 1 == 1 {
213 crc = gf2_times(&even, crc);
214 }
215 len >>= 1;
216 if len == 0 {
217 break;
218 }
219 gf2_square(&mut odd, &even);
220 if len & 1 == 1 {
221 crc = gf2_times(&odd, crc);
222 }
223 len >>= 1;
224 if len == 0 {
225 break;
226 }
227 }
228 crc ^ crc_b
229}
230
231/// One-shot convenience.
232pub fn crc64_nvme(data: &[u8]) -> u64 {
233 let mut c = Crc64Nvme::new();
234 c.update(data);
235 c.finalize()
236}
237
238/// The inverse of [`crc64_to_b64`]. `None` for anything that is not a
239/// 12-character base64 encoding of exactly 8 bytes — a caller that gets
240/// `None` has been handed something other than a CRC-64, and guessing a
241/// number for it would validate a publish against a checksum nobody
242/// computed.
243pub fn crc64_from_b64(s: &str) -> Option<u64> {
244 const AL: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
245 let s = s.trim();
246 if s.len() != 12 || !s.ends_with('=') {
247 return None;
248 }
249 let mut acc: u32 = 0;
250 let mut bits = 0u32;
251 let mut out: Vec<u8> = Vec::with_capacity(8);
252 for c in s.bytes() {
253 if c == b'=' {
254 break;
255 }
256 let v = AL.iter().position(|&a| a == c)? as u32;
257 acc = (acc << 6) | v;
258 bits += 6;
259 if bits >= 8 {
260 bits -= 8;
261 out.push((acc >> bits) as u8);
262 }
263 }
264 if out.len() != 8 {
265 return None;
266 }
267 let mut b = [0u8; 8];
268 b.copy_from_slice(&out);
269 Some(u64::from_be_bytes(b))
270}
271
272/// S3's wire form: base64 of the checksum's 8 big-endian bytes.
273pub fn crc64_to_b64(crc: u64) -> String {
274 const AL: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
275 let bytes = crc.to_be_bytes();
276 let mut out = String::with_capacity(12);
277 for chunk in bytes.chunks(3) {
278 let b = [chunk[0], *chunk.get(1).unwrap_or(&0), *chunk.get(2).unwrap_or(&0)];
279 let n = u32::from_be_bytes([0, b[0], b[1], b[2]]);
280 out.push(AL[(n >> 18) as usize & 63] as char);
281 out.push(AL[(n >> 12) as usize & 63] as char);
282 out.push(if chunk.len() > 1 { AL[(n >> 6) as usize & 63] as char } else { '=' });
283 out.push(if chunk.len() > 2 { AL[n as usize & 63] as char } else { '=' });
284 }
285 out
286}
287
288// ── stamps and metadata ──────────────────────────────────────────────
289
290/// The A6 publish stamps (`x-amz-meta-flint-*` on S3; each backend maps
291/// the bare keys to its metadata namespace). HEAD-based 412 arbitration
292/// keys off these — they are how a torn OWN flush is told apart from a
293/// genuinely foreign object.
294#[derive(Debug, Clone, PartialEq, Eq)]
295pub struct GenerationStamps {
296 /// (`gen` is reserved in edition 2024 — spelled out.)
297 pub generation: u64,
298 pub epoch: u64,
299 pub flush_uuid: String,
300 /// The coherence provenance of a lean manifest citation
301 /// (boundary-verbs plan §2.4.1): `sentinel`, `quiescence`,
302 /// `forced-lag-cap`, `forced-backlog-cap`, `cadence`, `drain`,
303 /// `recovered`. Stamped on the OBJECT so a downstream consumer —
304 /// checkout, a sibling cluster's sync, HITL — can tell a
305 /// declared-coherent citation from a forced possibly-torn one from
306 /// the bucket alone, for the price of a HEAD rather than a GET of a
307 /// manifest that can run to hundreds of MiB. `None` on every
308 /// non-manifest object.
309 pub boundary_source: Option<String>,
310 /// A12: POSIX metadata riding on the object, so a bucket reader —
311 /// and the DR import — can restore mode/ownership/mtime without
312 /// the manifest. OPTIONAL both ways: absence never makes an object
313 /// foreign (steps 4–11 published without it).
314 pub posix: Option<PosixStamps>,
315}
316
317/// The A12 per-object POSIX stamps (`flint-mode` is octal; times are
318/// unix seconds). Enumerated NON-goals of the round-trip: hard-link
319/// structure, sockets/FIFOs/devices, and sparseness — see
320/// `tier::manifest`.
321#[derive(Debug, Clone, Copy, PartialEq, Eq)]
322pub struct PosixStamps {
323 /// Full st_mode (type bits included; restore applies the 07777).
324 pub mode: u32,
325 pub uid: u32,
326 pub gid: u32,
327 pub mtime_unix: i64,
328}
329
330impl PosixStamps {
331 pub const META_MODE: &'static str = "flint-mode";
332 pub const META_UID: &'static str = "flint-uid";
333 pub const META_GID: &'static str = "flint-gid";
334 pub const META_MTIME: &'static str = "flint-mtime";
335
336 #[cfg(unix)]
337 pub fn from_metadata(m: &std::fs::Metadata) -> PosixStamps {
338 use std::os::unix::fs::MetadataExt;
339 PosixStamps { mode: m.mode(), uid: m.uid(), gid: m.gid(), mtime_unix: m.mtime() }
340 }
341
342 fn to_meta(self) -> Vec<(String, String)> {
343 vec![
344 (Self::META_MODE.into(), format!("{:o}", self.mode)),
345 (Self::META_UID.into(), self.uid.to_string()),
346 (Self::META_GID.into(), self.gid.to_string()),
347 (Self::META_MTIME.into(), self.mtime_unix.to_string()),
348 ]
349 }
350
351 /// Lenient: any stamp absent/malformed ⇒ None as a set (never a
352 /// foreignness signal).
353 pub fn from_meta(meta: &HashMap<String, String>) -> Option<PosixStamps> {
354 Some(PosixStamps {
355 mode: u32::from_str_radix(meta.get(Self::META_MODE)?, 8).ok()?,
356 uid: meta.get(Self::META_UID)?.parse().ok()?,
357 gid: meta.get(Self::META_GID)?.parse().ok()?,
358 mtime_unix: meta.get(Self::META_MTIME)?.parse().ok()?,
359 })
360 }
361}
362
363impl GenerationStamps {
364 pub const META_GEN: &'static str = "flint-gen";
365 pub const META_EPOCH: &'static str = "flint-epoch";
366 pub const META_FLUSH_UUID: &'static str = "flint-flush-uuid";
367 pub const META_BOUNDARY_SOURCE: &'static str = "flint-boundary-source";
368
369 pub fn to_meta(&self) -> Vec<(String, String)> {
370 let mut v = vec![
371 (Self::META_GEN.into(), self.generation.to_string()),
372 (Self::META_EPOCH.into(), self.epoch.to_string()),
373 (Self::META_FLUSH_UUID.into(), self.flush_uuid.clone()),
374 ];
375 if let Some(b) = &self.boundary_source {
376 v.push((Self::META_BOUNDARY_SOURCE.into(), b.clone()));
377 }
378 if let Some(p) = self.posix {
379 v.extend(p.to_meta());
380 }
381 v
382 }
383
384 /// Parse stamps back out of object metadata; None if any IDENTITY
385 /// stamp is absent or malformed (an unstamped object is by
386 /// definition foreign). The posix set parses leniently.
387 pub fn from_meta(meta: &HashMap<String, String>) -> Option<GenerationStamps> {
388 Some(GenerationStamps {
389 generation: meta.get(Self::META_GEN)?.parse().ok()?,
390 epoch: meta.get(Self::META_EPOCH)?.parse().ok()?,
391 flush_uuid: meta.get(Self::META_FLUSH_UUID)?.clone(),
392 boundary_source: meta.get(Self::META_BOUNDARY_SOURCE).cloned(),
393 posix: PosixStamps::from_meta(meta),
394 })
395 }
396}
397
398/// One version of one key (boundary-verbs plan D8's reclamation and DR
399/// surfacing).
400#[derive(Debug, Clone, PartialEq, Eq)]
401pub struct ListedVersion {
402 pub key: String,
403 pub version_id: String,
404 pub etag: String,
405 pub size: u64,
406 pub is_current: bool,
407 /// A delete marker carries no bytes; it makes the key read absent
408 /// while every prior version stays fetchable by id.
409 pub is_delete_marker: bool,
410 pub last_modified_unix: Option<u64>,
411}
412
413/// What HEAD/GET/publish return about an object.
414#[derive(Debug, Clone, PartialEq, Eq)]
415pub struct ObjectMeta {
416 pub etag: String,
417 pub size: u64,
418 /// Full-object CRC-64/NVME in wire (base64) form, when the store
419 /// has one (objects written by this tier always do).
420 pub crc64_b64: Option<String>,
421 /// User metadata with backend prefixes stripped (bare keys, e.g.
422 /// `flint-gen`).
423 pub meta: HashMap<String, String>,
424 pub last_modified_unix: Option<u64>,
425 /// Backend storage class (S3: None ≡ STANDARD). The A11 IA
426 /// copy-source guard reads this: a non-Standard base pays
427 /// retrieval on every CLEAN byte copied, silently inverting the
428 /// tier's saving — the flusher refuses BaseCopy from it.
429 pub storage_class: Option<String>,
430 /// The object VERSION this metadata describes, on a versioned
431 /// bucket (boundary-verbs plan D7). S3 already returns
432 /// `x-amz-version-id` on PUT and this crate used to discard it;
433 /// gated citation needs it and therefore costs no extra request.
434 ///
435 /// `None` means the backend returned no version id — an
436 /// unversioned bucket, or a proxy that STRIPS the header. The
437 /// second case is why gated mode probes for it and REFUSES rather
438 /// than degrading: falling back to etag semantics on a key whose
439 /// current version is uncited is precisely the torn view the mode
440 /// exists to prevent.
441 pub version_id: Option<String>,
442}
443
444impl ObjectMeta {
445 /// May this object serve as a server-side copy source without
446 /// per-byte retrieval charges? (A11's IA copy-source guard.)
447 pub fn copy_source_allowed(&self) -> bool {
448 matches!(self.storage_class.as_deref(), None | Some("STANDARD"))
449 }
450}
451
452#[derive(Debug, Clone, PartialEq, Eq)]
453pub struct ListedObject {
454 pub key: String,
455 pub size: u64,
456 pub etag: String,
457 pub last_modified_unix: Option<u64>,
458}
459
460/// An in-progress multipart assembly (A9's hygiene surface).
461#[derive(Debug, Clone, PartialEq, Eq)]
462pub struct PendingUpload {
463 pub key: String,
464 pub upload_id: String,
465 pub initiated_unix: Option<u64>,
466}
467
468// ── publish conditions ───────────────────────────────────────────────
469
470/// A6: every publish is conditional. There is deliberately NO
471/// unconditional variant — a caller wanting one has an upstream design
472/// error.
473#[derive(Debug, Clone, PartialEq, Eq)]
474pub enum PutCondition {
475 /// Publish generation g+1 only if the object is still generation
476 /// g's bytes (its ETag). The 412 this produces is an internal
477 /// fencing event — see `tier::arbitrate`.
478 IfMatch(String),
479 /// First generation of a new key: fail if ANY object exists
480 /// (closes the create race with outside writers).
481 IfNoneMatchAny,
482 /// No precondition: create, or overwrite whatever is there.
483 ///
484 /// Deliberately narrow. It exists for CONTENT-ADDRESSED objects,
485 /// where the rewrite is byte-identical and the POINT is to refresh
486 /// the object's age rather than to change its contents: an adopted
487 /// manifest chunk is an old object that a new publish is about to
488 /// make live, and a sweep that reads age would otherwise collect it
489 /// as the orphan it still looks like (flint-lean chunked-manifest
490 /// design §8.1, machine-checked by `LeanChunkGCAdoptSkips`).
491 ///
492 /// Never reach for this where a concurrent writer's content could
493 /// DIFFER from yours — that is what the other two variants are for,
494 /// and losing that distinction is how a last-writer-wins overwrite
495 /// gets reintroduced.
496 Unconditional,
497}
498
499// ── generation assembly ──────────────────────────────────────────────
500
501/// One part of a composed generation, in object order.
502#[derive(Debug, Clone, PartialEq, Eq)]
503pub enum PartSource {
504 /// Dirty range: bytes [offset, offset+len) read from the local
505 /// file and uploaded.
506 Local { offset: u64, len: u64 },
507 /// Clean range: server-side copy of [offset, offset+len) from the
508 /// base generation object at the SAME key, guarded by
509 /// copy-source-if-match on the base ETag (detects foreign bucket
510 /// overwrite; structurally cannot detect local staleness — that is
511 /// capture's job, finding C5).
512 BaseCopy { offset: u64, len: u64 },
513}
514
515/// The flusher's order for one generation publish.
516#[derive(Debug, Clone)]
517pub struct ComposeSpec<'a> {
518 pub key: &'a str,
519 /// Local source of `Local` parts. Clean ranges are byte-identical
520 /// local and remote by definition, so `crc64` is computable from
521 /// this file alone.
522 pub local_path: &'a std::path::Path,
523 /// Contiguous from offset 0, sizes within the backend's part
524 /// granularity (the A11 part-size grid upstream owns that).
525 pub parts: Vec<PartSource>,
526 /// Where the base generation LIVES, when it is not `key` — the A7
527 /// re-key flush publishes a renamed file under its new key while
528 /// clean ranges still copy from the old one. None = same as `key`.
529 pub base_key: Option<&'a str>,
530 /// Base generation's ETag — required iff any part is `BaseCopy`.
531 pub base_etag: Option<String>,
532 pub condition: PutCondition,
533 pub stamps: GenerationStamps,
534 /// Full-object CRC-64/NVME of the composed content, from local
535 /// truth. Backends hand it to the store for SERVER-SIDE validation
536 /// at publish: a mismatch fails the publish, never warns.
537 ///
538 /// `None` asks the store to accumulate it from the `Local` parts
539 /// as it reads them for upload. Parts go up in order, one at a
540 /// time, so a streaming CRC over them in that loop IS the CRC of
541 /// the object — the same local truth, without a second pass over
542 /// the file (a 40 GiB pack's pre-pass was ~70 s on forge's push
543 /// path, 2026-09-05). A `BaseCopy` part is never read locally, so
544 /// a spec with one and `None` is refused before any part moves.
545 pub crc64: Option<u64>,
546 /// Bytes landed so far, for a caller that has to prove LIVENESS
547 /// while a long compose runs: forge's lease renewer renews a push
548 /// only while this advances, so a wedged upload lets the token go
549 /// quiet and a challenger take over — which is the one takeover a
550 /// wedged holder can get. Advanced by `len` after every part,
551 /// `Local` and `BaseCopy` alike. `None` = nobody is watching.
552 pub progress: Option<std::sync::Arc<std::sync::atomic::AtomicU64>>,
553}
554
555impl ComposeSpec<'_> {
556 /// Record `bytes` more of the object as landed.
557 pub fn note_progress(&self, bytes: u64) {
558 if let Some(p) = &self.progress {
559 p.fetch_add(bytes, std::sync::atomic::Ordering::Relaxed);
560 }
561 }
562}
563
564// ── errors ───────────────────────────────────────────────────────────
565
566#[derive(Debug, thiserror::Error)]
567pub enum StoreError {
568 /// 412 — the guarded condition failed. Route to arbitration, never
569 /// to an operator runbook (A6).
570 #[error("precondition failed (412): {0}")]
571 PreconditionFailed(String),
572 /// 409 — a concurrent conditional writer; retry-after-arbitrate.
573 #[error("conditional conflict (409): {0}")]
574 Conflict(String),
575 #[error("not found: {0}")]
576 NotFound(String),
577 /// The assembly was fenced (aborted) under us — A8's takeover
578 /// sweep produces exactly this at a deposed hub's Complete.
579 #[error("no such upload: {0}")]
580 NoSuchUpload(String),
581 /// Server-side content validation failed — the store computed a
582 /// different full-object checksum than local truth claims.
583 #[error("checksum mismatch: {0}")]
584 ChecksumMismatch(String),
585 /// 401/403, or an S3 code that means the same thing: the request
586 /// was well-formed and we are not allowed to make it.
587 ///
588 /// Split out of `Other` because the caller's response is different
589 /// in kind. A transient 5xx or a connection reset is "the store is
590 /// having a moment, keep trying"; this is "the credentials are
591 /// wrong, expired, or the policy changed", and no amount of retrying
592 /// fixes it. It reached the epoch heartbeat as an ordinary renew
593 /// failure, so a rotated key produced a fence and an exit whose log
594 /// line talked about lease windows — pointing an operator at the
595 /// bucket, at contention, at anything but the credential that had
596 /// actually expired.
597 ///
598 /// `RequestTimeTooSkewed` belongs here too: S3 answers 403, and the
599 /// cause is the node's clock rather than the key, which is
600 /// diagnosable only if the error says so.
601 #[error("not authorized: {0}")]
602 Auth(String),
603 #[error("store: {0}")]
604 Other(String),
605}
606
607pub type StoreResult<T> = Result<T, StoreError>;
608
609// ── the epoch surface (A8; the step-7 state machine drives these) ────
610
611/// Observed epoch state (read side — takeover judgment input).
612#[derive(Debug, Clone, PartialEq, Eq)]
613pub struct EpochState {
614 pub holder_id: String,
615 pub epoch: u64,
616 /// Backend token guarding the next transition (S3: the epoch
617 /// object's ETag; Azure: the lease id).
618 pub token: String,
619 /// The store's own clock for the last renewal (S3 Last-Modified) —
620 /// A8: takeover is judged against the STORE's clock, not ours.
621 pub last_renew_unix: Option<u64>,
622 /// An opaque observed-state echo the holder wrote with its last
623 /// heartbeat, if any ([`LeaseEcho`]). Read-only to everyone but the
624 /// holder: it is the ONE fleet-visible surface that reports what a
625 /// syncer is actually *doing* rather than what its spec asked for,
626 /// and it costs nothing — the heartbeat CAS was already happening.
627 /// `None` = the holder wrote none (an older binary, a clean
628 /// release, or a backend that cannot carry it).
629 pub echo: Option<String>,
630 /// The holder shut down cleanly and will never publish under this
631 /// epoch again — a successor supersedes immediately instead of
632 /// waiting out the lease. Written by [`ObjectStore::epoch_release`].
633 pub released: bool,
634 /// The FIFO of holders waiting for the cell (lean's per-barrier
635 /// lease, design 2026-09-13 §4.2). A claimant that finds the cell
636 /// held, or released-and-handed to someone else, appends itself
637 /// ONCE ([`ObjectStore::epoch_enqueue`]); the holder's handoff pops
638 /// the head into `handoff`. Empty on every cell written by a holder
639 /// that never queues (the tier hub), which degrades to today's
640 /// behaviour and never to a second holder.
641 pub waiters: Vec<String>,
642 /// Who a RELEASED cell is reserved for: the queue head at the time
643 /// of the handoff. Only that holder may acquire it — or anyone,
644 /// once it has been quiet long enough to be judged dead. `None` =
645 /// first come, first served.
646 pub handoff: Option<String>,
647}
648
649/// A held lease (write side).
650#[derive(Debug, Clone, PartialEq, Eq)]
651pub struct EpochLease {
652 pub holder_id: String,
653 pub epoch: u64,
654 pub token: String,
655 /// The queue as the holder last saw it. A renew rewrites the whole
656 /// body, so it must carry the waiters forward or a heartbeat would
657 /// erase the queue; a 412 on renew re-reads the cell and adopts
658 /// whatever the waiters appended meanwhile.
659 pub waiters: Vec<String>,
660}
661
662/// What a live lean syncer echoes into its lease-heartbeat cell
663/// (boundary-verbs plan §2.6). The schema lives here, beside the cell
664/// that carries it, because the WRITER (the syncer) and the READER
665/// (the operator) are in different crates and a duplicated mirror
666/// struct on either side would drift silently — which is the failure
667/// this field exists to detect, not to reproduce.
668///
669/// It answers a question no spec field can: which binary, at which
670/// protocol, is actually serving that workspace. An old syncer reads a
671/// FIXED env list, so a knob it predates is ignored in silence, and the
672/// echo is the only place an operator can see that.
673#[derive(Debug, Clone, PartialEq, Eq, Default, serde::Serialize, serde::Deserialize)]
674pub struct LeaseEcho {
675 /// The syncer binary's own version — the mixed-fleet tell.
676 #[serde(default)]
677 pub syncer_version: String,
678 /// `.flint/capabilities.json`'s protocol number.
679 #[serde(default)]
680 pub protocol: u32,
681 /// The last citation this syncer installed.
682 #[serde(default)]
683 pub last_cited_seq: u64,
684 #[serde(default)]
685 pub last_cited_unix: u64,
686 /// Whether the boundary verbs are live in this workspace. The
687 /// pre-flight that turns them off (an app already owns `.flint/`)
688 /// runs INSIDE the pod against the agent's own tree, so this is the
689 /// only surface on which an operator can see the answer.
690 #[serde(default)]
691 pub sentinel_verbs_active: bool,
692 /// `None` = exposition not enabled. `Some(false)` = enabled and the
693 /// port was TAKEN — the workspace is fully operable and nothing is
694 /// scraping it, which is a degradation only this field can report.
695 #[serde(default, skip_serializing_if = "Option::is_none")]
696 pub metrics_bound: Option<bool>,
697}
698
699// ── the trait ────────────────────────────────────────────────────────
700
701#[async_trait]
702pub trait ObjectStore: Send + Sync {
703 /// Whole-object publish (below the multipart threshold).
704 /// `crc64` is validated server-side; stamps ride as metadata.
705 async fn put_whole(
706 &self,
707 key: &str,
708 body: Bytes,
709 condition: &PutCondition,
710 stamps: &GenerationStamps,
711 crc64: u64,
712 ) -> StoreResult<ObjectMeta>;
713
714 /// Assemble and publish one generation from local dirty bytes plus
715 /// server-side clean copies. MUST abort its partial assembly on
716 /// every failure path (A9) — an error return means nothing is left
717 /// pending under the key by this call.
718 /// Server-side copy of a WHOLE object to a DIFFERENT key.
719 ///
720 /// Exists because a key IS a path in every layout this crate serves,
721 /// so moving a file moves bytes. Without it a rename is a download
722 /// and a re-upload, and `PartSource::BaseCopy` cannot stand in: it
723 /// copies ranges from the SAME key by construction, so a destination
724 /// that has no generation of its own has nothing to copy from.
725 ///
726 /// Two rules the implementations must agree on, and the memory
727 /// double must model or it will pass a test the real store fails:
728 ///
729 /// - the destination's full-object CRC **is** the source's. A copy
730 /// is byte-identical; a checksum that changed means the bytes did.
731 /// - the destination's **stamps are not** the source's. `generation`,
732 /// `epoch` and `flush_uuid` describe a publish, and inheriting them
733 /// files one object's history under another object's key — a
734 /// reader asking "which flush wrote this?" would be told about a
735 /// flush that wrote something else.
736 ///
737 /// `src_if_match` guards the SOURCE: copying an object that moved
738 /// since the caller read it copies something the caller never saw.
739 /// `condition` guards the DESTINATION, exactly as on `put_whole`.
740 async fn copy_object(
741 &self,
742 src_key: &str,
743 src_if_match: Option<&str>,
744 dst_key: &str,
745 condition: &PutCondition,
746 stamps: &GenerationStamps,
747 ) -> StoreResult<ObjectMeta>;
748
749 async fn compose_generation(&self, spec: &ComposeSpec<'_>) -> StoreResult<ObjectMeta>;
750
751 async fn head(&self, key: &str) -> StoreResult<ObjectMeta>;
752
753 /// Whole-object read, optionally guarded (hydration always guards:
754 /// a 412 here is S3-WINS — the foreign-overwrite posture, opposite
755 /// of the publish path).
756 async fn get_whole(&self, key: &str, if_match: Option<&str>) -> StoreResult<(ObjectMeta, Bytes)>;
757
758 /// Ranged read (step 11's streaming restore — a multi-GiB
759 /// hydration must never buffer the whole object). ALWAYS guarded:
760 /// each chunk's If-Match pins the same object version end-to-end;
761 /// a 412 mid-restore is the S3-wins foreign-overwrite signal. The
762 /// caller never requests past the object's end.
763 async fn get_range(
764 &self,
765 key: &str,
766 offset: u64,
767 len: u64,
768 if_match: &str,
769 ) -> StoreResult<Bytes>;
770
771 /// The same ranged read, WITHOUT flattening the response into one
772 /// contiguous buffer.
773 ///
774 /// `get_range` ends in `AggregatedBytes::into_bytes`, which for any
775 /// multi-frame body — i.e. always — takes `SegmentedBuf`'s general
776 /// branch: `BytesMut::with_capacity(len); res.put(self.take(len))`.
777 /// That is one full-size allocation and one full-size copy per
778 /// range, on top of the frames the SDK is already holding. At a 16
779 /// MiB chunk the allocation goes through mmap and is returned on
780 /// free, so the next range faults in fresh zeroed pages: measured
781 /// on i4i.large as system time beating user time 6:1.
782 ///
783 /// The DEFAULT deliberately wraps `get_range`, so a store with
784 /// nothing to stream (the in-memory double) behaves exactly as it
785 /// did and no implementation is forced to care.
786 async fn get_range_segments(
787 &self,
788 key: &str,
789 offset: u64,
790 len: u64,
791 if_match: &str,
792 ) -> StoreResult<Vec<Bytes>> {
793 Ok(vec![self.get_range(key, offset, len, if_match).await?])
794 }
795
796 async fn list(&self, prefix: &str) -> StoreResult<Vec<ListedObject>>;
797
798 async fn delete(&self, key: &str) -> StoreResult<()>;
799
800 /// DELETE `key` only while its current ETag is `etag` (`If-Match`):
801 /// `PreconditionFailed` once the object has moved on, `NotFound`
802 /// when there is nothing to delete.
803 ///
804 /// This is the garbage collector's delete. A HEAD that recognizes an
805 /// etag followed by a plain DELETE leaves a window in which another
806 /// writer's guarded PUT replaces the object, and the DELETE then
807 /// removes bytes that writer's next commit cites. With one writer per
808 /// workspace nothing could land there; with several writers holding
809 /// the lease only for their commit sections, an upload can.
810 ///
811 /// The default REFUSES rather than falling back to [`delete`]: a
812 /// fallback would reopen exactly that window without a word, on
813 /// whichever backend happened not to override this.
814 ///
815 /// [`delete`]: ObjectStore::delete
816 async fn delete_if_match(&self, key: &str, etag: &str) -> StoreResult<()> {
817 let _ = (key, etag);
818 Err(StoreError::Other("this backend has no conditional DELETE".into()))
819 }
820
821 // ── version-scoped operations (boundary-verbs plan D7/D8) ────────
822 //
823 // On a versioned bucket an in-place PUT destroys nothing: the cited
824 // generation survives as a version, the manifest cites
825 // (key, version_id, etag), and readers resolve the cited version
826 // exactly. The version id ADDRESSES; the etag ATTESTS.
827 //
828 // Backends that cannot express these answer `Other` and the caller
829 // refuses gated mode — never degrades into it.
830
831 /// HEAD one specific version.
832 async fn head_version(&self, key: &str, version_id: &str) -> StoreResult<ObjectMeta> {
833 let _ = (key, version_id);
834 Err(StoreError::Other("this backend has no version-scoped HEAD".into()))
835 }
836
837 /// GET one specific version, when the backend keeps versions. Lean's
838 /// readers resolve citations by etag alone (version-pinned reads went
839 /// with gated mode, 2026-09-13); the method stays for tools and probes.
840 async fn get_version(&self, key: &str, version_id: &str) -> StoreResult<(ObjectMeta, Bytes)> {
841 let _ = (key, version_id);
842 Err(StoreError::Other("this backend has no version-scoped GET".into()))
843 }
844
845 /// DELETE one specific version — the exact reclamation flint's own
846 /// per-citation GC uses. Free, and the ONLY reaper that can tell
847 /// cited from uncited; lifecycle cannot, which is why the noncurrent
848 /// rule is a long backstop rather than the mechanism (D8).
849 async fn delete_version(&self, key: &str, version_id: &str) -> StoreResult<()> {
850 let _ = (key, version_id);
851 Err(StoreError::Other("this backend has no version-scoped DELETE".into()))
852 }
853
854 /// Every version under a prefix, current and noncurrent, oldest
855 /// first per key. The claim-time/DR fallback when `orphans.json` is
856 /// missing or stale — the expensive path, which is why the durable
857 /// summary is written eagerly.
858 async fn list_versions(&self, prefix: &str) -> StoreResult<Vec<ListedVersion>> {
859 let _ = prefix;
860 Err(StoreError::Other("this backend cannot list object versions".into()))
861 }
862
863 /// A time-limited URL that GETs `key` with no credential of the
864 /// caller's own.
865 ///
866 /// One consumer, and it is worth naming because it is what makes
867 /// the URL's lifetime a design constraint rather than a parameter:
868 /// flint forge advertises a clone BUNDLE this way, so that a
869 /// thousand agents cloning at once pull the bytes from the object
870 /// store instead of through one pod's NIC (forge design §8). The
871 /// URL is handed to a git client, which may hold it for the length
872 /// of a clone, and S3 caps a SigV4 presigned URL at seven days —
873 /// so the caller must re-sign on a schedule shorter than the TTL it
874 /// asked for, and this returns the URL rather than storing it
875 /// anywhere.
876 ///
877 /// Defaulted to a refusal: a backend that cannot presign must say
878 /// so, and the caller must fall back to serving the bytes itself
879 /// rather than advertising a URL that will not resolve.
880 async fn presign_get(&self, key: &str, ttl_secs: u64) -> StoreResult<String> {
881 let _ = (key, ttl_secs);
882 Err(StoreError::Other("this backend cannot presign a URL".into()))
883 }
884
885 /// A time-limited URL that PUTs `key` with no credential of the
886 /// caller's own.
887 ///
888 /// The counterpart of [`ObjectStore::presign_get`], and it exists
889 /// for the same consumer: flint forge's LFS batch API hands a git
890 /// client one of these so a multi-gigabyte checkpoint travels
891 /// straight to the object store and never crosses the repository
892 /// server's network interface.
893 ///
894 /// **The URL carries no content check.** Whoever holds it may put
895 /// anything at that key until it expires, so the caller must issue
896 /// it only for a key whose NAME already constrains the content —
897 /// a content-addressed one — and must verify after the fact.
898 async fn presign_put(&self, key: &str, ttl_secs: u64) -> StoreResult<String> {
899 let _ = (key, ttl_secs);
900 Err(StoreError::Other("this backend cannot presign a URL".into()))
901 }
902
903 /// Every lifecycle rule on the bucket, reduced to [`LifecycleView`].
904 ///
905 /// Defaulted to a refusal rather than to an empty list: "no rules"
906 /// and "I cannot see the rules" must never be the same answer here.
907 /// An empty list is a POSITIVE claim that nothing is reaping
908 /// noncurrent versions, and gated mode is accepted on the strength
909 /// of it (D8).
910 async fn lifecycle_rules(&self) -> StoreResult<Vec<LifecycleView>> {
911 Err(StoreError::Other("this backend cannot read lifecycle rules".into()))
912 }
913
914 /// Provision the noncurrent-version retention backstop on `prefix`
915 /// with read-merge-append, and report what is installed.
916 ///
917 /// `PutBucketLifecycleConfiguration` is FULL-REPLACE: an
918 /// implementation that writes its rule alone silently deletes the
919 /// MPU-abort rule and every rule the customer owns. Read, merge,
920 /// append — the discipline `bootstrap_lifecycle` already follows.
921 async fn ensure_noncurrent_retention(
922 &self,
923 prefix: &str,
924 days: u64,
925 ) -> StoreResult<RetentionOutcome> {
926 let _ = (prefix, days);
927 Err(StoreError::Other("this backend cannot write lifecycle rules".into()))
928 }
929
930 /// A9 hygiene: every in-progress assembly under the prefix.
931 async fn list_uploads(&self, prefix: &str) -> StoreResult<Vec<PendingUpload>>;
932
933 /// Abort one assembly. Aborting an already-absent upload is Ok —
934 /// the sweep and the abort-on-failure paths both race the
935 /// lifecycle rule.
936 async fn abort_upload(&self, key: &str, upload_id: &str) -> StoreResult<()>;
937
938 /// A9: verify/create the bucket posture (lifecycle abort rule,
939 /// versioning, encryption notes, IAM probe). Named prefix so
940 /// probes stay under the tier's namespace.
941 async fn bootstrap(&self, prefix: &str) -> StoreResult<BootstrapReport>;
942
943 // Epoch (A8). S3 implements CAS re-PUT on the epoch object; Azure
944 // will use native blob leases (strictly better — A13).
945
946 async fn epoch_read(&self, key: &str) -> StoreResult<Option<EpochState>>;
947
948 /// Claim: `supersede: None` creates (If-None-Match:*); `Some`
949 /// replaces the OBSERVED state via CAS on its token — the caller
950 /// (step 7) is responsible for having JUDGED that holder dead
951 /// against the store's clock. The new epoch is observed+1.
952 async fn epoch_acquire(
953 &self,
954 key: &str,
955 holder_id: &str,
956 supersede: Option<&EpochState>,
957 ) -> StoreResult<EpochLease>;
958
959 /// Heartbeat CAS. `PreconditionFailed` means deposed: self-fence.
960 ///
961 /// `echo` rides the same write (see [`EpochState::echo`]) — the
962 /// observed-state surface is deliberately a passenger on a request
963 /// the holder already pays for every ≤30 s. A caller with nothing
964 /// to report passes `None`, which CLEARS any previous echo rather
965 /// than preserving it: a stale echo read as live is exactly the
966 /// mixed-version hole the field exists to close.
967 async fn epoch_renew(
968 &self,
969 key: &str,
970 lease: &EpochLease,
971 echo: Option<&str>,
972 ) -> StoreResult<EpochLease>;
973
974 /// Mark the cell released: a clean handoff. The epoch NUMBER must
975 /// survive (deleting the cell would restart numbering at 1 and
976 /// break the monotonicity every publish stamp depends on), and the
977 /// write must be guarded on `lease`'s own token so a deposed
978 /// holder cannot mark a live successor's cell.
979 async fn epoch_release(&self, key: &str, lease: &EpochLease) -> StoreResult<()>;
980
981 /// Append `holder_id` to the cell's FIFO of waiters, by CAS on the
982 /// OBSERVED token, and return the cell as rewritten. A holder that
983 /// is already queued is not appended twice. The write moves the
984 /// token: a live holder's next renew/handoff 412s, re-reads, and
985 /// adopts the new token with the longer queue (lean `lease.rs`).
986 /// Default: unsupported — a backend without a queue serialises
987 /// claimants by the quiet-poll rule alone.
988 async fn epoch_enqueue(
989 &self,
990 key: &str,
991 observed: &EpochState,
992 holder_id: &str,
993 ) -> StoreResult<EpochState> {
994 let _ = (key, observed, holder_id);
995 Err(StoreError::Other("this store carries no lease queue".into()))
996 }
997
998 /// The per-BARRIER release (lean, design 2026-09-13 §4): mark the
999 /// cell released like [`ObjectStore::epoch_release`], but hand it to
1000 /// the queue head (`handoff = waiters[0]`, the rest stay queued) and
1001 /// KEEP `echo` — the cell is at rest between every barrier now, so
1002 /// the last holder's echo is the only thing that tells an operator
1003 /// which binary ran the last boundary. Guarded on the lease token
1004 /// like every other transition. Default: the plain release.
1005 async fn epoch_handoff(
1006 &self,
1007 key: &str,
1008 lease: &EpochLease,
1009 echo: Option<&str>,
1010 ) -> StoreResult<()> {
1011 let _ = echo;
1012 self.epoch_release(key, lease).await
1013 }
1014
1015 /// Backend part granularity for the A11 part-size grid.
1016 fn min_part_size(&self) -> u64;
1017 fn max_parts(&self) -> usize;
1018
1019 /// The store's upload bytes-in-flight gate ([`gate::ByteGate`]),
1020 /// when it was built with one. The store charges every local part
1021 /// of a compose to it; a caller that reads whole bodies ITSELF
1022 /// before `put_whole` (lean's `upload_one`) takes this so those
1023 /// bodies are charged to the SAME budget, and the bound is one
1024 /// number rather than two that must be set together. `None` = the
1025 /// upload path is bounded only by its counts.
1026 fn upload_gate(&self) -> Option<std::sync::Arc<gate::ByteGate>> {
1027 None
1028 }
1029
1030 /// Requests this store has sent since it was built, by kind
1031 /// (`counters.rs`). `None` = a store that does not count.
1032 fn request_counts(&self) -> Option<RequestCounts> {
1033 None
1034 }
1035}
1036
1037/// One lifecycle rule, reduced to what VERSION RETENTION cares about
1038/// (lean boundary-verbs plan D8).
1039///
1040/// Gated staging makes the CITED version noncurrent the moment a newer
1041/// generation stages, so a `NoncurrentVersionExpiration` rule covering
1042/// `<prefix>/files/` runs a clock against live cited data — and never
1043/// against the newest uncited bytes, which are current and which no
1044/// lifecycle rule can reach. That inversion is why the rules have to be
1045/// READABLE and not merely writable: a customer sitting at
1046/// noncurrent-days=1 arms the destroyer without touching flint at all.
1047#[derive(Debug, Clone, PartialEq, Eq)]
1048pub struct LifecycleView {
1049 pub id: String,
1050 pub enabled: bool,
1051 /// The rule's prefix filter; `""` = the whole bucket.
1052 pub prefix: String,
1053 /// `NoncurrentVersionExpiration.NoncurrentDays`, when the rule has
1054 /// one. `None` = this rule expires no noncurrent versions.
1055 pub noncurrent_days: Option<u64>,
1056 /// Whether the rule also expires orphaned delete markers.
1057 pub expired_delete_marker: bool,
1058}
1059
1060/// What [`ObjectStore::ensure_noncurrent_retention`] found or did.
1061#[derive(Debug, Clone, PartialEq, Eq)]
1062pub struct RetentionOutcome {
1063 pub rule_id: String,
1064 pub noncurrent_days: u64,
1065 /// False ⇒ a conforming rule was already installed and nothing was
1066 /// written (the read-merge-append path never runs blind).
1067 pub created: bool,
1068}
1069
1070/// What bootstrap found/did (A9). `errors` non-empty ⇒ the tier must
1071/// refuse to start; `warnings` are loud-degrade.
1072#[derive(Debug, Default, Clone)]
1073pub struct BootstrapReport {
1074 pub notes: Vec<String>,
1075 pub warnings: Vec<String>,
1076 pub errors: Vec<String>,
1077}
1078
1079impl BootstrapReport {
1080 pub fn ok(&self) -> bool {
1081 self.errors.is_empty()
1082 }
1083}
1084
1085#[cfg(test)]
1086mod tests {
1087 use super::*;
1088
1089 #[test]
1090 fn crc64_nvme_catalog_check_value() {
1091 // CRC-64/NVME check input from the reveng catalog.
1092 assert_eq!(crc64_nvme(b"123456789"), 0xAE8B_1486_0A79_9888);
1093 // Streaming across split updates must agree with one-shot.
1094 let mut c = Crc64Nvme::new();
1095 c.update(b"1234");
1096 c.update(b"56789");
1097 assert_eq!(c.finalize(), 0xAE8B_1486_0A79_9888);
1098 assert_eq!(crc64_nvme(b""), 0);
1099 }
1100
1101 #[test]
1102 fn crc64_slice_by_8_agrees_with_the_byte_at_a_time_form() {
1103 // `update` consumes 8-byte words with a byte-at-a-time tail, and
1104 // it is a STREAMING call — so the word/tail boundary can land
1105 // anywhere a caller happens to split. That makes split ALIGNMENT
1106 // load-bearing in a way the 4/5 split above never exercised:
1107 // every arbitrary split must give the one-shot digest.
1108 fn byte_at_a_time(data: &[u8]) -> u64 {
1109 let t = crc64_table();
1110 let mut crc = u64::MAX;
1111 for &b in data {
1112 crc = t[((crc ^ b as u64) & 0xFF) as usize] ^ (crc >> 8);
1113 }
1114 crc ^ u64::MAX
1115 }
1116 let data: Vec<u8> =
1117 (0..1000u32).map(|i| (i.wrapping_mul(2654435761) >> 13) as u8).collect();
1118
1119 // Every length across the word boundary, against the reference.
1120 for n in 0..40usize {
1121 assert_eq!(crc64_nvme(&data[..n]), byte_at_a_time(&data[..n]), "len {n}");
1122 }
1123 assert_eq!(crc64_nvme(&data), byte_at_a_time(&data));
1124
1125 // Every single split point of the full buffer.
1126 let want = crc64_nvme(&data);
1127 for cut in 0..data.len() {
1128 let mut c = Crc64Nvme::new();
1129 c.update(&data[..cut]);
1130 c.update(&data[cut..]);
1131 assert_eq!(c.finalize(), want, "split at {cut}");
1132 }
1133
1134 // A three-way split at two unaligned points.
1135 let mut c = Crc64Nvme::new();
1136 c.update(&data[..13]);
1137 c.update(&data[13..457]);
1138 c.update(&data[457..]);
1139 assert_eq!(c.finalize(), want);
1140 }
1141
1142 #[test]
1143 fn crc64_b64_is_8_bytes_big_endian_base64() {
1144 // 0xAE8B14860A799888 → bytes AE 8B 14 86 0A 79 98 88.
1145 assert_eq!(crc64_to_b64(0xAE8B_1486_0A79_9888), "rosUhgp5mIg=");
1146 assert_eq!(crc64_to_b64(0), "AAAAAAAAAAA=");
1147 }
1148
1149 #[test]
1150 fn stamps_roundtrip_and_reject_partial() {
1151 let s = GenerationStamps { generation: 7, epoch: 3, flush_uuid: "u-1".into(), boundary_source: None, posix: None };
1152 let m: HashMap<String, String> = s.to_meta().into_iter().collect();
1153 assert_eq!(GenerationStamps::from_meta(&m), Some(s));
1154 let mut partial = m.clone();
1155 partial.remove(GenerationStamps::META_FLUSH_UUID);
1156 assert_eq!(
1157 GenerationStamps::from_meta(&partial),
1158 None,
1159 "an unstamped/partially-stamped object is foreign by definition"
1160 );
1161 }
1162
1163 #[test]
1164 fn posix_stamps_roundtrip_and_stay_lenient() {
1165 let p = PosixStamps { mode: 0o100644, uid: 501, gid: 20, mtime_unix: 1_723_000_000 };
1166 let s = GenerationStamps {
1167 generation: 2,
1168 epoch: 1,
1169 flush_uuid: "u-2".into(),
1170 boundary_source: None,
1171 posix: Some(p),
1172 };
1173 let m: HashMap<String, String> = s.to_meta().into_iter().collect();
1174 assert_eq!(m.get(PosixStamps::META_MODE).map(String::as_str), Some("100644"));
1175 assert_eq!(GenerationStamps::from_meta(&m), Some(s));
1176 // A pre-step-12 object (identity stamps only) parses with
1177 // posix: None — NEVER foreign.
1178 let mut old = m.clone();
1179 old.remove(PosixStamps::META_UID);
1180 let parsed = GenerationStamps::from_meta(&old).expect("identity stamps intact");
1181 assert_eq!(parsed.posix, None);
1182 }
1183}
1184
1185#[cfg(test)]
1186mod combine_tests {
1187 use super::{crc64_combine, crc64_nvme};
1188
1189 /// The one-shot CRC over the concatenation is the oracle. Nothing
1190 /// here asserts a hand-computed constant: the existing
1191 /// implementation is the ground truth, and `combine` either agrees
1192 /// with it on every split or it is wrong.
1193 #[test]
1194 fn combining_two_parts_equals_hashing_the_whole() {
1195 // Non-uniform bytes: a run of one value would hide an operator
1196 // that shifted by the wrong number of positions.
1197 let whole: Vec<u8> = (0..4096u32).map(|i| (i.wrapping_mul(2654435761) >> 13) as u8).collect();
1198 for split in [0usize, 1, 2, 3, 7, 8, 9, 255, 256, 257, 1023, 2048, 4095, 4096] {
1199 let (a, b) = whole.split_at(split);
1200 assert_eq!(
1201 crc64_combine(crc64_nvme(a), crc64_nvme(b), b.len() as u64),
1202 crc64_nvme(&whole),
1203 "split at {split}"
1204 );
1205 }
1206 }
1207
1208 #[test]
1209 fn combining_many_parts_folds_left_to_right() {
1210 let whole: Vec<u8> = (0..10_000u32).map(|i| (i ^ (i >> 5)) as u8).collect();
1211 // An 8 MiB-style grid in miniature: unequal parts, last one short.
1212 let sizes = [1usize, 999, 4096, 1, 4903]; // sums to exactly 10_000
1213 let mut off = 0usize;
1214 let mut acc: Option<(u64, u64)> = None; // (crc, len)
1215 for sz in sizes {
1216 let part = &whole[off..off + sz];
1217 let c = crc64_nvme(part);
1218 acc = Some(match acc {
1219 None => (c, sz as u64),
1220 Some((pc, plen)) => (crc64_combine(pc, c, sz as u64), plen + sz as u64),
1221 });
1222 off += sz;
1223 }
1224 let (crc, len) = acc.unwrap();
1225 assert_eq!(len, whole.len() as u64, "the grid must cover the object");
1226 assert_eq!(crc, crc64_nvme(&whole), "folded parts must equal one pass");
1227 }
1228
1229 #[test]
1230 fn an_empty_tail_changes_nothing() {
1231 let a = b"some bytes";
1232 assert_eq!(crc64_combine(crc64_nvme(a), crc64_nvme(b""), 0), crc64_nvme(a));
1233 }
1234}
1235
1236#[cfg(test)]
1237mod fold_order_tests {
1238 use super::{crc64_combine, crc64_nvme};
1239
1240 /// The compose path sorts parts by number BEFORE folding, and this
1241 /// is why: `crc64_combine` composes A-then-B, so a grid folded in
1242 /// completion order rather than part order yields the checksum of a
1243 /// DIFFERENT object. Without this test the sort reads as being only
1244 /// about what CompleteMultipartUpload accepts.
1245 #[test]
1246 fn folding_out_of_order_yields_a_different_object() {
1247 let a = b"first-part-bytes";
1248 let b = b"second";
1249 let c = b"third-part!";
1250 let whole = [&a[..], &b[..], &c[..]].concat();
1251
1252 let fold = |parts: &[&[u8]]| {
1253 let mut acc: Option<u64> = None;
1254 for p in parts {
1255 let x = crc64_nvme(p);
1256 acc = Some(match acc {
1257 None => x,
1258 Some(prev) => crc64_combine(prev, x, p.len() as u64),
1259 });
1260 }
1261 acc.unwrap()
1262 };
1263
1264 assert_eq!(fold(&[a, b, c]), crc64_nvme(&whole), "part order IS the object");
1265 assert_ne!(
1266 fold(&[b, a, c]),
1267 crc64_nvme(&whole),
1268 "a shuffled fold must NOT coincidentally agree, or the sort proves nothing"
1269 );
1270 }
1271}