flint_lean/lib.rs
1//! flint-lean: the checkout/publish syncer core (plan of record:
2//! docs/plans/flint-lean-plan.md v2).
3//!
4//! Lean is a SEPARATE front end from the hub: no NFS, no daemon in the
5//! data path. An agent pod gets a full local checkout on an emptyDir
6//! (real ext4/APFS POSIX), and a syncer publishes snapshots to the
7//! bucket through a barrier. Durability is RPO-shaped (the flush floor);
8//! coherence is snapshot-level (the subtree manifest CAS is the atomic
9//! commit point). This module reuses `tier::store` (ObjectStore,
10//! GenerationStamps, conditional puts, the epoch cell) as a library and
11//! deliberately does NOT reuse the hub's flush/arbitration machinery —
12//! the plan pins that: the hub's 412 arbitration is LOCAL-WINS-overwrite
13//! (`tier/flush.rs`), which is exactly wrong under HITL second writers.
14//!
15//! The protocol here is the shipped shape `lean/PROTOCOL.md` writes out,
16//! from its model `lean/formal/LeanP1.tla` (the shape since the
17//! simplification of 2026-09-25: P1, P2, M1). PROTOCOL.md has every rule
18//! with the invariant it holds up and the model world that fails without
19//! it; the load-bearing ones, in brief:
20//!
21//! - **Every write lands at a fresh immutable handle**
22//! (`files/<path>@<flush>`), and **the pointer CAS is the only commit**
23//! — a writer's and the gateway's alike. Nothing overwrites a handle.
24//! - **The gateway commits each UI verb itself (P2)**: a save PUTs a fresh
25//! handle, then ONE pointer CAS that lands only over the version the UI
26//! read (else 412); a rename or a delete is one CAS. It never takes the
27//! writers' lease. The request cell (`inbox`, `.flint/lean/inbox`)
28//! carries only the two verb requests, "please publish" and "please
29//! pull" — no entries, no removals, no window.
30//! - **The barrier**: consume (the cheap path: the scan trigger) → scan →
31//! upload → claim the lease → verify the uploads (R4a) → install, a
32//! three-way merge onto the CURRENT document with the baseline as the
33//! merge base (mine wins modify/modify; R7 records theirs; a delete over
34//! theirs applies, theirs kept, M3) → collect → finish (the baseline
35//! follows what landed).
36//! - **What a commit stops citing is retired, not deleted**: logged at
37//! the CAS and reaped only once G old (M1), so a reader that loaded
38//! less than G ago can still fetch it. The orphan sweep runs only under
39//! the lease (R4b) and spares a save in flight (G3).
40//! - **Takeover rotation**: a successor rewrites the document before
41//! serving, so a deposed holder's pointer CAS 412s; the worker-facing
42//! verbs are epoch-validated per request.
43//! - **Restart matrix**: marker present ⇒ never re-materialize (a
44//! re-checkout would resurrect unpublished deletes); reload the
45//! persisted baseline, rescan, self-recognize the lease via the
46//! persisted incarnation id (emptyDir-scoped — a replacement pod gets
47//! a fresh identity and takes the takeover path).
48//! - **Deletion basis**: a path is delete-eligible only if absent in
49//! two consecutive scans AND present in our own baseline (the
50//! rename-vs-walk guard).
51
52pub mod barrier;
53pub mod checkout;
54pub mod chunk;
55pub mod chunkcache;
56pub mod conformance;
57pub mod control;
58pub mod docview;
59pub mod gauges;
60pub use gauges::{status_report, Gauges, StatusReport};
61pub mod inbox;
62pub mod lease;
63pub mod manifest;
64pub mod metrics;
65pub mod news;
66pub mod reader;
67pub mod scan;
68pub(crate) mod safefs;
69pub mod sentinel;
70pub mod state;
71pub mod sync;
72pub mod trace;
73pub mod tracked;
74pub mod untracked;
75pub mod uds;
76pub mod verbs;
77
78#[cfg(test)]
79mod tests;
80#[cfg(test)] mod tests_upload_gate;
81#[cfg(test)] mod tests_conformance;
82#[cfg(test)] mod tests_bench;
83#[cfg(test)] mod tests_steps;
84#[cfg(test)] mod tests_cache;
85#[cfg(test)] mod tests_baseline;
86#[cfg(test)] mod tests_walk;
87#[cfg(test)] mod tests_news;
88// The binary's allocator (`fastalloc`, bin/flint_sync.rs) never reached
89// the test binary: the battery and the latency benches ran the system
90// malloc (glibc on the box) while flint-sync ships mimalloc. Under
91// `fastalloc` they run the shipped allocator too.
92#[cfg(all(test, feature = "fastalloc"))]
93#[global_allocator]
94static TEST_GLOBAL: mimalloc::MiMalloc = mimalloc::MiMalloc;
95#[cfg(test)] mod tests_rechunk;
96#[cfg(test)] mod tests_docview;
97#[cfg(test)] mod tests_rehash;
98
99use std::path::PathBuf;
100use std::sync::Arc;
101
102use flint_store::ObjectStore;
103
104/// Reserved control namespace inside the subtree prefix. Never scanned,
105/// never part of a checkout, never GC'd by the barrier.
106pub const LEAN_DIR: &str = ".flint/lean";
107
108/// The syncer's durable bookkeeping directory inside the workspace
109/// (emptyDir-scoped: survives container restarts, dies with the pod).
110pub const STATE_DIR: &str = ".flint-sync";
111
112/// The chunk cache's directory inside the state dir (`chunkcache`).
113pub const CHUNK_CACHE_DIR: &str = "chunk-cache";
114
115/// Chunk GETs a manifest load keeps in flight (`LeanConfig::
116/// chunk_fetch_parallelism`). A chunk is about 1 MiB, so this many is
117/// 16 MiB in flight; the bodies are all held until the document is
118/// assembled anyway, as they were when they were fetched one at a time.
119pub const CHUNK_FETCH_PARALLELISM: usize = 16;
120
121/// The workspace-local control namespace (boundary-verbs plan D0): the
122/// agent's side of the file protocol. Reserved exactly as the gateway
123/// reserves `.flint/` on the HTTP side (flint-lean-gateway's `path_ok`) — the scan
124/// skips it, `classify` never makes it delete-eligible, and checkout
125/// never materializes a `files/.flint/...` citation into it.
126pub const CONTROL_DIR: &str = ".flint";
127
128/// Protocol version advertised in `.flint/capabilities.json`.
129pub const SENTINEL_PROTOCOL: u32 = 1;
130
131/// This binary's version, echoed to the agent (`capabilities.json`) and
132/// to the operator (the lease cell's echo, §2.6). Both mixed-version
133/// holes — agent↔syncer and operator↔syncer — are detected by
134/// comparing what is RUNNING against what was asked for, and neither
135/// comparison exists without a version on the running side.
136pub const SYNCER_VERSION: &str = env!("CARGO_PKG_VERSION");
137
138/// Default whole-object publish ceiling; larger files go through the
139/// multipart compose path (`tier/flush.rs` uses the same 64 MiB split).
140pub const WHOLE_PUT_MAX: u64 = 64 * 1024 * 1024;
141
142#[derive(Debug, thiserror::Error)]
143pub enum LeanError {
144 #[error("store: {0}")]
145 Store(#[from] flint_store::StoreError),
146 #[error("io: {0}")]
147 Io(#[from] std::io::Error),
148 #[error("state: {0}")]
149 State(String),
150 /// A gateway write's precondition, judged against the version the
151 /// workspace tracked, was lost at the inbox CELL's CAS: a different
152 /// write is tracked at the path now (design 2026-09-19, class 5 —
153 /// L-48's two browsers, decided atomically where the entry lands).
154 #[error("{path} is now tracked at {current}; re-read it and try again")]
155 Lost { path: String, current: String },
156 /// The cell moved under a commit section: this barrier is
157 /// abandoned — its manifest is never installed, its uploads stand
158 /// as uncited generations the next barrier adopts by `flush_uuid`.
159 /// Not a process exit and not a terminal state: the lease is held
160 /// per barrier, so the next one claims again.
161 #[error("fenced: {0}")]
162 Fenced(String),
163 /// A budget refused the operation (checkout bytes/file-count).
164 #[error("budget: {0}")]
165 Budget(String),
166 /// A precondition the OPERATOR must change refused the run (the
167 /// prefix is claimed by another project). A restart cannot fix it,
168 /// so the binary exits `EXIT_REFUSED` — the code the CSI delivery
169 /// reads as final. Any other non-zero exit is retried in place by
170 /// `restartPolicy: OnFailure`, and a refusal sharing that code was a
171 /// crash loop the plugin reported to the tenant as "checkout in
172 /// progress" for as long as it lived (audit 2026-09-03, finding 5,
173 /// leg S22).
174 #[error("refused: {0}")]
175 Refused(String),
176}
177
178/// Process exit code for `LeanError::Refused` (sysexits `EX_CONFIG`).
179/// Mirrored as `SYNCER_EXIT_REFUSED` in the CSI node plugin, which does
180/// not depend on this crate; drill leg S22 is where the two are checked
181/// against each other.
182pub const EXIT_REFUSED: i32 = 78;
183
184impl LeanError {
185 /// The store refused our credentials (401/403, `ExpiredToken`,
186 /// `RequestTimeTooSkewed`): a broker, token or clock fault.
187 ///
188 /// A predicate rather than a `LeanError` variant on purpose.
189 /// `Store` is built by `#[from]`, so every `?` in the crate
190 /// constructs it implicitly; a variant would have to be produced by
191 /// hand at each of those sites and would be missed at exactly the
192 /// one that mattered. Reading through the wrapper cannot be
193 /// bypassed by a conversion nobody remembered to special-case.
194 pub fn is_auth(&self) -> bool {
195 matches!(self, LeanError::Store(flint_store::StoreError::Auth(_)))
196 }
197}
198
199pub type LeanResult<T> = Result<T, LeanError>;
200
201/// Sentinel posture knob (D0.4). `auto` = verbs on unless the
202/// pre-existing-`.flint/` pre-flight trips; `force` accepts consumption
203/// of pre-existing sentinel-named files.
204#[derive(Clone, Copy, Debug, PartialEq, Eq)]
205pub enum SentinelMode {
206 Auto,
207 Off,
208 Force,
209}
210
211impl SentinelMode {
212 pub fn parse(s: &str) -> Option<SentinelMode> {
213 match s {
214 "auto" => Some(SentinelMode::Auto),
215 "off" => Some(SentinelMode::Off),
216 "force" => Some(SentinelMode::Force),
217 _ => None,
218 }
219 }
220 pub fn as_str(&self) -> &'static str {
221 match self {
222 SentinelMode::Auto => "auto",
223 SentinelMode::Off => "off",
224 SentinelMode::Force => "force",
225 }
226 }
227}
228
229/// What this syncer may do to the bucket (per-user access design §4.4).
230///
231/// `Read` is a syncer that follows the workspace and never writes to it:
232/// no fence, no barrier, no inbox consume, no garbage collection. Its
233/// floor tick pulls — the inbox and the pointer, and a `sync` when
234/// either moved — and a `publish` is answered `refused-read-only`. It is
235/// what a read-only credential is SUFFICIENT for; the credential, not
236/// this flag, is what keeps a reader's bytes out of the bucket.
237#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
238pub enum Access {
239 #[default]
240 ReadWrite,
241 Read,
242}
243
244impl Access {
245 /// `FLINT_SYNC_ACCESS`: `read` | `readWrite`.
246 pub fn parse(s: &str) -> Option<Access> {
247 match s {
248 "read" => Some(Access::Read),
249 "readWrite" => Some(Access::ReadWrite),
250 _ => None,
251 }
252 }
253 pub fn as_str(&self) -> &'static str {
254 match self {
255 Access::ReadWrite => "readWrite",
256 Access::Read => "read",
257 }
258 }
259 pub fn is_read(&self) -> bool {
260 *self == Access::Read
261 }
262}
263
264#[derive(Clone)]
265pub struct LeanConfig {
266 /// Bucket key prefix for this subtree (project- or subtree-scoped;
267 /// the proxy's tenancy boundary).
268 pub prefix: String,
269 /// Workspace root (the agent's tree).
270 pub root: PathBuf,
271 /// Publish cadence floor, seconds (the durability contract).
272 pub floor_secs: u64,
273 /// Stamp `sole_writer` on every manifest this syncer installs.
274 ///
275 /// Set for a workspace that is PUBLISHED rather than worked in —
276 /// forge's legible export is the shipped case. It tells every later
277 /// reader that an object off its citation was moved by a stranger,
278 /// so the reader refuses instead of adopting.
279 pub sole_writer: bool,
280 /// Read or read-write (`Access`). Default read-write.
281 pub access: Access,
282 /// Whole-object ceiling; larger files use multipart compose.
283 pub whole_put_max: u64,
284 /// Entries per manifest chunk, in expectation, and the floor and
285 /// ceiling around it (chunked design §3). Config rather than
286 /// constants because §4 already anticipates this moving: the
287 /// pointer body is O(entries / target), and past ~10M entries the
288 /// target is one of the two things that can be changed instead of
289 /// adding a second level. Not surfaced on the CRD — nothing has
290 /// needed to tune it per workspace yet, and a knob with no caller
291 /// is a support burden.
292 /// Publish the manifest as a CHUNK LIST rather than one generation
293 /// object per citation (chunked design). Default ON since
294 /// 2026-09-04.
295 ///
296 /// The migration is FAIL-CLOSED and one-way per workspace: a
297 /// pointer-era binary cannot parse a chunked pointer, which is the
298 /// point — every layout change has to make an old reader REFUSE
299 /// rather than conclude the project is empty and re-seed over it.
300 ///
301 /// Small projects are not penalised, which is what made turning it
302 /// on unconditional rather than threshold-gated: under the target a
303 /// project is ONE chunk, so it costs a pointer plus one object and
304 /// two GETs to read — exactly what the single-generation layout
305 /// already cost. The indirection was paid for by step one.
306 ///
307 /// `false` is still a supported READ path forever (a workspace that
308 /// has not published since the migration) and is what the
309 /// single-layout tests set explicitly.
310 pub chunked: bool,
311 /// How long an unreferenced chunk must have sat before the reaper
312 /// may take it. Config rather than a constant because the model
313 /// makes it load-bearing in a workload-dependent way: it must
314 /// outlive the LONGEST publish, not the longest plausible one
315 /// (`LeanChunkGCRacyGrace`).
316 pub orphan_grace_secs: u64,
317 /// RETIRE-AGE G (M1 of the 2026-09-24 simplification analysis): a
318 /// handle or chunk a commit stopped referencing is collected only once
319 /// its RETIREMENT is this old — not its write, which for a long-lived
320 /// file or chunk is long past the moment a UI save supersedes it. A
321 /// reader that loaded a document less than G ago can fetch everything
322 /// it cites. 0 = collect at once (the shape before; the battery's
323 /// default). `FLINT_SYNC_RETIRE_GRACE_SECS`.
324 pub retire_grace_secs: u64,
325 /// THE COLLECTION CADENCE (latency plan 2026-10-23, lever C): how often
326 /// a writer's commit section runs the collection pass — read the retire
327 /// logs, reap what is due, the orphan sweep when it is due too, the
328 /// generation and chunk sweeps. Each pass is a LIST of `retired/`, of
329 /// `manifests/` and of `chunks/`, and pointer GETs, all under the
330 /// lease; run on every publish they were seven sequential requests
331 /// added to every commit. Between passes nothing is deleted, so what a
332 /// commit retires waits up to G plus this long: storage, never safety
333 /// (the model's reap and sweeps may run at any commit, or never).
334 /// 0 = every commit, as before (the battery's setting).
335 /// `FLINT_SYNC_COLLECT_EVERY_SECS`.
336 pub collect_every_secs: u64,
337 /// Manifest chunks kept locally by content address, verified on every
338 /// use (`chunkcache`; latency plan lever A). `None` fetches every
339 /// chunk of every load, as before. The syncer keeps them under its
340 /// state dir, the gateway in memory.
341 pub chunk_cache: Option<Arc<dyn chunkcache::ChunkCache>>,
342 /// Chunk fetches a load keeps in flight at once: the misses of a
343 /// cached load, every chunk of an uncached one. 1 = one at a time,
344 /// the shape before. `FLINT_SYNC_CHUNK_FETCH_PARALLELISM`.
345 pub chunk_fetch_parallelism: usize,
346 /// A commit reads the document chunk by chunk (latency plan lever G,
347 /// `docview`): only the chunks its paths fall in, and it re-chunks only
348 /// what it changed. `false` loads and merges the whole document, the
349 /// shape before. `FLINT_SYNC_CHUNK_VIEW=off`.
350 pub chunk_view: bool,
351 /// Tests only: every chunk-view commit also runs the whole-document
352 /// merge and asserts the same document, chunk list, retire set and
353 /// per-path decisions (latency plan §12, "Verification").
354 pub g_shadow: bool,
355 /// A checkout measures its entries' racy flags when it opens the
356 /// agent's gate, not when it wrote each file (latency plan §17;
357 /// LeanScanRacy's `MeasureAtGate`), so the first scan hashes only what
358 /// it wrote in its last window. `false` leaves every checked-out entry
359 /// racy, the shape before. `FLINT_SYNC_RACY_AT_GATE=off`.
360 pub racy_at_gate: bool,
361 /// The tree's reserved blocks are this syncer's (the s3csi quota
362 /// image reserves 1/16 of itself for a group only the syncer's worker
363 /// holds): tree CONTENT it writes — a checkout, a consume, a sync — is
364 /// held to what its tenant could still write (`f_bavail`), so the
365 /// reserve is left for the bookkeeping that must outlive a full tree
366 /// (`safefs::leave_the_reserve`). `FLINT_SYNC_TREE_RESERVE=on`, set by
367 /// the plugin on a quota'd tree; off, nothing is checked.
368 pub tree_reserve: bool,
369 /// Tests only: the bytes `leave_the_reserve` reads as the tenant's room
370 /// instead of asking `statvfs` (a full filesystem needs root to build).
371 pub tree_room_for_tests: Option<u64>,
372 /// The fewest files still racy at the gate for which the checkout opens
373 /// it the rest of their window later (at most two seconds), so the
374 /// first scan hashes none of them: about where hashing them costs more
375 /// than the wait. 0 never waits. `FLINT_SYNC_RACY_WAIT_MIN`.
376 pub racy_wait_min: usize,
377 /// This workspace's chunks' aliases, by address (`docview`): what lets
378 /// a commit answer "who else cites this handle" without the document.
379 /// Shared by every clone of the config, so a syncer's views share it.
380 pub alias_cache: Arc<docview::AliasCache>,
381 pub chunk_target: usize,
382 pub chunk_min: usize,
383 pub chunk_max: usize,
384 /// Checkout refusal budgets (0 = unlimited).
385 pub max_bytes: u64,
386 pub max_files: u64,
387 /// Bounded concurrency for uploads and checkout fetches. The 0b
388 /// rig measured the sequential loops at 561-854 PUTs/s and
389 /// 1,000-2,000 GETs/s; fan-out multiplies directly against those.
390 pub fanout: usize,
391 /// Concurrent UPLOADS. Deliberately separate from `fanout`, and
392 /// measured separately: the read path's width is what the checkout
393 /// rig moved, this one is what the publish rig moved. Both paths are
394 /// byte-bounded, by different gates — the read side by
395 /// `fetch_inflight_max_bytes` here, the upload side by the store's
396 /// own gate (`with_upload_inflight_max_bytes`, 512 MiB from the
397 /// binary), which charges every whole body and every multipart part
398 /// from before its read until its PUT returns. So this number sets
399 /// request concurrency, not peak RSS.
400 pub upload_fanout: usize,
401 /// The project this workspace claims to be, stamped from the CR
402 /// (`FLINT_SYNC_PROJECT_ID`). When set, `lease::verify_claim`
403 /// refuses to run over a prefix whose claim cell names another
404 /// project — the operator's refuse-foreign, enforced on the DATA
405 /// plane (audit 2026-09-03, finding 5). `None` = unstamped: no
406 /// check, the pre-operator posture.
407 pub project_id: Option<String>,
408 /// Ceiling on bytes in flight across the checkout fan-out window.
409 ///
410 /// `fanout` bounds the number of concurrent fetches but NOT their
411 /// size, and `get_whole` holds each whole object in RAM before it
412 /// reaches disk — so peak RSS was `fanout x largest object`, an
413 /// unbounded product of two numbers nobody sets together. A 32-wide
414 /// window over 64 MiB objects is 2 GiB in a syncer that ships with
415 /// no memory limit at all. Each entry takes permits proportional to
416 /// its size, so small-file trees still run the full width.
417 pub fetch_inflight_max_bytes: u64,
418 /// Driver tasks for the checkout fan-out (see `materialize`). Each
419 /// runs `fanout / fetch_drivers` fetches at a time over its own
420 /// slice of the tree, so the per-request SDK work spreads over that
421 /// many cores instead of one. Default: the machine's cores, at most
422 /// 8 (`FLINT_SYNC_FETCH_DRIVERS` / `spec.fetchDrivers`, 0 = auto).
423 /// Measured 2026-09-12: one driver is the ~3,300 files/s plateau on
424 /// i4i.xlarge whatever `fanout` says; four are 6,188-6,521 at
425 /// fanout 256, and fanout 256 beats 128 for the first time.
426 pub fetch_drivers: usize,
427
428 /// Materialise an object this size or larger as PARALLEL RANGES
429 /// rather than one whole-object GET. `0` disables it.
430 ///
431 /// Defaults to 8 MiB on the measurement that the repo's rule asked
432 /// for — runcr, i4i.large spot, us-west-1, one AZ, n=3, arms
433 /// interleaved per rep, RANGES not means:
434 ///
435 /// 6 x 1 GiB 71.33-71.88 s -> 21.24-23.96 s
436 /// 4 GiB + 2k x 16 K 57.02-57.83 s -> 15.30-18.30 s
437 /// 20k x 8 KiB 16.92-19.44 s -> 16.40-17.39 s
438 ///
439 /// The third row is the one that justifies a THRESHOLD rather than
440 /// ranging everything: every object there is under it, the ranged
441 /// path never fires, and the arms agree. Before this, the shipped
442 /// path lost a cold 6 GiB checkout to a plain `aws s3 cp` of the
443 /// same prefix on the same node (21.7 s); it now ties it.
444 ///
445 /// Ranging also LOWERS peak RSS for a large object — see below — so
446 /// this default costs memory nothing and returns some.
447 ///
448 /// NOTE the interaction with `range_get_chunk_bytes`: a single part
449 /// is "one whole GET with extra steps" and `fetch_ranged` declines
450 /// it, so an object in [`range_get_min_bytes`, `range_get_chunk_bytes`)
451 /// passes this threshold and still takes the whole-object path. With
452 /// the defaults below the EFFECTIVE threshold is therefore 16 MiB,
453 /// not 8.
454 ///
455 /// Two costs of `get_whole` are paid together and this is what
456 /// removes both: one object is one TCP stream, so a multi-GiB
457 /// checkpoint runs at single-connection throughput no matter how
458 /// wide the fan-out; and the body is held whole in RAM before it
459 /// reaches disk, which is the product `fetch_inflight_max_bytes`
460 /// exists to bound. Ranges write at their offset as they land, so
461 /// peak RSS per object becomes `range_get_chunk_bytes x
462 /// range_get_parallelism` instead of the object's size.
463 pub range_get_min_bytes: u64,
464 /// Bytes per range request. Large enough that per-request overhead
465 /// is noise against S3's first-byte latency; small enough that a
466 /// retried range is cheap.
467 pub range_get_chunk_bytes: u64,
468 /// Ranges in flight FOR ONE OBJECT. The checkout's byte semaphore
469 /// still bounds the whole window, so this multiplies concurrency
470 /// only where the fan-out has run out of objects to work on — which
471 /// is exactly the tail this exists to shorten.
472 pub range_get_parallelism: usize,
473
474 // --- boundary verbs (plan docs/plans/flint-lean-boundary-verbs-plan.md) ---
475 /// Sentinel posture (D0.4 pre-flight override).
476 pub sentinel_mode: SentinelMode,
477 /// A consumed sentinel arriving sooner than this after the previous
478 /// sentinel-honoring barrier waits; touches inside the interval
479 /// coalesce into the pending record.
480 pub sentinel_min_interval_secs: u64,
481 /// Work-metered hourly cap (D3.1): a honor charges
482 /// `max(1, ceil(published_bytes / whole_put_max))` units, or 0 for
483 /// a no-diff honor. Exhaustion defers honors to the floor tick —
484 /// the workspace degrades to exactly cadence behavior.
485 pub sentinel_hourly_budget: u64,
486 /// Sentinel poll cadence (env-only, not a fleet contract).
487 pub sentinel_poll_secs: u64,
488
489 // --- the news poll (latency plan 2026-10-23, lever B; `news.rs`) ---
490 /// While the workspace is active, read the pointer (a writer the cell
491 /// too) this often, and run the floor's barrier early when a peer or
492 /// the gateway moved it. 0 = off: news waits for the floor, as
493 /// before. `FLINT_SYNC_NEWS_POLL_SECS`.
494 pub news_poll_secs: u64,
495 /// How long after the last sign of work (a publish, a consume, an ack,
496 /// a served request, news) the workspace counts as active. Past it
497 /// the poll stops and only the floor reads the bucket.
498 /// `FLINT_SYNC_NEWS_ACTIVE_SECS`.
499 pub news_active_secs: u64,
500 /// The fewest seconds between two news-triggered barriers. News inside
501 /// it waits, so two busy writers cannot answer each other's publishes
502 /// faster than this. `FLINT_SYNC_NEWS_MIN_INTERVAL_SECS`.
503 pub news_min_interval_secs: u64,
504
505 // --- the publish fence (design 2026-09-13 §4; `lease.rs`) ---
506 /// How often a barrier waiting for the cell re-reads it.
507 pub claim_poll_secs: u64,
508 /// The poll cadence of the waiter at the head of the queue
509 /// (`lease::CLAIM_POLL_HEAD_MS`).
510 pub claim_poll_head_ms: u64,
511 /// Minimum spacing between two observations that COUNT toward the
512 /// dead-holder (`QUIET_POLLS`) and abandoned-handoff thresholds.
513 /// The tests set it to 0 so a deposal takes six polls, not a minute.
514 pub claim_quiet_spacing_secs: u64,
515 /// Longest a barrier waits for the cell before it is abandoned and
516 /// retried at the next floor.
517 pub claim_deadline_secs: u64,
518 /// DRILL-ONLY (`FLINT_SYNC_DRILL_HOLD_COMMIT_SECS`, never stamped by
519 /// the operator): sleep this long inside the commit section, right
520 /// after the claim. The one straggler the per-barrier lease still
521 /// has is a holder that stalls INSIDE its commit section, and that
522 /// section is milliseconds long — no drill can hit it by timing, so
523 /// this is how `run-writers.sh` opens the window. 0 = off.
524 pub drill_hold_commit_secs: u64,
525 /// DRILL-ONLY (`FLINT_SYNC_DRILL_HOLD_GC_SECS`, never stamped by the
526 /// operator): sleep this long before the collector's batched DELETE
527 /// of what the install retired, once per barrier. Under immutable
528 /// handles the collector is one unconditional `delete_many` with no
529 /// HEAD before it, so the window a drill wants is the one between
530 /// the CAS and that batch — a peer's sweep, or its commit, running
531 /// while this barrier still owes its tidy-up. 0 = off.
532 pub drill_hold_gc_secs: u64,
533 /// The protocol event trace (`trace.rs`); `None` = off.
534 pub event_trace: Option<trace::Sink>,
535 /// How often a WRITER sweeps for an upload a lost writer left at a
536 /// cited key (`untracked.rs`, finding 10), seconds;
537 /// `FLINT_SYNC_UNTRACKED_SWEEP_SECS`, 0 = off. Each sweep is one LIST of
538 /// the files prefix plus a manifest and an inbox read.
539 pub untracked_sweep_secs: u64,
540 /// How long such an object must have sat untracked before the sweep
541 /// tracks it — the gateway's `UNTRACKED_GRACE_SECS`, past any live
542 /// writer's claim and commit.
543 pub untracked_grace_secs: u64,
544 /// Threads the scan walks the tree with (`scan::scan_with`, lever E);
545 /// `FLINT_SYNC_SCAN_THREADS`. The CPUs this process may use, at most
546 /// 8; 1 walks with one worker.
547 pub scan_threads: usize,
548 /// How old the last cell WRITE (claim or renew) may be before a
549 /// delete in the commit section renews first (review 2026-09-18,
550 /// C2). A deposal needs the token still for six spaced polls (60 s),
551 /// so a write younger than this is proof no deposal has happened;
552 /// an older one is renewed — a conditional write that a deposal has
553 /// moved, so it fences. Comfortably below the threshold. Tests set 0
554 /// to collapse a stall.
555 pub renew_within_secs: u64,
556}
557
558/// The gateway's flush id for a UI write's handle: `ui-<added_unix>-<uuid>`.
559/// The time is the order a consume reads off two UI handles of one path
560/// (design 2026-09-19, R7's "later"): a citation that moved to a LATER
561/// gateway write supersedes an entry, one that moved to an earlier one
562/// leaves it live. One gateway's clock orders its own writes exactly;
563/// two replicas' clocks are the residual, and a tie or an inversion
564/// between them costs a surfaced conflict, never a silent drop.
565pub fn ui_flush(added_unix: u64) -> String {
566 format!("ui-{added_unix}-{}", uuid::Uuid::new_v4())
567}
568
569/// The `added_unix` a UI flush id carries; `None` for any other flush.
570pub fn ui_flush_added(flush: &str) -> Option<u64> {
571 let rest = flush.strip_prefix("ui-")?;
572 let (t, _) = rest.split_once('-')?;
573 t.parse().ok()
574}
575
576/// Does `flush` read as a flush id this crate or the gateway mints — a
577/// uuid, the `ui-…` form, or the gateway's `gateway-…` forms — rather than
578/// a tail of a path that happens to follow an `@`?
579fn flush_looks_minted(flush: &str) -> bool {
580 if flush.starts_with("ui-")
581 || flush.starts_with("gateway-")
582 || flush.starts_with("ingress-")
583 || flush == "conflict-preserve"
584 {
585 return true;
586 }
587 uuid::Uuid::parse_str(flush).is_ok()
588}
589
590impl LeanConfig {
591 pub fn new(prefix: &str, root: impl Into<PathBuf>) -> Self {
592 let root: PathBuf = root.into();
593 let chunk_cache: Arc<dyn chunkcache::ChunkCache> =
594 Arc::new(chunkcache::DiskChunkCache::new(root.join(STATE_DIR).join(CHUNK_CACHE_DIR)));
595 LeanConfig {
596 prefix: prefix.trim_end_matches('/').to_string(),
597 root,
598 floor_secs: 60,
599 // Off by default: a workspace an agent WORKS IN wants the
600 // S3-wins arm, where an object past its citation is a human
601 // whose bytes should win. Only a published mirror sets it.
602 sole_writer: false,
603 access: Access::ReadWrite,
604 whole_put_max: WHOLE_PUT_MAX,
605 chunked: true,
606 orphan_grace_secs: manifest::ORPHAN_GRACE_SECS,
607 retire_grace_secs: manifest::RETIRE_GRACE_SECS,
608 collect_every_secs: manifest::RETIRE_GRACE_SECS / 2,
609 chunk_cache: Some(chunk_cache),
610 chunk_fetch_parallelism: CHUNK_FETCH_PARALLELISM,
611 chunk_view: true,
612 g_shadow: false,
613 racy_at_gate: true,
614 tree_reserve: false,
615 tree_room_for_tests: None,
616 racy_wait_min: 10_000,
617 alias_cache: Arc::default(),
618 chunk_target: chunk::CHUNK_TARGET,
619 chunk_min: chunk::CHUNK_MIN,
620 chunk_max: chunk::CHUNK_MAX,
621 max_bytes: 0,
622 max_files: 0,
623 fanout: 128,
624 upload_fanout: 32,
625 project_id: None,
626 // 128 MiB (was 512): fits the deployed worker's 1Gi limit on a
627 // tree of 1 GiB objects at no cost in wall time (door drill
628 // 2026-09-12 §5, finding 4).
629 fetch_inflight_max_bytes: 128 * 1024 * 1024,
630 fetch_drivers: std::thread::available_parallelism()
631 .map(|n| n.get())
632 .unwrap_or(1)
633 .clamp(1, 8),
634 range_get_min_bytes: 8 * 1024 * 1024,
635 range_get_chunk_bytes: 16 * 1024 * 1024,
636 range_get_parallelism: 4,
637 sentinel_mode: SentinelMode::Auto,
638 sentinel_min_interval_secs: 5,
639 sentinel_hourly_budget: 60,
640 sentinel_poll_secs: 1,
641 news_poll_secs: 1,
642 news_active_secs: 300,
643 news_min_interval_secs: 5,
644 claim_poll_secs: lease::CLAIM_POLL_SECS,
645 claim_poll_head_ms: lease::CLAIM_POLL_HEAD_MS,
646 claim_quiet_spacing_secs: lease::QUIET_SPACING_SECS,
647 claim_deadline_secs: lease::CLAIM_DEADLINE_SECS,
648 drill_hold_commit_secs: 0,
649 drill_hold_gc_secs: 0,
650 event_trace: None,
651 untracked_sweep_secs: 3600,
652 untracked_grace_secs: untracked::UNTRACKED_GRACE_SECS,
653 scan_threads: scan::default_threads(),
654 renew_within_secs: 20,
655 }
656 }
657
658 /// The INGRESS key of a path: where an outside writer's `aws s3 cp`
659 /// lands, and where every object of this workspace lived before the
660 /// immutable-handles layout (design 2026-09-19, R5). Nothing this
661 /// crate publishes writes it any more; the read door, the consume and
662 /// the checkout fetch HANDLES.
663 pub fn file_key(&self, path: &str) -> String {
664 format!("{}/files/{}", self.prefix, path)
665 }
666 /// A HANDLE: the one key a write lands at, `files/<path>@<flush>`
667 /// (design 2026-09-19, R1). Nobody else ever writes it, the manifest
668 /// cites it by name, and it is deleted only once no document cites it
669 /// (R3). It sorts beside the bare path, so a listing of a directory
670 /// shows every live version of a file together. `flush` is the
671 /// writer's flush id: a barrier's uuid, or the gateway's `ui-…` form
672 /// ([`ui_flush`]), whose ORDER a consume can read off the name.
673 pub fn handle_key(&self, path: &str, flush: &str) -> String {
674 format!("{}/files/{}@{}", self.prefix, path, flush)
675 }
676 /// The files namespace this workspace's handles and ingress objects
677 /// live under, with its trailing slash — what a sweep lists.
678 pub fn files_prefix(&self) -> String {
679 format!("{}/files/", self.prefix)
680 }
681 /// `(path, flush)` of a handle under this prefix; `None` for a key
682 /// that is not a handle here — the bare path of an ingress object
683 /// included, so a sweep can tell the two apart by the name alone. A
684 /// path may itself contain `@`: the flush is the LAST `@`-suffix, and
685 /// a flush is a uuid or the gateway's `ui-` form, neither of which a
686 /// path component would be mistaken for in the same position.
687 pub fn handle_parts<'a>(&self, key: &'a str) -> Option<(&'a str, &'a str)> {
688 let rest = key.strip_prefix(&self.files_prefix())?;
689 let (path, flush) = rest.rsplit_once('@')?;
690 if path.is_empty() || !flush_looks_minted(flush) {
691 return None;
692 }
693 Some((path, flush))
694 }
695 /// The LEGACY single-object manifest key. Still read (a workspace
696 /// written before the pointer layout has one) and, once migrated,
697 /// overwritten with a document that cannot parse as a manifest —
698 /// see `manifest::REFUSAL_DOC` for why deleting it would be a
699 /// data-loss shape rather than a tidy-up.
700 pub fn manifest_key(&self) -> String {
701 format!("{}/{}/manifest", self.prefix, LEAN_DIR)
702 }
703 /// The pointer: the ONLY mutable metadata object. Small, CAS'd on
704 /// every citation and on every takeover rotation.
705 pub fn current_key(&self) -> String {
706 format!("{}/{}/current", self.prefix, LEAN_DIR)
707 }
708 /// One immutable generation of the entries.
709 ///
710 /// Zero-padded seq FIRST, so a plain lexical listing is also
711 /// chronological — what the reaper and a human with `mc ls` both
712 /// want — and the writer's flush uuid after it, so the key is
713 /// unique per WRITE rather than per generation. Two writers that
714 /// reach the same seq therefore write two different objects and
715 /// race only at the pointer, which is the one place a race should
716 /// be decided; and a path that legitimately rewrites without
717 /// bumping is not refused by a write-once key it never meant to
718 /// collide with.
719 pub fn generation_key(&self, seq: u64, flush_uuid: &str) -> String {
720 format!("{}/{}/manifests/{seq:020}-{flush_uuid}", self.prefix, LEAN_DIR)
721 }
722
723 /// A chunk object, addressed by CONTENT rather than by generation.
724 /// Two generations that share a chunk share the object, which is
725 /// where the O(changed) publish actually comes from — naming chunks
726 /// by seq would rewrite every one of them on every publish even
727 /// when their contents were identical.
728 pub fn chunk_key(&self, addr: &str) -> String {
729 format!("{}/{}/chunks/{addr}", self.prefix, LEAN_DIR)
730 }
731 pub fn inbox_key(&self) -> String {
732 format!("{}/{}/inbox", self.prefix, LEAN_DIR)
733 }
734 pub fn epoch_key(&self) -> String {
735 format!("{}/{}/epoch", self.prefix, LEAN_DIR)
736 }
737 /// The operator's claim cell for this prefix (`lean_operator::
738 /// reconcile::claim_key` writes it; the syncer only READS it).
739 pub fn claim_key(&self) -> String {
740 format!("{}/{}/claim", self.prefix, LEAN_DIR)
741 }
742 pub fn conflict_key(&self, uuid: &str, path: &str) -> String {
743 format!("{}/{}/conflicts/{}/{}", self.prefix, LEAN_DIR, uuid, path)
744 }
745
746 /// A per-user DRAFT: a durable edit that has NOT been published.
747 ///
748 /// Under `LEAN_DIR`, which is the whole safety argument: that
749 /// namespace is never scanned, never checked out, never cited by a
750 /// manifest, and never swept (both sweeps are prefix-scoped —
751 /// `manifest::sweep_generations` to `manifests/`, `sweep_chunks` to
752 /// `chunks/`). So a draft is durable in the bucket while being
753 /// invisible to `classify`, to `checkout`, to every other user, and
754 /// to the agent — which is exactly what "saved but not published"
755 /// has to mean.
756 ///
757 /// Body and meta live under DISJOINT subtrees rather than sharing
758 /// one with a suffix: with `drafts/<u>/<path>.meta` a file legally
759 /// named `notes.meta` would have its BODY at the key that is
760 /// `notes`'s META, and one user's draft would silently read as
761 /// another draft's base etag.
762 pub fn draft_body_key(&self, user: &str, path: &str) -> String {
763 format!("{}/{}/drafts/{}/body/{}", self.prefix, LEAN_DIR, user, path)
764 }
765 /// The draft's base: which version of `files/<path>` it was edited
766 /// against. Written AFTER the body, so the only crash residue is a
767 /// body with no meta — an INCOMPLETE draft, which `promote` refuses
768 /// by name rather than publishing against a base it had to guess.
769 pub fn draft_meta_key(&self, user: &str, path: &str) -> String {
770 format!("{}/{}/drafts/{}/meta/{}", self.prefix, LEAN_DIR, user, path)
771 }
772 /// Listing prefix for one user's draft metas (the resume view).
773 pub fn draft_meta_prefix(&self, user: &str) -> String {
774 format!("{}/{}/drafts/{}/meta/", self.prefix, LEAN_DIR, user)
775 }
776 pub fn state_dir(&self) -> PathBuf {
777 self.root.join(STATE_DIR)
778 }
779 /// The workspace-local control namespace (D0).
780 pub fn control_dir(&self) -> PathBuf {
781 self.root.join(CONTROL_DIR)
782 }
783}
784
785/// Everything a syncer operation needs: store + config + durable state.
786pub struct Syncer {
787 pub store: Arc<dyn ObjectStore>,
788 pub cfg: LeanConfig,
789 pub state: state::SyncerState,
790 /// The lease held for the CURRENT commit section, if any. `None`
791 /// between barriers: the cell arbitrates who installs a manifest and
792 /// nothing else (design 2026-09-13 §4), so a barrier claims after
793 /// its uploads and releases after its baseline rewrite.
794 pub lease: Option<flint_store::EpochLease>,
795 /// When this process last WROTE the cell (a claim, a renew): the
796 /// clock the commit section's deletes fence on (review 2026-09-18,
797 /// C2). `None` while no write is known — an adopted claim writes
798 /// nothing — so the first delete renews.
799 pub cell_written_at: Option<std::time::Instant>,
800 /// Standing conditions already written to `conflicts.jsonl` by THIS
801 /// process, so a condition that persists across every poll tick is
802 /// recorded once rather than per tick. Deliberately in-memory: a
803 /// restart is a new incarnation and should re-record what it finds.
804 pub noted_not_regular: std::collections::BTreeSet<String>,
805}
806
807/// Seconds since the epoch, saturating at 0 on a clock before it.
808pub fn now_unix() -> u64 {
809 std::time::SystemTime::now()
810 .duration_since(std::time::UNIX_EPOCH)
811 .map(|d| d.as_secs())
812 .unwrap_or(0)
813}