Skip to main content

flint_lean/
state.rs

1//! Durable emptyDir bookkeeping (plan §2.1 "restart matrix").
2//!
3//! Everything the barrier needs to survive a CONTAINER restart lives
4//! here as small JSON files under `<root>/.flint-sync/`, each written
5//! temp+rename. A POD replacement gets a fresh emptyDir and therefore a
6//! fresh identity — that asymmetry is deliberate (the plan's P4: the
7//! incarnation id is emptyDir-scoped, so only the same pod's restarted
8//! container may self-supersede the lease).
9
10use std::collections::{BTreeMap, BTreeSet};
11use std::fs;
12use std::path::{Path, PathBuf};
13
14use serde::{Deserialize, Serialize};
15
16use super::{LeanError, LeanResult};
17
18/// One published path as this syncer last knew it: the recognized ETag
19/// is the If-Match guard for the next publish and the HEAD-guard for GC.
20#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
21pub struct BaselineEntry {
22    pub etag: String,
23    pub generation: u64,
24    pub size: u64,
25    pub mtime_unix: i64,
26    /// CRC-64/NVME (wire form) of the object bytes this syncer
27    /// integrated at this path — computed from the bytes it wrote or
28    /// uploaded, never from a HEAD. A citation repair cites it, which
29    /// is what lets the manifest carry a CRC for an object whose
30    /// backend returns none (Ozone) or whose HITL uploader sent none.
31    ///
32    /// `None` only on the consume-dirty sentinel (`size == u64::MAX`):
33    /// the bytes on disk are the LOCAL edit, about to publish under a
34    /// CRC of its own, and the sentinel never repairs.
35    pub crc64_b64: Option<String>,
36    /// The version the manifest cites for this path, when the bucket is
37    /// versioned (boundary-verbs plan D7). Carried so a gated citation
38    /// can re-validate its staging base: if this moved between staging
39    /// and citation, a HITL consume or sync landed in between and
40    /// installing the staged version would UNCITE the foreign bytes.
41    #[serde(default)]
42    pub version_id: Option<String>,
43}
44
45/// The persisted baseline snapshot: what this syncer believes the
46/// bucket holds AND has integrated locally. Distinct from `inst_base`
47/// (the manifest view at our last install — the three-way merge base):
48/// consuming a HITL entry advances the baseline for that path but not
49/// the merge base. The formal model carries the same split
50/// (baseline vs instBase in LeanSubtree.tla) — collapsing them made a
51/// syncer mistake its own consumed adoption for a foreign entry.
52#[derive(Debug, Clone, Default, Serialize, Deserialize)]
53pub struct Baseline {
54    /// Manifest seq at our last install/checkout.
55    pub seq: u64,
56    /// Manifest document ETag we expect at the next CAS.
57    pub manifest_etag: Option<String>,
58    pub entries: BTreeMap<String, BaselineEntry>,
59    /// The merge base: path -> ETag as cited by the manifest we last
60    /// installed (or checked out).
61    pub inst_base: BTreeMap<String, String>,
62    /// Paths present at the PREVIOUS scan (the two-consecutive-scans
63    /// deletion rule: absence must survive two scans).
64    pub prev_scan: BTreeSet<String>,
65}
66
67/// A rescope in flight (scoped-read design §4.3). `target` is the scope
68/// the workspace is moving TO; `None` means the whole tree.
69#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
70pub struct ScopeIntent {
71    pub target: Option<Vec<String>>,
72    /// The paths this rescope is removing from the held set, recorded
73    /// BEFORE the first mutation.
74    ///
75    /// Load-bearing, and the mutation check that found it: replay
76    /// cannot RE-DERIVE this set. Once a path is out of
77    /// `baseline.entries` it is indistinguishable from a file the agent
78    /// just created — same scan row, same absence from the baseline —
79    /// and the two have opposite correct answers: unlink the leftover,
80    /// KEEP the agent's new file. Deriving the drop set from the
81    /// baseline made a crash between the uncite and the unlink leave
82    /// six uncited files on disk forever; deriving it from the tree
83    /// would delete the agent's work instead.
84    #[serde(default)]
85    pub drop: Vec<String>,
86}
87
88/// The pod-incarnation identity + lease bookkeeping ({last_token,
89/// quiet_polls} persist so container restarts RESUME the takeover
90/// observation instead of resetting it — plan §2.1).
91#[derive(Debug, Clone, Serialize, Deserialize)]
92pub struct Incarnation {
93    pub holder_id: String,
94    pub epoch: u64,
95    pub last_token: Option<String>,
96    pub quiet_polls: u32,
97}
98
99/// The intent journal written BEFORE uploads: which keys this barrier
100/// will touch and under which flush_uuid, so a restarted container can
101/// recognize its own crashed/torn PUT at the 412 (AdoptOwn) instead of
102/// mistaking it for a foreign write. `recent_uuids` keeps the last few
103/// barriers' uuids for the same reason.
104#[derive(Debug, Clone, Default, Serialize, Deserialize)]
105pub struct IntentJournal {
106    pub flush_uuid: String,
107    pub keys: Vec<String>,
108    pub recent_uuids: Vec<String>,
109    /// The ETag of the manifest document THIS workspace last installed,
110    /// written immediately after the CAS.
111    ///
112    /// The merge base (`Baseline::inst_base`) and the baseline are both
113    /// rewritten at step 7, after the CAS and after the GC deletes. A
114    /// container restart in that window leaves the bucket holding a
115    /// document we wrote and our persisted merge base one generation
116    /// behind it — so at the next merge our own entries read as foreign
117    /// changes, delete/modify resolves conservatively against the
118    /// agent's own delete, and the path is queued into the inbox as a
119    /// conflict nobody else ever touched. Recording the installed ETag
120    /// costs one small local write and restores exactly what step 7 was
121    /// going to say: if the bucket is still at this document, the merge
122    /// base IS this document.
123    #[serde(default)]
124    pub installed_etag: Option<String>,
125}
126
127/// One surfaced conflict: both versions stay recoverable (local bytes in
128/// the tree, foreign bytes preserved at `preserved_key` or still current
129/// under the data key). Never a silent winner.
130#[derive(Debug, Clone, Serialize, Deserialize)]
131pub struct ConflictRecord {
132    pub path: String,
133    pub foreign_etag: String,
134    /// Where the foreign bytes were preserved (server-side copy), when
135    /// the local version is about to overwrite them.
136    pub preserved_key: Option<String>,
137    pub kind: String, // "consume-dirty" | "upload-412-parked" | "sync-dirty" | "gc-skip"
138    pub at_unix: u64,
139}
140
141pub struct SyncerState {
142    dir: PathBuf,
143    /// The state-directory occupancy lock (flock, held for the process
144    /// lifetime). Self-recognition of the lease via the persisted
145    /// incarnation id is only sound because the PREVIOUS process is
146    /// gone — and this lock is what makes that true. Without it, a
147    /// second flint-sync on the same workspace self-recognizes,
148    /// deposes a LIVE sibling, and both write the tree concurrently
149    /// (observed on the 0b rig: a diagnostic re-run raced a live 1M
150    /// checkout into tmp-rename ENOENT collisions). The hub has the
151    /// identical gate (`state_backend::is_single_occupant`).
152    _lock: std::fs::File,
153}
154
155const MARKER: &str = "checkout-complete";
156/// Written by the SIGTERM drain only after it published: the node
157/// plugin's evidence that a worker that is now gone actually drained
158/// (audit 2026-09-03, finding 3). Absent ⇒ the tree is preserved.
159pub const DRAINED: &str = "drained.json";
160const LOCK: &str = "lock";
161const BASELINE: &str = "baseline.json";
162/// The admitted set of a SCOPED checkout. Deliberately its own
163/// document rather than a field on `Baseline`: the baseline is
164/// rewritten by every barrier, every sync and every consume, and a
165/// scope that rides along is one `Baseline::default()` away from
166/// silently widening a workspace to the whole tree. This file is
167/// written once, by checkout, and thereafter only read. Absent means
168/// UNSCOPED — the only encoding of "no restriction", since an empty
169/// admitted set is refused before it can be written.
170const SCOPE: &str = "scope.json";
171
172/// A rescope IN FLIGHT: the target scope, written before the first
173/// mutation and removed only after the last (scoped-read design §4.3).
174///
175/// Its own document and not a field on `scope.json`, because the two
176/// answer different questions — `scope.json` is what this workspace
177/// holds, this is what it is on its way to holding — and a crash must
178/// leave both answers readable.
179///
180/// `null` is a LEGAL target (the whole tree), so absence of the file
181/// means "no rescope in flight", never "unscoped". That is why the
182/// document wraps the target in a struct instead of being a bare
183/// `Option<Vec<String>>`: a bare `null` on disk and a missing file
184/// would deserialize to the same thing.
185const SCOPE_INTENT: &str = "scope-intent.json";
186const INCARNATION: &str = "incarnation.json";
187const INTENT: &str = "intent.json";
188const CONFLICTS: &str = "conflicts.jsonl";
189/// The rotated generation. `load_conflicts` reads it FIRST, so the
190/// sequence a reader sees is unbroken across a rotation — which matters
191/// because `honor_sync` takes the count before a sync and `skip`s it
192/// after, and a rotation that SHORTENED the list would make it skip past
193/// the very records the sync just produced.
194const CONFLICTS_PREV: &str = "conflicts.1.jsonl";
195/// How many records were dropped when a SECOND rotation overwrote the
196/// first. Truncation that nobody can count is truncation that reads as
197/// "there were no more".
198const CONFLICTS_DROPPED: &str = "conflicts.dropped";
199/// Rotate past this. The file is append-only and `load_conflicts` parses
200/// it WHOLE — twice per sync honor, again per status read and per
201/// scrape (U23) — so an unbounded file is an unbounded parse on a hot
202/// path, and a standing condition (a UI autosaving over a path the agent
203/// holds dirty) appends on every barrier. Two generations bound the
204/// resident set at ~2 MiB, which is thousands of records.
205const CONFLICTS_MAX_BYTES: u64 = 1 << 20;
206
207fn write_atomic(path: &Path, bytes: &[u8]) -> LeanResult<()> {
208    // The state dir lives in the same app-writable emptyDir.
209    super::safefs::check_parent(path)?;
210    let tmp = path.with_extension("tmp");
211    super::safefs::write_via_tmp(path, &tmp, bytes, None).map(|_| ())
212}
213
214impl SyncerState {
215    pub fn open(dir: PathBuf) -> LeanResult<SyncerState> {
216        fs::create_dir_all(&dir)?;
217        let lock = fs::OpenOptions::new()
218            .create(true)
219            .truncate(false)
220            .write(true)
221            .open(dir.join(LOCK))?;
222        #[cfg(unix)]
223        {
224            use std::os::fd::AsRawFd;
225            // SAFETY: flock on an owned, open fd.
226            let rc = unsafe { libc::flock(lock.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) };
227            if rc != 0 {
228                return Err(LeanError::State(format!(
229                    "another flint-sync already holds this workspace ({}): \
230                     refusing to run two syncers over one tree",
231                    dir.display()
232                )));
233            }
234        }
235        Ok(SyncerState { dir, _lock: lock })
236    }
237
238    pub fn marker_present(&self) -> bool {
239        self.dir.join(MARKER).exists()
240    }
241
242    /// Flush the filesystem holding the tree (the state dir lives in
243    /// it) so everything materialised so far is on stable storage.
244    pub fn sync_tree(&self) -> LeanResult<()> {
245        super::safefs::sync_tree(&self.dir)
246    }
247
248    /// The drain's attestation. `seq` is the manifest the drain left
249    /// installed, when it knows it.
250    pub fn write_drained(&self, seq: Option<u64>, acks: usize) -> LeanResult<()> {
251        let doc = serde_json::json!({
252            "unix": super::now_unix(),
253            "seq": seq,
254            "acks": acks,
255        });
256        write_atomic(&self.dir.join(DRAINED), doc.to_string().as_bytes())
257    }
258
259    /// A fresh incarnation owes its own attestation; a stale one from
260    /// an earlier life of this tree must not vouch for it.
261    pub fn clear_drained(&self) -> LeanResult<()> {
262        match fs::remove_file(self.dir.join(DRAINED)) {
263            Ok(()) => Ok(()),
264            Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()),
265            Err(e) => Err(LeanError::State(format!("clear {DRAINED}: {e}"))),
266        }
267    }
268
269    pub fn drained_path(&self) -> PathBuf {
270        self.dir.join(DRAINED)
271    }
272
273    /// Written LAST at checkout: the agent-start gate.
274    pub fn write_marker(&self) -> LeanResult<()> {
275        write_atomic(&self.dir.join(MARKER), b"ok\n")
276    }
277
278    pub fn load_baseline(&self) -> LeanResult<Baseline> {
279        let p = self.dir.join(BASELINE);
280        if !p.exists() {
281            return Ok(Baseline::default());
282        }
283        let bytes = fs::read(&p)?;
284        serde_json::from_slice(&bytes).map_err(|e| LeanError::State(format!("baseline: {e}")))
285    }
286
287    /// COMPACT: the baseline is the other O(files) document, rewritten
288    /// on the cadence tick and re-parsed several times per barrier. The
289    /// agent-facing O(1) files (gauges, capabilities, acks) stay pretty
290    /// — those exist to be `cat`-ed.
291    pub fn save_baseline(&self, b: &Baseline) -> LeanResult<()> {
292        let bytes =
293            serde_json::to_vec(b).map_err(|e| LeanError::State(format!("baseline: {e}")))?;
294        write_atomic(&self.dir.join(BASELINE), &bytes)
295    }
296
297    /// What this workspace was admitted to hold, or `None` for an
298    /// unscoped (whole-manifest) checkout.
299    ///
300    /// `fs::read` directly, with NO `exists()` pre-check: `exists()`
301    /// answers false for EACCES and EIO alike, and an unreadable scope
302    /// answered as "unscoped" is the same class of bug as an unreadable
303    /// path answered as "deleted" (`barrier.rs`, 14b3637c). Only
304    /// NotFound means absent.
305    pub fn load_scope(&self) -> LeanResult<Option<Vec<String>>> {
306        let p = self.dir.join(SCOPE);
307        let bytes = match fs::read(&p) {
308            Ok(b) => b,
309            Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None),
310            Err(e) => {
311                return Err(LeanError::State(format!(
312                    "cannot read the checkout scope at {}: {e} — refusing to \
313                     guess what this workspace is holding",
314                    p.display()
315                )))
316            }
317        };
318        serde_json::from_slice(&bytes).map_err(|e| LeanError::State(format!("scope: {e}")))
319    }
320
321    /// `Some` writes the admitted set; `None` REMOVES the document.
322    /// Removing matters: a scoped checkout that crashed before its
323    /// marker leaves a scope behind, and the whole-tree checkout that
324    /// replaces it must not inherit a claim it did not make.
325    pub fn save_scope(&self, scope: Option<&[String]>) -> LeanResult<()> {
326        let p = self.dir.join(SCOPE);
327        match scope {
328            Some(entries) => {
329                let bytes = serde_json::to_vec(entries)
330                    .map_err(|e| LeanError::State(format!("scope: {e}")))?;
331                write_atomic(&p, &bytes)
332            }
333            None => match fs::remove_file(&p) {
334                Ok(()) => Ok(()),
335                Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()),
336                Err(e) => Err(LeanError::State(format!("clear {SCOPE}: {e}"))),
337            },
338        }
339    }
340
341    /// Read a rescope in flight. `None` = none in flight.
342    pub fn load_scope_intent(&self) -> LeanResult<Option<ScopeIntent>> {
343        let p = self.dir.join(SCOPE_INTENT);
344        let bytes = match fs::read(&p) {
345            Ok(b) => b,
346            Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None),
347            Err(e) => {
348                return Err(LeanError::State(format!(
349                    "cannot read the rescope intent at {}: {e} — refusing to run a barrier \
350                     over a half-applied scope",
351                    p.display()
352                )))
353            }
354        };
355        serde_json::from_slice(&bytes)
356            .map(Some)
357            .map_err(|e| LeanError::State(format!("scope intent: {e}")))
358    }
359
360    pub fn save_scope_intent(&self, intent: &ScopeIntent) -> LeanResult<()> {
361        let bytes = serde_json::to_vec(intent)
362            .map_err(|e| LeanError::State(format!("scope intent: {e}")))?;
363        write_atomic(&self.dir.join(SCOPE_INTENT), &bytes)
364    }
365
366    /// Cleared LAST, after the new scope is durable. Clearing it first
367    /// would turn a crash into a workspace whose scope says one thing
368    /// and whose held set says another, with nothing left to replay.
369    pub fn clear_scope_intent(&self) -> LeanResult<()> {
370        match fs::remove_file(self.dir.join(SCOPE_INTENT)) {
371            Ok(()) => Ok(()),
372            Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()),
373            Err(e) => Err(LeanError::State(format!("clear {SCOPE_INTENT}: {e}"))),
374        }
375    }
376
377    pub fn load_incarnation(&self) -> LeanResult<Option<Incarnation>> {
378        let p = self.dir.join(INCARNATION);
379        if !p.exists() {
380            return Ok(None);
381        }
382        let bytes = fs::read(&p)?;
383        serde_json::from_slice(&bytes)
384            .map(Some)
385            .map_err(|e| LeanError::State(format!("incarnation: {e}")))
386    }
387
388    pub fn save_incarnation(&self, i: &Incarnation) -> LeanResult<()> {
389        let bytes = serde_json::to_vec_pretty(i)
390            .map_err(|e| LeanError::State(format!("incarnation: {e}")))?;
391        write_atomic(&self.dir.join(INCARNATION), &bytes)
392    }
393
394    pub fn load_intent(&self) -> LeanResult<IntentJournal> {
395        let p = self.dir.join(INTENT);
396        if !p.exists() {
397            return Ok(IntentJournal::default());
398        }
399        let bytes = fs::read(&p)?;
400        serde_json::from_slice(&bytes).map_err(|e| LeanError::State(format!("intent: {e}")))
401    }
402
403    pub fn save_intent(&self, j: &IntentJournal) -> LeanResult<()> {
404        let bytes =
405            serde_json::to_vec_pretty(j).map_err(|e| LeanError::State(format!("intent: {e}")))?;
406        write_atomic(&self.dir.join(INTENT), &bytes)
407    }
408
409    /// Clear the per-barrier key list but KEEP the uuid history (the
410    /// AdoptOwn recognizer needs uuids from completed barriers whose
411    /// baseline rewrite raced a crash).
412    pub fn clear_intent_keys(&self) -> LeanResult<()> {
413        let mut j = self.load_intent()?;
414        if !j.flush_uuid.is_empty() {
415            if !j.recent_uuids.contains(&j.flush_uuid) {
416                j.recent_uuids.push(j.flush_uuid.clone());
417            }
418            let excess = j.recent_uuids.len().saturating_sub(8);
419            if excess > 0 {
420                j.recent_uuids.drain(..excess);
421            }
422        }
423        j.flush_uuid = String::new();
424        j.keys.clear();
425        self.save_intent(&j)
426    }
427
428    pub fn append_conflict(&self, c: &ConflictRecord) -> LeanResult<()> {
429        use std::io::Write;
430        let line =
431            serde_json::to_string(c).map_err(|e| LeanError::State(format!("conflict: {e}")))?;
432        let live = self.dir.join(CONFLICTS);
433        let mut f = fs::OpenOptions::new().create(true).append(true).open(&live)?;
434        writeln!(f, "{line}")?;
435        // Size off the handle we just wrote through — no extra stat of
436        // the path, and no line count, which would make every append
437        // O(records).
438        let len = f.metadata()?.len();
439        drop(f);
440        if len > CONFLICTS_MAX_BYTES {
441            self.rotate_conflicts()?;
442        }
443        Ok(())
444    }
445
446    /// Rotate live -> `.1`, counting whatever the previous `.1` held so
447    /// the loss is a NUMBER rather than a silence. Best effort: a
448    /// rotation that fails leaves a large file, which is a performance
449    /// problem; losing the record we just appended would be a
450    /// correctness one.
451    fn rotate_conflicts(&self) -> LeanResult<()> {
452        let live = self.dir.join(CONFLICTS);
453        let prev = self.dir.join(CONFLICTS_PREV);
454        // Only read the outgoing generation at ROTATION time — rare by
455        // construction, since it takes CONFLICTS_MAX_BYTES to get here.
456        if let Ok(text) = fs::read_to_string(&prev) {
457            let dropped = text.lines().filter(|l| !l.trim().is_empty()).count() as u64;
458            let total = self.conflicts_dropped()? + dropped;
459            write_atomic(&self.dir.join(CONFLICTS_DROPPED), total.to_string().as_bytes())?;
460        }
461        fs::rename(&live, &prev)?;
462        Ok(())
463    }
464
465    /// Records lost to rotation. A caller rendering conflicts owes the
466    /// user this number: a truncated list that does not say it was
467    /// truncated reads as a complete one.
468    pub fn conflicts_dropped(&self) -> LeanResult<u64> {
469        match fs::read_to_string(self.dir.join(CONFLICTS_DROPPED)) {
470            Ok(s) => Ok(s.trim().parse().unwrap_or(0)),
471            Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(0),
472            Err(e) => Err(LeanError::State(format!("{CONFLICTS_DROPPED}: {e}"))),
473        }
474    }
475
476    /// The rotated generation first, then the live one: oldest to
477    /// newest, unbroken across a single rotation.
478    pub fn load_conflicts(&self) -> LeanResult<Vec<ConflictRecord>> {
479        let mut out = vec![];
480        for name in [CONFLICTS_PREV, CONFLICTS] {
481            let p = self.dir.join(name);
482            // `fs::read_to_string` directly: `exists()` answers false
483            // for EACCES and EIO alike, and a conflict log that reads as
484            // EMPTY because it is unreadable is the same shape of bug as
485            // an unreadable path reading as deleted.
486            let text = match fs::read_to_string(&p) {
487                Ok(t) => t,
488                Err(e) if e.kind() == std::io::ErrorKind::NotFound => continue,
489                Err(e) => {
490                    return Err(LeanError::State(format!(
491                        "cannot read {name}: {e} — refusing to report an unreadable \
492                         conflict log as an empty one"
493                    )))
494                }
495            };
496            for line in text.lines() {
497                if line.trim().is_empty() {
498                    continue;
499                }
500                out.push(
501                    serde_json::from_str(line)
502                        .map_err(|e| LeanError::State(format!("conflict line: {e}")))?,
503                );
504            }
505        }
506        Ok(out)
507    }
508}