Skip to main content

flint_lean/
barrier.rs

1//! The publish barrier (plan §2.1, seven steps) — the machine
2//! `lean/formal/LeanSubtree.tla` checks. Order is load-bearing:
3//! consume → scan → intent/window → uploads → manifest CAS (merge) →
4//! GC deletes LAST → baseline rewrite.
5
6use std::collections::{BTreeMap, BTreeSet};
7use std::path::Path;
8
9use bytes::Bytes;
10
11use flint_store::{crc64_nvme, crc64_to_b64, GenerationStamps, PosixStamps, PutCondition, StoreError};
12
13use super::inbox;
14use super::manifest::{self, LeanEntry};
15use super::scan;
16use super::state::{BaselineEntry, Carrier, ConflictRecord, IntentJournal};
17use super::{now_unix, LeanError, LeanResult, Syncer};
18
19/// The last gateway request this workspace acted on, per verb. A
20/// watermark rather than a consumed queue — see `note_verb_requests`.
21#[derive(Debug, Clone, Default, serde::Serialize, serde::Deserialize)]
22pub struct VerbWatermark {
23    #[serde(default)]
24    pub boundary_unix: u64,
25    #[serde(default)]
26    pub sync_unix: u64,
27}
28
29#[derive(Debug, Default)]
30pub struct BarrierReport {
31    pub seq: Option<u64>,
32    pub uploaded: Vec<String>,
33    pub deleted: Vec<String>,
34    /// Paths a DECLARED removal (delete/rename design) cited out this
35    /// barrier — a subset of `deleted` once the GC has run.
36    pub removed: Vec<String>,
37    /// Declared removals this barrier REFUSED (locally dirty, not a
38    /// file, uncontainable); the cell carries the reason.
39    pub removals_refused: usize,
40    pub parked: Vec<String>,
41    pub consumed: usize,
42    pub foreign_queued: usize,
43    /// Paths whose transfer drifted or was swept mid-compose: nothing
44    /// published, nothing advanced; the next scan re-queues them.
45    pub deferred: Vec<String>,
46    /// Paths whose object the collector LEFT BEHIND because this store
47    /// does not enforce `If-Match` on DELETE (`conformance.rs`). The
48    /// delete still reached the boundary; only the object survives.
49    ///
50    /// NOT added to `deleted`, and so NOT dropped from the merge base:
51    /// the rule step 7 follows is "drop the entry once the key no longer
52    /// holds our bytes", which is why the absent and replaced-absent
53    /// arms drop it and the skipped-etag arm does not. A leaked key
54    /// still holds them. The model names that rule
55    /// `BaselineKeepsUncollected` and it is what ships, so a leak
56    /// follows the arm that already exists rather than inventing a
57    /// third; the cost is that the collector re-offers the path (one
58    /// HEAD) at every later barrier, exactly as a skipped one is.
59    pub leaked: Vec<String>,
60    /// Paths this barrier published OVER a version it never integrated;
61    /// each has a conflict record naming the preserved copy (R7).
62    pub surfaced: Vec<String>,
63    /// Retired handles the batch delete took.
64    pub collected: usize,
65    /// Orphan handles the sweep took, when it was due.
66    pub swept: usize,
67    pub no_change: bool,
68    /// Bytes this barrier actually published — the input to the
69    /// sentinel work meter (boundary-verbs plan D3.1). Metering work
70    /// rather than calls is what keeps a sentinel storm from
71    /// un-coalescing a hot large file's republish: a counted budget
72    /// charges a 2 GiB checkpoint the same one unit as a 4 KiB file.
73    pub published_bytes: u64,
74    /// The manifest ETag this barrier installed (the ack's CAS token).
75    pub manifest_etag: Option<String>,
76    /// What the manifest HEAD/install told us the bucket is at, for the
77    /// news ticker (D5) — free, off requests the barrier already made.
78    pub observed_seq: Option<u64>,
79    pub observed_etag: Option<String>,
80    /// Paths this barrier saw absent for the FIRST time: their deletes
81    /// are withheld to the next scan (the rename-vs-walk guard). On a
82    /// declared boundary a non-empty set means the confirmation lstat
83    /// found them back on disk — the race the guard exists for.
84    pub first_absence: Vec<String>,
85    /// First-absence paths a DECLARED boundary confirmed gone by direct
86    /// lstat and published as ordinary deletes (`confirm_absences`).
87    pub absences_confirmed: usize,
88    /// This barrier finished a rescope a crash had left half-applied
89    /// before it did anything else. Reported so a run that looks like
90    /// an ordinary barrier can be told from one that had to converge a
91    /// workspace first.
92    pub rescope_replayed: bool,
93}
94
95/// Upload waves per chunk. The chunk is `fanout * this`, so a wave
96/// still saturates fan-out and the sync point between chunks is rare.
97const UPLOAD_CHUNK_WAVES: usize = 16;
98
99
100impl Syncer {
101    /// Verify the cell still names us at OUR epoch; anything else is a
102    /// fence. Read-verify before the manifest CAS (the per-request
103    /// validation the gateway will also enforce).
104    async fn verify_not_deposed(&self) -> LeanResult<()> {
105        let lease = self
106            .lease
107            .as_ref()
108            .ok_or_else(|| LeanError::State("no lease".into()))?;
109        match self.store.epoch_read(&self.cfg.epoch_key()).await? {
110            Some(state) if state.epoch == lease.epoch && state.holder_id == lease.holder_id => {
111                Ok(())
112            }
113            Some(state) => Err(LeanError::Fenced(format!(
114                "cell at epoch {} holder {} (we are epoch {})",
115                state.epoch, state.holder_id, lease.epoch
116            ))),
117            None => Err(LeanError::Fenced("epoch cell vanished".into())),
118        }
119    }
120
121    /// Step 1 (P1-lite, 2026-09-25): what the tree is OWED, derived from
122    /// the document and taken in one pass. A path is owed where the
123    /// document differs from the baseline — which is also the merge base —
124    /// and the tree is clean there; only a path the tree HOLDS or its
125    /// scope covers (what the scope declined stays declined). Nothing is
126    /// stored between deriving it and taking it, so nothing can be
127    /// overtaken: the queue this replaces needed a prune for that (L-123).
128    /// A DIRTY path is the agent's newer work and is not owed: it
129    /// publishes, and the merge records what it publishes over (R7, the
130    /// delete override). Unless its bytes already ARE the document's —
131    /// a restart between this writer's CAS and step 7 leaves exactly
132    /// that — and then the baseline simply follows (content convergence).
133    /// Returns how many paths it took, and the pointer's (seq, etag) as it
134    /// read them — the barrier's fast path needs exactly that, and must not
135    /// pay a second GET for it (an idle tick is the cell and the pointer).
136    pub async fn consume_owed(&mut self) -> LeanResult<(usize, Option<(u64, String)>)> {
137        let mut baseline = self.state.load_baseline()?;
138        // THE CHEAP PATH (scan trigger). Only three things make a path
139        // newly owed: the document moved (the pointer is not the one last
140        // derived against — a peer, a UI save, or this tree's own commit
141        // over a document that had moved), the baseline moved (only this
142        // tree's own commit, which moves the pointer too), or the agent
143        // backed out of a path the last derive skipped as its work. So: one
144        // small GET, a stat per skipped path, never the entries.
145        if let Some(d) = baseline.derived_etag.clone() {
146            if let Some(p) = manifest::load_pointer(self.store.as_ref(), &self.cfg).await? {
147                let still_theirs = baseline.skipped.iter().all(|path| {
148                    check_contained(&self.cfg.root, path).is_ok()
149                        && local_dirty(&self.cfg.root.join(path), baseline.entries.get(path))
150                });
151                if d == p.etag && still_theirs {
152                    return Ok((0, Some((p.pointer.seq, p.etag))));
153                }
154            }
155        }
156        let Some(current) = manifest::load(self.store.as_ref(), &self.cfg).await? else {
157            return Ok((0, None));
158        };
159        let doc = &current.manifest;
160        // H10: whatever this barrier does next — the fast path included —
161        // the ack names this document or a later one.
162        self.note_carrier_uncited(doc)?;
163        let scope = self.state.load_scope()?.map(|v| super::sync::Scope::new(&v));
164        let same = |a: &str, b: &str| a.trim_matches('"') == b.trim_matches('"');
165        let mut taken = 0usize;
166        // Something owed could not be taken now (a fetch that lost to a
167        // newer document, an unreadable path, a failed write): the next
168        // consume derives again even if the pointer does not move.
169        let mut left = false;
170        // What is not owed because the agent is working on it: owed the
171        // moment it backs out, which the cheap path checks.
172        let mut skipped: BTreeSet<String> = BTreeSet::new();
173
174        // Deletions first: a document that turned the file `build` into
175        // the directory `build/log.txt` owes both, and the file must go
176        // before the directory can be made.
177        let gone: Vec<String> =
178            baseline.entries.keys().filter(|p| !doc.entries.contains_key(*p)).cloned().collect();
179        for path in gone {
180            if check_contained(&self.cfg.root, &path).is_err() {
181                // Never materializable here, so nothing to remove.
182                baseline.entries.remove(&path);
183                baseline.prev_scan.remove(&path);
184                continue;
185            }
186            let local = self.cfg.root.join(&path);
187            let be = baseline.entries.get(&path).cloned();
188            let record = |kind: String| ConflictRecord {
189                path: path.clone(),
190                foreign_etag: String::new(),
191                preserved_key: None,
192                kind,
193                at_unix: now_unix(),
194            };
195            match std::fs::symlink_metadata(&local) {
196                Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
197                    self.trace("tombstone", serde_json::json!({"path": path, "action": "absent"}));
198                }
199                Err(e) => {
200                    // Unreadable is not absent.
201                    self.trace("tombstone", serde_json::json!({"path": path, "action": "deferred"}));
202                    self.state.append_conflict(&record(format!(
203                        "consume-foreign-delete-deferred: cannot stat the path: {e}"
204                    )))?;
205                    left = true;
206                    continue;
207                }
208                Ok(m) if !m.is_file() || local_dirty(&local, be.as_ref()) => {
209                    // The agent's newer work: not owed. It publishes over
210                    // the delete, with a record (`commit-recreated-deleted`).
211                    // Owed again if the agent backs out.
212                    self.trace("tombstone", serde_json::json!({"path": path, "action": "kept-dirty"}));
213                    skipped.insert(path.clone());
214                    continue;
215                }
216                Ok(_) => {
217                    if let Err(e) = std::fs::remove_file(&local) {
218                        self.state.append_conflict(&record(format!(
219                            "consume-foreign-delete-failed (will retry): {e}"
220                        )))?;
221                        left = true;
222                        continue;
223                    }
224                    // CONFIRM: only NotFound is absence.
225                    if !matches!(
226                        std::fs::symlink_metadata(&local),
227                        Err(ref e) if e.kind() == std::io::ErrorKind::NotFound
228                    ) {
229                        self.state.append_conflict(&record(
230                            "consume-foreign-delete-unconfirmed (will retry)".into(),
231                        ))?;
232                        left = true;
233                        continue;
234                    }
235                    self.trace("tombstone", serde_json::json!({"path": path, "action": "removed"}));
236                    taken += 1;
237                }
238            }
239            baseline.entries.remove(&path);
240            baseline.prev_scan.remove(&path);
241        }
242
243        for (path, e) in &doc.entries {
244            let be = baseline.entries.get(path).cloned();
245            if be.as_ref().is_some_and(|b| same(&b.etag, &e.etag)) {
246                continue;
247            }
248            let held = be.is_some() || scope.as_ref().is_none_or(|s| s.covers(path));
249            if !held {
250                continue;
251            }
252            if let Err(err) = check_contained(&self.cfg.root, path) {
253                // A path this tree can never safely materialise: surfaced,
254                // and not left owed — nothing here will ever take it.
255                self.state.append_conflict(&ConflictRecord {
256                    path: path.clone(),
257                    foreign_etag: e.etag.clone(),
258                    preserved_key: None,
259                    kind: format!("consume-refused-containment: {err}"),
260                    at_unix: now_unix(),
261                })?;
262                self.trace("consume", serde_json::json!({"path": path, "etag": e.etag, "from": "manifest", "action": "refused"}));
263                continue;
264            }
265            let local = self.cfg.root.join(path);
266            if local_dirty(&local, be.as_ref()) {
267                // CONTENT CONVERGENCE: the tree's bytes are the document's.
268                let converged = std::fs::symlink_metadata(&local).is_ok_and(|m| m.is_file() && m.len() == e.size)
269                    && file_crc(&self.cfg.root, path).is_ok_and(|c| same(&crc64_to_b64(c), &e.crc64_b64));
270                if converged {
271                    let st = std::fs::metadata(&local)?;
272                    baseline.entries.insert(
273                        path.clone(),
274                        BaselineEntry {
275                            etag: e.etag.clone(),
276                            key: Some(e.key.clone()),
277                            generation: e.generation,
278                            size: st.len(),
279                            mtime_unix: mtime_of(&st),
280                            mtime_nanos: Some(mtime_nanos_of(&st)),
281                            crc64_b64: Some(e.crc64_b64.clone()),
282                        },
283                    );
284                    baseline.prev_scan.insert(path.clone());
285                    self.trace("consume", serde_json::json!({"path": path, "etag": e.etag, "from": "manifest", "action": "converged"}));
286                    taken += 1;
287                } else {
288                    // The agent's work, not owed — until it backs out.
289                    skipped.insert(path.clone());
290                }
291                continue;
292            }
293            let (meta, body) = match self.store.get_whole(&e.key, Some(&e.etag)).await {
294                Ok(got) => got,
295                // A newer document replaced it (and its collector took the
296                // handle): owed again against that one.
297                Err(StoreError::NotFound(_)) | Err(StoreError::PreconditionFailed(_)) => {
298                    self.trace("consume", serde_json::json!({"path": path, "etag": e.etag, "from": "manifest", "action": "missing"}));
299                    left = true;
300                    continue;
301                }
302                Err(err) => return Err(err.into()),
303            };
304            // VERIFIED before it is written, as checkout's fetch is: against
305            // the CRC the document cites, else the backend's attestation.
306            let got = crc64_to_b64(crc64_nvme(&body));
307            let want = Some(e.crc64_b64.clone()).filter(|c| !c.is_empty()).or_else(|| meta.crc64_b64.clone());
308            if let Some(want) = want {
309                if want != got {
310                    self.state.append_conflict(&ConflictRecord {
311                        path: path.clone(),
312                        foreign_etag: e.etag.clone(),
313                        preserved_key: None,
314                        kind: format!(
315                            "consume-refused-checksum: etag {} is cited with CRC-64 {want} but the \
316                             bytes fetched under it hash to {got}",
317                            e.etag
318                        ),
319                        at_unix: now_unix(),
320                    })?;
321                    self.trace("consume", serde_json::json!({"path": path, "etag": e.etag, "from": "manifest", "action": "refused-checksum"}));
322                    left = true;
323                    continue;
324                }
325            }
326            let mode = PosixStamps::from_meta(&meta.meta).map(|p| p.mode);
327            consume_window("before-write", path);
328            // H7: the licence to overwrite is re-checked with the temp
329            // written, immediately before the rename; a write since is the
330            // agent's, and it stays (and publishes).
331            let still_clean = || !local_dirty(&local, be.as_ref());
332            let st = match contained_path(&self.cfg.root, path)
333                .and_then(|target| write_file_atomic_if(&target, &body, mode, &still_clean))
334            {
335                Ok(Some(st)) => st,
336                // The agent wrote first: as a dirty path above.
337                Ok(None) => {
338                    skipped.insert(path.clone());
339                    continue;
340                }
341                Err(err) => {
342                    // TRANSIENT (a full disk is not a planted symlink): the
343                    // path stays owed and the record repeats.
344                    self.state.append_conflict(&ConflictRecord {
345                        path: path.clone(),
346                        foreign_etag: e.etag.clone(),
347                        preserved_key: None,
348                        kind: format!("consume-write-failed (will retry): {err}"),
349                        at_unix: now_unix(),
350                    })?;
351                    self.trace("consume", serde_json::json!({"path": path, "etag": e.etag, "from": "manifest", "action": "deferred"}));
352                    left = true;
353                    continue;
354                }
355            };
356            consume_window("after-rename", path);
357            // The baseline records the inode this consume WROTE (H7).
358            let stamps = GenerationStamps::from_meta(&meta.meta);
359            baseline.entries.insert(
360                path.clone(),
361                BaselineEntry {
362                    etag: meta.etag.clone(),
363                    key: Some(e.key.clone()),
364                    generation: stamps.map(|s| s.generation).unwrap_or(e.generation),
365                    size: st.len(),
366                    mtime_unix: mtime_of(&st),
367                    mtime_nanos: Some(mtime_nanos_of(&st)),
368                    crc64_b64: Some(got),
369                },
370            );
371            baseline.prev_scan.insert(path.clone());
372            self.trace("consume", serde_json::json!({"path": path, "etag": e.etag, "from": "manifest", "action": "adopted"}));
373            taken += 1;
374        }
375        baseline.derived_etag = (!left).then(|| current.etag.clone());
376        baseline.skipped = skipped;
377        if !left {
378            // Everything owed is taken: the tree is integrated with this
379            // document (its dirty paths are the agent's, about to publish).
380            baseline.seq = doc.seq;
381            baseline.manifest_etag = Some(current.etag.clone());
382        }
383        // The files this baseline vouches for reached the disk before the
384        // baseline does (audit 2026-09-03, finding 9).
385        self.state.sync_tree()?;
386        self.state.save_baseline(&baseline)?;
387        // The pointer as this load saw it (a legacy single object has none,
388        // and the fast path asks the bucket itself).
389        let seen = current.pointer.as_ref().map(|_| (doc.seq, current.etag.clone()));
390        Ok((taken, seen))
391    }
392
393    /// The cell's verb requests alone (§2.5), as a barrier's step 1 reads
394    /// them: no consume, no fetch.
395    pub async fn read_cell_requests(&mut self) -> LeanResult<()> {
396        let doc = inbox::load(self.store.as_ref(), &self.cfg).await?.doc;
397        self.note_verb_requests(&doc)
398    }
399
400    /// Act on the inbox document's two request fields (§2.5, D14).
401    ///
402    /// The asymmetry is deliberate and is about blast radius, not
403    /// principle: a boundary request is PERFORMED (it publishes what is
404    /// already on disk and mutates nothing local), a sync request is
405    /// CARRIED into the ticker as advisory news and the agent decides.
406    ///
407    /// Both are watermarked by `requested_unix` rather than consumed by
408    /// a clearing CAS. The field is idempotent state, so a repeat is a
409    /// no-op and a lost clear cannot double-publish; and not writing
410    /// means the doors cost no request at all, which is what §2.5
411    /// promises.
412    fn note_verb_requests(&mut self, doc: &inbox::InboxDoc) -> LeanResult<()> {
413        let mut mark = self.load_verb_watermark()?;
414        if let Some(r) = &doc.sync_request {
415            if r.requested_unix > mark.sync_unix {
416                self.carry_sync_request(r.requested_unix, &r.requestor)?;
417                mark.sync_unix = r.requested_unix;
418            }
419        }
420        if let Some(r) = &doc.boundary_request {
421            if r.requested_unix > mark.boundary_unix {
422                self.request_boundary(
423                    &format!("gw:{}:{}", r.requested_unix, r.requestor),
424                    Some(format!("boundary requested by {}", r.requestor)),
425                )?;
426                mark.boundary_unix = r.requested_unix;
427            }
428        }
429        self.save_verb_watermark(&mark)
430    }
431
432    fn verb_watermark_path(&self) -> std::path::PathBuf {
433        self.cfg.state_dir().join("verb-requests.json")
434    }
435
436    pub(crate) fn load_verb_watermark(&self) -> LeanResult<VerbWatermark> {
437        let p = self.verb_watermark_path();
438        if !p.exists() {
439            return Ok(VerbWatermark::default());
440        }
441        Ok(std::fs::read(&p)
442            .ok()
443            .and_then(|b| serde_json::from_slice(&b).ok())
444            .unwrap_or_default())
445    }
446
447    fn save_verb_watermark(&self, m: &VerbWatermark) -> LeanResult<()> {
448        let bytes = serde_json::to_vec_pretty(m)
449            .map_err(|e| LeanError::State(format!("verb watermark: {e}")))?;
450        super::control::write_atomic(&self.verb_watermark_path(), &bytes)
451    }
452
453    /// The consume's dirty case: the agent's local version wins; the
454    /// FOREIGN bytes are preserved first (a conflict record keeps both
455    /// recoverable), then the recognized ETag advances so the eventual
456    /// publish supersedes them KNOWINGLY.
457    /// Preserve the bytes at `key` (a handle, or an ingress object) under
458    /// `conflicts/<uuid>/<path>`, by a server-side copy guarded on `etag`:
459    /// no bytes cross this process, and a 10 GB checkpoint is preserved
460    /// in one request. The copy is what a conflict record names, and what
461    /// outlives the handle once the collector or the orphan sweep takes it.
462    async fn preserve_conflict_copy(&self, path: &str, key: &str, etag: &str) -> LeanResult<String> {
463        let dst = self.cfg.conflict_key(&uuid::Uuid::new_v4().to_string(), path);
464        let stamps = GenerationStamps {
465            generation: 0,
466            epoch: self
467                .lease
468                .as_ref()
469                .map(|l| l.epoch)
470                .or_else(|| self.state.load_incarnation().ok().flatten().map(|i| i.epoch))
471                .unwrap_or(0),
472            flush_uuid: "conflict-preserve".into(),
473            boundary_source: None,
474            posix: None,
475        };
476        self.store
477            .copy_object(key, Some(etag), &dst, &PutCondition::IfNoneMatchAny, &stamps)
478            .await?;
479        Ok(dst)
480    }
481
482    /// Take the SECOND absence observation now, by direct `lstat`.
483    ///
484    /// `scan::classify` withholds a path's delete until absence has
485    /// survived two consecutive scans — the rename-vs-walk race guard
486    /// (`lib.rs:37`). The hazard that rule names is the WALK missing a
487    /// file renamed under it, not deletion itself. On the cadence path
488    /// the second walk arrives at the next floor tick and nobody has
489    /// been promised otherwise. On a DECLARED boundary it cannot wait:
490    /// the ack would claim a coherent point (D1 — "everything
491    /// ordered-before T") while the manifest still cites a file the
492    /// agent removed before it touched the sentinel, and it would say
493    /// so with `report.deleted: 0` and `status: "ok"`.
494    ///
495    /// A direct `lstat` is exactly what the rename-vs-walk guard asks
496    /// for and is immune to the walk race by construction, so the
497    /// second observation costs one syscall per transiently-absent
498    /// path — never a second full pass. The cadence path is unchanged
499    /// and still waits for the second walk.
500    pub(crate) fn confirm_absences(&self, classified: &mut scan::Classified) -> LeanResult<usize> {
501        if classified.first_absence.is_empty() {
502            return Ok(0);
503        }
504        let mut confirmed = 0;
505        for path in std::mem::take(&mut classified.first_absence) {
506            // ONLY NotFound is absence. Every other errno — EACCES on a
507            // parent, EIO, EMFILE, ELOOP — used to read as "the agent
508            // deleted it", and this is the oracle that PUBLISHES the
509            // delete and then DELETES THE OBJECT. An unreadable file is
510            // the one case where guessing is unrecoverable, so it fails
511            // CLOSED, exactly as the walk does at `scan.rs`'s
512            // `symlink_metadata(&path)?`. Two call sites, one syscall:
513            // they must not have opposite error policies.
514            let gone = match std::fs::symlink_metadata(self.cfg.root.join(&path)) {
515                Err(e) if e.kind() == std::io::ErrorKind::NotFound => true,
516                Err(e) => {
517                    classified.first_absence.insert(path.clone());
518                    return Err(LeanError::State(format!(
519                        "cannot confirm the absence of {path:?}: {e} — refusing to publish \
520                         a deletion on an unreadable path"
521                    )));
522                }
523                Ok(_) => false,
524            };
525            if gone {
526                classified.deletes.insert(path);
527                confirmed += 1;
528            } else {
529                // Back on disk: the rename-vs-walk race, caught exactly
530                // as the rule intends. Still only a first absence.
531                classified.first_absence.insert(path);
532            }
533        }
534        Ok(confirmed)
535    }
536
537    /// Steps 2–7. `barrier` = one full publish cycle (the cadence arm).
538    pub async fn run_barrier(&mut self) -> LeanResult<BarrierReport> {
539        self.barrier_inner(false, "manual").await
540    }
541
542    /// The floor tick's barrier. Stamped `cadence` so the bucket can
543    /// answer "which clock installed this boundary?" without the ack —
544    /// the ack is a LOCAL file, and the fleet-visible question is asked
545    /// by operators and by the gateway's `/status`, neither of which
546    /// can see it.
547    pub async fn cadence_barrier(&mut self) -> LeanResult<BarrierReport> {
548        self.barrier_inner(false, "cadence").await
549    }
550
551    /// A barrier whose result somebody is going to ACK: a sentinel
552    /// honor (D1) or the preStop drain (D10). Identical to
553    /// `run_barrier` except that it confirms first-absence paths rather
554    /// than acking a boundary that withholds them.
555    pub async fn declared_barrier(&mut self) -> LeanResult<BarrierReport> {
556        self.barrier_inner(true, "sentinel").await
557    }
558
559    /// `declared_barrier` under an explicit provenance stamp — the
560    /// drain and the budget-deferred honor are the same barrier
561    /// reporting a different clock.
562    pub async fn declared_barrier_as(&mut self, source: &str) -> LeanResult<BarrierReport> {
563        self.barrier_inner(true, source).await
564    }
565
566    async fn barrier_inner(&mut self, declared: bool, source: &str) -> LeanResult<BarrierReport> {
567        // Every publishing path ends here — cadence, sentinel, drain, the
568        // one-shot verb — so a reader is refused here before the first
569        // request, whichever of them a caller reached. The callers that
570        // owe an answer (the publish sentinel, the drain) give it before
571        // this; this is the backstop for the ones that do not.
572        self.refuse_if_read("barrier")?;
573        // Review 2026-09-18, H10: a barrier that begins while a publish
574        // declaration stands CARRIES it, whoever called — the floor's
575        // cadence barrier after a failed honor as much as the honor itself
576        // (the model's `DSet` and `InstallSource` read the live pending,
577        // not the caller). So it confirms first absences as a declared
578        // barrier does, stamps the deferred clock, and journals itself
579        // with its CAS as the install the ack names (`IntentJournal::
580        // carrier`). A torn record has no id and carries nothing.
581        let carries: Option<String> = self
582            .load_pending(super::sentinel::Verb::Publish)
583            .ok()
584            .flatten()
585            .map(|p| p.id)
586            .filter(|id| !id.is_empty());
587        let declared = declared || carries.is_some();
588        let source = if carries.is_some() && source == "cadence" { "sentinel-deferred" } else { source };
589        // No lease is held until the commit section (design 2026-09-13
590        // §4): the consume, the scan and the uploads below run with the
591        // cell at rest, guarded by each object's own etag. What the
592        // uploads are STAMPED with is the last epoch this incarnation
593        // held — informational, like every epoch stamp on an object; the
594        // manifest entries carry the commit section's real epoch.
595        let epoch_hint = self.state.load_incarnation()?.map(|i| i.epoch).unwrap_or(0);
596        let mut report = BarrierReport::default();
597        let barrier_started = std::time::Instant::now();
598        self.trace("barrier_start", serde_json::json!({"source": source, "declared": declared}));
599
600        // STEP 0: finish any rescope a crash left half-applied, before
601        // the scan reads the tree (scoped-read design §4.3). This is the
602        // gate that makes the narrow verb safe at all: a half-applied
603        // narrow is a tree whose files and whose citations disagree, and
604        // `classify` reads that disagreement as an upload or as a
605        // DELETE depending on which half landed. Replay is idempotent,
606        // so the cost on the normal path is one `stat` of a file that
607        // is not there.
608        if let Some(r) = self.replay_scope_intent().await? {
609            report.rescope_replayed = true;
610            eprintln!(
611                "flint-sync: finished an interrupted rescope before the barrier \
612                 (uncited {}, unlinked {}, materialised {})",
613                r.uncited, r.unlinked, r.materialized
614            );
615        }
616
617        // Step 1: the cell's verb requests (§2.5's doors ride this GET), then
618        // what the tree is owed. A UI save, delete or rename COMMITS (P2), so
619        // it reaches the tree as a peer's change does: derived, not queued.
620        let inbox_doc = inbox::load(self.store.as_ref(), &self.cfg).await?.doc;
621        // A failure here must never fail the barrier: the request is
622        // idempotent state and the next tick re-reads it.
623        if let Err(e) = self.note_verb_requests(&inbox_doc) {
624            eprintln!("flint-sync: verb request not consumed (retrying next tick): {e}");
625        }
626        let (consumed, seen_pointer) = self.consume_owed().await?;
627        report.consumed = consumed;
628        // The agent runs alongside: what it does to the tree between the
629        // removal pass above and the scan below is the model's interleaving
630        // of a local edit between Consume and Scan (the rename world's
631        // tenth box run reached its counterexample through it). A test
632        // window, like the consume's (H7); nothing in it calls the store.
633        consume_window("before-scan", "");
634        // Step 2: scan-diff against the persisted baseline.
635        let mut baseline = self.state.load_baseline()?;
636        let scanned = scan::scan(&self.cfg.root)?;
637        let mut classified = scan::classify(&scanned, &baseline);
638        if declared {
639            report.absences_confirmed = self.confirm_absences(&mut classified)?;
640        }
641        report.first_absence = classified.first_absence.iter().cloned().collect();
642
643        // Skip-on-no-diff: nothing local, and the bucket manifest where the
644        // consume left it.
645        if classified.uploads.is_empty()
646            && classified.deletes.is_empty()
647            && classified.first_absence.is_empty()
648        {
649            // Read the POINTER, never the entries: the 0b rig measured
650            // the idle tick at 1M entries as 27 s / 1.3 GiB — dominated
651            // by fetching and parsing a 264 MiB document just to read
652            // `seq`. The pointer is a few hundred bytes and carries the
653            // seq in its body, so a GET of it costs one round trip and
654            // answers strictly more than a HEAD of the old object did.
655            //
656            // Legacy workspaces (no pointer yet) keep the HEAD they had.
657            let pointer = match seen_pointer {
658                // The consume just read it: no second GET.
659                Some((seq, etag)) => Some((seq, etag)),
660                None => manifest::load_pointer(self.store.as_ref(), &self.cfg).await?.map(|l| (l.pointer.seq, l.etag)),
661            };
662            let unchanged = match pointer {
663                Some((seq, etag)) => {
664                    // The news ticker rides this request for free — D5's
665                    // "zero added bucket requests" is still literal.
666                    report.observed_seq = Some(seq);
667                    report.observed_etag = Some(etag.clone());
668                    baseline.manifest_etag.as_deref() == Some(etag.as_str())
669                }
670                None => match self.store.head(&self.cfg.manifest_key()).await {
671                    Ok(meta) => {
672                        report.observed_seq =
673                            GenerationStamps::from_meta(&meta.meta).map(|s| s.generation);
674                        report.observed_etag = Some(meta.etag.clone());
675                        baseline.manifest_etag.as_deref() == Some(meta.etag.as_str())
676                    }
677                    Err(StoreError::NotFound(_)) => baseline.manifest_etag.is_none(),
678                    Err(e) => return Err(e.into()),
679                },
680            };
681            if unchanged {
682                report.no_change = true;
683                report.seq = Some(baseline.seq);
684                // prev_scan still advances (the two-scan rule's clock) —
685                // but the baseline document (hundreds of MB at 1M
686                // entries) is rewritten only when the scan SET moved.
687                // Compare without building the set: both sides iterate
688                // sorted, and the allocation this used to make was the
689                // size of the very document it was trying not to write.
690                if scanned.len() != baseline.prev_scan.len()
691                    || !scanned.keys().eq(baseline.prev_scan.iter())
692                {
693                    baseline.prev_scan = scanned.keys().cloned().collect();
694                    self.state.save_baseline(&baseline)?;
695                }
696                self.trace_barrier_end(&report, barrier_started);
697                return Ok(report);
698            }
699        }
700
701        // Step 3: intent journal, then the window (the commitment
702        // point: the same CAS drops the consumed entries).
703        let flush_uuid = uuid::Uuid::new_v4().to_string();
704        self.trace("scan", serde_json::json!({"flush": flush_uuid, "uploads": classified.uploads.len(),
705            "deletes": classified.deletes.len(), "first_absence": classified.first_absence.len()}));
706        let mut intent = self.state.load_intent()?;
707        intent = IntentJournal { flush_uuid: flush_uuid.clone(), carrier: intent.carrier.clone() };
708        self.state.save_intent(&intent)?;
709        // No window (P2): a UI save commits without the lease, and the
710        // uploads below race it the way two writers race each other —
711        // the commit's CAS decides, and the loser is preserved and
712        // recorded.
713
714        // Step 4: guarded uploads, fanned out under a bounded window
715        // (each key's guard chain is independent; the 412 policy and
716        // conflict records are applied to the collected results below,
717        // in deterministic path order).
718        let mut upserts: BTreeMap<String, LeanEntry> = BTreeMap::new();
719        let mut parked: BTreeSet<String> = BTreeSet::new();
720        // Citations whose etag was observed with no lease held (adopted
721        // uploads, citation repairs): re-read inside the commit section.
722        let mut observed: BTreeSet<String> = BTreeSet::new();
723        let mut new_baseline_entries: BTreeMap<String, BaselineEntry> = BTreeMap::new();
724        let outcomes: Vec<(String, LeanResult<UploadOutcome>)> = {
725            use futures::stream::{self, StreamExt};
726            // CHUNKED into waves, so a wave's outcomes are collected
727            // before the next is fanned out. No lease is held here
728            // (design 2026-09-13 §4), so nothing renews or fences
729            // between chunks any more — the between-chunk fence that
730            // stopped a deposed straggler's PUTs went with the straggler:
731            // a PUT outside the lease is one legitimate writer's PUT,
732            // guarded by If-Match, and a collision is preserved and
733            // superseded, never silently overwritten.
734            let mut outcomes: Vec<(String, LeanResult<UploadOutcome>)> = Vec::new();
735            // NOT cfg.fanout. That knob was raised to 128 for the READ
736            // path, and the read-side measurement (2.5x on 20k small
737            // files) says nothing about this one, so uploads keep the
738            // value they were measured at until someone measures them.
739            // Memory is no longer the reason they are separate: this
740            // path is byte-bounded too now, by the store's gate
741            // (`with_upload_inflight_max_bytes`), which charges every
742            // whole body below and every multipart part inside the
743            // store from before its read until its PUT returns.
744            let fanout = self.cfg.upload_fanout.max(1);
745            let chunk = fanout.saturating_mul(UPLOAD_CHUNK_WAVES).max(1);
746            let all: Vec<&String> = classified.uploads.iter().collect();
747            for group in all.chunks(chunk) {
748                {
749                    let this: &Syncer = &*self;
750                    let mut part: Vec<(String, LeanResult<UploadOutcome>)> =
751                        stream::iter(group.iter().map(|path| {
752                            let path = *path;
753                            let scanned_entry = &scanned[path];
754                            let base = baseline.entries.get(path);
755                            let flush_uuid = &flush_uuid;
756                            async move {
757                                let r = this
758                                    .upload_one(path, scanned_entry, base, epoch_hint, flush_uuid)
759                                    .await;
760                                (path.clone(), r)
761                            }
762                        }))
763                        .buffer_unordered(fanout)
764                        .collect()
765                        .await;
766                    outcomes.append(&mut part);
767                }
768            }
769            outcomes
770        };
771        let mut outcomes = outcomes;
772        outcomes.sort_by(|a, b| a.0.cmp(&b.0));
773        for (path, outcome) in outcomes {
774            let path = &path;
775            match outcome? {
776                UploadOutcome::Published { entry, baseline_entry, adopted } => {
777                    self.trace("upload", serde_json::json!({"flush": flush_uuid, "path": path, "etag": entry.etag,
778                        "key": entry.key, "outcome": if adopted { "adopted" } else { "put" }}));
779                    if adopted {
780                        observed.insert(path.clone());
781                    }
782                    report.published_bytes += entry.size;
783                    upserts.insert(path.clone(), entry);
784                    new_baseline_entries.insert(path.clone(), baseline_entry);
785                    report.uploaded.push(path.clone());
786                }
787                UploadOutcome::Deferred => {
788                    self.trace("upload", serde_json::json!({"flush": flush_uuid, "path": path, "outcome": "deferred"}));
789                    report.deferred.push(path.clone());
790                }
791            }
792        }
793
794        // A PULL-ONLY boundary: nothing uploaded or deleted, so the merge
795        // can only add nothing — and then the commit section writes nothing
796        // to the bucket (no CAS, no GC) and what remains is local: note what
797        // theirs owes this tree and take its seq. That needs no
798        // fence and no window; claiming for it queued every such writer
799        // behind the publishing ones (65 of 191 claims in the writers drill).
800        // A merge that does add something (a mirror flag to restamp, say)
801        // falls through to the commit section.
802        if classified.uploads.is_empty()
803            && classified.deletes.is_empty()
804            && upserts.is_empty()
805            && observed.is_empty()
806        {
807            let current = manifest::load(self.store.as_ref(), &self.cfg).await?;
808            let m = self.merge_onto(
809                current.as_ref(),
810                &merge_base(&baseline),
811                &upserts,
812                &classified.deletes,
813                &parked,
814                &flush_uuid,
815            );
816            if let Some(handle) = m.expected.as_ref().filter(|_| m.adds_nothing()) {
817                // What theirs changed at a path this tree holds is owed: the
818                // next consume derives it, because theirs is not the document
819                // it last derived against (or is, and there is nothing).
820                self.note_carrier_uncited(&m.theirs)?;
821                report.seq = Some(m.theirs.seq);
822                report.no_change = true;
823                report.manifest_etag = Some(handle.etag.clone());
824                report.observed_seq = Some(m.theirs.seq);
825                report.observed_etag = Some(handle.etag.clone());
826                report.foreign_queued = m.foreign.len();
827                baseline.seq = m.theirs.seq;
828                baseline.manifest_etag = Some(handle.etag.clone());
829                baseline.prev_scan = scanned.keys().cloned().collect();
830                self.state.save_baseline(&baseline)?;
831                self.state.clear_intent_keys()?;
832                self.trace_barrier_end(&report, barrier_started);
833                return Ok(report);
834            }
835        }
836
837        // THE COMMIT SECTION (design 2026-09-13 §4). Everything above ran
838        // with no lease: the uploads are durable and etag-guarded, and
839        // nothing is cited yet. Claim the cell now — for the merge, the
840        // CAS, the deletes and the baseline — and hand it to the next
841        // waiter when done. This is the only stretch two writers of one
842        // workspace serialise on, and it is small: one pointer CAS and
843        // the guarded deletes, milliseconds to seconds, never the upload
844        // of a checkpoint.
845        let held = super::lease::claim(self).await?;
846        let epoch = held.epoch;
847        eprintln!("flint-sync: publish fence held (epoch {epoch})");
848        if self.cfg.drill_hold_commit_secs > 0 {
849            eprintln!(
850                "flint-sync: DRILL: holding the fence for {}s inside the commit section",
851                self.cfg.drill_hold_commit_secs
852            );
853            tokio::time::sleep(std::time::Duration::from_secs(self.cfg.drill_hold_commit_secs)).await;
854        }
855        let commit: LeanResult<()> = async {
856            // The entries carry the epoch the commit HOLDS, not the hint
857            // the uploads were stamped with.
858            for e in upserts.values_mut() {
859                e.epoch = epoch;
860            }
861            // Step 5: the manifest CAS (three-way merge; bounded retries).
862            // The cell is read after each manifest load below, not here: a
863            // read here preceded the HEAD fan-out and the window, and a
864            // holder deposed after it CASed onto its successor's document
865            // (review 2026-09-18, H2).
866            // EVERY citation this barrier adds was read or written with no
867            // lease held. Another writer's commit may since have uncited
868            // the path and collected the object: its GC deletes by the etag
869            // it integrated. That etag names an ADOPTED object (the model's
870            // LeanBarrierLeaseAdoptBlind) — and, since an S3 whole-PUT etag
871            // is the MD5 of the bytes, it also names this barrier's own PUT
872            // of IDENTICAL bytes (finding 13, the writers drill's A3: a
873            // same-content rewrite re-uploaded, the peer's GC deleted it,
874            // the commit cited a hole). Collection runs only inside a
875            // commit section, so a re-read HERE, holding the fence, cannot
876            // be overtaken before this CAS — held, that is, until the read
877            // of the cell after the load: a deposal before it is seen
878            // there, and after it the successor's rotation moves the
879            // pointer the CAS expects (H2). Whatever is gone or replaced is
880            // withheld: parked, recorded, and left dirty for the next
881            // barrier to publish with a PUT of its own.
882            let heads: Vec<(String, LeanResult<bool>)> = {
883                use futures::stream::{self, StreamExt};
884                let this: &Syncer = &*self;
885                stream::iter(upserts.iter().map(|(path, cited)| async move {
886                    let still = match this.store.head(&cited.key).await {
887                        Ok(meta) => Ok(meta.etag == cited.etag),
888                        Err(StoreError::NotFound(_)) => Ok(false),
889                        Err(e) => Err(e.into()),
890                    };
891                    (path.clone(), still)
892                }))
893                .buffer_unordered(self.cfg.upload_fanout.max(1))
894                .collect()
895                .await
896            };
897            let mut heads = heads;
898            heads.sort_by(|a, b| a.0.cmp(&b.0));
899            for (path, still) in heads {
900                let still_there = still?;
901                let was_observed = observed.contains(&path);
902                let cited = &upserts[&path];
903                self.trace("observed", serde_json::json!({"flush": flush_uuid, "path": path, "etag": cited.etag, "still": still_there, "own_put": !was_observed}));
904                if still_there {
905                    continue;
906                }
907                let gone = upserts.remove(&path).expect("looked up above");
908                new_baseline_entries.remove(&path);
909                report.uploaded.retain(|p| p != &path);
910                report.published_bytes = report.published_bytes.saturating_sub(gone.size);
911                // ADOPTED bytes that are the baseline's own (a file touched
912                // without a change, re-uploaded by a restarted barrier under
913                // the same flush) that went before the commit: nothing new
914                // is lost, so the path is not parked, and the next consume
915                // takes the manifest's version. (Once this was the citation
916                // repair's arm; storm drill S0, 2026-09-15, showed parking
917                // it kept a writer on withheld bytes for good.)
918                let integrated = was_observed
919                    && baseline.entries.get(&path).is_some_and(|be| be.etag == gone.etag);
920                if integrated {
921                    self.state.append_conflict(&ConflictRecord {
922                        path: path.clone(),
923                        foreign_etag: gone.etag,
924                        preserved_key: None,
925                        kind: "repair-withheld: the object this barrier re-cited was replaced or \
926                               collected before its commit; nothing cited, and the next consume \
927                               installs the manifest's version"
928                            .into(),
929                        at_unix: now_unix(),
930                    })?;
931                    continue;
932                }
933                parked.insert(path.clone());
934                let kind = if was_observed {
935                    "adopt-withheld: the object this barrier found already at its key was \
936                     replaced or collected before its commit; nothing cited, the path stays \
937                     dirty and publishes next barrier"
938                } else {
939                    "upload-withheld: the object this barrier PUT was replaced or collected \
940                     before its commit (a peer's GC recognizes the etag of identical bytes); \
941                     nothing cited, the path stays dirty and publishes next barrier"
942                };
943                self.state.append_conflict(&ConflictRecord {
944                    path: path.clone(),
945                    foreign_etag: gone.etag,
946                    preserved_key: None,
947                    kind: kind.into(),
948                    at_unix: now_unix(),
949                })?;
950                report.parked.push(path.clone());
951            }
952            let mut foreign_entries: Vec<(String, LeanEntry)> = vec![];
953            // Set when the merge added nothing to the document: nothing is
954            // installed, and theirs becomes the merge base as it stands.
955            let mut installed_nothing = false;
956            let mut attempt = 0;
957            // The last value carried out: the adoptions this install
958            // declined for a move, whose entries stay in the cell.
959            let (theirs_at_cas, installed, installed_etag, overridden, recreated, over_theirs, replaced_etag) = loop {
960                attempt += 1;
961                if attempt > CAS_ATTEMPTS {
962                    return Err(LeanError::State(format!(
963                        "manifest CAS lost {CAS_ATTEMPTS} merge races — refusing this barrier"
964                    )));
965                }
966                let current = manifest::load(self.store.as_ref(), &self.cfg).await?;
967                // Review 2026-09-18, H2: THE fence — the cell read AFTER the
968                // load this CAS merges onto. The read at the top of step 5
969                // comes before the HEAD fan-out and the window, and a holder
970                // deposed in between loaded its successor's document,
971                // rotation included, and CASed onto it: the rotation fences
972                // only a load that PRECEDES it. Read here, the order closes
973                // both ways: deposed before this load, and this read sees
974                // it; deposed after, and the successor's rotation has moved
975                // the pointer this CAS expects.
976                self.verify_not_deposed().await?;
977                // The baseline IS the merge base (P1-lite).
978                let base = merge_base(&baseline);
979                let MergeOnto { theirs, expected, merged, foreign, overridden, recreated, over_theirs } = self.merge_onto(
980                    current.as_ref(),
981                    &base,
982                    &upserts,
983                    &classified.deletes,
984                    &parked,
985                    &flush_uuid,
986                );
987                // A DOCUMENT MUST BE MATERIALISABLE. No filesystem can hold
988                // a file `a` and a file `a/x`, so no document may cite
989                // both — a fresh checkout would have to create a directory
990                // where its own manifest says a file goes. The agent makes
991                // exactly that shape by replacing a published file with a
992                // directory (or the reverse): the scan sees the old path
993                // absent and the new one new, the two-scan guard withholds a
994                // FIRST absence, and the upload lands beside the citation it
995                // was meant to replace (review 2026-09-18, M5's agent-side
996                // twin). Judged here because this is where the document's
997                // final shape is known — theirs, my upserts and the deletes
998                // that actually applied. Mine is the side that yields: the
999                // path stays dirty and publishes at the next barrier, by
1000                // which time the withheld absence is confirmed and its
1001                // citation gone. This re-merges without spending a CAS
1002                // attempt; the clash is decided, not raced.
1003                let clash = path_clashes(&merged.entries, &upserts);
1004                if !clash.is_empty() {
1005                    for path in clash {
1006                        let gone = upserts.remove(&path).expect("named from upserts above");
1007                        new_baseline_entries.remove(&path);
1008                        report.uploaded.retain(|p| p != &path);
1009                        report.published_bytes =
1010                            report.published_bytes.saturating_sub(gone.size);
1011                        parked.insert(path.clone());
1012                        report.parked.push(path.clone());
1013                        self.state.append_conflict(&ConflictRecord {
1014                            path: path.clone(),
1015                            foreign_etag: gone.etag,
1016                            preserved_key: None,
1017                            kind: "upload-withheld-path-clash: the document still cites a path \
1018                                   this one would sit inside (or around) — a published file \
1019                                   replaced by a directory, or the reverse. No workspace can \
1020                                   hold both, so nothing is cited here until that citation \
1021                                   goes; the path stays dirty and publishes next barrier"
1022                                .into(),
1023                            at_unix: now_unix(),
1024                        })?;
1025                        self.trace(
1026                            "path_clash",
1027                            serde_json::json!({"flush": flush_uuid, "path": path}),
1028                        );
1029                    }
1030                    attempt -= 1;
1031                    continue;
1032                }
1033                // Nothing of ours changes the document — a barrier that only
1034                // found the manifest moved by another writer. Installing it
1035                // anyway was an empty generation, and the peer's next tick
1036                // then found the manifest moved and did the same: two idle
1037                // writers traded generations (and cell claims) for as long
1038                // as both ran. Theirs becomes the merge base as it stands.
1039                if let Some(handle) = expected.as_ref() {
1040                    if merged.entries == theirs.entries && merged.sole_writer == theirs.sole_writer {
1041                        foreign_entries = foreign;
1042                        installed_nothing = true;
1043                        break (theirs.clone(), theirs, handle.etag.clone(), vec![], vec![], vec![], Some(handle.etag.clone()));
1044                    }
1045                }
1046                match manifest::cas_write_retiring(
1047                    self.store.as_ref(),
1048                    &self.cfg,
1049                    &merged,
1050                    Some(&theirs),
1051                    expected.as_ref(),
1052                    epoch,
1053                    &flush_uuid,
1054                    Some(source),
1055                )
1056                .await
1057                {
1058                    Ok(meta) => {
1059                        // Before the deletes and before step 7: this is the
1060                        // only record that survives a crash in that window.
1061                        self.trace("cas", serde_json::json!({"flush": flush_uuid, "seq": merged.seq,
1062                            "expected": expected.as_ref().map(|h| h.etag.clone()), "etag": meta.etag, "result": "ok"}));
1063                        // H10: what this install carried of the standing
1064                        // declaration survives a restart, for the ack.
1065                        if let Some(id) = carries.as_ref() {
1066                            let mut c = intent
1067                                .carrier
1068                                .take()
1069                                .filter(|c| &c.pending_id == id)
1070                                .unwrap_or_else(|| Carrier { pending_id: id.clone(), ..Default::default() });
1071                            c.paths.extend(classified.uploads.iter().chain(&classified.deletes).cloned());
1072                            c.deletes.extend(classified.deletes.iter().cloned());
1073                            // `honor_publish`'s dropped set, decided here:
1074                            // parks and deferrals are settled before the
1075                            // CAS, and an outranked delete is one the merged
1076                            // document still cites.
1077                            c.dropped.extend(report.parked.iter().chain(&report.deferred).cloned());
1078                            c.dropped.extend(
1079                                classified.deletes.iter().filter(|p| merged.entries.contains_key(p.as_str())).cloned(),
1080                            );
1081                            intent.carrier = Some(c);
1082                        }
1083                        self.state.save_intent(&intent)?;
1084                        foreign_entries = foreign;
1085                        let replaced = expected.as_ref().map(|h| h.etag.clone());
1086                        break (theirs, merged, meta.etag, overridden, recreated, over_theirs, replaced);
1087                    }
1088                    Err(LeanError::Store(StoreError::PreconditionFailed(_)))
1089                    | Err(LeanError::Store(StoreError::Conflict(_))) => {
1090                        self.trace("cas", serde_json::json!({"flush": flush_uuid, "seq": merged.seq,
1091                            "expected": expected.as_ref().map(|h| h.etag.clone()), "result": "lost"}));
1092                        // A rotation is exactly this 412, and re-merging past
1093                        // it would be the straggler install: the next
1094                        // attempt's read after its load is the fence.
1095                        // Back off first: under P2 a UI save never waits on
1096                        // the lease, so the race is usually lost to saves,
1097                        // and the gap between two of them is the way in (G2).
1098                        tokio::time::sleep(cas_backoff(attempt)).await;
1099                        continue;
1100                    }
1101                    Err(e) => return Err(e),
1102                }
1103            };
1104            report.seq = Some(installed.seq);
1105            report.no_change = installed_nothing;
1106            // A fused install IS a coherent point, and cadence/hybrid have
1107            // exactly one source. The gauges must not report "no boundary
1108            // ever" on a workspace that publishes every minute. A barrier
1109            // that installed nothing marks no boundary of its own.
1110            if !installed_nothing {
1111                self.note_boundary("cadence", installed.seq)?;
1112            }
1113            report.manifest_etag = Some(installed_etag.clone());
1114            report.observed_seq = Some(installed.seq);
1115            report.observed_etag = Some(installed_etag.clone());
1116            report.foreign_queued = foreign_entries.len();
1117
1118            // Step 6: RETIREMENT and collection (design 2026-09-19, R3 and
1119            // R7). What the document this CAS merged onto cited and the
1120            // installed document does not — a modified path's old handle,
1121            // a deleted path's — is retired, minus every handle the
1122            // installed document still cites at another path (a rename
1123            // cites the source's handle at the destination) and every
1124            // handle an inbox entry names (a rename whose destination is
1125            // still only in the cell). A retired handle can never be cited
1126            // again: nothing discovers handles from paths, and the merge
1127            // carries forward only what the base cites. So the collector
1128            // deletes it UNCONDITIONALLY, in one batch — no HEAD, no
1129            // If-Match, no fence, no renew (a straggler deposed after its
1130            // CAS has an exact retired set too; the model's
1131            // `LeanImmutableStragglerGC`). The HEAD-then-If-Match dance,
1132            // the collector that gave way on a store without a conditional
1133            // DELETE (review H1's leak) and the C2 renew-before-delete
1134            // clock all went with the slot.
1135            //
1136            // And what this barrier published OVER without ever integrating
1137            // it — a peer's publish, a UI write consumed elsewhere — is
1138            // preserved by a server-side copy and a record BEFORE the batch
1139            // takes the handle. The slot's 412 caught that at the PUT and
1140            // `Upload412Preserves` did the same; a fresh handle has no slot
1141            // to fail on, so the CAS, the one place the citation is read,
1142            // takes the decision (R7; the model's first HitlOverAny run
1143            // under handles cited an acked write over blind without it).
1144            let still_cited: BTreeSet<&str> = installed.entries.values().map(|e| e.key.as_str()).collect();
1145            let mut retired: Vec<String> = vec![];
1146            for (path, was) in &theirs_at_cas.entries {
1147                let dropped = installed.entries.get(path).map(|now| now.key != was.key).unwrap_or(true);
1148                if dropped && !still_cited.contains(was.key.as_str()) {
1149                    retired.push(was.key.clone());
1150                }
1151            }
1152            for (path, was) in &overridden {
1153                let integrated = baseline
1154                    .entries
1155                    .get(path)
1156                    .is_some_and(|be| be.key.as_deref() == Some(was.key.as_str()));
1157                if integrated || parked.contains(path) {
1158                    continue;
1159                }
1160                let preserved = self.preserve_conflict_copy(path, &was.key, &was.etag).await?;
1161                self.state.append_conflict(&ConflictRecord {
1162                    path: path.clone(),
1163                    foreign_etag: was.etag.clone(),
1164                    preserved_key: Some(preserved),
1165                    kind: "commit-surfaced-foreign: this barrier published over a version it never \
1166                           integrated (another writer's publish, or a UI write consumed elsewhere); \
1167                           that version is preserved under this record and superseded knowingly"
1168                        .into(),
1169                    at_unix: now_unix(),
1170                })?;
1171                report.surfaced.push(path.clone());
1172                self.trace("surface", serde_json::json!({"flush": flush_uuid, "path": path, "etag": was.etag, "key": was.key}));
1173            }
1174            for (path, deleted) in &recreated {
1175                self.state.append_conflict(&ConflictRecord {
1176                    path: path.clone(),
1177                    foreign_etag: deleted.clone(),
1178                    preserved_key: None,
1179                    kind: "commit-recreated-deleted: this barrier published over a DELETE it never \
1180                           integrated (another writer's, or the UI's); mine wins, the path is cited \
1181                           again with this tree's bytes, and the deleted version is named here"
1182                        .into(),
1183                    at_unix: now_unix(),
1184                })?;
1185                report.surfaced.push(path.clone());
1186                self.trace("surface", serde_json::json!({"flush": flush_uuid, "path": path, "etag": deleted, "deleted": true}));
1187            }
1188            // M3: what this barrier's DELETE removed that it never
1189            // integrated — theirs, changed since the baseline — is preserved
1190            // before the batch below takes the handle, and named.
1191            for (path, was) in &over_theirs {
1192                let preserved = self.preserve_conflict_copy(path, &was.key, &was.etag).await?;
1193                self.state.append_conflict(&ConflictRecord {
1194                    path: path.clone(),
1195                    foreign_etag: was.etag.clone(),
1196                    preserved_key: Some(preserved),
1197                    kind: "commit-deleted-over-theirs: this barrier deleted a path whose version it \
1198                           never integrated (another writer's publish, or a UI save); the delete \
1199                           stands, and that version is preserved under this record"
1200                        .into(),
1201                    at_unix: now_unix(),
1202                })?;
1203                report.surfaced.push(path.clone());
1204                self.trace("surface", serde_json::json!({"flush": flush_uuid, "path": path, "etag": was.etag, "key": was.key, "over_delete": true}));
1205            }
1206            for path in &classified.deletes {
1207                if installed.entries.contains_key(path) {
1208                    // Never expected: since M3 a delete applies over theirs,
1209                    // and only uploads are parked, so every delete leaves the
1210                    // document. Were one still cited it is not in this
1211                    // boundary — PARKED, which the ack names as not carried —
1212                    // and the next scan classifies it again. Traced like
1213                    // every outcome: a replay owes a GC step for every path
1214                    // in the delete set (W4 phase 2, R3-S2).
1215                    self.trace("gc", serde_json::json!({"flush": flush_uuid, "path": path, "result": "still-cited"}));
1216                    report.parked.push(path.clone());
1217                } else {
1218                    let key = theirs_at_cas.entries.get(path).map(|e| e.key.clone());
1219                    self.trace("gc", serde_json::json!({"flush": flush_uuid, "path": path, "key": key, "result": "retired"}));
1220                    report.deleted.push(path.clone());
1221                }
1222            }
1223            if self.cfg.drill_hold_gc_secs > 0 && !retired.is_empty() {
1224                eprintln!(
1225                    "flint-sync: DRILL: holding the GC for {}s before the batch delete",
1226                    self.cfg.drill_hold_gc_secs
1227                );
1228                self.trace("drill_hold", serde_json::json!({"flush": flush_uuid, "where": "gc",
1229                    "secs": self.cfg.drill_hold_gc_secs}));
1230                tokio::time::sleep(std::time::Duration::from_secs(self.cfg.drill_hold_gc_secs)).await;
1231            }
1232            // RETIRE-AGE G (M1): what this commit retired was LOGGED with its
1233            // CAS (`manifest::cas_write_retiring`), as the gateway's commits
1234            // log theirs. It is collected once the retirement is
1235            // `retire_grace_secs` old — at once when that is 0 — by whichever
1236            // writer's commit section comes next; until then the sweeps spare
1237            // it, so a reader that loaded the document before this CAS can
1238            // still fetch it. No ledger, no sweep: a leak, never a deletion
1239            // a lagging reader meets.
1240            let ledger = match self.retire_ledger(now_unix()).await {
1241                Ok(l) => Some(l),
1242                Err(e) => {
1243                    eprintln!("flint-sync: could not read the retire logs ({e}); no sweep this time");
1244                    None
1245                }
1246            };
1247            if let Some(l) = &ledger {
1248                match self.reap_retired(l, &installed, &flush_uuid).await {
1249                    Ok(n) => report.collected = n,
1250                    Err(e) => eprintln!("flint-sync: retired handles not collected (next time): {e}"),
1251                }
1252            }
1253            if !retired.is_empty() {
1254                self.trace("gc", serde_json::json!({"flush": flush_uuid, "retired": retired.len(),
1255                    "collected": report.collected}));
1256            }
1257            // The orphan sweep (R4): a handle nothing cites, no young retire
1258            // log names, older than its grace — left by a writer that never
1259            // committed. Inside the commit section, under the cell, so the
1260            // commit's re-read of its own uploads above and this CAS are
1261            // race-free against it; never this barrier's own handles.
1262            if let Some(l) = &ledger {
1263                match self.sweep_orphans_if_due(&installed, &flush_uuid, now_unix(), &l.spared).await {
1264                    Ok(n) => report.swept = n,
1265                    Err(e) => eprintln!("flint-sync: orphan sweep (retrying next time it is due): {e}"),
1266                }
1267            }
1268
1269            // Step 7: the baseline follows what this barrier published. What
1270            // theirs changed is owed, and the next consume derives it: the
1271            // pointer now names a document it never derived against. UNLESS
1272            // this CAS replaced exactly the document the consume derived
1273            // against — then the installed one is that plus this tree's own
1274            // changes, nothing new is owed, and the next tick stays cheap
1275            // (a busy agent's publishes would otherwise each cost a full
1276            // derive). The paths published or deleted here are no longer the
1277            // agent's pending work.
1278            let same = |a: &str, b: &str| a.trim_matches('"') == b.trim_matches('"');
1279            // No document replaced ("") is the empty workspace's derive.
1280            let over_derived = matches!(&baseline.derived_etag,
1281                Some(d) if same(replaced_etag.as_deref().unwrap_or(""), d));
1282            if over_derived {
1283                baseline.derived_etag = Some(installed_etag.clone());
1284                for path in new_baseline_entries.keys().chain(&report.deleted) {
1285                    baseline.skipped.remove(path);
1286                }
1287            }
1288            for (path, be) in new_baseline_entries {
1289                baseline.entries.insert(path, be);
1290            }
1291            for path in &report.deleted {
1292                baseline.entries.remove(path);
1293            }
1294            self.note_carrier_uncited(&installed)?;
1295            baseline.seq = installed.seq;
1296            baseline.manifest_etag = Some(installed_etag);
1297            baseline.prev_scan = scanned.keys().cloned().collect();
1298            self.state.save_baseline(&baseline)?;
1299            self.state.clear_intent_keys()?;
1300            // The commit section's end (the model's `Finish`). No window is
1301            // written: under P2 a UI save never waits on one (G1).
1302            self.trace("window_clear", serde_json::json!({"flush": flush_uuid}));
1303            // Reap superseded generations. Immutable metadata that is never
1304            // collected is a leak that grows by a whole manifest per
1305            // publish, and this also collects the orphan a crash between the
1306            // entries PUT and the pointer CAS leaves behind. Best effort by
1307            // design: a publish that succeeded is not un-done by a failure
1308            // to tidy up after it.
1309            let swept_generations = match manifest::sweep_generations(self.store.as_ref(), &self.cfg).await {
1310                Ok(0) => 0,
1311                Ok(n) => {
1312                    eprintln!("flint-sync: reaped {n} superseded manifest generation(s)");
1313                    n
1314                }
1315                Err(e) => {
1316                    eprintln!("flint-sync: generation sweep: {e}");
1317                    0
1318                }
1319            };
1320            self.trace("sweep", serde_json::json!({"flush": flush_uuid, "what": "generations", "removed": swept_generations}));
1321            // And the CHUNK reaper, same reason, same best-effort terms.
1322            // `sweep_chunks` returns 0 without a request on a workspace that
1323            // is not chunked, so this costs nothing until the layout moves.
1324            //
1325            // It was written to four model-established rules, guarded by six
1326            // mutation configs, and called from nothing but its own tests —
1327            // so with chunking on, every publish left its superseded chunks
1328            // in the bucket forever. The rules ran in the model and in the
1329            // suite and never once in production. `the_barrier_reaps...`
1330            // below is the test that asks whether this line exists at all.
1331            let swept_chunks = match ledger.as_ref() {
1332                None => Ok(0),
1333                Some(l) => manifest::sweep_chunks_sparing(self.store.as_ref(), &self.cfg, &l.spared).await,
1334            };
1335            let swept_chunks = match swept_chunks {
1336                Ok(0) => 0,
1337                Ok(n) => {
1338                    eprintln!("flint-sync: reaped {n} unreferenced manifest chunk(s)");
1339                    n
1340                }
1341                Err(e) => {
1342                    eprintln!("flint-sync: chunk sweep: {e}");
1343                    0
1344                }
1345            };
1346            self.trace("sweep", serde_json::json!({"flush": flush_uuid, "what": "chunks", "removed": swept_chunks}));
1347            Ok(())
1348        }
1349        .await;
1350        // Hand the cell on whatever happened — unless it is no longer
1351        // ours to hand on: a fence means a successor holds it, and the
1352        // barrier is simply abandoned (its manifest never installed; its
1353        // uploads stand, and the next barrier adopts them by flush_uuid).
1354        match &commit {
1355            Err(LeanError::Fenced(m)) => {
1356                self.trace("fence", serde_json::json!({"where": "commit", "detail": m}));
1357                self.lease = None
1358            }
1359            _ => {
1360                if let Err(e) = super::lease::release(self).await {
1361                    eprintln!(
1362                        "flint-sync: the publish fence could not be released ({e}); a waiter \
1363                         deposes it after the quiet threshold"
1364                    );
1365                }
1366            }
1367        }
1368        commit?;
1369        self.trace_barrier_end(&report, barrier_started);
1370        Ok(report)
1371    }
1372
1373    fn trace_barrier_end(&self, report: &BarrierReport, started: std::time::Instant) {
1374        if self.cfg.event_trace.is_none() {
1375            return;
1376        }
1377        self.trace(
1378            "barrier_end",
1379            serde_json::json!({
1380                "seq": report.seq, "uploaded": report.uploaded.len(), "deleted": report.deleted.len(),
1381                "parked": report.parked.len(),
1382                "leaked": report.leaked.len(),
1383                "consumed": report.consumed, "no_change": report.no_change,
1384                "ms": started.elapsed().as_millis() as u64, "requests": self.trace_requests(),
1385            }),
1386        );
1387    }
1388
1389    /// The > whole_put_max path: contiguous `PartSource::Local` chunks
1390    /// through `compose_generation` (streaming multipart; the store
1391    /// aborts its partial assembly on every failure path). The CRC is
1392    /// computed by a streaming pass first; a writer racing the compose
1393    /// fails server-side validation and the path DEFERS to the next
1394    /// barrier — publish-possibly-torn is put_whole's documented
1395    /// dilemma, not this path's.
1396    #[allow(clippy::too_many_arguments)]
1397    #[allow(clippy::too_many_arguments)]
1398    async fn upload_compose(
1399        &self,
1400        path: &str,
1401        key: &str,
1402        // The ONE descriptor `upload_one` opened by a walk that follows
1403        // no link at any depth. The store reads its parts from this and
1404        // never reopens the path (review 2026-09-18, H5's residual).
1405        file: std::sync::Arc<std::fs::File>,
1406        size: u64,
1407        scanned: &scan::ScanEntry,
1408        stamps: GenerationStamps,
1409        generation: u64,
1410        epoch: u64,
1411    ) -> LeanResult<UploadOutcome> {
1412        // NO PRE-PASS. The store accumulates the full-object CRC from
1413        // the parts as it reads them for upload, so this file is read
1414        // ONCE (the 2026-09-10 door drill measured the second read at
1415        // roughly 11 s of the `mixed` workload's 24.3 s).
1416        // Part grid: within [min_part_size, ...], at most max_parts,
1417        // contiguous from 0.
1418        let min_part = self.store.min_part_size().max(1);
1419        let max_parts = self.store.max_parts().max(1) as u64;
1420        let mut chunk = self.cfg.whole_put_max.max(min_part);
1421        let need = size.div_ceil(chunk);
1422        if need > max_parts {
1423            chunk = size.div_ceil(max_parts).div_ceil(min_part) * min_part;
1424        }
1425        let mut parts = vec![];
1426        let mut off = 0u64;
1427        while off < size {
1428            let len = chunk.min(size - off);
1429            parts.push(flint_store::PartSource::Local { offset: off, len });
1430            off += len;
1431        }
1432
1433
1434        // A fresh handle: the Complete lands on a key nobody else writes
1435        // (design 2026-09-19, R1). The one thing that can already sit
1436        // there is this barrier's OWN Complete whose response was lost —
1437        // a torn response — and the recogniser is the bytes' checksum:
1438        // the same, cite them (re-read under the fence first, like every
1439        // citation); different, nothing minted this key but us, so the
1440        // barrier refuses rather than guess. The 412 arms this replaced
1441        // — adopt-own through the crash journal, preserve-a-foreign-
1442        // version, park — arbitrated a slot that no longer exists.
1443        let spec = flint_store::ComposeSpec {
1444            progress: None,
1445            key,
1446            local: Some(file),
1447            parts: parts.clone(),
1448            base_key: None,
1449            base_etag: None,
1450            condition: PutCondition::IfNoneMatchAny,
1451            stamps: stamps.clone(),
1452            crc64: None,
1453        };
1454        match self.store.compose_generation(&spec).await {
1455            Ok(meta) => {
1456                // The store computed it; refuse to cite bytes nothing
1457                // vouched for rather than invent a number for the
1458                // manifest. A backend that returns no checksum has not
1459                // validated the publish server-side either.
1460                let crc = meta
1461                    .crc64_b64
1462                    .as_deref()
1463                    .and_then(flint_store::crc64_from_b64)
1464                    .ok_or_else(|| {
1465                        LeanError::State(format!(
1466                            "compose of {key} returned no full-object checksum — refusing to \
1467                             cite bytes nothing vouched for"
1468                        ))
1469                    })?;
1470                Ok(UploadOutcome::published(
1471                    path, key.to_string(), meta.etag, crc, size, scanned, generation, epoch,
1472                ))
1473            }
1474            Err(StoreError::ChecksumMismatch(_)) | Err(StoreError::NoSuchUpload(_)) => {
1475                // Drift mid-compose, or the operator sweep aborted us:
1476                // nothing published; the next barrier re-queues.
1477                Ok(UploadOutcome::Deferred)
1478            }
1479            Err(StoreError::PreconditionFailed(_)) => {
1480                // The torn-response recogniser compares OUR bytes' checksum
1481                // against what landed, and without the pre-pass we do not
1482                // have one — so the file is read HERE, on the rare recovery
1483                // path, instead of on every publish.
1484                let crc = file_crc(&self.cfg.root, path)?;
1485                let head = self.store.head(key).await?;
1486                if head.crc64_b64.as_deref() == Some(crc64_to_b64(crc).as_str()) {
1487                    let g = GenerationStamps::from_meta(&head.meta).map(|s| s.generation).unwrap_or(generation);
1488                    return Ok(UploadOutcome::adopted(
1489                        path, key.to_string(), head.etag, crc, head.size, scanned, g, epoch,
1490                    ));
1491                }
1492                Err(LeanError::State(format!(
1493                    "handle {key} already holds different bytes (etag {}): a handle is minted once \
1494                     per flush, so something other than this barrier wrote it; refusing",
1495                    head.etag
1496                )))
1497            }
1498            Err(e) => Err(e.into()),
1499        }
1500    }
1501
1502
1503    async fn upload_one(
1504        &self,
1505        path: &str,
1506        scanned: &scan::ScanEntry,
1507        base: Option<&BaselineEntry>,
1508        epoch: u64,
1509        flush_uuid: &str,
1510    ) -> LeanResult<UploadOutcome> {
1511        let key = self.cfg.handle_key(path, flush_uuid);
1512        let local_path = self.cfg.root.join(path);
1513        let generation = base.map(|b| b.generation + 1).unwrap_or(1);
1514        // Review 2026-09-12, atomicity-6: the scan skipped symlinks; this
1515        // read followed them. A regular file swapped for a symlink between
1516        // the two published the link's TARGET — a file outside the
1517        // workspace, the syncer's own /proc/self/environ included. Every
1518        // stat here is an lstat and the read opens O_NOFOLLOW; a path that
1519        // is no longer a regular file is refused, recorded, and deferred
1520        // (the next scan skips it, and the two-scan rule retires it).
1521        //
1522        // Review 2026-09-18, H5: and not only the last component. A
1523        // DIRECTORY on the path swapped for a link (`mv d d.bak; ln -s
1524        // /proc/self d`) made `d/environ` a regular file outside the
1525        // workspace; the lstat and the O_NOFOLLOW open guarded the last
1526        // component only. The file is opened by a walk that follows no
1527        // link at any depth, and everything below — the stamps, the
1528        // size, the bytes — comes from that one descriptor.
1529        let file = match super::safefs::open_beneath_nofollow(&self.cfg.root, path) {
1530            Ok(f) => f,
1531            Err(e)
1532                if e.kind() == std::io::ErrorKind::InvalidInput
1533                    || matches!(e.raw_os_error(), Some(libc::ELOOP) | Some(libc::ENOTDIR)) =>
1534            {
1535                self.state.append_conflict(&ConflictRecord {
1536                    path: path.to_string(),
1537                    foreign_etag: String::new(),
1538                    preserved_key: None,
1539                    kind: format!(
1540                        "upload-refused-not-regular: no longer a regular file inside the workspace after \
1541                         the scan (a symlink or special file replaced it or a directory above it: {e}); \
1542                         nothing published"
1543                    ),
1544                    at_unix: now_unix(),
1545                })?;
1546                return Ok(UploadOutcome::Deferred);
1547            }
1548            Err(e) => return Err(LeanError::State(format!("stat {}: {e}", local_path.display()))),
1549        };
1550        let lmeta = file
1551            .metadata()
1552            .map_err(|e| LeanError::State(format!("stat {}: {e}", local_path.display())))?;
1553        let posix = Some(PosixStamps::from_metadata(&lmeta));
1554        let stamps = GenerationStamps {
1555            generation,
1556            epoch,
1557            flush_uuid: flush_uuid.to_string(),
1558            boundary_source: None,
1559            posix,
1560        };
1561        let size = lmeta.len();
1562        if size > self.cfg.whole_put_max {
1563            // Streaming multipart compose: put_whole is never fed past
1564            // whole_put_max (unbounded memory + S3's 5 GiB wall).
1565            return self
1566                .upload_compose(path, &key, std::sync::Arc::new(file), size, scanned, stamps, generation, epoch)
1567                .await;
1568        }
1569        // The upload byte gate — the store's own, shared with the compose
1570        // arm above, which charges its parts inside the store. This body
1571        // is charged from before it is read (the read is the allocation)
1572        // until its PUT, retried or not, has returned: the permit lives
1573        // to the end of this function. `None` = a store with no gate.
1574        let _upload_permit = match self.store.upload_gate() {
1575            Some(g) => Some(g.acquire(size).await),
1576            None => None,
1577        };
1578        // `Bytes::from(Vec<u8>)` TAKES OWNERSHIP without copying, so the
1579        // old `Bytes::from(body.clone())` was a full memcpy of every
1580        // published file body — bought solely to leave `body` intact for
1581        // the 412 retry below, which is reached almost never. Build the
1582        // `Bytes` once; the retry gets a refcount clone.
1583        let body = Bytes::from({
1584            use std::io::Read;
1585            let mut v = Vec::with_capacity(size as usize);
1586            (&file).read_to_end(&mut v)?;
1587            v
1588        });
1589        let uploaded_len = body.len() as u64;
1590        let crc = crc64_nvme(&body);
1591        // A fresh handle (design 2026-09-19, R1): no If-Match, because
1592        // nothing else ever writes this key. The one thing that can sit
1593        // there is this barrier's OWN PUT whose response was lost, and
1594        // the bytes' checksum recognises it: the same, cite it (re-read
1595        // under the fence first, like every citation); different, nothing
1596        // minted this key but us, so refuse rather than guess. The 412
1597        // policy this replaced — adopt-own, preserve-then-supersede a
1598        // foreign version, park, the 404-on-If-Match create arm —
1599        // arbitrated a slot that no longer exists; a foreign version is
1600        // now met at the CAS, the one place a citation is read (R7).
1601        match self
1602            .store
1603            .put_whole(&key, body, &PutCondition::IfNoneMatchAny, &stamps, crc)
1604            .await
1605        {
1606            Ok(meta) => Ok(UploadOutcome::published(
1607                path, key, meta.etag, crc, uploaded_len, scanned, generation, epoch,
1608            )),
1609            Err(StoreError::PreconditionFailed(_)) => {
1610                let head = self.store.head(&key).await?;
1611                if head.crc64_b64.as_deref() == Some(crc64_to_b64(crc).as_str()) {
1612                    let g = GenerationStamps::from_meta(&head.meta).map(|s| s.generation).unwrap_or(generation);
1613                    return Ok(UploadOutcome::adopted(
1614                        path, key, head.etag, crc, head.size, scanned, g, epoch,
1615                    ));
1616                }
1617                Err(LeanError::State(format!(
1618                    "handle {key} already holds different bytes (etag {}): a handle is minted once \
1619                     per flush, so something other than this barrier wrote it; refusing",
1620                    head.etag
1621                )))
1622            }
1623            Err(e) => Err(e.into()),
1624        }
1625    }
1626}
1627
1628enum UploadOutcome {
1629    /// `adopted`: the etag was OBSERVED at the handle (bytes already
1630    /// there, no PUT of ours produced them — a torn response), so the
1631    /// commit section re-reads it before citing, as it does every
1632    /// citation.
1633    Published { entry: LeanEntry, baseline_entry: BaselineEntry, adopted: bool },
1634    /// The source drifted mid-transfer (checksum refused server-side)
1635    /// or the assembly was swept: publish nothing, advance nothing —
1636    /// the next scan re-queues the path.
1637    Deferred,
1638}
1639
1640impl UploadOutcome {
1641    #[allow(clippy::too_many_arguments)]
1642    fn published(
1643        path: &str,
1644        key: String,
1645        etag: String,
1646        crc: u64,
1647        uploaded_len: u64,
1648        scanned: &scan::ScanEntry,
1649        generation: u64,
1650        epoch: u64,
1651    ) -> UploadOutcome {
1652        let _ = path;
1653        UploadOutcome::Published {
1654            adopted: false,
1655            entry: LeanEntry {
1656                key: key.clone(),
1657                etag: etag.clone(),
1658                crc64_b64: crc64_to_b64(crc),
1659                // The length the object HAS (review 2026-09-12,
1660                // atomicity-1): the scanned size was cited while the
1661                // body was read fresh, so a file that grew between the
1662                // two was cited short and every fresh checkout of it
1663                // failed its CRC fold — the successor never started.
1664                size: uploaded_len,
1665                mode: scanned.mode,
1666                mtime_unix: scanned.mtime_unix,
1667                generation,
1668                epoch,
1669            },
1670            baseline_entry: BaselineEntry {
1671                etag,
1672                key: Some(key),
1673                generation,
1674                // The PRE-read stat: if the agent wrote during our read,
1675                // the next scan sees the drift and re-queues (the
1676                // re-stat/re-queue valve).
1677                size: scanned.size,
1678                mtime_unix: scanned.mtime_unix,
1679                mtime_nanos: Some(scanned.mtime_nanos),
1680                crc64_b64: Some(crc64_to_b64(crc)),
1681            },
1682        }
1683    }
1684}
1685
1686impl UploadOutcome {
1687    /// `published`, for bytes this barrier found already at the key and
1688    /// cites without a PUT of its own.
1689    #[allow(clippy::too_many_arguments)]
1690    fn adopted(
1691        path: &str,
1692        key: String,
1693        etag: String,
1694        crc: u64,
1695        uploaded_len: u64,
1696        scanned: &scan::ScanEntry,
1697        generation: u64,
1698        epoch: u64,
1699    ) -> UploadOutcome {
1700        match UploadOutcome::published(path, key, etag, crc, uploaded_len, scanned, generation, epoch) {
1701            UploadOutcome::Published { entry, baseline_entry, .. } => {
1702                UploadOutcome::Published { entry, baseline_entry, adopted: true }
1703            }
1704            other => other,
1705        }
1706    }
1707}
1708
1709/// The paths THIS barrier must withhold because the document would cite a
1710/// file and something under it (a published file replaced by a directory,
1711/// or the reverse). Whichever side is this barrier's upsert yields; if both
1712/// are, so does the parent.
1713///
1714/// Every key under `p/` sits in one contiguous run of the sorted map, so a
1715/// range lookup finds them: O(N log N). The first version scanned every
1716/// key for every key, and a 200k-path commit spent 80 s here (bench
1717/// 2026-09-25). The run does NOT start right after `p`: `p-b` and `p.txt`
1718/// sort between `p` and `p/`.
1719pub(super) fn path_clashes<V, U>(
1720    cited: &BTreeMap<String, V>,
1721    upserts: &BTreeMap<String, U>,
1722) -> Vec<String> {
1723    let mut mine: Vec<String> = vec![];
1724    for p in cited.keys() {
1725        let pfx = format!("{p}/");
1726        let mut under = cited.range::<str, _>((std::ops::Bound::Included(pfx.as_str()), std::ops::Bound::Unbounded))
1727            .map(|(k, _)| k)
1728            .take_while(|q| q.starts_with(&pfx))
1729            .peekable();
1730        if under.peek().is_none() {
1731            continue;
1732        }
1733        if upserts.contains_key(p) {
1734            mine.push(p.clone());
1735        } else if let Some(c) = under.find(|q| upserts.contains_key(*q)) {
1736            mine.push(c.clone());
1737        }
1738    }
1739    mine.sort();
1740    mine.dedup();
1741    mine
1742}
1743
1744pub(super) fn local_dirty(local: &Path, base: Option<&BaselineEntry>) -> bool {
1745    match (std::fs::metadata(local), base) {
1746        (Err(_), None) => false,                   // both absent: clean
1747        (Err(_), Some(_)) => true,                 // locally deleted vs baseline
1748        (Ok(_), None) => true,                     // local exists, never published
1749        (Ok(m), Some(b)) => {
1750            scan::stat_changed(b.size, b.mtime_unix, b.mtime_nanos, m.len(), mtime_of(&m), mtime_nanos_of(&m))
1751        }
1752    }
1753}
1754
1755fn file_crc(root: &Path, rel: &str) -> LeanResult<u64> {
1756    use std::io::Read;
1757    let mut crc = flint_store::Crc64Nvme::new();
1758    // No link anywhere on the path (H5): this hashes what a 412 recovery
1759    // is about to call "already there".
1760    let mut f = super::safefs::open_beneath_nofollow(root, rel)?;
1761    let mut buf = vec![0u8; 4 << 20];
1762    loop {
1763        let n = f.read(&mut buf)?;
1764        if n == 0 {
1765            break;
1766        }
1767        crc.update(&buf[..n]);
1768    }
1769    Ok(crc.finalize())
1770}
1771
1772pub(super) fn mtime_nanos_of(m: &std::fs::Metadata) -> u32 {
1773    m.modified()
1774        .ok()
1775        .and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
1776        .map(|d| d.subsec_nanos())
1777        .unwrap_or(0)
1778}
1779
1780pub(super) fn mtime_of(m: &std::fs::Metadata) -> i64 {
1781    m.modified()
1782        .ok()
1783        .and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
1784        .map(|d| d.as_secs() as i64)
1785        .unwrap_or(0)
1786}
1787
1788/// Validate `rel` under `root` WITHOUT creating anything — for callers
1789/// that must decide whether a path is writable before doing any work
1790/// (inbox consume refuses a refused path outright rather than routing it
1791/// through conflict-preserve, which would cost a GET+PUT and leave the
1792/// path in the baseline).
1793pub(super) fn check_contained(root: &Path, rel: &str) -> LeanResult<()> {
1794    resolve_contained(root, rel, false).map(|_| ())
1795}
1796
1797/// Resolve `rel` under `root`, refusing escapes, creating missing parent
1798/// directories. Walks the parent chain component by component: a
1799/// component that EXISTS as a symlink is a refusal (never followed).
1800pub(super) fn contained_path(root: &Path, rel: &str) -> LeanResult<std::path::PathBuf> {
1801    resolve_contained(root, rel, true).map(|(p, _)| p)
1802}
1803
1804/// As `contained_path`, and also what the walk already learned about
1805/// the FINAL component: its `lstat` if it exists, `None` if it does
1806/// not. The walk stats every component to refuse a symlink; a caller
1807/// that then asked `exists()` and `metadata()` paid two more stats for
1808/// an answer it was already holding (checkout's resume check did, on
1809/// every one of 20,000 files).
1810pub(super) fn contained_path_stat(
1811    root: &Path,
1812    rel: &str,
1813) -> LeanResult<(std::path::PathBuf, Option<std::fs::Metadata>)> {
1814    resolve_contained(root, rel, true)
1815}
1816
1817fn resolve_contained(
1818    root: &Path,
1819    rel: &str,
1820    create_dirs: bool,
1821) -> LeanResult<(std::path::PathBuf, Option<std::fs::Metadata>)> {
1822    use std::path::Component;
1823    let refuse = |why: &str| {
1824        Err(LeanError::State(format!(
1825            "refusing write to {rel:?}: {why} (containment)"
1826        )))
1827    };
1828    if rel.is_empty() {
1829        return refuse("empty path");
1830    }
1831    if super::scan::is_control_path(rel) {
1832        // The reserved namespace is the syncer's own; a citation or
1833        // inbox entry naming it is surfaced, never materialized (D0.3).
1834        return refuse("reserved control namespace");
1835    }
1836    if rel.split('/').any(|seg| seg.ends_with(super::scan::TMP_SUFFIX)) {
1837        // Review 2026-09-18, C1: the walk skips this suffix at every
1838        // depth (the consume's own temp sibling, atomicity-7), so a file
1839        // materialised under it is absent from every scan — cited once
1840        // by the repair as a first absence, then classified a delete and
1841        // its object collected. Surfaced and never materialised, like the
1842        // control namespace; the gateway refuses the name at the door.
1843        return refuse("a name reserved for the syncer's temporary files");
1844    }
1845    let relp = Path::new(rel);
1846    let mut cur = root.to_path_buf();
1847    let mut comps: Vec<&std::ffi::OsStr> = vec![];
1848    for c in relp.components() {
1849        match c {
1850            Component::Normal(n) => comps.push(n),
1851            Component::CurDir => {}
1852            Component::ParentDir => return refuse("`..` component"),
1853            Component::RootDir | Component::Prefix(_) => return refuse("absolute path"),
1854        }
1855    }
1856    if comps.is_empty() {
1857        return refuse("no path components");
1858    }
1859    let last = comps.len() - 1;
1860    let mut final_meta = None;
1861    for (i, c) in comps.iter().enumerate() {
1862        cur.push(c);
1863        match std::fs::symlink_metadata(&cur) {
1864            Ok(m) if m.file_type().is_symlink() => {
1865                return refuse("path traverses a symlink");
1866            }
1867            Ok(m) if i < last && !m.is_dir() => {
1868                return refuse("parent component is not a directory");
1869            }
1870            Ok(m) => {
1871                if i == last {
1872                    final_meta = Some(m);
1873                }
1874            }
1875            Err(_) if i < last => {
1876                if create_dirs {
1877                    if let Err(e) = std::fs::create_dir(&cur) {
1878                        // A SIBLING may have created it between the stat
1879                        // above and this mkdir: fetches run on their own
1880                        // tasks, so the first files of one directory
1881                        // race here, and the loser's EEXIST is not a
1882                        // containment refusal. It is fine only if what
1883                        // exists now is a plain directory — a symlink
1884                        // that appeared in the window is refused exactly
1885                        // as one the stat found.
1886                        match std::fs::symlink_metadata(&cur) {
1887                            Ok(m) if m.file_type().is_symlink() => {
1888                                return refuse("path traverses a symlink");
1889                            }
1890                            Ok(m) if m.is_dir() => {}
1891                            _ => {
1892                                return Err(LeanError::State(format!(
1893                                    "mkdir {}: {e}",
1894                                    cur.display()
1895                                )))
1896                            }
1897                        }
1898                    }
1899                }
1900            }
1901            Err(_) => {}
1902        }
1903    }
1904    Ok((cur, final_meta))
1905}
1906
1907/// Write `bytes` to `path` through an exclusive temp sibling and a
1908/// rename. The parent already exists — containment created it — and
1909/// one that vanished since is recreated on the retry path in `safefs`,
1910/// so the common path pays no `mkdir` and no `stat` for it. Returns
1911/// the written file's metadata.
1912pub(super) fn write_file_atomic(
1913    path: &Path,
1914    bytes: &[u8],
1915    mode: Option<u32>,
1916) -> LeanResult<std::fs::Metadata> {
1917    super::safefs::check_parent(path)?;
1918    // NOT with_extension(): that REPLACES the final extension, so
1919    // "a.txt" and "a.md" would collide on one tmp name.
1920    let tmp = path.with_file_name(format!(
1921        "{}.flint-sync-tmp",
1922        path.file_name().map(|n| n.to_string_lossy()).unwrap_or_default()
1923    ));
1924    // The temp sibling is computed AFTER containment ran, so the walk
1925    // never saw it: it needs its own refusal, not a plain write.
1926    // FAST (no per-file fsync): materialisations are made durable by
1927    // `sync_tree` before the marker or baseline that vouches for them.
1928    super::safefs::write_via_tmp_fast(path, &tmp, bytes, mode)
1929}
1930
1931/// `write_file_atomic`, renamed over `path` only if `proceed()` holds once
1932/// the temp is written (`safefs::write_via_tmp_fast_if`).
1933pub(super) fn write_file_atomic_if(
1934    path: &Path,
1935    bytes: &[u8],
1936    mode: Option<u32>,
1937    proceed: &dyn Fn() -> bool,
1938) -> LeanResult<Option<std::fs::Metadata>> {
1939    super::safefs::check_parent(path)?;
1940    let tmp = path.with_file_name(format!(
1941        "{}.flint-sync-tmp",
1942        path.file_name().map(|n| n.to_string_lossy()).unwrap_or_default()
1943    ));
1944    super::safefs::write_via_tmp_fast_if(path, &tmp, bytes, mode, proceed)
1945}
1946
1947// Test-only: run a closure inside a write window for one path —
1948// `"before-write"` (the licence to overwrite checked, the temp not yet
1949// written), `"after-rename"` (before the baseline records the write), or
1950// `"before-delete"` (`sync`'s remote-delete arm). The consume and `sync`
1951// both open them. Nothing in either window calls the store, so the hooked double
1952// cannot reach them (review 2026-09-18, H7).
1953#[cfg(test)]
1954thread_local! {
1955    pub(super) static CONSUME_WINDOW_HOOK: std::cell::RefCell<Option<(String, &'static str, Box<dyn Fn()>)>> =
1956        std::cell::RefCell::new(None);
1957}
1958
1959#[cfg(test)]
1960pub(super) fn consume_window(stage: &'static str, path: &str) {
1961    let hook = CONSUME_WINDOW_HOOK.with(|h| {
1962        let mut h = h.borrow_mut();
1963        if matches!(&*h, Some((p, s, _)) if p == path && *s == stage) {
1964            h.take().map(|(_, _, f)| f)
1965        } else {
1966            None
1967        }
1968    });
1969    if let Some(f) = hook {
1970        f();
1971    }
1972}
1973
1974#[cfg(not(test))]
1975#[inline(always)]
1976pub(super) fn consume_window(_: &'static str, _: &str) {}
1977
1978/// How many merge races a commit may lose before its barrier gives up (the
1979/// next tick tries again). Under P2 the UI saves without the lease (G1), so
1980/// the races are lost to saves, and backing off finds the gaps between them.
1981const CAS_ATTEMPTS: u32 = 12;
1982
1983/// The wait after the `attempt`-th lost race: 10 ms, doubling, capped at
1984/// 640 ms, plus up to half again of jitter from the clock's nanoseconds, so
1985/// a writer and a stream of saves do not fall into lockstep.
1986fn cas_backoff(attempt: u32) -> std::time::Duration {
1987    let base = 10u64 << attempt.saturating_sub(1).min(6);
1988    let nanos = std::time::SystemTime::now()
1989        .duration_since(std::time::UNIX_EPOCH)
1990        .map(|d| d.subsec_nanos() as u64)
1991        .unwrap_or(0);
1992    std::time::Duration::from_millis(base + nanos % (base / 2 + 1))
1993}
1994
1995
1996/// The merge base, P1-lite: the baseline's own citations. A tree holds no
1997/// version the document never cited (P2), so what it integrated IS what it
1998/// merges from; one base serves the merge and every reader of its outcome
1999/// (M5, L-124).
2000fn merge_base(baseline: &super::state::Baseline) -> BTreeMap<String, String> {
2001    baseline.entries.iter().map(|(p, e)| (p.clone(), e.etag.clone())).collect()
2002}
2003
2004/// One three-way merge of a barrier's changes onto the bucket's manifest.
2005struct MergeOnto {
2006    theirs: manifest::LeanManifest,
2007    /// The CAS handle over `theirs`; `None` when the bucket has no manifest.
2008    expected: Option<manifest::ManifestHandle>,
2009    merged: manifest::LeanManifest,
2010    /// Other writers' changes since the merge base that the tree lacks.
2011    foreign: Vec<(String, LeanEntry)>,
2012    /// Theirs' version at a path this barrier uploaded, changed since the
2013    /// merge base: what mine publishes OVER. The caller surfaces those it
2014    /// never integrated (design 2026-09-19, R7).
2015    overridden: Vec<(String, LeanEntry)>,
2016    /// Theirs' DELETES this barrier's uploads publish over (`merge`).
2017    recreated: Vec<(String, String)>,
2018    /// Theirs' version at a path this barrier DELETES, changed since the
2019    /// merge base (M3): the caller preserves and records each.
2020    over_theirs: Vec<(String, LeanEntry)>,
2021}
2022
2023impl MergeOnto {
2024    /// The merge adds nothing to the document: installing it would be an
2025    /// empty generation.
2026    fn adds_nothing(&self) -> bool {
2027        self.merged.entries == self.theirs.entries && self.merged.sole_writer == self.theirs.sole_writer
2028    }
2029}
2030
2031impl Syncer {
2032    /// H10: the carried uploads the document this barrier ended at does not
2033    /// cite (a peer deleted them since). The ack names that document, so it
2034    /// reads this; no request is made for it.
2035    fn note_carrier_uncited(&self, doc: &manifest::LeanManifest) -> LeanResult<()> {
2036        let mut intent = self.state.load_intent()?;
2037        let Some(c) = intent.carrier.as_mut() else { return Ok(()) };
2038        let uncited: BTreeSet<String> = c
2039            .paths
2040            .iter()
2041            .filter(|p| !c.deletes.contains(*p) && !doc.entries.contains_key(p.as_str()))
2042            .cloned()
2043            .collect();
2044        if uncited != c.uncited {
2045            c.uncited = uncited;
2046            self.state.save_intent(&intent)?;
2047        }
2048        Ok(())
2049    }
2050
2051    fn merge_onto(
2052        &self,
2053        current: Option<&manifest::LoadedManifest>,
2054        // `merge_base`'s answer, which the caller also gives every other
2055        // reader of this merge's outcome.
2056        base: &BTreeMap<String, String>,
2057        upserts: &BTreeMap<String, LeanEntry>,
2058        deletes: &BTreeSet<String>,
2059        parked: &BTreeSet<String>,
2060        flush_uuid: &str,
2061    ) -> MergeOnto {
2062        let (theirs, expected) = match current {
2063            // The handle carries the LAYOUT as well as the tag: a
2064            // workspace still on the legacy single object CASes a
2065            // pointer that must not exist yet, not one it read.
2066            Some(l) => (l.manifest.clone(), Some(l.handle())),
2067            None => (Default::default(), None),
2068        };
2069        let manifest::Merged { doc: mut merged, foreign, overridden, deletes: outcomes, recreated, over_theirs } =
2070            manifest::merge(base, &theirs, upserts, deletes, parked);
2071        // The deletes theirs outranked, named: the trace's record of the
2072        // merge's per-path decision (`TraceCore.tla` checks it against
2073        // `Install`'s `Foreign(s, p)`).
2074        // Since M3 no delete is outranked; the trace keeps the field (empty)
2075        // and names the deletes that went over theirs.
2076        let outranked: Vec<&String> = vec![];
2077        let deleted_over: Vec<&String> =
2078            outcomes.iter().filter(|(_, o)| **o == manifest::DeleteOutcome::OverTheirs).map(|(p, _)| p).collect();
2079        // Deletions another writer made since this workspace's
2080        // merge base: in the base, gone from theirs, and not this
2081        // barrier's own upsert, delete or park. `merge` has no use
2082        // for them — theirs already lacks the path — but the TREE
2083        // does: they reach it through the local queue, as the
2084        // foreign upserts do.
2085        let gone: Vec<(String, String)> = base
2086            .iter()
2087            .filter(|(p, _)| {
2088                !theirs.entries.contains_key(*p)
2089                    && !upserts.contains_key(*p)
2090                    && !deletes.contains(*p)
2091                    && !parked.contains(*p)
2092            })
2093            .map(|(p, retired)| (p.clone(), retired.clone()))
2094            .collect();
2095        // `merge` clears it; the installing pass owns it. A mirror
2096        // is a property of how this workspace is DEPLOYED, so it
2097        // comes from config on every publish rather than being
2098        // inherited from whatever wrote last.
2099        merged.sole_writer = self.cfg.sole_writer;
2100        self.trace("merge", serde_json::json!({"flush": flush_uuid, "theirs_seq": theirs.seq, "upserts": upserts.len(),
2101            "deletes": deletes.len(), "foreign": foreign.len(), "gone": gone.len(), "overridden": overridden.len(),
2102            "outranked": outranked, "over_theirs": deleted_over, "adds_nothing": merged.entries == theirs.entries}));
2103        MergeOnto { theirs, expected, merged, foreign, overridden, recreated, over_theirs }
2104    }
2105}