Skip to main content

memstead_base/storage/
filesystem.rs

1//! Filesystem-backed [`MemBackend`](crate::backend::MemBackend) — the
2//! gix-free companion to `memstead_git_branch::storage::git_tree::GitTreeBackend`.
3//! Used by filesystem mems, where entities live as plain files under a
4//! workspace root and there is no commit history.
5//!
6//! ## Buffer + commit
7//!
8//! Mutations buffer in memory until [`FilesystemBackend::commit`].
9//! Per-path final-state collapse mirrors the git-tree adapter: a chain
10//! of write/delete ops on the same path collapses to a single terminal
11//! state by commit time. Move resolves at call-time into a
12//! `Delete(from)` + `Upsert(to, bytes)` pair — bytes come from the
13//! pending buffer when present, otherwise from the live file on disk.
14//!
15//! ## One commit point
16//!
17//! A commit is all of its files and its ledger lines, or none of them.
18//! It runs in two halves around one commit point:
19//!
20//! 1. **Before.** Every new file content is written to a temp file
21//!    beside its target and synced, the directories that name the
22//!    temps are synced, and the ledger lines of the staged provenance
23//!    records are rendered. Then a commit record naming every file
24//!    operation and every ledger line is written under `.memstead/`
25//!    (temp, sync, rename). The rename that puts the record in place
26//!    is the commit point; syncing `.memstead/` makes it durable.
27//! 2. **After.** The temps are renamed into place, the deletes are
28//!    applied, the touched directories are synced, the ledger lines
29//!    are appended and synced, the record is removed and `.memstead/`
30//!    is synced. Only then does the commit return success.
31//!
32//! A failure before the commit point removes what the attempt wrote
33//! and returns the IO error: storage is what it was. A failure after
34//! it returns [`BackendError::CommitNotApplied`]: the commit is decided,
35//! and [`MemBackend::complete_interrupted_commit`] finishes it from the
36//! record at the next load. The same call removes the temps of an
37//! attempt that died before its commit point. Nothing has to be undone
38//! in either case, because nothing is moved into place before every
39//! content is safely beside its target.
40//!
41//! All of it runs through the [`io::FolderIo`] seam, so tests record
42//! the order of the steps and fail or cut off any one of them.
43//!
44//! Writers are serialised by the engine's cross-process write lock
45//! ([`MemBackend::write_lock_path`]); the backend itself assumes one
46//! writer at a time.
47//!
48//! ## CommitId
49//!
50//! There is no commit history. [`Self::commit`] returns a synthetic
51//! opaque id (UNIX-nanos + counter, hex) to satisfy the trait surface.
52//! Callers that pass this through `_hash` envelopes get a unique
53//! per-commit token but no CAS guarantee — there is no parent state to
54//! compare against.
55
56use std::collections::{BTreeSet, HashMap, HashSet};
57use std::path::{Path, PathBuf};
58use std::sync::Mutex;
59use std::sync::atomic::{AtomicU64, Ordering};
60
61use self::io::{FolderIo, RealIo};
62use super::CommitId;
63use super::path_lock;
64use crate::backend::BackendError;
65use crate::backend::CompletedCommit;
66use crate::backend::MemBackend;
67use crate::filesystem::changelog::{
68    self, ChangeEntry, MutationKind, changelog_path, parse_rfc3339_utc,
69};
70use crate::provenance::{Provenance, ProvenanceKind};
71use crate::vcs::{Actor, CommitContext, parse_client_id};
72
73/// Per-path final state for the buffered op log. Move operations
74/// resolve at call time into a `Delete(from)` + `Upsert(to, bytes)`
75/// pair, mirroring the git-tree adapter so commit-time replay only
76/// ever sees these two terminal states.
77enum PendingState {
78    Upsert(Vec<u8>),
79    Delete,
80}
81
82/// In-flight mutation buffer: the staged file operations and the
83/// provenance records that belong to the same commit. Emptied by every
84/// exit of a commit, successful or not, and by a discard.
85struct Pending {
86    ops: HashMap<String, PendingState>,
87    records: Vec<Provenance>,
88}
89
90impl Pending {
91    fn new() -> Self {
92        Self {
93            ops: HashMap::new(),
94            records: Vec::new(),
95        }
96    }
97
98    fn clear(&mut self) {
99        self.ops.clear();
100        self.records.clear();
101    }
102}
103
104/// Mem-relative path of the commit record: present from a commit's
105/// commit point until the commit is fully applied, absent otherwise.
106pub(crate) const COMMIT_RECORD_REL: &str = ".memstead/commit.json";
107
108/// The drift cursor a mem reports while a commit record is on disk.
109/// No ledger timestamp ever equals it, so the engine's staleness probe
110/// sees a change and reloads, and the reload completes the commit.
111const COMMIT_PENDING_HEAD: &str = "commit-pending";
112
113/// One file operation of a commit, as its record names it. Paths are
114/// mem-relative with forward slashes.
115#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
116#[serde(tag = "op", rename_all = "lowercase")]
117enum RecordOp {
118    /// `tmp` holds the synced new content and is renamed onto `path`.
119    Upsert {
120        path: String,
121        tmp: String,
122    },
123    Delete {
124        path: String,
125    },
126}
127
128impl RecordOp {
129    fn path(&self) -> &str {
130        match self {
131            RecordOp::Upsert { path, .. } | RecordOp::Delete { path } => path,
132        }
133    }
134}
135
136/// The commit record: everything needed to finish a decided commit
137/// without the process that decided it.
138#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
139struct CommitRecord {
140    v: u32,
141    /// File operations, in path order.
142    ops: Vec<RecordOp>,
143    /// The commit's ledger lines, in order, without their newline.
144    ledger: Vec<String>,
145}
146
147/// What one commit attempt has put on disk before its commit point,
148/// so a failed attempt can take all of it away again.
149#[derive(Default)]
150struct Attempt {
151    /// Temp files written, the record's temp included.
152    temps: Vec<PathBuf>,
153    /// Directories created, outermost first.
154    created_dirs: Vec<PathBuf>,
155}
156
157/// Filesystem-backed [`MemBackend`]. Mutations buffer in memory until
158/// [`Self::commit`], which lands them as one commit (module docs).
159pub struct FilesystemBackend {
160    root: PathBuf,
161    pending: Mutex<Pending>,
162    io: Box<dyn FolderIo>,
163    /// Set while the record of an applied commit is removed and the
164    /// sync of that removal has not succeeded: the files of that
165    /// commit. The commit has not returned success, and must not until
166    /// the sync is made good: a removal that is not durable lets a
167    /// power loss bring the record back after later writes. Reads
168    /// refuse meanwhile, as they do while a record is on disk.
169    removal_sync_owed: Mutex<Option<Vec<String>>>,
170    /// This backend has synced the mem root since it was built, so the
171    /// name of `.memstead/` is durable.
172    meta_named: std::sync::atomic::AtomicBool,
173    /// How long a load or a direct read waits for the mem's write lock
174    /// while a commit record is on disk, as an engine handed it over
175    /// (the workspace's write-lock deadline; the inner `None` waits
176    /// without bound). `None` until then: a backend nobody told waits
177    /// that setting's default.
178    lock_wait: Mutex<Option<Option<std::time::Duration>>>,
179    /// When a wait for the write lock last ran out. For as long again
180    /// as the limit, the next load or read looks at the lock once and
181    /// answers: one operation that loads and then reads pays the wait
182    /// once, not once per step.
183    lock_wait_spent: Mutex<Option<std::time::Instant>>,
184}
185
186/// A wait for the mem's write lock that ran out: how long it was,
187/// whether an engine had set that limit, and whether this call waited
188/// it or looked once because a wait had run out a moment before.
189#[derive(Clone, Copy)]
190struct LockWait {
191    limit: std::time::Duration,
192    told: bool,
193    looked_once: bool,
194}
195
196/// The wait a backend starts with, before an engine hands it the
197/// workspace's setting: that setting's default.
198fn default_lock_wait() -> Option<std::time::Duration> {
199    Some(std::time::Duration::from_secs(
200        crate::workspace::MutationsSection::DEFAULT_WRITE_LOCK_TIMEOUT_SECS,
201    ))
202}
203
204impl FilesystemBackend {
205    /// Build a writer rooted at `root`. The directory must already
206    /// exist; sub-directories are created lazily as commits run.
207    pub fn new(root: PathBuf) -> Self {
208        Self {
209            root,
210            pending: Mutex::new(Pending::new()),
211            io: Box::new(RealIo),
212            removal_sync_owed: Mutex::new(None),
213            meta_named: std::sync::atomic::AtomicBool::new(false),
214            lock_wait: Mutex::new(None),
215            lock_wait_spent: Mutex::new(None),
216        }
217    }
218
219    /// [`Self::new`] over a caller-supplied IO, for tests that trace
220    /// or fault the steps of a commit.
221    #[cfg(test)]
222    pub(crate) fn with_io(root: PathBuf, io: impl FolderIo + 'static) -> Self {
223        Self {
224            root,
225            pending: Mutex::new(Pending::new()),
226            io: Box::new(io),
227            removal_sync_owed: Mutex::new(None),
228            meta_named: std::sync::atomic::AtomicBool::new(false),
229            lock_wait: Mutex::new(None),
230            lock_wait_spent: Mutex::new(None),
231        }
232    }
233
234    fn meta_dir(&self) -> PathBuf {
235        self.root.join(crate::mem::MEM_META_DIR)
236    }
237
238    /// The write lock's file, by its canonical path: the engine's lock
239    /// and this backend's own recovery take the same lock, and the lock
240    /// table is keyed by path.
241    fn lock_file(&self) -> PathBuf {
242        let root = std::fs::canonicalize(&self.root).unwrap_or_else(|_| self.root.clone());
243        root.join(".memstead").join("locks").join("write.lock")
244    }
245
246    /// The config lock's file, by its canonical path, beside the write lock.
247    fn config_lock_file(&self) -> PathBuf {
248        let root = std::fs::canonicalize(&self.root).unwrap_or_else(|_| self.root.clone());
249        root.join(".memstead").join("locks").join("config.lock")
250    }
251
252    fn record_path(&self) -> PathBuf {
253        self.root.join(COMMIT_RECORD_REL)
254    }
255
256    /// The limit of a wait for the mem's write lock in front of a
257    /// commit record (see [`MemBackend::set_lock_wait`]), and whether
258    /// an engine set it or it is the default of a backend nobody told.
259    fn lock_wait_limit(&self) -> (Option<std::time::Duration>, bool) {
260        match self.lock_wait.lock().map(|told| *told) {
261            Ok(Some(limit)) => (limit, true),
262            _ => (default_lock_wait(), false),
263        }
264    }
265
266    /// Wait for the mem's write lock in front of a commit record, no
267    /// longer than the limit. `Ok(None)`: the lock is held now and needs
268    /// one release. `Ok(Some(limit))`: the limit passed, or passed a
269    /// moment ago, with the lock still held elsewhere.
270    ///
271    /// A wait that ran out is not repeated at once. For as long again
272    /// as the limit, a further call looks at the lock once and answers,
273    /// so an operation that loads the mem and then reads it pays the
274    /// wait once. A lock that came free in the meantime is taken by that
275    /// one look.
276    fn wait_for_write_lock(&self, lock: &Path) -> std::io::Result<Option<LockWait>> {
277        let (limit, told) = self.lock_wait_limit();
278        let spent_recently = limit.is_some_and(|limit| {
279            self.lock_wait_spent
280                .lock()
281                .ok()
282                .and_then(|at| *at)
283                .is_some_and(|at| at.elapsed() < limit)
284        });
285        let wait = if spent_recently {
286            Some(std::time::Duration::ZERO)
287        } else {
288            limit
289        };
290        if path_lock::acquire_within(lock, wait)? {
291            return Ok(None);
292        }
293        if !spent_recently && let Ok(mut spent) = self.lock_wait_spent.lock() {
294            *spent = Some(std::time::Instant::now());
295        }
296        Ok(Some(LockWait {
297            limit: limit.unwrap_or_default(),
298            told,
299            looked_once: spent_recently,
300        }))
301    }
302
303    /// What a load or a read says when the mem's write lock stayed held
304    /// past the limit over a commit record: the commit is decided and
305    /// not applied, nothing of the mem is served, and the next load
306    /// after the lock is free completes it.
307    fn lock_wait_passed(&self, wait: LockWait) -> BackendError {
308        let whose = if wait.told {
309            "`write_lock_timeout_secs` in the workspace's `[mutations]` table sets that wait, \
310             `0` waits without bound"
311        } else {
312            "the default wait of a reader that has no workspace to ask; \
313             `write_lock_timeout_secs` does not reach it"
314        };
315        // A call inside the span after a wait that ran out waited for
316        // nothing itself, and says so.
317        let waited = if wait.looked_once {
318            format!(
319                "another process holds its write lock; a wait of {} s for that lock ran out a \
320                 moment ago and is not repeated yet",
321                wait.limit.as_secs_f64()
322            )
323        } else {
324            format!(
325                "another process held its write lock for the whole wait of {} s",
326                wait.limit.as_secs_f64()
327            )
328        };
329        BackendError::CommitNotApplied {
330            detail: format!(
331                "the mem holds a commit that is decided and not applied, and {waited} \
332                 ({whose}); nothing of the mem was read; loading the mem completes the commit \
333                 once the lock is free"
334            ),
335        }
336    }
337
338    /// Create `dir` and every missing directory above it, noting each
339    /// one created so a failed attempt can remove it again.
340    fn ensure_dir(&self, dir: &Path, attempt: &mut Attempt) -> std::io::Result<()> {
341        let mut missing: Vec<PathBuf> = Vec::new();
342        let mut cursor = Some(dir);
343        while let Some(d) = cursor {
344            if d.as_os_str().is_empty() || self.io.exists(d)? {
345                break;
346            }
347            missing.push(d.to_path_buf());
348            cursor = d.parent();
349        }
350        for d in missing.into_iter().rev() {
351            self.io.create_dir(&d)?;
352            attempt.created_dirs.push(d);
353        }
354        Ok(())
355    }
356
357    /// Render the ledger lines of `records`, each with a timestamp
358    /// strictly after the ledger's last line and after the line before
359    /// it: the last line's `ts` is the drift cursor, and two lines that
360    /// shared one would hide the second from every reader.
361    fn render_ledger(&self, records: &[Provenance]) -> std::io::Result<Vec<String>> {
362        if records.is_empty() {
363            return Ok(Vec::new());
364        }
365        let mut last = self
366            .io
367            .read_tail(&changelog_path(&self.root), 4096)?
368            .and_then(|tail| changelog::last_ts_in_tail(&tail));
369        let mut lines = Vec::with_capacity(records.len());
370        for record in records {
371            let ts = changelog::monotonic_ts(last, record.timestamp);
372            let line = changelog::render_change_line(&change_entry(record), ts)
373                .map_err(|e| std::io::Error::other(e.to_string()))?;
374            lines.push(line.trim_end_matches('\n').to_string());
375            last = Some(ts);
376        }
377        Ok(lines)
378    }
379
380    /// Everything before the commit point: contents beside their
381    /// targets and synced, then the record in place. Returns the
382    /// record once its rename has happened; an error means the rename
383    /// has not, and `attempt` lists what to remove.
384    fn prepare_commit(
385        &self,
386        ops: &[(String, PendingState)],
387        records: &[Provenance],
388        attempt: &mut Attempt,
389    ) -> std::io::Result<CommitRecord> {
390        // The record and the ledger live under `.memstead/`; a link there
391        // would carry them outside the mem.
392        refuse_symlinked_meta(&self.root).map_err(|e| std::io::Error::other(e.to_string()))?;
393        self.ensure_dir(&self.meta_dir(), attempt)?;
394
395        let mut record_ops = Vec::with_capacity(ops.len());
396        for (key, state) in ops {
397            // Checked again at commit: a link can appear after staging.
398            if let Some(link) = symlink_on_path(&self.root, key)? {
399                return Err(std::io::Error::other(format!(
400                    "{key} passes through the symbolic link {}; a mem writes only inside its own directory",
401                    link.display()
402                )));
403            }
404            match state {
405                PendingState::Upsert(bytes) => {
406                    let target = self.root.join(key);
407                    if let Some(parent) = target.parent() {
408                        self.ensure_dir(parent, attempt)?;
409                    }
410                    let tmp = make_tmp_path(&target);
411                    attempt.temps.push(tmp.clone());
412                    self.io.write(&tmp, bytes)?;
413                    self.io.sync_file(&tmp)?;
414                    record_ops.push(RecordOp::Upsert {
415                        path: key.clone(),
416                        tmp: sibling_key(key, &tmp),
417                    });
418                }
419                PendingState::Delete => record_ops.push(RecordOp::Delete { path: key.clone() }),
420            }
421        }
422
423        // The names must be as durable as the contents: a record that
424        // survives a power loss while a temp's directory entry does not
425        // would name a content that is gone.
426        let mut dirs: BTreeSet<PathBuf> = BTreeSet::new();
427        for path in attempt.temps.iter().chain(attempt.created_dirs.iter()) {
428            // Every directory from the file's own up to the mem root,
429            // not only the ones this attempt created: a directory left
430            // behind by an earlier attempt that was cut off exists
431            // already and was never named durably.
432            let mut dir = path.parent();
433            while let Some(d) = dir {
434                if !d.starts_with(&self.root) {
435                    break;
436                }
437                dirs.insert(d.to_path_buf());
438                if d == self.root {
439                    break;
440                }
441                dir = d.parent();
442            }
443        }
444        // `.memstead/` itself must be named durably before a record is
445        // put in it. This backend cannot know who created the directory
446        // (the write lock makes it for its lock file, outside any
447        // commit), so the first commit of each backend syncs the mem
448        // root once, whatever it found.
449        let name_meta = !self.meta_named.load(Ordering::SeqCst);
450        if name_meta {
451            dirs.insert(self.root.clone());
452        }
453        for dir in &dirs {
454            self.io.sync_dir(dir)?;
455        }
456        if name_meta {
457            self.meta_named.store(true, Ordering::SeqCst);
458        }
459
460        let record = CommitRecord {
461            v: 1,
462            ops: record_ops,
463            ledger: self.render_ledger(records)?,
464        };
465        let bytes =
466            serde_json::to_vec(&record).map_err(|e| std::io::Error::other(e.to_string()))?;
467        let record_path = self.record_path();
468        let record_tmp = make_tmp_path(&record_path);
469        attempt.temps.push(record_tmp.clone());
470        self.io.write(&record_tmp, &bytes)?;
471        self.io.sync_file(&record_tmp)?;
472        self.io.rename(&record_tmp, &record_path)?;
473        Ok(record)
474    }
475
476    /// Take away what an attempt that never reached its commit point
477    /// put on disk. Best effort: a temp that stays is removed by the
478    /// next load, and an empty directory that stays changes nothing.
479    fn abandon(&self, attempt: &Attempt) {
480        for tmp in &attempt.temps {
481            let _ = self.io.remove_file(tmp);
482        }
483        for dir in attempt.created_dirs.iter().rev() {
484            let _ = self.io.remove_dir(dir);
485        }
486    }
487
488    /// Everything after the commit point, written so that running it
489    /// again from any cut-off point ends in the same state: a temp
490    /// still present is renamed, a temp already gone means its file is
491    /// in place, a ledger line already written is not written twice.
492    /// Shared by the commit itself and by the completion at load.
493    fn apply_record(&self, record: &CommitRecord) -> std::io::Result<()> {
494        // The record's own name first, on every run: it is what makes
495        // the commit point durable, and a completion cannot know
496        // whether the run it finishes got this far. Without it a power
497        // loss could bring back the record of an older commit, whose
498        // deletes would then be applied over this one's files.
499        self.io.sync_dir(&self.meta_dir())?;
500
501        let mut dirs: BTreeSet<PathBuf> = BTreeSet::new();
502        for op in &record.ops {
503            let target = self.root.join(op.path());
504            match op {
505                RecordOp::Upsert { path, tmp } => {
506                    let tmp = self.root.join(tmp);
507                    if self.io.exists(&tmp)? {
508                        self.io.rename(&tmp, &target)?;
509                    } else if !self.io.exists(&target)? {
510                        return Err(std::io::Error::other(format!(
511                            "commit record names {path}, and neither its staged content \
512                             nor the file is on disk"
513                        )));
514                    }
515                }
516                RecordOp::Delete { .. } => match self.io.remove_file(&target) {
517                    Ok(()) => {}
518                    Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
519                    Err(e) => return Err(e),
520                },
521            }
522            // Every operation's directory is synced on every run, also
523            // where this run found the move already made: an earlier
524            // run may have been cut off between the move and its sync,
525            // and this one cannot tell.
526            if let Some(parent) = target.parent() {
527                dirs.insert(parent.to_path_buf());
528            }
529        }
530        for dir in &dirs {
531            self.io.sync_dir(dir)?;
532        }
533
534        if !record.ledger.is_empty() {
535            let log = changelog_path(&self.root);
536            // The commit's lines, if any are there, are the last thing
537            // in the ledger, so a tail that can hold all of them is
538            // enough to see which are missing.
539            let span: u64 = record.ledger.iter().map(|l| l.len() as u64 + 1).sum();
540            let tail = self.io.read_tail(&log, span + 8192)?.unwrap_or_default();
541            let tail_text = String::from_utf8_lossy(&tail);
542            let present: HashSet<&str> = tail_text.lines().collect();
543            let mut out = String::new();
544            // A cut-off append leaves a line without its newline. Close
545            // it, so it stays one unparseable line (which every reader
546            // skips) and cannot swallow the line written after it.
547            if !tail.is_empty() && !tail.ends_with(b"\n") {
548                out.push('\n');
549            }
550            let mut missing = false;
551            for line in &record.ledger {
552                if !present.contains(line.as_str()) {
553                    out.push_str(line);
554                    out.push('\n');
555                    missing = true;
556                }
557            }
558            if missing {
559                self.io.append(&log, out.as_bytes())?;
560            }
561            self.io.sync_file(&log)?;
562        }
563
564        match self.io.remove_file(&self.record_path()) {
565            Ok(()) => {}
566            Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
567            Err(e) => return Err(e),
568        }
569        // The removal is synced like everything else. A record that a
570        // power loss brought back would be applied again by the next
571        // load, and its deletes would then hit whatever was written to
572        // those paths since. The same sync names a ledger file this
573        // commit created, which lives in the same directory.
574        *self.owed() = Some(record.ops.iter().map(|op| op.path().to_string()).collect());
575        self.sync_record_removal().map(|_| ())
576    }
577
578    fn owed(&self) -> std::sync::MutexGuard<'_, Option<Vec<String>>> {
579        self.removal_sync_owed
580            .lock()
581            .unwrap_or_else(|e| e.into_inner())
582    }
583
584    /// Sync the removal of the commit record, if that sync is still
585    /// owed, and return the files of the commit it belonged to. The
586    /// record is gone by then, so nothing on disk says the sync is
587    /// missing; the backend remembers it until it succeeds.
588    fn sync_record_removal(&self) -> std::io::Result<Option<Vec<String>>> {
589        let mut owed = self.owed();
590        if owed.is_some() {
591            self.io.sync_dir(&self.meta_dir())?;
592        }
593        Ok(owed.take())
594    }
595
596    /// Remove the temp files of attempts that never reached their
597    /// commit point. Walks where entities and the sidecars live; the
598    /// lock directory is another process's business.
599    fn sweep_leftovers(&self) -> std::io::Result<()> {
600        let locks = self.meta_dir().join("locks");
601        let mut stack = vec![self.root.clone()];
602        while let Some(dir) = stack.pop() {
603            for entry in self.io.list_dir(&dir)? {
604                let path = dir.join(&entry.name);
605                if entry.is_dir {
606                    if path != locks {
607                        stack.push(path);
608                    }
609                } else if is_temp_name(&entry.name) {
610                    match self.io.remove_file(&path) {
611                        Ok(()) => {}
612                        Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
613                        Err(e) => return Err(e),
614                    }
615                }
616            }
617        }
618        Ok(())
619    }
620
621    /// Refuse to read storage that holds part of a commit. Every read
622    /// of files a commit can move (entities, the sidecars, the ledger)
623    /// starts here. While a commit record is on disk the commit is
624    /// decided and possibly half applied: a live writer is given the
625    /// time to finish it (the read waits for the mem's write lock), and
626    /// a record that is still there afterwards belongs to a commit that
627    /// was cut off, so the read returns that condition instead of
628    /// bytes. Completing it is left to a load, the one place that
629    /// reports what it completed. This is what keeps a cut-off commit
630    /// from being served in part by a reader that goes to storage
631    /// directly (an anchor read, a publish) while the engine's own view
632    /// still shows the state before it. One existence check when no
633    /// record is on disk.
634    fn ensure_whole(&self) -> Result<(), BackendError> {
635        if self.owed().is_some() {
636            return Err(BackendError::CommitNotApplied {
637                detail: "the removal of the last commit's record is not synced yet; \
638                         loading the mem makes it good"
639                    .to_string(),
640            });
641        }
642        let record = self.record_path();
643        if !self.io.exists(&record).map_err(BackendError::Io)? {
644            return Ok(());
645        }
646        let lock = self.lock_file();
647        // A reader that holds another mem's write lock does not wait
648        // here: this lock is not one of the sorted set it took, and a
649        // writer of this mem may be waiting for one of those. It gets
650        // the condition at once and takes no lock.
651        if path_lock::holds_another(&lock) {
652            return Err(BackendError::CommitNotApplied {
653                detail: "the mem holds a commit that is in progress or was cut off, and this \
654                         operation holds another mem's write lock, so it does not wait for it; \
655                         loading the mem completes it"
656                    .to_string(),
657            });
658        }
659        // A live writer finishes its own commit and the record is gone
660        // by the time it lets go. The wait is the workspace's write-lock
661        // deadline: a writer that stopped inside its commit and still
662        // holds the lock must not hold a reader for ever.
663        match self.wait_for_write_lock(&lock) {
664            Ok(None) => path_lock::release(&lock),
665            Ok(Some(wait)) => {
666                if self.io.exists(&record).map_err(BackendError::Io)? {
667                    return Err(self.lock_wait_passed(wait));
668                }
669            }
670            Err(_) => {}
671        }
672        if !self.io.exists(&record).map_err(BackendError::Io)? {
673            return Ok(());
674        }
675        Err(BackendError::CommitNotApplied {
676            detail: "the mem holds a commit that was cut off; loading the mem completes it"
677                .to_string(),
678        })
679    }
680
681    /// Is a temp file of an abandoned attempt on disk? The read-only
682    /// half of [`Self::sweep_leftovers`], so a mem with nothing to
683    /// remove is never locked or written for the asking.
684    fn has_leftovers(&self) -> bool {
685        let locks = self.meta_dir().join("locks");
686        let mut stack = vec![self.root.clone()];
687        while let Some(dir) = stack.pop() {
688            let Ok(entries) = self.io.list_dir(&dir) else {
689                continue;
690            };
691            for entry in entries {
692                let path = dir.join(&entry.name);
693                if entry.is_dir {
694                    if path != locks {
695                        stack.push(path);
696                    }
697                } else if is_temp_name(&entry.name) {
698                    return true;
699                }
700            }
701        }
702        false
703    }
704
705    /// Finish the commit whose record is on disk. The caller holds the
706    /// mem's write lock. `Ok(None)` when a live writer finished it
707    /// while this call waited for the lock.
708    fn complete_decided_commit(&self) -> Result<Option<CompletedCommit>, BackendError> {
709        let record_path = self.record_path();
710        let Some(bytes) = self.io.read(&record_path).map_err(BackendError::Io)? else {
711            return Ok(None);
712        };
713        let unreadable = |why: String| {
714            BackendError::Other(format!(
715                "commit record {} cannot be read ({why}); the mem holds a decided commit \
716                 that cannot be completed",
717                record_path.display()
718            ))
719        };
720        let record: CommitRecord =
721            serde_json::from_slice(&bytes).map_err(|e| unreadable(e.to_string()))?;
722        if record.v != 1 {
723            return Err(unreadable(format!("unknown record version {}", record.v)));
724        }
725        // The record is input from disk: hold its paths to the same
726        // rules as a staged path before anything is moved or removed.
727        for op in &record.ops {
728            normalise_rel_path(Path::new(op.path())).map_err(|e| unreadable(e.to_string()))?;
729            if let RecordOp::Upsert { tmp, .. } = op {
730                normalise_rel_path(Path::new(tmp)).map_err(|e| unreadable(e.to_string()))?;
731            }
732        }
733        self.apply_record(&record)
734            .map_err(|e| BackendError::CommitNotApplied {
735                detail: e.to_string(),
736            })?;
737        let _ = self.sweep_leftovers();
738        Ok(Some(CompletedCommit {
739            files: record.ops.iter().map(|op| op.path().to_string()).collect(),
740        }))
741    }
742
743    /// Land one set of file operations and provenance records behind
744    /// one commit point. The body of [`MemBackend::commit`], and of the
745    /// standalone provenance append, which is a commit of ledger lines
746    /// and no file.
747    fn commit_staged_set(
748        &self,
749        ops: HashMap<String, PendingState>,
750        records: &[Provenance],
751    ) -> Result<CommitId, BackendError> {
752        // An earlier commit whose record removal is not synced yet is
753        // not finished either: a load makes it good and reports it.
754        if self.owed().is_some() {
755            return Err(BackendError::Other(
756                "an earlier commit of this mem is applied but not yet durable; \
757                 the mem must be loaded, which finishes it, before it is written again"
758                    .to_string(),
759            ));
760        }
761
762        // A record already on disk is an earlier commit, decided and
763        // not yet applied. Putting a new record over it would lose it.
764        match self.io.exists(&self.record_path()) {
765            Ok(false) => {}
766            Ok(true) => {
767                return Err(BackendError::Other(
768                    "an earlier commit of this mem is decided and not yet applied; \
769                     the mem must be loaded, which completes it, before it is written again"
770                        .to_string(),
771                ));
772            }
773            Err(e) => return Err(BackendError::Io(e)),
774        }
775
776        // Path order, so the commit's steps and its record read the
777        // same on every run.
778        let mut ops: Vec<(String, PendingState)> = ops.into_iter().collect();
779        ops.sort_by(|a, b| a.0.cmp(&b.0));
780
781        // Failure handling is spelled out here rather than left to a
782        // drop guard: a process that dies mid-commit runs none of it,
783        // and the recovery at load must cope with exactly that.
784        let mut attempt = Attempt::default();
785        let record = match self.prepare_commit(&ops, records, &mut attempt) {
786            Ok(record) => record,
787            Err(e) => {
788                self.abandon(&attempt);
789                return Err(BackendError::Io(e));
790            }
791        };
792
793        // The record is in place: the commit is decided. From here an
794        // error leaves a commit that the next load completes, never a
795        // failed write.
796        let not_applied = |e: std::io::Error| BackendError::CommitNotApplied {
797            detail: e.to_string(),
798        };
799        self.apply_record(&record).map_err(not_applied)?;
800        Ok(make_commit_id())
801    }
802
803    /// Read the current bytes at `rel_key` from the buffered op log if
804    /// present, otherwise from disk. Used by `move_entity` to resolve
805    /// the source content.
806    fn read_source(
807        &self,
808        pending: &Pending,
809        rel_key: &str,
810    ) -> Result<Option<Vec<u8>>, BackendError> {
811        if let Some(PendingState::Upsert(bytes)) = pending.ops.get(rel_key) {
812            return Ok(Some(bytes.clone()));
813        }
814        if let Some(PendingState::Delete) = pending.ops.get(rel_key) {
815            return Ok(None);
816        }
817        let full = self.root.join(rel_key);
818        match std::fs::read(&full) {
819            Ok(bytes) => Ok(Some(bytes)),
820            Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
821            Err(e) => Err(BackendError::Io(e)),
822        }
823    }
824}
825
826/// Refuse to read the folder mem at `root` while it holds a commit that
827/// was cut off. For readers that walk a mem's directory without a
828/// backend in hand; the backend's own reads refuse through
829/// `FilesystemBackend::ensure_whole`. A directory with no commit record
830/// costs one existence check and is not touched.
831pub(crate) fn refuse_cut_off_commit(root: &Path) -> Result<(), BackendError> {
832    FilesystemBackend::new(root.to_path_buf()).ensure_whole()
833}
834
835/// [`refuse_cut_off_commit`] for a reader the engine calls with its
836/// workspace's settings at hand: the wait for the mem's write lock is
837/// the workspace's write-lock deadline, `None` for no bound.
838pub(crate) fn refuse_cut_off_commit_within(
839    root: &Path,
840    limit: Option<std::time::Duration>,
841) -> Result<(), BackendError> {
842    let backend = FilesystemBackend::new(root.to_path_buf());
843    backend.set_lock_wait(limit);
844    backend.ensure_whole()
845}
846
847/// Normalise a mem-relative path to a forward-slash key. Rejects
848/// empty paths, absolute paths, and any path that escapes the mem
849/// root via `..`. Every backend (folder, in-memory, git-branch) keys
850/// its entries through this one function, so they reject the same
851/// inputs.
852pub fn normalise_rel_path(rel_path: &Path) -> Result<String, BackendError> {
853    if rel_path.as_os_str().is_empty() {
854        return Err(BackendError::Path("mem-relative path is empty".to_string()));
855    }
856    let mut parts: Vec<String> = Vec::new();
857    for component in rel_path.components() {
858        use std::path::Component;
859        match component {
860            Component::Normal(s) => match s.to_str() {
861                Some(p) if !p.is_empty() => parts.push(p.to_string()),
862                _ => {
863                    return Err(BackendError::Path(format!(
864                        "non-utf-8 or empty path component in {}",
865                        rel_path.display()
866                    )));
867                }
868            },
869            Component::CurDir => continue,
870            Component::ParentDir | Component::RootDir | Component::Prefix(_) => {
871                return Err(BackendError::Path(format!(
872                    "path traversal or absolute component in {}",
873                    rel_path.display()
874                )));
875            }
876        }
877    }
878    if parts.is_empty() {
879        return Err(BackendError::Path(
880            "mem-relative path is empty after normalisation".to_string(),
881        ));
882    }
883    Ok(parts.join("/"))
884}
885
886impl crate::backend::MemBackend for FilesystemBackend {
887    fn list_entities(&self) -> Result<Vec<PathBuf>, BackendError> {
888        self.ensure_whole()?;
889        let mut out = Vec::new();
890        if !self.root.exists() {
891            return Ok(out);
892        }
893        walk_for_md(&self.root, &self.root, &mut out)?;
894        Ok(out)
895    }
896
897    /// Folder-mem drift cursor: the changelog's last-line `ts` (or the
898    /// commit-pending marker while a decided commit is unapplied) — the
899    /// same RFC3339-millisecond dialect `folder_changes_since` accepts
900    /// as its cursor, so drift heads feed straight into delta reads.
901    /// Every mutation appends a changelog line (in this process or a
902    /// sibling's), advancing the cursor; the drift check then treats
903    /// the advance exactly like a git-branch tip move. Absent
904    /// changelog (a mem never mutated through the engine) keeps the
905    /// historical no-drift-signal `None`. Appends go through
906    /// `append_change_monotonic`, so the cursor strictly advances even
907    /// for same-millisecond commits; only a read-append race between
908    /// separate processes can momentarily share a cursor value —
909    /// detection then rides the next append.
910    fn current_head(&self) -> Result<Option<String>, BackendError> {
911        // A commit record on disk is a decided commit not yet applied:
912        // report a cursor no ledger line carries, so the staleness
913        // probe reloads the mem and the reload completes the commit.
914        // The same while the sync of an applied commit's record removal
915        // is owed: a commit that carried no ledger line would otherwise
916        // leave the cursor where it was, and nothing would ever reload
917        // the mem and make the sync good.
918        if std::fs::symlink_metadata(self.record_path()).is_ok() || self.owed().is_some() {
919            return Ok(Some(COMMIT_PENDING_HEAD.to_string()));
920        }
921        let log_path = crate::filesystem::changelog::changelog_path(&self.root);
922        let raw = match std::fs::read_to_string(&log_path) {
923            Ok(s) => s,
924            Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None),
925            Err(e) => {
926                return Err(BackendError::Other(format!(
927                    "reading folder changelog {}: {e}",
928                    log_path.display()
929                )));
930            }
931        };
932        let last_ts = raw
933            .lines()
934            .rev()
935            .filter_map(|line| {
936                let trimmed = line.trim();
937                if trimmed.is_empty() {
938                    return None;
939                }
940                serde_json::from_str::<serde_json::Value>(trimmed)
941                    .ok()?
942                    .get("ts")?
943                    .as_str()
944                    .map(str::to_string)
945            })
946            .next();
947        Ok(last_ts)
948    }
949
950    /// Inside the mem's own `.memstead/`, in a self-ignoring `locks/`
951    /// subtree, so every process that mounts this folder, from any
952    /// workspace, contends on the same file.
953    ///
954    /// The path is the canonical one. Two processes that spell the
955    /// folder differently (through a symlink, through `..`) must sort
956    /// their locks alike, or each takes the other's second lock first;
957    /// and within one process the lock table is keyed by this path.
958    fn write_lock_path(&self) -> Option<PathBuf> {
959        Some(self.lock_file())
960    }
961
962    fn read_entity(&self, rel_path: &Path) -> Result<Option<Vec<u8>>, BackendError> {
963        let key = normalise_rel_path(rel_path)?;
964        let pending = self.pending.lock().map_err(|_| {
965            BackendError::Other("filesystem writer pending state poisoned".to_string())
966        })?;
967        if let Some(state) = pending.ops.get(&key) {
968            return Ok(match state {
969                PendingState::Upsert(bytes) => Some(bytes.clone()),
970                PendingState::Delete => None,
971            });
972        }
973        drop(pending);
974        self.ensure_whole()?;
975        let full = self.root.join(&key);
976        match std::fs::read(&full) {
977            Ok(bytes) => Ok(Some(bytes)),
978            Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
979            Err(e) => Err(BackendError::Io(e)),
980        }
981    }
982
983    /// Metadata-class existence probe: pending buffer first (same
984    /// precedence as `read_entity`), then one `symlink_metadata` call —
985    /// no file open, no byte read.
986    /// The mem root directory exists. A folder mount whose path is
987    /// gone (a moved checkout, a mem never materialised) lists zero
988    /// entities exactly like an empty one; this is how boot tells the
989    /// two apart.
990    fn storage_present(&self) -> Result<bool, BackendError> {
991        Ok(self.root.is_dir())
992    }
993
994    fn entity_exists(&self, rel_path: &Path) -> Result<bool, BackendError> {
995        let key = normalise_rel_path(rel_path)?;
996        let pending = self.pending.lock().map_err(|_| {
997            BackendError::Other("filesystem writer pending state poisoned".to_string())
998        })?;
999        if let Some(state) = pending.ops.get(&key) {
1000            return Ok(matches!(state, PendingState::Upsert(_)));
1001        }
1002        drop(pending);
1003        self.ensure_whole()?;
1004        match std::fs::symlink_metadata(self.root.join(&key)) {
1005            Ok(md) => Ok(md.is_file()),
1006            Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(false),
1007            Err(e) => Err(BackendError::Io(e)),
1008        }
1009    }
1010
1011    fn write_entity(&self, rel_path: &Path, content: &[u8]) -> Result<(), BackendError> {
1012        let key = normalise_rel_path(rel_path)?;
1013        refuse_unwritable(&self.root, &key)?;
1014        let mut pending = self.pending.lock().map_err(|_| {
1015            BackendError::Path("filesystem writer pending state poisoned".to_string())
1016        })?;
1017        pending
1018            .ops
1019            .insert(key, PendingState::Upsert(content.to_vec()));
1020        Ok(())
1021    }
1022
1023    fn delete_entity(&self, rel_path: &Path) -> Result<(), BackendError> {
1024        let key = normalise_rel_path(rel_path)?;
1025        refuse_unwritable(&self.root, &key)?;
1026        let mut pending = self.pending.lock().map_err(|_| {
1027            BackendError::Path("filesystem writer pending state poisoned".to_string())
1028        })?;
1029        pending.ops.insert(key, PendingState::Delete);
1030        Ok(())
1031    }
1032
1033    fn move_entity(&self, from: &Path, to: &Path) -> Result<(), BackendError> {
1034        let from_key = normalise_rel_path(from)?;
1035        let to_key = normalise_rel_path(to)?;
1036        refuse_unwritable(&self.root, &from_key)?;
1037        refuse_unwritable(&self.root, &to_key)?;
1038        let mut pending = self.pending.lock().map_err(|_| {
1039            BackendError::Path("filesystem writer pending state poisoned".to_string())
1040        })?;
1041
1042        // The target is checked before the source is touched, so a
1043        // refused move leaves the staged state exactly as it was.
1044        match pending.ops.get(&to_key) {
1045            Some(PendingState::Upsert(_)) => {
1046                return Err(BackendError::Path(format!(
1047                    "move target {} already has a pending write",
1048                    to.display()
1049                )));
1050            }
1051            Some(PendingState::Delete) => {}
1052            None => {
1053                if self.read_source(&pending, &to_key)?.is_some() {
1054                    return Err(BackendError::Path(format!(
1055                        "move target {} already exists",
1056                        to.display()
1057                    )));
1058                }
1059            }
1060        }
1061
1062        let bytes = match pending.ops.remove(&from_key) {
1063            Some(PendingState::Upsert(b)) => b,
1064            Some(PendingState::Delete) => {
1065                pending.ops.insert(from_key, PendingState::Delete);
1066                return Err(BackendError::Path(format!(
1067                    "move source {} is already pending deletion",
1068                    from.display()
1069                )));
1070            }
1071            None => match self.read_source(&pending, &from_key)? {
1072                Some(b) => b,
1073                None => {
1074                    return Err(BackendError::Path(format!(
1075                        "move source {} does not exist",
1076                        from.display()
1077                    )));
1078                }
1079            },
1080        };
1081
1082        pending.ops.insert(from_key, PendingState::Delete);
1083        pending.ops.insert(to_key, PendingState::Upsert(bytes));
1084        Ok(())
1085    }
1086
1087    fn discard_pending(&self) -> Result<(), BackendError> {
1088        // Drop the staged operations and their provenance records
1089        // without replaying them: nothing staged has touched disk.
1090        let mut pending = self.pending.lock().map_err(|_| {
1091            BackendError::Other("filesystem writer pending state poisoned".to_string())
1092        })?;
1093        pending.clear();
1094        Ok(())
1095    }
1096
1097    fn commit(&self, _message: &str, _ctx: &CommitContext<'_>) -> Result<CommitId, BackendError> {
1098        let mut pending = self.pending.lock().map_err(|_| {
1099            BackendError::Path("filesystem writer pending state poisoned".to_string())
1100        })?;
1101        // Taken out before anything can fail: whatever this commit
1102        // comes to, nothing stays staged behind it, so no later read
1103        // can serve a write that never landed.
1104        let staged = std::mem::replace(&mut *pending, Pending::new());
1105        if staged.ops.is_empty() && staged.records.is_empty() {
1106            return Ok(make_commit_id());
1107        }
1108
1109        self.commit_staged_set(staged.ops, &staged.records)
1110    }
1111
1112    fn set_lock_wait(&self, limit: Option<std::time::Duration>) {
1113        if let Ok(mut wait) = self.lock_wait.lock() {
1114            *wait = Some(limit);
1115        }
1116    }
1117
1118    fn lock_wait(&self) -> Option<Option<std::time::Duration>> {
1119        Some(self.lock_wait_limit().0)
1120    }
1121
1122    /// Recovery writes, so it excludes a live writer first: the record
1123    /// it applies and the temps it removes belong to a writer that is
1124    /// gone only if no one holds the mem's write lock. A record on disk
1125    /// waits for that lock, no longer than the workspace's write-lock
1126    /// deadline (a live writer finishes its own commit and the record
1127    /// is gone by then); leftover temps are removed only if the lock is
1128    /// free at once, since they are invisible to readers and a load
1129    /// must not wait on hygiene. A mem with nothing to recover is not
1130    /// touched at all, lock file included.
1131    fn complete_interrupted_commit(&self) -> Result<Option<CompletedCommit>, BackendError> {
1132        // A commit of this backend that is applied except for the sync
1133        // of its record's removal: make the sync good, and that commit
1134        // is the one this call completed.
1135        if let Some(files) =
1136            self.sync_record_removal()
1137                .map_err(|e| BackendError::CommitNotApplied {
1138                    detail: e.to_string(),
1139                })?
1140        {
1141            return Ok(Some(CompletedCommit { files }));
1142        }
1143        let lock = self.lock_file();
1144        if self
1145            .io
1146            .exists(&self.record_path())
1147            .map_err(BackendError::Io)?
1148        {
1149            // A load that runs under another mem's write lock (the
1150            // reload of a peer before a write) does not wait for this
1151            // one: the lock is outside the sorted set its operation
1152            // took, and a writer of this mem may be waiting for one of
1153            // those. It takes the lock if it is free and otherwise
1154            // leaves the commit to its writer, or to the next load.
1155            if path_lock::holds_another(&lock) {
1156                return match path_lock::try_acquire(&lock) {
1157                    Ok(true) => {
1158                        let result = self.complete_decided_commit();
1159                        path_lock::release(&lock);
1160                        result
1161                    }
1162                    _ => Err(BackendError::CommitNotApplied {
1163                        detail: "the mem holds a commit in progress and another writer holds \
1164                                 its lock; loading the mem completes it once the lock is free"
1165                            .to_string(),
1166                    }),
1167                };
1168            }
1169            // A lock that cannot be taken (a read-only location) is not
1170            // a reason to serve the mem half applied: the completion
1171            // below then fails with its own error. A lock another
1172            // process keeps past the workspace's write-lock deadline
1173            // ends the wait: the commit is that process's to finish or
1174            // a later load's, and this load serves nothing of the mem.
1175            let locked = match self.wait_for_write_lock(&lock) {
1176                Ok(None) => true,
1177                Ok(Some(wait)) => {
1178                    // The holder may have finished its commit while
1179                    // this load waited out the last moment.
1180                    if !self
1181                        .io
1182                        .exists(&self.record_path())
1183                        .map_err(BackendError::Io)?
1184                    {
1185                        return Ok(None);
1186                    }
1187                    return Err(self.lock_wait_passed(wait));
1188                }
1189                Err(_) => false,
1190            };
1191            let result = self.complete_decided_commit();
1192            if locked {
1193                path_lock::release(&lock);
1194            }
1195            return result;
1196        }
1197        // Best effort from here: a temp that stays is removed by a
1198        // later load and changes nothing a reader sees.
1199        if self.has_leftovers() && matches!(path_lock::try_acquire(&lock), Ok(true)) {
1200            // Look again under the lock: a sibling writer may have
1201            // passed its commit point and died since the first look.
1202            // Its temps are then the contents of a decided commit, to
1203            // be moved into place and never swept.
1204            let result = if self
1205                .io
1206                .exists(&self.record_path())
1207                .map_err(BackendError::Io)?
1208            {
1209                self.complete_decided_commit()
1210            } else {
1211                let _ = self.sweep_leftovers();
1212                Ok(None)
1213            };
1214            path_lock::release(&lock);
1215            return result;
1216        }
1217        Ok(None)
1218    }
1219
1220    fn read_mem_config(&self) -> Result<Option<Vec<u8>>, BackendError> {
1221        // Folder backend reads `<root>/.memstead/config.json`.
1222        // Missing file → Ok(None); other IO errors propagate as
1223        // BackendError.
1224        let config_path = self.root.join(crate::mem::MEM_META_DIR).join("config.json");
1225        match std::fs::read(&config_path) {
1226            Ok(bytes) => Ok(Some(bytes)),
1227            Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
1228            Err(e) => Err(BackendError::Io(e)),
1229        }
1230    }
1231
1232    fn write_mem_config(
1233        &self,
1234        bytes: &[u8],
1235        _ctx: &crate::vcs::CommitContext<'_>,
1236    ) -> Result<(), BackendError> {
1237        // Folder backend writes `<root>/.memstead/config.json` to disk.
1238        // Creates the `.memstead/` directory if missing. Existing config
1239        // is overwritten — caller's responsibility to gate against
1240        // overwrites if that's the contract (the unified
1241        // `mem_management::create_mem` Step 4 already does the
1242        // refusal-to-overwrite check upstream).
1243        let memstead_dir = self.root.join(crate::mem::MEM_META_DIR);
1244        std::fs::create_dir_all(&memstead_dir).map_err(BackendError::Io)?;
1245        refuse_symlinked_meta(&self.root)?;
1246        let _lock = ConfigLock::take(self.config_lock_file())?;
1247        replace_file(&memstead_dir.join("config.json"), bytes)
1248    }
1249
1250    /// Compare-and-set under the mem's config lock (an operating-system
1251    /// file lock, shared with [`Self::write_mem_config`]), which is what
1252    /// makes the check and the write one step. A hand edit is still
1253    /// detected, because the compare reads the file. The write replaces the
1254    /// file through a renamed temp, so a crash leaves the old config or the
1255    /// new one.
1256    fn write_mem_config_cas(
1257        &self,
1258        expected: Option<&[u8]>,
1259        bytes: &[u8],
1260        _ctx: &crate::vcs::CommitContext<'_>,
1261    ) -> Result<bool, BackendError> {
1262        let memstead_dir = self.root.join(crate::mem::MEM_META_DIR);
1263        std::fs::create_dir_all(&memstead_dir).map_err(BackendError::Io)?;
1264        let config_path = memstead_dir.join("config.json");
1265        // The config lock makes the compare and the write one step against
1266        // every other config writer of this mem, in any process. It is an
1267        // operating-system lock: a writer that dies releases it, so there is
1268        // no stale age to guess and no live holder is ever overtaken.
1269        refuse_symlinked_meta(&self.root)?;
1270        let _lock = ConfigLock::take(self.config_lock_file())?;
1271
1272        let current = match std::fs::read(&config_path) {
1273            Ok(b) => Some(b),
1274            Err(e) if e.kind() == std::io::ErrorKind::NotFound => None,
1275            Err(e) => return Err(BackendError::Io(e)),
1276        };
1277        if let Some(expected) = expected
1278            && current.as_deref() != Some(expected)
1279        {
1280            return Ok(false);
1281        }
1282        replace_file(&config_path, bytes).map(|_| true)
1283    }
1284
1285    fn read_anchors_sidecar(&self) -> Result<Option<Vec<u8>>, BackendError> {
1286        // Read via the entity path so a staged (pending) sidecar write is
1287        // visible before its commit, symmetric with the other backends.
1288        self.read_entity(Path::new(crate::anchor::ANCHOR_SIDECAR_PATH))
1289    }
1290
1291    fn write_anchors_sidecar(&self, bytes: &[u8]) -> Result<(), BackendError> {
1292        // Stage into the same op buffer entity writes use so the sidecar
1293        // rides the entity mutation's commit. `list_entities`
1294        // (`walk_for_md`) skips `.memstead/`, so it never lists as an
1295        // entity.
1296        <Self as MemBackend>::write_entity(
1297            self,
1298            Path::new(crate::anchor::ANCHOR_SIDECAR_PATH),
1299            bytes,
1300        )
1301    }
1302
1303    fn stage_provenance(&self, record: &Provenance) -> Result<(), BackendError> {
1304        let mut pending = self.pending.lock().map_err(|_| {
1305            BackendError::Other("filesystem writer pending state poisoned".to_string())
1306        })?;
1307        pending.records.push(record.clone());
1308        Ok(())
1309    }
1310
1311    fn append_provenance(&self, record: &Provenance) -> Result<(), BackendError> {
1312        // A record on its own is a commit of one ledger line and no
1313        // file, behind the same commit point as any other: it is
1314        // durable when this returns, and a failure after the commit
1315        // point is the decided-and-not-applied condition, never a line
1316        // that is in the ledger while the caller is told it failed.
1317        // Writes staged for a later commit are not touched.
1318        self.commit_staged_set(HashMap::new(), std::slice::from_ref(record))
1319            .map(|_| ())
1320    }
1321
1322    fn read_provenance(&self, cursor: Option<&str>) -> Result<Vec<Provenance>, BackendError> {
1323        self.ensure_whole()?;
1324        let log_path = changelog_path(&self.root);
1325        let raw = match std::fs::read_to_string(&log_path) {
1326            Ok(s) => s,
1327            Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(Vec::new()),
1328            Err(e) => return Err(BackendError::Io(e)),
1329        };
1330        let mut out = Vec::new();
1331        for line in raw.lines() {
1332            let trimmed = line.trim();
1333            if trimmed.is_empty() {
1334                continue;
1335            }
1336            let value: serde_json::Value = match serde_json::from_str(trimmed) {
1337                Ok(v) => v,
1338                Err(_) => continue,
1339            };
1340            let ts_str = value.get("ts").and_then(|v| v.as_str()).unwrap_or("");
1341            if let Some(c) = cursor
1342                && ts_str <= c
1343            {
1344                continue;
1345            }
1346            let timestamp = parse_rfc3339_utc(ts_str).unwrap_or(std::time::UNIX_EPOCH);
1347            let kind = value
1348                .get("kind")
1349                .and_then(|v| v.as_str())
1350                .and_then(ProvenanceKind::parse)
1351                .unwrap_or(ProvenanceKind::Update);
1352            let entity = value
1353                .get("entity")
1354                .and_then(|v| v.as_str())
1355                .map(|s| s.to_string());
1356            let actor = value
1357                .get("actor")
1358                .and_then(|v| v.as_str())
1359                .and_then(Actor::from_trailer)
1360                .unwrap_or(Actor::Unknown);
1361            let client = value
1362                .get("client")
1363                .and_then(|v| v.as_str())
1364                .and_then(parse_client_id);
1365            let note = value
1366                .get("note")
1367                .and_then(|v| v.as_str())
1368                .map(|s| s.to_string());
1369            let logical_operation_id = value
1370                .get("logical_op")
1371                .and_then(|v| v.as_str())
1372                .map(|s| s.to_string());
1373            let mut record = Provenance::new(timestamp, kind, entity, actor, client, note);
1374            if let Some(id) = logical_operation_id {
1375                record = record.with_logical_operation_id(id);
1376            }
1377            if let Some(from) = value.get("renamed_from").and_then(|v| v.as_str()) {
1378                record = record.with_renamed_from(from.to_string());
1379            }
1380            if let Some(role) = value
1381                .get("role")
1382                .and_then(|v| v.as_str())
1383                .and_then(crate::vcs::Role::from_wire)
1384            {
1385                record = record.with_role(role);
1386            }
1387            record = record.with_identity(
1388                value
1389                    .get("identity")
1390                    .and_then(|v| v.as_str())
1391                    .map(|s| s.to_string()),
1392            );
1393            out.push(record);
1394        }
1395        Ok(out)
1396    }
1397}
1398
1399/// Walk `dir` for `.md` files, accumulating mem-relative paths in
1400/// `out`. Skips the mem's `.memstead/` umbrella so the engine never
1401/// confuses changelog / config / schema files with entity-bearing
1402/// markdown, and `README.md` — repository documentation beside the
1403/// entity files, never an entity (mirrors the entity-source walker's
1404/// skip; entities are slug-named after their titles, so no legitimate
1405/// entity file carries this name).
1406fn walk_for_md(root: &Path, dir: &Path, out: &mut Vec<PathBuf>) -> Result<(), BackendError> {
1407    let entries = match std::fs::read_dir(dir) {
1408        Ok(e) => e,
1409        Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(()),
1410        Err(e) => return Err(BackendError::Io(e)),
1411    };
1412    for entry in entries {
1413        let entry = entry.map_err(BackendError::Io)?;
1414        let path = entry.path();
1415        let file_type = entry.file_type().map_err(BackendError::Io)?;
1416        if file_type.is_dir() {
1417            let name = entry.file_name();
1418            if name == crate::mem::MEM_META_DIR {
1419                continue;
1420            }
1421            // A subdirectory with its own mem config is another mem.
1422            if crate::mem::is_nested_mem_root(&path) {
1423                continue;
1424            }
1425            walk_for_md(root, &path, out)?;
1426        } else if file_type.is_file()
1427            && crate::filesystem::changelog::is_entity_file(&path)
1428            && let Ok(rel) = path.strip_prefix(root)
1429        {
1430            out.push(rel.to_path_buf());
1431        }
1432    }
1433    Ok(())
1434}
1435
1436/// The ledger entry a provenance record writes.
1437fn change_entry(record: &Provenance) -> ChangeEntry<'_> {
1438    let kind: MutationKind = record.kind.into();
1439    ChangeEntry {
1440        kind,
1441        entity: record.entity.as_deref(),
1442        actor: record.actor,
1443        client: record.client.as_ref(),
1444        note: record.note.as_deref(),
1445        logical_operation_id: record.logical_operation_id.as_deref(),
1446        role: record.role,
1447        identity: record.identity.as_deref(),
1448        renamed_from: record.renamed_from.as_deref(),
1449    }
1450}
1451
1452/// The mem-relative key of `tmp`, the temp file beside the target at
1453/// `key`: same directory, the temp's file name.
1454fn sibling_key(key: &str, tmp: &Path) -> String {
1455    let name = tmp
1456        .file_name()
1457        .map(|n| n.to_string_lossy().into_owned())
1458        .unwrap_or_default();
1459    match key.rsplit_once('/') {
1460        Some((dir, _)) => format!("{dir}/{name}"),
1461        None => name,
1462    }
1463}
1464
1465/// Is `name` a temp file of this backend ([`make_tmp_path`]):
1466/// `.<target>.tmp.<hex>-<hex>`?
1467fn is_temp_name(name: &str) -> bool {
1468    let Some(rest) = name.strip_prefix('.') else {
1469        return false;
1470    };
1471    let Some((target, suffix)) = rest.rsplit_once(".tmp.") else {
1472        return false;
1473    };
1474    let Some((nanos, counter)) = suffix.split_once('-') else {
1475        return false;
1476    };
1477    let hex = |s: &str| !s.is_empty() && s.bytes().all(|b| b.is_ascii_hexdigit());
1478    !target.is_empty() && hex(nanos) && hex(counter)
1479}
1480
1481/// Build a sibling temp path of the form `.<name>.tmp.<suffix>` next
1482/// to `target`. The leading dot keeps the temp file out of the way of
1483/// directory listings; the suffix combines UNIX-nanos with a process-
1484/// scoped counter so concurrent writes never collide.
1485fn make_tmp_path(target: &Path) -> PathBuf {
1486    let name = target
1487        .file_name()
1488        .map(|n| n.to_string_lossy().to_string())
1489        .unwrap_or_else(|| "_".to_string());
1490    let suffix = unique_suffix();
1491    let tmp_name = format!(".{name}.tmp.{suffix}");
1492    target.with_file_name(tmp_name)
1493}
1494
1495static TMP_COUNTER: AtomicU64 = AtomicU64::new(0);
1496static COMMIT_COUNTER: AtomicU64 = AtomicU64::new(0);
1497
1498fn unique_suffix() -> String {
1499    let nanos = std::time::SystemTime::now()
1500        .duration_since(std::time::UNIX_EPOCH)
1501        .map(|d| d.as_nanos())
1502        .unwrap_or(0);
1503    let counter = TMP_COUNTER.fetch_add(1, Ordering::Relaxed);
1504    format!("{nanos:x}-{counter:x}")
1505}
1506
1507/// `pub(crate)` so the in-memory backend mints the same synthetic
1508/// write-id shape (UNIX-nanos + counter, hex) the folder backend
1509/// produces — both are history-free backends and must hand callers an
1510/// identically-shaped opaque identity. It is NOT a change cursor:
1511/// the change feed's cursor is an RFC3339 timestamp, and passing this
1512/// token as `since` refuses with `INVALID_CURSOR` (it would otherwise
1513/// sort below every timestamp and replay the whole history).
1514pub(crate) fn make_commit_id() -> CommitId {
1515    let nanos = std::time::SystemTime::now()
1516        .duration_since(std::time::UNIX_EPOCH)
1517        .map(|d| d.as_nanos())
1518        .unwrap_or(0);
1519    let counter = COMMIT_COUNTER.fetch_add(1, Ordering::Relaxed);
1520    format!("{nanos:032x}{counter:016x}")
1521}
1522
1523#[cfg(test)]
1524mod commit_point_tests;
1525#[cfg(test)]
1526pub(crate) mod fault_io;
1527#[cfg(test)]
1528mod folder_drift_tests;
1529pub(crate) mod io;
1530#[cfg(test)]
1531mod tests;
1532
1533/// Replace `path` with `bytes`: write a sibling temp file, sync it, rename
1534/// it over `path` and sync the directory. A crash leaves either the old
1535/// file or the new one, never a truncated one.
1536fn replace_file(path: &Path, bytes: &[u8]) -> Result<(), BackendError> {
1537    use std::io::Write as _;
1538    let dir = path
1539        .parent()
1540        .ok_or_else(|| BackendError::Path(format!("{} has no parent", path.display())))?;
1541    let name = path
1542        .file_name()
1543        .ok_or_else(|| BackendError::Path(format!("{} has no file name", path.display())))?;
1544    let mut tmp_name = name.to_os_string();
1545    tmp_name.push(format!(".tmp-{}", lock_token()));
1546    let tmp = dir.join(tmp_name);
1547    let written = (|| -> std::io::Result<()> {
1548        let mut f = std::fs::File::create(&tmp)?;
1549        f.write_all(bytes)?;
1550        f.sync_all()?;
1551        std::fs::rename(&tmp, path)?;
1552        RealIo.sync_dir(dir)
1553    })();
1554    if written.is_err() {
1555        let _ = std::fs::remove_file(&tmp);
1556    }
1557    written.map_err(BackendError::Io)
1558}
1559
1560/// A token unique to this process and call, naming a temp file.
1561fn lock_token() -> String {
1562    use std::sync::atomic::{AtomicU64, Ordering};
1563    static SEQ: AtomicU64 = AtomicU64::new(0);
1564    let nanos = std::time::SystemTime::now()
1565        .duration_since(std::time::UNIX_EPOCH)
1566        .map(|d| d.as_nanos())
1567        .unwrap_or(0);
1568    format!(
1569        "{}-{}-{}",
1570        std::process::id(),
1571        nanos,
1572        SEQ.fetch_add(1, Ordering::Relaxed)
1573    )
1574}
1575
1576/// The first component of `key` under `root` that is a symbolic link, if
1577/// any. A write or delete through one would land outside the mem, where no
1578/// listing, commit record or ledger of this mem sees it.
1579fn symlink_on_path(root: &Path, key: &str) -> std::io::Result<Option<PathBuf>> {
1580    let mut at = root.to_path_buf();
1581    for part in Path::new(key).components() {
1582        at.push(part);
1583        match std::fs::symlink_metadata(&at) {
1584            Ok(md) if md.file_type().is_symlink() => return Ok(Some(at)),
1585            // Nothing below a file can exist; the write fails on its own.
1586            Ok(md) if !md.is_dir() => return Ok(None),
1587            Ok(_) => {}
1588            Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None),
1589            Err(e) => return Err(e),
1590        }
1591    }
1592    Ok(None)
1593}
1594
1595/// Refuse `key` when it passes through a symbolic link inside the mem.
1596fn refuse_symlinked(root: &Path, key: &str) -> Result<(), BackendError> {
1597    match symlink_on_path(root, key).map_err(BackendError::Io)? {
1598        Some(link) => Err(BackendError::Path(format!(
1599            "{key} passes through the symbolic link {}; a mem writes only inside its own directory",
1600            link.display()
1601        ))),
1602        None => Ok(()),
1603    }
1604}
1605
1606/// The mem's config lock, held for the scope of one config write.
1607struct ConfigLock(PathBuf);
1608
1609impl ConfigLock {
1610    fn take(path: PathBuf) -> Result<Self, BackendError> {
1611        path_lock::acquire(&path).map_err(BackendError::Io)?;
1612        Ok(Self(path))
1613    }
1614}
1615
1616impl Drop for ConfigLock {
1617    fn drop(&mut self) {
1618        path_lock::release(&self.0);
1619    }
1620}
1621
1622/// The paths under `.memstead/` an entity-path write may reach: the
1623/// sidecars that ride a commit. Everything else there (the commit record,
1624/// the ledger, the config, the locks) is the backend's own.
1625const WRITABLE_META_PATHS: &[&str] = &[
1626    crate::anchor::ANCHOR_SIDECAR_PATH,
1627    crate::derivation::DERIVATION_SIDECAR_PATH,
1628    crate::ops::proposal::PROPOSAL_RECORD_PATH,
1629];
1630
1631/// Refuse an entity-path write to one of the backend's own files under
1632/// `.memstead/`, and any path through a symbolic link.
1633fn refuse_unwritable(root: &Path, key: &str) -> Result<(), BackendError> {
1634    let meta = format!("{}/", crate::mem::MEM_META_DIR);
1635    if key.starts_with(&meta) && !WRITABLE_META_PATHS.contains(&key) {
1636        return Err(BackendError::Path(format!(
1637            "{key} is the backend's own file; only {} are written through entity paths",
1638            WRITABLE_META_PATHS.join(", ")
1639        )));
1640    }
1641    refuse_symlinked(root, key)
1642}
1643
1644/// Refuse a `.memstead` directory that is a symbolic link: the config, the
1645/// commit record and the ledger would land outside the mem.
1646fn refuse_symlinked_meta(root: &Path) -> Result<(), BackendError> {
1647    refuse_symlinked(root, crate::mem::MEM_META_DIR)
1648}