Skip to main content

flint_lean/
manifest.rs

1//! The lean subtree manifest: one JSON document, CAS-written, the
2//! atomic commit point every reader trusts (checkout, sync, DR).
3//!
4//! Deliberately NOT `tier::manifest`: the hub's writer rebuilds the
5//! whole document from its local walk and cannot merge (its Entry has
6//! no author identity), which is the amputation engine the lean review
7//! reproduced three ways. This writer merges three-way:
8//! base = the manifest view at OUR last install, mine = this barrier's
9//! walk, theirs = bucket-current. Foreign entries are preserved and
10//! surfaced for the next consume; a local delete loses to a foreign
11//! modify (delete/modify resolves conservative — the formal model's
12//! GC-vs-merge counterexample is exactly this case).
13
14use std::collections::{BTreeMap, BTreeSet};
15
16use serde::{Deserialize, Serialize};
17
18use flint_store::{
19    crc64_nvme, GenerationStamps, ObjectMeta, ObjectStore, PutCondition, StoreError,
20};
21
22use super::{LeanConfig, LeanError, LeanResult};
23
24#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
25pub struct LeanEntry {
26    /// Object key (under `<prefix>/files/`).
27    pub key: String,
28    pub etag: String,
29    /// Full-object CRC-64/NVME of the cited bytes, in wire (base64)
30    /// form — computed by the flint client that MOVED the bytes (the
31    /// publisher over what it uploaded, a consume or checkout over what
32    /// it wrote), never copied from a backend header. It is the one
33    /// integrity check that holds on every backend: S3 attests a
34    /// checksum on the wire, Ozone attests none, and the manifest's
35    /// value describes the bytes either way. Every reader verifies a
36    /// fresh fetch against it before the file becomes visible.
37    pub crc64_b64: String,
38    pub size: u64,
39    pub mode: u32,
40    pub mtime_unix: i64,
41    pub generation: u64,
42    /// The publishing writer's lease epoch (0 = a gateway/HITL write).
43    pub epoch: u64,
44}
45
46#[derive(Debug, Clone, Default, Serialize, Deserialize)]
47pub struct LeanManifest {
48    pub seq: u64,
49    /// path -> entry. Paths are workspace-relative, '/'-separated.
50    pub entries: BTreeMap<String, LeanEntry>,
51    /// This workspace is published by exactly ONE writer, so an object
52    /// that has moved off its citation was moved by something that is
53    /// not the publisher.
54    ///
55    /// It exists because a reader's default arm on a 412 is an
56    /// explicit S3-wins adopt — right for a lean workspace, where an
57    /// object past its citation means a human wrote newer bytes that
58    /// ought to win. On a MIRROR that reading is exactly inverted: the
59    /// publisher is the only party entitled to write, so "past the
60    /// citation" means a stranger did, and adopting copies bytes no
61    /// manifest cites into a reader's tree with no error and no
62    /// conflict record. Composition drill C4 measured that against
63    /// forge's legible export.
64    ///
65    /// Set by the installing pass from config, never inherited.
66    #[serde(default)]
67    pub sole_writer: bool,
68    /// Which citation source installed this manifest (§2.4.1). Also
69    /// stamped on the object's metadata so it is readable by HEAD.
70    #[serde(default, skip_serializing_if = "Option::is_none")]
71    pub boundary_source: Option<String>,
72    /// What each published delete RETIRED, path -> the etag the document
73    /// cited before the delete, kept until the path is cited again (or
74    /// `TOMBSTONE_KEEP_SEQS` generations pass). Review 2026-09-18, H1e: a
75    /// writer that adopted a UI write while it was still pending, and
76    /// merges after another writer cited it and then deleted it knowingly,
77    /// otherwise sees only "baseline ≠ merge base, object at the key" —
78    /// the same view a delete that RACED the write leaves, where modify
79    /// rightly wins — and the citation repair (removed in step 5) resurrected
80    /// the deleted generation. The tombstone is the one fact that tells the
81    /// two apart.
82    /// Empty on every document written before this field existed.
83    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
84    pub tombstones: BTreeMap<String, Tombstone>,
85}
86
87/// A published delete's record in the document: the generation it retired
88/// and the generation of the document that published it.
89#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
90pub struct Tombstone {
91    pub etag: String,
92    pub seq: u64,
93}
94
95/// How many document generations a tombstone outlives its delete. A writer
96/// whose merge base is older than this can still re-cite what it holds —
97/// the residual, named in SAFETY.md §4.14.
98pub const TOMBSTONE_KEEP_SEQS: u64 = 10_000;
99
100impl LeanManifest {
101    /// COMPACT, not pretty. This document is O(entries) and it moves on
102    /// every path that matters: the pre-marker checkout GET, every
103    /// barrier merge GET and CAS PUT, and every gateway read verb. The
104    /// indentation was ~22% of those bytes and of the parse that
105    /// follows. `mc cat | jq` — the operator's and every rig's only
106    /// debugging surface for the CAS commit point — is unaffected.
107    pub fn to_bytes(&self) -> Vec<u8> {
108        serde_json::to_vec(self).expect("manifest serializes")
109    }
110    pub fn parse(bytes: &[u8]) -> Result<LeanManifest, String> {
111        serde_json::from_slice(bytes).map_err(|e| e.to_string())
112    }
113}
114
115/// The bucket-current manifest + its document ETag (the CAS token).
116/// The pointer document at `<prefix>/.flint/lean/current` — the ONLY
117/// mutable metadata object under the pointer layout (design of record:
118/// `docs/plans/flint-lean-manifest-pointer-design.md`).
119///
120/// Everything a reader needs before it decides whether to fetch entries
121/// at all lives here, so the barrier's idle tick reads a few hundred
122/// bytes instead of a document that runs to 264 MiB at 1M entries.
123#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
124pub struct Pointer {
125    /// The manifest generation this pointer publishes. Bumped by a
126    /// citation AND by a takeover rotation, which is why it is not the
127    /// same number as `entries_seq`.
128    pub seq: u64,
129    /// The single immutable object holding every entry of this
130    /// generation — the step-one layout. `None` on a CHUNKED pointer.
131    ///
132    /// Optional here and REQUIRED in the step-one binary's schema, and
133    /// that asymmetry is the migration: a step-one reader handed a
134    /// chunked pointer fails to parse it and refuses, rather than
135    /// decoding a pointer it half-understands. `manifest::load` maps a
136    /// missing object to `Ok(None)`, `None` means FIRST WRITE, and a
137    /// barrier answers that with `If-None-Match: *` — so every layout
138    /// change has to make an old reader refuse rather than conclude the
139    /// project is empty. **Do not give this field a serde default in a
140    /// released binary; that is what makes the refusal work.**
141    #[serde(default, skip_serializing_if = "Option::is_none")]
142    pub entries_key: Option<String>,
143    /// The `seq` the entries object was written under. A rotation
144    /// leaves this ALONE while bumping `seq`, which is exactly what
145    /// lets a follower skip the entries GET after a takeover.
146    #[serde(default, skip_serializing_if = "Option::is_none")]
147    pub entries_seq: Option<u64>,
148    /// The chunk list — the step-two layout. `Some(vec![])` is a
149    /// legitimately EMPTY project and is distinguishable from absence,
150    /// which is why this is an Option around a Vec rather than a bare
151    /// Vec with a default.
152    #[serde(default, skip_serializing_if = "Option::is_none")]
153    pub chunks: Option<Vec<super::chunk::ChunkRef>>,
154    /// Carried here as well as on the manifest because the pointer is
155    /// the authority for the fields it carries, and a reader that
156    /// reconstructs a manifest from it must not lose the flag that
157    /// decides whether it may adopt.
158    #[serde(default)]
159    pub sole_writer: bool,
160    #[serde(default, skip_serializing_if = "Option::is_none")]
161    pub boundary_source: Option<String>,
162    /// The epoch that installed this pointer. Diagnostic; the fence is
163    /// the CAS, not this field.
164    pub epoch: u64,
165    /// The content address of the document's tombstones in the chunked
166    /// layout (`chunk::TombstoneBody`, at `chunk_key`), `None` when the
167    /// document has none. The single-object layout carries them inline.
168    #[serde(default, skip_serializing_if = "Option::is_none")]
169    pub tombstones: Option<String>,
170}
171
172/// Where a pointer's entries actually live.
173#[derive(Debug)]
174pub enum Entries<'a> {
175    /// One generation object (step one).
176    Single { key: &'a str, seq: u64 },
177    /// A chunk list (step two). Empty = an empty project.
178    Chunked(&'a [super::chunk::ChunkRef]),
179}
180
181impl Pointer {
182    /// Resolve the layout, refusing anything ambiguous.
183    ///
184    /// BOTH forms present, or NEITHER, is malformed and must fail —
185    /// never pick one. A pointer carrying both would let two readers
186    /// that broke the tie differently disagree about the contents of
187    /// the same seq, which is the one thing a single visible object was
188    /// supposed to make impossible.
189    pub fn entries(&self) -> LeanResult<Entries<'_>> {
190        match (&self.entries_key, &self.chunks) {
191            (Some(k), None) => {
192                Ok(Entries::Single { key: k, seq: self.entries_seq.unwrap_or(self.seq) })
193            }
194            (None, Some(c)) => Ok(Entries::Chunked(c)),
195            (Some(_), Some(_)) => Err(super::LeanError::State(format!(
196                "manifest pointer at seq {} names BOTH a generation object and a chunk list; \
197                 refusing to guess which describes this manifest",
198                self.seq
199            ))),
200            (None, None) => Err(super::LeanError::State(format!(
201                "manifest pointer at seq {} names no entries at all — neither a generation \
202                 object nor a chunk list; an empty project is an empty chunk LIST, not a \
203                 missing one",
204                self.seq
205            ))),
206        }
207    }
208}
209
210/// What a writer must present to CAS. Carries the LAYOUT as well as the
211/// tag, because a workspace mid-migration has a legacy manifest and no
212/// pointer yet, and the two cases take different preconditions: an
213/// If-Match on the object the writer read, versus an If-None-Match on a
214/// pointer that must not already exist.
215#[derive(Debug, Clone, PartialEq)]
216pub struct ManifestHandle {
217    pub etag: String,
218    /// True when the document was read from the LEGACY single-object
219    /// key, i.e. this write is the migration.
220    pub legacy: bool,
221    /// The chunk list this write is superseding, empty if the workspace
222    /// is not chunked yet. Carried on the handle rather than re-read at
223    /// publish time because the caller has just loaded it, and because
224    /// a publish that had to GET the pointer again to find out what it
225    /// already knew would pay a request per barrier for nothing.
226    ///
227    /// This is what makes a publish O(changed): a chunk whose address
228    /// is already here is not sent.
229    pub prev_chunks: Vec<super::chunk::ChunkRef>,
230    /// The tombstones object the superseded pointer names, if any: retired
231    /// with the chunks when the new pointer names another (M1).
232    pub prev_tombstones: Option<String>,
233}
234
235/// What the legacy key is overwritten with once a workspace has moved to
236/// the pointer layout. It must NOT parse as a manifest: `LeanManifest`
237/// gives `seq` and `entries` no serde default, so an OLD `flint-sync`
238/// reading this gets `LeanError::State` and refuses.
239///
240/// Deleting the legacy key instead would be a data-loss shape, not a
241/// tidy-up: `manifest::load` maps a missing object to `Ok(None)`, `None`
242/// means FIRST WRITE, and a barrier answers that with
243/// `IfNoneMatchAny` — so an old syncer would conclude the project is
244/// empty and re-seed over it.
245pub const REFUSAL_DOC: &str = concat!(
246    "{\"moved\":\".flint/lean/current\",",
247    "\"note\":\"this workspace uses the manifest pointer layout; upgrade flint-sync\"}"
248);
249
250pub struct LoadedManifest {
251    pub manifest: LeanManifest,
252    /// The CAS handle: the POINTER's etag under the pointer layout, the
253    /// legacy object's etag before migration.
254    pub etag: String,
255    /// The object's own Last-Modified. The GET already carries it; a
256    /// caller that wants the coherence stamp must not pay a second
257    /// request for what this one threw away (review: U31).
258    pub last_modified_unix: Option<u64>,
259    /// `None` ⇒ this workspace is still on the legacy single-object
260    /// layout and the next write migrates it.
261    pub pointer: Option<Pointer>,
262}
263
264impl LoadedManifest {
265    /// The handle a writer presents to CAS over this read.
266    pub fn handle(&self) -> ManifestHandle {
267        ManifestHandle {
268            etag: self.etag.clone(),
269            legacy: self.pointer.is_none(),
270            prev_chunks: match self.pointer.as_ref().map(|p| p.entries()) {
271                Some(Ok(Entries::Chunked(c))) => c.to_vec(),
272                _ => Vec::new(),
273            },
274            prev_tombstones: self.pointer.as_ref().and_then(|p| p.tombstones.clone()),
275        }
276    }
277}
278
279/// Read the pointer alone. The barrier's idle tick wants exactly this
280/// and nothing else: a few hundred bytes that answer "did anything
281/// move, and were the ENTRIES part of it".
282pub struct LoadedPointer {
283    pub pointer: Pointer,
284    pub etag: String,
285    /// The pointer object's own Last-Modified — the citation's clock,
286    /// which /status reports and which the GET already carries.
287    pub last_modified_unix: Option<u64>,
288}
289
290pub async fn load_pointer(
291    store: &dyn ObjectStore,
292    cfg: &LeanConfig,
293) -> LeanResult<Option<LoadedPointer>> {
294    match store.get_whole(&cfg.current_key(), None).await {
295        Ok((meta, bytes)) => {
296            let pointer: Pointer = serde_json::from_slice(&bytes)
297                .map_err(|e| super::LeanError::State(format!("manifest pointer parse: {e}")))?;
298            Ok(Some(LoadedPointer { pointer, etag: meta.etag, last_modified_unix: meta.last_modified_unix }))
299        }
300        Err(StoreError::NotFound(_)) => Ok(None),
301        Err(e) => Err(e.into()),
302    }
303}
304
305/// The whole document: pointer, then the generation it names. Falls
306/// back to the legacy single-object key for a workspace that has not
307/// been migrated — which every existing workspace is, exactly once.
308/// How many times `load` will restart onto a newer generation before
309/// giving up. A restart happens only when a chunk we needed was swept
310/// AND the pointer moved under us, so it is bounded by publish rate,
311/// not by anything we control — three is generous for a workspace whose
312/// floor is measured in seconds.
313const LOAD_ATTEMPTS: u32 = 3;
314
315pub async fn load(
316    store: &dyn ObjectStore,
317    cfg: &LeanConfig,
318) -> LeanResult<Option<LoadedManifest>> {
319  for attempt in 0..LOAD_ATTEMPTS {
320    if let Some(LoadedPointer { pointer: p, etag, last_modified_unix: pointer_lm }) =
321        load_pointer(store, cfg).await?
322    {
323        // A pointer naming an object that is not there is not an empty
324        // workspace — it is a broken one, and answering `None` would
325        // invite a re-seed over a live project. That rule holds one
326        // level deeper for chunks: a chunk list with a hole is a
327        // manifest missing entries, and a missing entry reads to every
328        // consumer as a file the agent deleted.
329        let (mut manifest, meta_lm) = match p.entries()? {
330            Entries::Single { key, .. } => {
331                let (meta, bytes) = match store.get_whole(key, None).await {
332                    Ok(v) => v,
333                    Err(StoreError::NotFound(_)) => {
334                        return Err(super::LeanError::State(format!(
335                            "manifest pointer at seq {} names {key}, which does not exist — \
336                             refusing to treat a broken pointer as an empty workspace",
337                            p.seq
338                        )))
339                    }
340                    Err(e) => return Err(e.into()),
341                };
342                let m = LeanManifest::parse(&bytes)
343                    .map_err(|e| super::LeanError::State(format!("manifest parse: {e}")))?;
344                (m, meta.last_modified_unix)
345            }
346            Entries::Chunked(refs) => {
347                // Sequential on purpose for now: a chunk fetch is
348                // ordinary and the interesting property is that a hole
349                // FAILS rather than silently shortening the manifest.
350                let mut bodies = Vec::with_capacity(refs.len());
351                let mut raced = false;
352                for r in refs {
353                    let key = cfg.chunk_key(&r.addr);
354                    match store.get_whole(&key, None).await {
355                        Ok((_, b)) => bodies.push(b.to_vec()),
356                        Err(StoreError::NotFound(_)) => {
357                            // A chunk we need is gone. Which of two very
358                            // different things happened is decided by
359                            // the POINTER, not by the chunk:
360                            //
361                            // - the pointer MOVED ⇒ we raced a sweep
362                            //   that collected a generation we were
363                            //   still reading. The current generation is
364                            //   a complete snapshot, so start over
365                            //   against it: coherent, just newer. This
366                            //   is what makes a reader safe for a
367                            //   DURATION rather than for `Retain`
368                            //   publishes (chunked design §8.2,
369                            //   machine-checked by
370                            //   `LeanChunkGCSlowReader`).
371                            // - the pointer is UNCHANGED ⇒ the live
372                            //   manifest genuinely has a hole, and there
373                            //   is nothing newer to restart onto. Fail,
374                            //   and never as `Ok(None)`, which every
375                            //   caller reads as FIRST WRITE.
376                            let moved = match load_pointer(store, cfg).await? {
377                                Some(now) => now.etag != etag,
378                                None => true,
379                            };
380                            if moved && attempt + 1 < LOAD_ATTEMPTS {
381                                raced = true;
382                                break;
383                            }
384                            return Err(super::LeanError::State(format!(
385                                "manifest pointer at seq {} names chunk {} (first key {:?}), \
386                                 which does not exist — refusing to serve a manifest with a \
387                                 hole in it as though those entries had been deleted",
388                                p.seq, r.addr, r.first
389                            )));
390                        }
391                        Err(e) => return Err(e.into()),
392                    }
393                }
394                if raced {
395                    continue;
396                }
397                let entries = super::chunk::assemble(refs, &bodies)?;
398                let tombstones = match &p.tombstones {
399                    None => BTreeMap::new(),
400                    Some(addr) => match store.get_whole(&cfg.chunk_key(addr), None).await {
401                        Ok((_, b)) => super::chunk::decode_tombstones(&b, addr)?,
402                        // The same two cases as a missing chunk, decided the
403                        // same way: by whether the pointer moved.
404                        Err(StoreError::NotFound(_)) => {
405                            let moved = match load_pointer(store, cfg).await? {
406                                Some(now) => now.etag != etag,
407                                None => true,
408                            };
409                            if moved && attempt + 1 < LOAD_ATTEMPTS {
410                                continue;
411                            }
412                            return Err(super::LeanError::State(format!(
413                                "manifest pointer at seq {} names tombstones {addr}, which do not exist",
414                                p.seq
415                            )));
416                        }
417                        Err(e) => return Err(e.into()),
418                    },
419                };
420                (
421                    LeanManifest {
422                        seq: p.seq,
423                        entries,
424                        sole_writer: p.sole_writer,
425                        boundary_source: p.boundary_source.clone(),
426                        tombstones,
427                    },
428                    None,
429                )
430            }
431        };
432        // The pointer is the authority for the fields it carries: a
433        // rotation moves `seq` without rewriting the entries object, so
434        // the generation's own copy is stale by construction.
435        manifest.seq = p.seq;
436        manifest.sole_writer = p.sole_writer;
437        manifest.boundary_source = p.boundary_source.clone();
438        return Ok(Some(LoadedManifest {
439            manifest,
440            etag,
441            // The CITATION's clock is when the pointer moved, not when
442            // the entries object happened to be written: a rotation
443            // republishes the same entries under a new generation.
444            last_modified_unix: pointer_lm.or(meta_lm),
445            pointer: Some(p),
446        }));
447    }
448    // No pointer: the pre-migration layout, which has no chunks and so
449    // nothing to race a sweep over. Answer it and leave the loop.
450    return match store.get_whole(&cfg.manifest_key(), None).await {
451        Ok((meta, bytes)) => {
452            let manifest = LeanManifest::parse(&bytes)
453                .map_err(|e| super::LeanError::State(format!("manifest parse: {e}")))?;
454            Ok(Some(LoadedManifest {
455                manifest,
456                etag: meta.etag,
457                last_modified_unix: meta.last_modified_unix,
458                pointer: None,
459            }))
460        }
461        Err(StoreError::NotFound(_)) => Ok(None),
462        Err(e) => Err(e.into()),
463    };
464  }
465  // Every attempt raced a sweep. Refusing is right: the alternative is
466  // to serve a manifest we know is short, and short reads as deleted.
467  Err(super::LeanError::State(format!(
468      "manifest load restarted {LOAD_ATTEMPTS} times without settling — a sweep is \
469       collecting generations faster than this reader can finish one"
470  )))
471}
472
473/// How many lost races a one-CAS edit re-reads and retries before it gives
474/// up `Contended`.
475pub const EDIT_CAS_ATTEMPTS: usize = 16;
476
477/// Why a one-CAS edit did not land.
478#[derive(Debug)]
479pub enum EditError<E> {
480    /// The edit refused the document it was shown.
481    Refused(E),
482    Store(LeanError),
483    /// Lost `EDIT_CAS_ATTEMPTS` races in a row.
484    Contended,
485}
486
487/// ONE manifest CAS for an edit by a party that holds no lease (P2): the
488/// gateway's UI saves, deletes and renames, and the ingress sweep's
489/// adoptions. Load the current document; let `edit` judge it and change a
490/// copy — the next generation, with the installing party's fields reset as
491/// `merge` resets them; keep tombstones to `TOMBSTONE_KEEP_SEQS`; CAS it in
492/// with epoch 0; on a lost race do it all again against what won, so every
493/// precondition is judged against the document the CAS replaces.
494pub async fn commit_edit<E>(
495    store: &dyn ObjectStore,
496    cfg: &LeanConfig,
497    flush: &str,
498    edit: impl Fn(Option<&LoadedManifest>, &mut LeanManifest) -> Result<(), E>,
499) -> Result<(), EditError<E>> {
500    for _ in 0..EDIT_CAS_ATTEMPTS {
501        let current = load(store, cfg).await.map_err(EditError::Store)?;
502        let mut doc = current.as_ref().map(|l| l.manifest.clone()).unwrap_or_default();
503        doc.seq += 1;
504        doc.sole_writer = false;
505        doc.boundary_source = None;
506        edit(current.as_ref(), &mut doc).map_err(EditError::Refused)?;
507        let seq = doc.seq;
508        doc.tombstones.retain(|_, t| seq.saturating_sub(t.seq) <= TOMBSTONE_KEEP_SEQS);
509        let expected = current.as_ref().map(|l| l.handle());
510        let before = current.as_ref().map(|l| &l.manifest);
511        match cas_write_retiring(store, cfg, &doc, before, expected.as_ref(), 0, flush, None).await {
512            Ok(_) => return Ok(()),
513            Err(LeanError::Store(StoreError::PreconditionFailed(_))) | Err(LeanError::Store(StoreError::Conflict(_))) => {
514                continue
515            }
516            Err(e) => return Err(EditError::Store(e)),
517        }
518    }
519    Err(EditError::Contended)
520}
521
522/// CAS-write the manifest document. `expected`: None ⇒ first write
523/// (If-None-Match:*); Some(etag) ⇒ If-Match. The caller owns 412
524/// handling (merge-retry or fence — never blind re-seed).
525pub async fn cas_write(
526    store: &dyn ObjectStore,
527    cfg: &LeanConfig,
528    m: &LeanManifest,
529    expected: Option<&ManifestHandle>,
530    epoch: u64,
531    flush_uuid: &str,
532) -> LeanResult<ObjectMeta> {
533    cas_write_stamped(store, cfg, m, expected, epoch, flush_uuid, None).await
534}
535
536/// `cas_write` with an explicit boundary-source stamp on the manifest
537/// OBJECT (§2.4.1): downstream consumers distinguish a declared-coherent
538/// citation from a forced possibly-torn one from the bucket alone, for
539/// the price of a HEAD rather than a GET of a manifest that can run to
540/// hundreds of MiB.
541pub async fn cas_write_stamped(
542    store: &dyn ObjectStore,
543    cfg: &LeanConfig,
544    m: &LeanManifest,
545    expected: Option<&ManifestHandle>,
546    epoch: u64,
547    flush_uuid: &str,
548    boundary_source: Option<&str>,
549) -> LeanResult<ObjectMeta> {
550    Ok(cas_write_refs(store, cfg, m, expected, epoch, flush_uuid, boundary_source).await?.0)
551}
552
553/// `cas_write_stamped`, also returning the chunk objects the new pointer
554/// references (its chunks and its tombstones object) — `None` on the
555/// single-object layout.
556async fn cas_write_refs(
557    store: &dyn ObjectStore,
558    cfg: &LeanConfig,
559    m: &LeanManifest,
560    expected: Option<&ManifestHandle>,
561    epoch: u64,
562    flush_uuid: &str,
563    boundary_source: Option<&str>,
564) -> LeanResult<(ObjectMeta, Option<Vec<String>>)> {
565    // The manifest's own document must agree with its object stamp:
566    // a reader that GETs and a reader that HEADs must never disagree
567    // about how coherent the citation claims to be.
568    // The layout switch. Every publisher routes through here — the
569    // barrier, the takeover rotation and the gateway's HITL CAS — so the
570    // decision lives at one site rather than three, and §6's "chunk
571    // server-side on receipt" falls out rather than needing its own
572    // path.
573    if cfg.chunked {
574        let (meta, refs) = cas_write_chunked_refs(
575            store,
576            cfg,
577            m,
578            expected,
579            expected.map(|h| h.prev_chunks.as_slice()).unwrap_or(&[]),
580            PublishStamps { epoch, flush_uuid, boundary_source },
581        )
582        .await?;
583        return Ok((meta, Some(refs)));
584    }
585    let mut m = m.clone();
586    if boundary_source.is_some() {
587        m.boundary_source = boundary_source.map(|s| s.to_string());
588    }
589    let m = &m;
590    let bytes = m.to_bytes();
591    let crc = crc64_nvme(&bytes);
592    let stamps = GenerationStamps {
593        generation: m.seq,
594        epoch,
595        flush_uuid: flush_uuid.to_string(),
596        // Stamp what the DOCUMENT carries, not merely what this call
597        // passed. An explicit source has already been written into the
598        // document above, so the two agree there either way; the case
599        // this closes is a `None` caller over a document that already
600        // names its clock — the gateway's HITL CAS relays a document it
601        // did not author. Stamping `None` on those left the object
602        // saying nothing while the document said `sentinel`, which is
603        // exactly the GET/HEAD divergence the contract above forbids.
604        boundary_source: m.boundary_source.clone(),
605        posix: None,
606    };
607
608    // 1. The ENTRIES, to a fresh immutable key. `IfNoneMatchAny` is the
609    //    whole safety story for this object: two writers that raced to
610    //    the same seq cannot both land, and the loser is told so here
611    //    rather than discovering it after it has already published.
612    let entries_key = cfg.generation_key(m.seq, flush_uuid);
613    match store
614        .put_whole(&entries_key, bytes.into(), &PutCondition::IfNoneMatchAny, &stamps, crc)
615        .await
616    {
617        Ok(_) => {}
618        // The key carries this writer's flush uuid, so this is not a
619        // race with another writer — it is a retry of OUR OWN write
620        // whose pointer CAS we never learned the outcome of. The object
621        // is byte-identical by construction; fall through to the CAS,
622        // which is where the race is actually decided.
623        Err(StoreError::PreconditionFailed(_)) | Err(StoreError::Conflict(_)) => {}
624        Err(e) => return Err(e.into()),
625    }
626
627    // 2. The POINTER, which is what makes the publish visible and what
628    //    decides the race. Everything above this line is invisible to
629    //    every reader; a crash here leaves an orphan generation object
630    //    that nobody reads and the sweep collects.
631    let pointer = Pointer {
632        seq: m.seq,
633        entries_key: Some(entries_key.clone()),
634        entries_seq: Some(m.seq),
635        // The step-one layout. `cas_write_chunked` is what produces a
636        // chunk list; this path stays byte-for-byte what it was.
637        chunks: None,
638        sole_writer: m.sole_writer,
639        boundary_source: m.boundary_source.clone(),
640        epoch,
641        tombstones: None,
642    };
643    Ok((put_pointer(store, cfg, &pointer, expected, &stamps).await?, None))
644}
645
646/// Who is publishing, and under what coherence claim. Grouped because
647/// they travel together through every publish path and are meaningless
648/// apart — and because a positional list of three scalars is how an
649/// epoch ends up where a flush uuid was meant to go.
650pub struct PublishStamps<'a> {
651    pub epoch: u64,
652    pub flush_uuid: &'a str,
653    pub boundary_source: Option<&'a str>,
654}
655
656/// Publish a manifest as a CHUNK LIST (chunked design §2).
657///
658/// The ordering is the atomicity story and is not negotiable: every
659/// chunk is durable BEFORE the pointer CAS, and the pointer is the only
660/// thing that ever becomes visible. A crash between the two leaves
661/// orphan chunks nobody references and no reader can observe — never a
662/// half-written manifest.
663///
664/// `prev` is the chunk list this publish is replacing. Chunks whose
665/// address is already in it are skipped ENTIRELY — not uploaded and
666/// re-conditioned, but never sent. That is where O(changed) actually
667/// comes from: without it, a one-file publish still ships every chunk's
668/// bytes over the wire and only the store's 412 saves the storage.
669pub async fn cas_write_chunked(
670    store: &dyn ObjectStore,
671    cfg: &LeanConfig,
672    m: &LeanManifest,
673    expected: Option<&ManifestHandle>,
674    prev: &[super::chunk::ChunkRef],
675    pub_stamps: PublishStamps<'_>,
676) -> LeanResult<ObjectMeta> {
677    Ok(cas_write_chunked_refs(store, cfg, m, expected, prev, pub_stamps).await?.0)
678}
679
680/// `cas_write_chunked`, also returning the chunk addresses the new pointer
681/// references, its tombstones object included.
682async fn cas_write_chunked_refs(
683    store: &dyn ObjectStore,
684    cfg: &LeanConfig,
685    m: &LeanManifest,
686    expected: Option<&ManifestHandle>,
687    prev: &[super::chunk::ChunkRef],
688    pub_stamps: PublishStamps<'_>,
689) -> LeanResult<(ObjectMeta, Vec<String>)> {
690    let PublishStamps { epoch, flush_uuid, boundary_source } = pub_stamps;
691    let mut m = m.clone();
692    if boundary_source.is_some() {
693        m.boundary_source = boundary_source.map(|s| s.to_string());
694    }
695    let m = &m;
696    let split =
697        super::chunk::split_with(&m.entries, cfg.chunk_target, cfg.chunk_min, cfg.chunk_max)?;
698    let have: std::collections::HashSet<&str> = prev.iter().map(|r| r.addr.as_str()).collect();
699
700    let stamps = GenerationStamps {
701        generation: m.seq,
702        epoch,
703        flush_uuid: flush_uuid.to_string(),
704        boundary_source: m.boundary_source.clone(),
705        posix: None,
706    };
707
708    for (r, body) in &split {
709        if have.contains(r.addr.as_str()) {
710            continue;
711        }
712        // UNCONDITIONAL, and that is a correctness requirement rather
713        // than laziness — `LeanChunkGCAdoptSkips` in the formal model
714        // fails without it.
715        //
716        // This chunk is not in `prev`, so nothing references it yet. It
717        // may nonetheless already EXIST: a crashed publish of ours left
718        // it, and content addressing means our retry produces the same
719        // key. Adopting it by reference alone would make an old object
720        // live without making it LOOK live, and the orphan sweep reads
721        // age — so the sweep would collect it as the orphan it still
722        // appears to be, between this call and our pointer CAS.
723        // Rewriting refreshes the age the sweep reads. The bytes are
724        // identical either way, so the write is idempotent; the cost
725        // falls only on adopted orphans, which are rare by
726        // construction, and chunks already in `prev` are skipped above.
727        let key = cfg.chunk_key(&r.addr);
728        let crc = crc64_nvme(body);
729        store.put_whole(&key, body.clone().into(), &PutCondition::Unconditional, &stamps, crc).await?;
730    }
731
732    // The tombstones, one object beside the chunks (rewritten like an
733    // adopted chunk: the sweep reads age, and the bytes are identical).
734    let tombstones = if m.tombstones.is_empty() {
735        None
736    } else {
737        let (addr, body) = super::chunk::encode_tombstones(&m.tombstones)?;
738        let crc = crc64_nvme(&body);
739        store.put_whole(&cfg.chunk_key(&addr), body.into(), &PutCondition::Unconditional, &stamps, crc).await?;
740        Some(addr)
741    };
742    let pointer = Pointer {
743        seq: m.seq,
744        entries_key: None,
745        entries_seq: None,
746        chunks: Some(split.into_iter().map(|(r, _)| r).collect()),
747        sole_writer: m.sole_writer,
748        boundary_source: m.boundary_source.clone(),
749        epoch,
750        tombstones: tombstones.clone(),
751    };
752    let meta = put_pointer(store, cfg, &pointer, expected, &stamps).await?;
753    let mut refs: Vec<String> = pointer.chunks.iter().flatten().map(|r| r.addr.clone()).collect();
754    refs.extend(tombstones);
755    Ok((meta, refs))
756}
757
758/// What a commit retired (M1): the handles its document no longer cites
759/// and the chunk objects its pointer no longer references. One immutable
760/// log object per commit, under `retired/`, keyed by the unix second it
761/// was written — the retirement's clock. The sweeps spare everything a
762/// log younger than `retire_grace_secs` names; a writer reaps the older
763/// ones (`untracked.rs`).
764#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
765pub struct RetireLog {
766    pub at_unix: u64,
767    #[serde(default, skip_serializing_if = "Vec::is_empty")]
768    pub handles: Vec<String>,
769    /// Chunk ADDRESSES (`LeanConfig::chunk_key` names the object).
770    #[serde(default, skip_serializing_if = "Vec::is_empty")]
771    pub chunks: Vec<String>,
772}
773
774pub fn retired_prefix(cfg: &LeanConfig) -> String {
775    format!("{}/{}/retired/", cfg.prefix, super::LEAN_DIR)
776}
777
778/// The unix second a retire log's KEY carries (`<at:020>-...`): a listing
779/// dates every log with no GET.
780pub fn retire_log_at(cfg: &LeanConfig, key: &str) -> Option<u64> {
781    key.strip_prefix(&retired_prefix(cfg))?.get(..20)?.parse().ok()
782}
783
784/// A commit, and the log of what it retired, written right after the CAS.
785/// A crash between the two leaves those handles and chunks to the sweeps'
786/// write-age rule — the shape before the retire age — and nothing worse.
787/// The log is best effort for the same reason: a failure to write it costs
788/// a lagging reader a re-resolve, never the commit.
789#[allow(clippy::too_many_arguments)]
790pub async fn cas_write_retiring(
791    store: &dyn ObjectStore,
792    cfg: &LeanConfig,
793    m: &LeanManifest,
794    before: Option<&LeanManifest>,
795    expected: Option<&ManifestHandle>,
796    epoch: u64,
797    flush_uuid: &str,
798    boundary_source: Option<&str>,
799) -> LeanResult<ObjectMeta> {
800    let (meta, refs) = cas_write_refs(store, cfg, m, expected, epoch, flush_uuid, boundary_source).await?;
801    let still: std::collections::HashSet<&str> = m.entries.values().map(|e| e.key.as_str()).collect();
802    let mut handles: Vec<String> = before
803        .map(|b| b.entries.values().map(|e| e.key.clone()).filter(|k| !still.contains(k.as_str())).collect())
804        .unwrap_or_default();
805    handles.sort();
806    handles.dedup();
807    let mut chunks: Vec<String> = vec![];
808    if let (Some(refs), Some(h)) = (refs.as_ref(), expected) {
809        let now: std::collections::HashSet<&str> = refs.iter().map(|a| a.as_str()).collect();
810        chunks = h
811            .prev_chunks
812            .iter()
813            .map(|r| r.addr.clone())
814            .chain(h.prev_tombstones.clone())
815            .filter(|a| !now.contains(a.as_str()))
816            .collect();
817        chunks.sort();
818        chunks.dedup();
819    }
820    if !handles.is_empty() || !chunks.is_empty() {
821        let at = super::now_unix();
822        let log = RetireLog { at_unix: at, handles, chunks };
823        let key = format!("{}{at:020}-{flush_uuid}-{}.json", retired_prefix(cfg), uuid::Uuid::new_v4());
824        let body = serde_json::to_vec(&log).map_err(|e| LeanError::State(format!("retire log: {e}")))?;
825        let crc = crc64_nvme(&body);
826        let stamps = GenerationStamps {
827            generation: m.seq,
828            epoch,
829            flush_uuid: flush_uuid.to_string(),
830            boundary_source: None,
831            posix: None,
832        };
833        if let Err(e) = store.put_whole(&key, body.into(), &PutCondition::IfNoneMatchAny, &stamps, crc).await {
834            eprintln!("flint-sync: could not log what seq {} retired ({e}); the sweeps judge it by write age", m.seq);
835        }
836    }
837    Ok(meta)
838}
839
840/// CAS the pointer. Split out because a takeover rotation writes ONLY
841/// this — no entries object, no multi-MB anything.
842async fn put_pointer(
843    store: &dyn ObjectStore,
844    cfg: &LeanConfig,
845    pointer: &Pointer,
846    expected: Option<&ManifestHandle>,
847    stamps: &GenerationStamps,
848) -> LeanResult<ObjectMeta> {
849    let body = serde_json::to_vec(pointer)
850        .map_err(|e| super::LeanError::State(format!("pointer encode: {e}")))?;
851    let crc = crc64_nvme(&body);
852    // A LEGACY handle is a migration: the writer read the old single
853    // object and the pointer does not exist yet, so the precondition is
854    // "no pointer", not "the pointer I read". A concurrent migration
855    // therefore loses here and retries against the layout that won,
856    // instead of both of them believing they installed it.
857    let cond = match expected {
858        Some(h) if !h.legacy => PutCondition::IfMatch(h.etag.clone()),
859        _ => PutCondition::IfNoneMatchAny,
860    };
861    let meta = store.put_whole(&cfg.current_key(), body.into(), &cond, stamps, crc).await?;
862    if let Some(h) = expected.filter(|h| h.legacy) {
863        // The workspace has moved. Poison the legacy key rather than
864        // delete it — see REFUSAL_DOC. Conditional on the very object
865        // this writer read, so a racing writer's view is never
866        // clobbered, and best effort: the refusal doc is decorative to
867        // every new reader, and the ONLY reader it speaks to is an old
868        // binary that must refuse rather than re-seed.
869        let bytes = REFUSAL_DOC.as_bytes().to_vec();
870        let crc = crc64_nvme(&bytes);
871        if let Err(e) = store
872            .put_whole(
873                &cfg.manifest_key(),
874                bytes.into(),
875                &PutCondition::IfMatch(h.etag.clone()),
876                stamps,
877                crc,
878            )
879            .await
880        {
881            eprintln!("flint-sync: could not poison the legacy manifest key after migration: {e}");
882        }
883    }
884    Ok(meta)
885}
886
887/// Bump the generation without touching the entries.
888///
889/// This is what a takeover does, and under the single-object layout it
890/// was a multi-MB GET + PUT per claim that also moved the ETag every
891/// other syncer's no-change early exit compares against — so one claim
892/// cost every follower a full fetch and parse of a document in which
893/// nothing had changed. Here it is one small CAS: `seq` moves, so an
894/// outstanding pointer handle goes stale exactly as before, and
895/// `entries_seq` does NOT, so a follower can see that the entries are
896/// the ones it already has.
897pub async fn rotate_for_takeover(
898    store: &dyn ObjectStore,
899    cfg: &LeanConfig,
900    epoch: u64,
901) -> LeanResult<Option<(LeanManifest, String)>> {
902    for _ in 0..3 {
903        // The legacy layout has no pointer to rotate: migrate by
904        // rewriting the document once, then rotations are cheap forever.
905        let Some(LoadedPointer { pointer: p, etag, .. }) = load_pointer(store, cfg).await? else {
906            let Some(loaded) = load(store, cfg).await? else {
907                return Ok(None);
908            };
909            let mut rotated = loaded.manifest.clone();
910            rotated.seq += 1;
911            let h = loaded.handle();
912            match cas_write(store, cfg, &rotated, Some(&h), epoch, "takeover-rotation").await {
913                Ok(meta) => return Ok(Some((rotated, meta.etag))),
914                Err(super::LeanError::Store(StoreError::PreconditionFailed(_) | StoreError::Conflict(_))) => continue,
915                Err(e) => return Err(e),
916            }
917        };
918        let next = Pointer { seq: p.seq + 1, epoch, ..p.clone() };
919        let stamps = GenerationStamps {
920            generation: next.seq,
921            epoch,
922            flush_uuid: "takeover-rotation".to_string(),
923            boundary_source: next.boundary_source.clone(),
924            posix: None,
925        };
926        let h = ManifestHandle { etag, legacy: false, prev_chunks: Vec::new(), prev_tombstones: None };
927        match put_pointer(store, cfg, &next, Some(&h), &stamps).await {
928            Ok(meta) => {
929                // The document the caller gets back is the standing one
930                // with the rotated seq — the entries were not read and
931                // did not need to be.
932                let mut m = LeanManifest::default();
933                m.seq = next.seq;
934                m.sole_writer = next.sole_writer;
935                m.boundary_source = next.boundary_source.clone();
936                return Ok(Some((m, meta.etag)));
937            }
938            // S3 answers a conditional write racing another on the key with 409,
939            // and a takeover whose acquire has LANDED must not fail on a lost race
940            // (review 2026-09-18, H2).
941            Err(super::LeanError::Store(StoreError::PreconditionFailed(_) | StoreError::Conflict(_))) => continue,
942            Err(e) => return Err(e),
943        }
944    }
945    Err(super::LeanError::State(
946        "takeover rotation lost 3 CAS races — a live writer is still publishing".into(),
947    ))
948}
949
950/// How many superseded generations to keep behind the live one.
951///
952/// Not zero, and not one. A reader GETs the pointer and then GETs the
953/// object it names, and those are two requests with a gap between them:
954/// reaping the generation a reader has just resolved would turn a
955/// perfectly ordinary read into a `NotFound`. A handful is a few hundred
956/// KiB at any realistic entry count and buys that gap several publishes.
957pub const KEEP_GENERATIONS: usize = 5;
958
959/// How long a generation NEWER than the live one is left alone before it
960/// is treated as an orphan.
961///
962/// An object above the live generation is one of two things: a publish
963/// that is in flight right now — its entries written, its pointer CAS
964/// not yet landed — or the wreckage of one that died in that window. The
965/// two are indistinguishable from a listing, and deleting the first
966/// breaks a live publish, so age is the only honest discriminator. Well
967/// past any plausible manifest PUT, including a 264 MiB one over a slow
968/// link.
969pub const ORPHAN_GRACE_SECS: u64 = 3600;
970
971/// Retire-age G's default (`LeanConfig::retire_grace_secs`): how long a
972/// handle or chunk stays after the commit that stopped referencing it.
973/// Past a large checkout's manifest load and a UI read's two GETs; a
974/// reader that lags longer re-resolves the pointer, as it always has. It
975/// costs storage: every version a commit replaced, kept this long.
976pub const RETIRE_GRACE_SECS: u64 = 600;
977
978/// Delete superseded generation objects, and orphans left by a publish
979/// that died between its entries PUT and its pointer CAS.
980///
981/// Immutable metadata that is never collected is a leak, and this one
982/// grows by a whole manifest per publish.
983///
984/// The two cases are NOT symmetric, which the first cut of this got
985/// wrong. BELOW the live generation, everything is superseded by
986/// definition and the only question is how much slack to leave a reader
987/// mid-resolve — that is `KEEP_GENERATIONS`. ABOVE it, an object may be
988/// a publish still in flight, and a keep-window is exactly the wrong
989/// tool: an orphan at a high seq sorts to the front and the window
990/// protects it forever while costing a real generation its slot. Age
991/// decides that case instead.
992///
993/// Best effort and off the critical path: a failure here costs storage,
994/// never correctness, so it warns rather than failing a publish.
995pub async fn sweep_generations(store: &dyn ObjectStore, cfg: &LeanConfig) -> LeanResult<usize> {
996    let Some(lp) = load_pointer(store, cfg).await? else {
997        return Ok(0);
998    };
999    // A chunked pointer names no generation object at all, so there is
1000    // nothing here to keep a window of. Chunks are shared across
1001    // generations and are collected by a different rule entirely
1002    // (chunked design §8.1) — sweeping them by "not named by the live
1003    // pointer" would delete history the window exists to preserve.
1004    let Some(live) = lp.pointer.entries_key else {
1005        // The workspace has MOVED to the chunk layout, so no pointer
1006        // names a generation object any more and every one of them is
1007        // superseded. Collect them past the grace rather than leaking
1008        // the whole pre-migration history forever — a reader still
1009        // resolving one revalidates and restarts (§8.2), and the grace
1010        // covers the window in which it might not have noticed yet.
1011        let prefix = format!("{}/{}/manifests/", cfg.prefix, super::LEAN_DIR);
1012        let now = super::now_unix();
1013        let mut removed = 0;
1014        for o in store.list(&prefix).await? {
1015            let age = o.last_modified_unix.map(|t| now.saturating_sub(t));
1016            if !age.is_some_and(|a| a >= cfg.orphan_grace_secs) {
1017                continue;
1018            }
1019            match store.delete(&o.key).await {
1020                Ok(()) => removed += 1,
1021                Err(e) => eprintln!("flint-sync: could not reap migrated generation {}: {e}", o.key),
1022            }
1023        }
1024        return Ok(removed);
1025    };
1026    let prefix = format!("{}/{}/manifests/", cfg.prefix, super::LEAN_DIR);
1027    let mut listed = store.list(&prefix).await?;
1028    // The key is `<seq:020>-<uuid>`, so lexical order IS generation
1029    // order and a plain sort is enough — the zero padding is doing this
1030    // job, which is why it is there.
1031    listed.sort_by(|a, b| a.key.cmp(&b.key));
1032    let now = super::now_unix();
1033    let live_ix = listed.iter().position(|o| o.key == live);
1034
1035    let mut doomed: Vec<String> = Vec::new();
1036    for (i, o) in listed.iter().enumerate() {
1037        if o.key == live {
1038            continue;
1039        }
1040        match live_ix {
1041            // Newer than the live pointer: in flight, or wreckage.
1042            Some(ix) if i > ix => {
1043                let age = o.last_modified_unix.map(|t| now.saturating_sub(t));
1044                // No timestamp ⇒ leave it. A store that cannot date its
1045                // objects gets a leak, not a deleted live publish.
1046                if age.is_some_and(|a| a > ORPHAN_GRACE_SECS) {
1047                    doomed.push(o.key.clone());
1048                }
1049            }
1050            // Older than the live pointer: superseded. Keep a window — by
1051            // count, and (M1) until the generation that superseded it is
1052            // `retire_grace_secs` old: at one UI save a second, the count
1053            // alone is seconds. No date on the successor ⇒ keep it.
1054            Some(ix) => {
1055                let superseded_for = listed[i + 1].last_modified_unix.map(|t| now.saturating_sub(t));
1056                if ix.saturating_sub(i) > KEEP_GENERATIONS
1057                    && superseded_for.is_some_and(|a| a >= cfg.retire_grace_secs)
1058                {
1059                    doomed.push(o.key.clone());
1060                }
1061            }
1062            // The pointer names an object that is not in the listing.
1063            // `load` already refuses that workspace; sweep nothing.
1064            None => return Ok(0),
1065        }
1066    }
1067    let mut removed = 0;
1068    for k in doomed {
1069        match store.delete(&k).await {
1070            Ok(()) => removed += 1,
1071            Err(e) => eprintln!("flint-sync: could not reap superseded generation {k}: {e}"),
1072        }
1073    }
1074    Ok(removed)
1075}
1076
1077/// Collect chunk objects that no live pointer references.
1078///
1079/// Built to `lean/formal/LeanChunkGC.tla`, which refuted the ordering
1080/// rule the design originally prescribed. Four things carry the safety
1081/// here and each has a mutation config that breaks it alone:
1082///
1083/// 1. **The reference set must not predate a CAS the delete follows.**
1084///    S3 cannot make the read and the delete atomic, so this fences
1085///    instead: the pointer's ETag is read before the listing and again
1086///    after, and the pass ABORTS if it moved. A publish landed, and we
1087///    no longer know whether it references a candidate.
1088/// 2. **A grace.** A chunk written and not yet referenced would
1089///    otherwise be collected out from under its own publish.
1090/// 3. **The grace outlives the longest publish** — a timing
1091///    assumption, which is why `orphan_grace_secs` is config and why
1092///    this comment names it rather than leaving it implied.
1093/// 4. **Adoption rewrites what it adopts** (`cas_write_chunked`), so
1094///    any chunk a concurrent publish could reference is FRESH and the
1095///    grace covers it. Without that rule an adopted orphan is old, and
1096///    the age this reads is a lie about whether it is in use.
1097///
1098/// Deliberately no history window, unlike `sweep_generations`. That
1099/// window existed partly so a reader mid-resolve could finish; readers
1100/// now revalidate against the pointer and restart onto the current
1101/// generation (§8.2), which removes the reason. Adding one back means
1102/// retaining pointer SNAPSHOTS so their chunk sets are enumerable
1103/// (§9) — chunks are shared, so "what the live pointer does not name"
1104/// is the only reference set available without them.
1105pub async fn sweep_chunks(store: &dyn ObjectStore, cfg: &LeanConfig) -> LeanResult<usize> {
1106    sweep_chunks_sparing(store, cfg, &std::collections::HashSet::new()).await
1107}
1108
1109/// `sweep_chunks`, sparing the chunk KEYS a young retire log names (M1):
1110/// a chunk a commit superseded less than `retire_grace_secs` ago, however
1111/// long ago it was written. A reader mid-load of the previous pointer
1112/// finds it.
1113pub async fn sweep_chunks_sparing(
1114    store: &dyn ObjectStore,
1115    cfg: &LeanConfig,
1116    spared: &std::collections::HashSet<String>,
1117) -> LeanResult<usize> {
1118    let Some(before) = load_pointer(store, cfg).await? else {
1119        return Ok(0);
1120    };
1121    let mut refs: std::collections::HashSet<String> = match before.pointer.entries()? {
1122        Entries::Chunked(c) => c.iter().map(|r| r.addr.clone()).collect(),
1123        // The single-object layout has no chunks; `sweep_generations`
1124        // owns it, and running both over one workspace would have each
1125        // reasoning about objects the other manages.
1126        Entries::Single { .. } => return Ok(0),
1127    };
1128    // The tombstone object lives beside the chunks and is referenced
1129    // the same way.
1130    if let Some(t) = &before.pointer.tombstones {
1131        refs.insert(t.clone());
1132    }
1133
1134    let prefix = format!("{}/{}/chunks/", cfg.prefix, super::LEAN_DIR);
1135    let listed = store.list(&prefix).await?;
1136
1137    // THE FENCE (rule 1). Nothing published across the reference read
1138    // and the listing, so the candidates and the references describe
1139    // the same moment. A publish that lands after this still cannot
1140    // lose a chunk: everything it references is either already in
1141    // `refs` or was just written or rewritten, and rule 4 guarantees
1142    // the latter are fresh.
1143    let after = load_pointer(store, cfg).await?;
1144    if after.map(|p| p.etag) != Some(before.etag) {
1145        return Ok(0);
1146    }
1147
1148    let now = super::now_unix();
1149    let mut removed = 0;
1150    for o in listed {
1151        let Some(addr) = o.key.rsplit('/').next() else { continue };
1152        if refs.contains(addr) || spared.contains(&o.key) {
1153            continue;
1154        }
1155        // A candidate the LISTING already shows inside the grace cannot be
1156        // past it on a HEAD taken now: a rewrite only makes an object
1157        // younger, so the listing's age bounds the HEAD's from above.
1158        // Skipping it keeps a chunk longer — a leak, never a deleted live
1159        // chunk — and every deletion still rests on the HEAD below. Without
1160        // this every commit HEADed every chunk superseded within the grace,
1161        // one at a time inside the fence: 700 ms of a 1 s hold after five
1162        // minutes of six writers (contention drill), growing for the hour.
1163        if let Some(listed) = o.last_modified_unix {
1164            if now.saturating_sub(listed) < cfg.orphan_grace_secs {
1165                continue;
1166            }
1167        }
1168        // The age must come from a HEAD taken NOW, never from the
1169        // listing above. That listing predates the fence, and rule 4
1170        // (adoption REWRITES what it adopts) works by refreshing a
1171        // chunk's age — so judging by the listing's timestamp makes
1172        // exactly the refresh that rule exists to produce invisible,
1173        // and the reaper deletes a chunk an in-flight publish is about
1174        // to name. The model computed this against the store's state at
1175        // DELETE time; reading it from a pre-fence snapshot was an
1176        // implementation that did not match the rule it was built to.
1177        //
1178        // One HEAD per CANDIDATE past the grace by the listing, not per
1179        // chunk: a busy workspace supersedes chunks on every publish.
1180        //
1181        // Gone already ⇒ nothing to do. Any other HEAD failure, or no
1182        // timestamp ⇒ leave it: a store that cannot date its objects
1183        // gets a leak, not a deleted live chunk, the same rule
1184        // `sweep_generations` follows and for the same reason.
1185        let fresh = match store.head(&o.key).await {
1186            Ok(m) => m.last_modified_unix,
1187            Err(StoreError::NotFound(_)) => continue,
1188            Err(e) => {
1189                eprintln!("flint-sync: could not date orphan chunk {} ({e}); leaving it", o.key);
1190                continue;
1191            }
1192        };
1193        // `>=`, not `>`: the config value is a DURATION the object must
1194        // have survived, so `orphan_grace_secs = 0` has to mean "no
1195        // grace". With `>` it would silently mean "collect nothing
1196        // written this second", which is most of them — a knob whose
1197        // zero disables the thing it configures is a trap.
1198        let age = fresh.map(|t| now.saturating_sub(t));
1199        if !age.is_some_and(|a| a >= cfg.orphan_grace_secs) {
1200            continue;
1201        }
1202        match store.delete(&o.key).await {
1203            Ok(()) => removed += 1,
1204            Err(e) => eprintln!("flint-sync: could not reap orphan chunk {}: {e}", o.key),
1205        }
1206    }
1207    Ok(removed)
1208}
1209
1210/// The three-way merge (the model's `inst`). Starts from THEIRS so
1211/// foreign entries survive by construction; applies my upserts; applies
1212/// my deletes only where theirs is unchanged since my merge base.
1213///
1214/// **`mine_upserts` and `mine_deletes` must be DISJOINT**, and that is
1215/// the caller's job, not this function's: which one wins depends on
1216/// which the tree saw LAST, and neither set carries that. The fused
1217/// barrier gets it free (both are computed from one scan). Resolving an
1218/// overlap here —
1219/// in either direction — cites a deleted file half the time and
1220/// amputates a live one the other half. TLC found both halves.
1221/// Returns (as `Merged`) the merged document, the foreign entries a consume must
1222/// integrate next (present in theirs, changed vs base, not mine), each
1223/// declared delete's outcome, and the entries MINE PUBLISHES OVER: theirs' version at a path this barrier
1224/// uploaded, changed since the merge base. The slot's 412 used to catch
1225/// those at the PUT; under handles the merge is the one place they show,
1226/// and the caller decides which it never integrated and must surface
1227/// (design 2026-09-19, R7).
1228pub fn merge(
1229    base: &BTreeMap<String, String>,
1230    theirs: &LeanManifest,
1231    mine_upserts: &BTreeMap<String, LeanEntry>,
1232    mine_deletes: &BTreeSet<String>,
1233    parked: &BTreeSet<String>,
1234) -> Merged {
1235    let mut merged = theirs.clone();
1236    merged.seq = theirs.seq + 1;
1237    // Same discipline, and for a sharper reason: inheriting it would
1238    // let a workspace that once published as a mirror keep refusing
1239    // adopts forever, and NOT inheriting it would let a mirror silently
1240    // stop being one the first time anything else wrote a manifest.
1241    // The installing pass sets it from its own config.
1242    merged.sole_writer = false;
1243    merged.boundary_source = None;
1244
1245    let mut foreign: Vec<(String, LeanEntry)> = vec![];
1246    let mut overridden: Vec<(String, LeanEntry)> = vec![];
1247    // The DELETES mine publishes over: a path mine uploads that the merge
1248    // base cited and theirs no longer does. Named by the version the
1249    // delete removed — theirs' tombstone, else the base's citation.
1250    let recreated: Vec<(String, String)> = mine_upserts
1251        .keys()
1252        .filter(|p| !theirs.entries.contains_key(*p))
1253        .filter_map(|p| {
1254            let base_etag = base.get(p)?;
1255            let deleted = theirs.tombstones.get(p).map(|t| t.etag.clone()).unwrap_or_else(|| base_etag.clone());
1256            Some((p.clone(), deleted))
1257        })
1258        .collect();
1259    for (p, e) in &theirs.entries {
1260        let changed = base.get(p).map(|b| b != &e.etag).unwrap_or(true);
1261        if changed && !mine_upserts.contains_key(p) && !parked.contains(p) {
1262            foreign.push((p.clone(), e.clone()));
1263        }
1264        if changed && mine_upserts.contains_key(p) {
1265            overridden.push((p.clone(), e.clone()));
1266        }
1267    }
1268
1269    for (p, e) in mine_upserts {
1270        merged.entries.insert(p.clone(), e.clone());
1271        // A path cited again has no delete to remember.
1272        merged.tombstones.remove(p);
1273    }
1274    let mut deletes = BTreeMap::new();
1275    let mut over_theirs: Vec<(String, LeanEntry)> = vec![];
1276    for p in mine_deletes {
1277        let outcome = delete_outcome(base, theirs, p, parked);
1278        deletes.insert(p.clone(), outcome);
1279        if outcome == DeleteOutcome::OverTheirs {
1280            if let Some(e) = theirs.entries.get(p) {
1281                over_theirs.push((p.clone(), e.clone()));
1282            }
1283        }
1284        if outcome != DeleteOutcome::Parked {
1285            if let Some(retired) = merged.entries.remove(p) {
1286                // H1e: the document says what this delete retired.
1287                merged.tombstones.insert(p.clone(), Tombstone { etag: retired.etag, seq: merged.seq });
1288            }
1289        }
1290    }
1291    merged.tombstones.retain(|_, t| merged.seq.saturating_sub(t.seq) <= TOMBSTONE_KEEP_SEQS);
1292    Merged { doc: merged, foreign, overridden, deletes, recreated, over_theirs }
1293}
1294
1295/// What `merge` returns: the document, and what it decided per path.
1296pub struct Merged {
1297    pub doc: LeanManifest,
1298    /// Entries a consume must integrate next: present in theirs, changed
1299    /// vs base, not mine.
1300    pub foreign: Vec<(String, LeanEntry)>,
1301    /// Theirs' version at a path this barrier uploaded, changed since the
1302    /// merge base (R7).
1303    pub overridden: Vec<(String, LeanEntry)>,
1304    /// Every declared delete, and what the merge did with it.
1305    pub deletes: BTreeMap<String, DeleteOutcome>,
1306    /// The deletes mine publishes over: `(path, the deleted version's
1307    /// etag)` for a path mine uploads that the merge base cited and theirs
1308    /// deleted. Mine wins; the caller records each (the user's rule: a
1309    /// delete over a dirty path lands, with a record).
1310    pub recreated: Vec<(String, String)>,
1311    /// The versions mine DELETES over: theirs at a path this barrier
1312    /// deletes, changed since the merge base (M3, P1-lite). Mine wins; the
1313    /// caller preserves and records each before the collector takes it.
1314    pub over_theirs: Vec<(String, LeanEntry)>,
1315}
1316
1317/// What the merge does with one of my deletes.
1318#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1319pub enum DeleteOutcome {
1320    /// Theirs is unchanged since my merge base, or already gone: the
1321    /// citation goes.
1322    Applied,
1323    /// Theirs moved off my merge base to a version this tree never had
1324    /// (M3, P1-lite): the delete still applies — mine wins — and theirs is
1325    /// preserved and recorded (`Merged::over_theirs`). Before P1-lite theirs
1326    /// stayed cited (outranked), and under a derived owed set that never
1327    /// settles: the tree lacks the path, the document cites theirs, the
1328    /// path is dirty so nothing is owed, and every barrier repeats.
1329    OverTheirs,
1330    /// Withheld this barrier.
1331    Parked,
1332}
1333
1334/// The ONE place a delete's outcome is decided. `merge` applies it, and
1335/// a caller that must know whether an install moves a path off its
1336/// citation asks this with the same base — never re-derives it. Re-deriving
1337/// it is how the repair rule came to read a different base from the merge
1338/// (M5, L-124).
1339pub fn delete_outcome(
1340    base: &BTreeMap<String, String>,
1341    theirs: &LeanManifest,
1342    p: &str,
1343    parked: &BTreeSet<String>,
1344) -> DeleteOutcome {
1345    if parked.contains(p) {
1346        return DeleteOutcome::Parked;
1347    }
1348    match (theirs.entries.get(p), base.get(p)) {
1349        (Some(e), Some(b)) if &e.etag == b => DeleteOutcome::Applied,
1350        // Already deleted by someone else: nothing is left to cite.
1351        (None, _) => DeleteOutcome::Applied,
1352        // Changed since base, or present in theirs and not in base.
1353        (Some(_), _) => DeleteOutcome::OverTheirs,
1354    }
1355}
1356
1357