Skip to main content

memstead_base/engine/
roster.rs

1//! Mem membership follows reload-before-operation.
2//!
3//! Content drift is probed per operation ([`super::Engine::reload_if_stale`]
4//! compares each mount's branch tip with the head it last loaded). Membership
5//! used to be fixed at boot: a mem registered or unregistered by another
6//! process (the CLI, a sibling server) stayed invisible, or kept being served,
7//! until a restart — on 2026-09-02 a ui-api served a retired mem for hours.
8//! This module is the membership half of the same discipline: before each
9//! operation the engine compares a fingerprint of the mount roster
10//! (`.memstead/state/mounts.json`) with the one it booted or last reconciled
11//! on, and on a change mounts the new entries cold under the boot quarantine
12//! rules, unmounts the gone entries atomically, re-scans the schema sources,
13//! and reports the change (`MEM_ROSTER_CHANGED`) so an agent drops the cached
14//! hashes of the mems that left.
15//!
16//! The probe is a `stat` plus, only when size or mtime moved, a hash of the
17//! file — the same cost band as the branch-tip probe, never a boot.
18
19use std::collections::{BTreeSet, HashSet};
20use std::path::PathBuf;
21use std::sync::Arc;
22
23use serde::{Deserialize, Serialize};
24
25use super::{Engine, EngineError};
26
27/// What the engine last saw of the roster file: size and mtime for the
28/// cheap comparison, the content hash for the decision.
29#[derive(Debug, Clone, PartialEq, Eq)]
30pub struct RosterFingerprint {
31    len: u64,
32    modified: Option<std::time::SystemTime>,
33    hash: u64,
34}
35
36/// One applied roster reconciliation.
37#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
38pub struct RosterChange {
39    /// Mems the roster gained and the engine mounted cold, ready to serve.
40    pub added: Vec<String>,
41    /// Mems the roster lost and the engine unmounted: their entities,
42    /// search index, community partition and derived views are gone.
43    pub removed: Vec<String>,
44    /// Mems the roster gained that failed to mount and are quarantined
45    /// under the boot rules (each with its reason on the quarantine
46    /// roster); the other mems keep serving.
47    pub quarantined: Vec<String>,
48    /// Per-item failures that were not a quarantine: the schema-source
49    /// re-scan, or an unmount that could not complete (the roster change
50    /// for that mem is not applied and it stays fully served).
51    pub failures: Vec<crate::ops::RefreshFailure>,
52}
53
54impl RosterChange {
55    /// Whether anything at all changed or failed.
56    pub fn is_empty(&self) -> bool {
57        self.added.is_empty()
58            && self.removed.is_empty()
59            && self.quarantined.is_empty()
60            && self.failures.is_empty()
61    }
62}
63
64/// The event a roster subscriber receives — the applied change.
65pub type RosterChangedEvent = RosterChange;
66
67/// Callback shape for roster subscribers, mirroring
68/// [`super::events::EventCallback`].
69pub type RosterCallback = Arc<dyn Fn(&RosterChangedEvent) + Send + Sync + 'static>;
70
71/// The roster subscriber registry: the next id, then `(id, callback)`.
72pub(crate) type RosterSubscribers = std::sync::Mutex<(u64, Vec<(u64, RosterCallback)>)>;
73
74fn hash_bytes(bytes: &[u8]) -> u64 {
75    use std::hash::{Hash, Hasher};
76    let mut h = std::collections::hash_map::DefaultHasher::new();
77    bytes.hash(&mut h);
78    h.finish()
79}
80
81impl Engine {
82    /// The roster file this engine's membership is read from, when the
83    /// engine knows its workspace root.
84    fn roster_path(&self) -> Option<PathBuf> {
85        self.workspace_root.as_ref().map(|root| {
86            root.join(crate::workspace_store::WORKSPACE_STORE_DIR)
87                .join("state")
88                .join("mounts.json")
89        })
90    }
91
92    /// The roster's current fingerprint. `Ok(None)` when the engine has no
93    /// workspace root or the file does not exist (an ad-hoc mount list, a
94    /// standalone folder mem). Size and mtime unchanged from the cached
95    /// fingerprint short-circuits without reading the file.
96    fn roster_fingerprint_now(&self) -> Result<Option<RosterFingerprint>, std::io::Error> {
97        let Some(path) = self.roster_path() else {
98            return Ok(None);
99        };
100        let meta = match std::fs::metadata(&path) {
101            Ok(m) => m,
102            Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None),
103            Err(e) => return Err(e),
104        };
105        let len = meta.len();
106        let modified = meta.modified().ok();
107        if let Some(cached) = &self.roster_fingerprint
108            && cached.len == len
109            && cached.modified == modified
110        {
111            return Ok(Some(cached.clone()));
112        }
113        let bytes = std::fs::read(&path)?;
114        Ok(Some(RosterFingerprint {
115            len,
116            modified,
117            hash: hash_bytes(&bytes),
118        }))
119    }
120
121    /// Capture the roster as it stands as the reconciliation baseline —
122    /// what boot and every applied reconcile leave behind.
123    pub(crate) fn capture_roster_fingerprint(&mut self) {
124        self.roster_fingerprint = self.roster_fingerprint_now().ok().flatten();
125    }
126
127    /// Reconcile membership with the roster file: `Ok(None)` when the roster
128    /// did not change since the last reconcile; `Ok(Some(change))` after
129    /// applying a change; `Err` only when the roster could not be read or
130    /// parsed at all (the baseline is kept, so the next operation retries).
131    ///
132    /// A roster file that did not exist at boot (a workspace whose first
133    /// mem is created by another process after this engine started) is a
134    /// change like any other: the first observation is applied, never
135    /// swallowed as a baseline. Boot captures its own baseline through
136    /// [`Engine::capture_roster_fingerprint`], so an engine that saw the
137    /// file at boot is not re-mounted here.
138    ///
139    /// Per mem the change is atomic: an unmount that cannot complete leaves
140    /// that mem fully served, is reported under `failures`, and keeps the
141    /// baseline where it was so it is retried next time; a cold mount that
142    /// fails quarantines the mem exactly as boot would. Read-only
143    /// attachments (installed archives) are not roster entries and never
144    /// count as removals.
145    pub fn reconcile_roster(&mut self) -> Result<Option<RosterChange>, EngineError> {
146        let now = self.roster_fingerprint_now().map_err(|e| {
147            EngineError::Backend(crate::backend::BackendError::Other(format!(
148                "roster unreadable: {e}"
149            )))
150        })?;
151        let Some(now) = now else {
152            return Ok(None);
153        };
154        let Some(cached) = self.roster_fingerprint.clone() else {
155            // No baseline: the file appeared after boot. Mount what it names.
156            return self.apply_roster(now).map(Some);
157        };
158        if cached.hash == now.hash {
159            self.roster_fingerprint = Some(now);
160            return Ok(None);
161        }
162        self.apply_roster(now).map(Some)
163    }
164
165    /// The reconciliation without the fingerprint gate — what
166    /// `full_refresh` runs so its report is authoritative even when the
167    /// roster file did not move (a first observation, a probe that was
168    /// skipped). An engine without a roster file yields an empty change.
169    pub(crate) fn reconcile_roster_forced(&mut self) -> Result<RosterChange, EngineError> {
170        let now = self.roster_fingerprint_now().map_err(|e| {
171            EngineError::Backend(crate::backend::BackendError::Other(format!(
172                "roster unreadable: {e}"
173            )))
174        })?;
175        match now {
176            Some(now) => self.apply_roster(now),
177            None => Ok(RosterChange::default()),
178        }
179    }
180
181    fn apply_roster(&mut self, now: RosterFingerprint) -> Result<RosterChange, EngineError> {
182        let root = self
183            .workspace_root
184            .clone()
185            .expect("a roster fingerprint implies a workspace root");
186        let workspace = crate::workspace_store::WorkspaceStoreAdapter::load(
187            &crate::workspace_store::FileWorkspaceStore::new(),
188            &root,
189        )
190        .map_err(|e| {
191            EngineError::Backend(crate::backend::BackendError::Other(format!(
192                "roster under {} unreadable: {e}",
193                root.display()
194            )))
195        })?;
196
197        let cross_mem_links = workspace.settings.cross_mem_links.clone();
198        let manifest: BTreeSet<String> = workspace
199            .mounts
200            .iter()
201            .filter(|m| m.capability == crate::workspace::MountCapability::Write)
202            .map(|m| m.mem.clone())
203            .collect();
204        let mounted: BTreeSet<String> = self
205            .mounts
206            .iter()
207            .filter(|m| m.mount.capability == crate::workspace::MountCapability::Write)
208            .map(|m| m.mount.mem.clone())
209            .collect();
210        let quarantined_now: BTreeSet<String> = self
211            .quarantined
212            .iter()
213            .map(|q| q.mount.mem.clone())
214            .collect();
215
216        let mut change = RosterChange::default();
217        let mut all_applied = true;
218
219        // The schema catalogue first: a mem that arrived may pin a schema
220        // installed since boot, and a cold mount resolves against the
221        // catalogue as it stands.
222        let mut schema_report = crate::ops::FullRefreshReport::default();
223        self.refresh_schema_sources(&mut schema_report);
224        change.failures.extend(schema_report.failures);
225
226        // Removals first, each atomic. A gone quarantined entry just leaves
227        // the quarantine roster: it served nothing.
228        for name in mounted.difference(&manifest) {
229            match self.unmount_mem(name) {
230                Ok(()) => change.removed.push(name.clone()),
231                Err(e) => {
232                    all_applied = false;
233                    change.failures.push(crate::ops::RefreshFailure {
234                        item: format!("unmount:{name}"),
235                        error: e.to_string(),
236                    });
237                }
238            }
239        }
240        let gone_quarantined: Vec<String> =
241            quarantined_now.difference(&manifest).cloned().collect();
242        if !gone_quarantined.is_empty() {
243            self.quarantined
244                .retain(|q| !gone_quarantined.contains(&q.mount.mem));
245            change.removed.extend(gone_quarantined);
246        }
247
248        // Additions: cold mount under the boot quarantine rules.
249        let mut any_mounted = false;
250        for mount in workspace.mounts {
251            if mount.capability != crate::workspace::MountCapability::Write
252                || mounted.contains(&mount.mem)
253                || quarantined_now.contains(&mount.mem)
254            {
255                continue;
256            }
257            let name = mount.mem.clone();
258            let backend = match (self.backend_factory)(&mount) {
259                Ok(b) => b,
260                Err(e) => {
261                    self.quarantine_mount(mount, e.code(), e.to_string());
262                    change.quarantined.push(name);
263                    continue;
264                }
265            };
266            // Boot's rule for storage that is gone (a branch the mem-repo
267            // lacks, a folder that does not exist): quarantine under
268            // MOUNT_UNBACKED rather than serving an empty graph.
269            if let Some(crate::ops::WarningHint::MountUnbacked { reason, .. }) =
270                super::boot::unbacked_mount_warning(&mount, backend.as_ref())
271                && reason != crate::ops::MountUnbackedReason::Empty
272            {
273                let (code, message) = super::boot::missing_storage_reason(&mount);
274                self.quarantine_mount(mount, &code, message);
275                change.quarantined.push(name);
276                continue;
277            }
278            match self.register_writable_mem_batched(
279                mount.clone(),
280                backend,
281                crate::mem::MemOrigin::ExplicitToml,
282            ) {
283                Ok(()) => {
284                    any_mounted = true;
285                    self.recently_unmounted.remove(&name);
286                    change.added.push(name);
287                }
288                Err(e) => {
289                    self.quarantine_mount(mount, e.code(), e.to_string());
290                    change.quarantined.push(name);
291                }
292            }
293        }
294        if any_mounted {
295            self.finish_batched_registrations();
296        }
297
298        // The cross-mem grants come from the same load. They are the one
299        // policy that names mems, so they move with the roster (a rename
300        // rewrites them with the mount) and must govern the next write as
301        // the mounts do. The rest of the policy keeps its own refresh path.
302        let mut current = self.settings().clone();
303        current.cross_mem_links = cross_mem_links;
304        self.set_settings(current);
305        if all_applied {
306            self.roster_fingerprint = Some(now);
307        }
308        self.invalidate_communities();
309        self.invalidate_search_indexes();
310        self.emit_roster_changed(&change);
311        Ok(change)
312    }
313
314    fn quarantine_mount(&mut self, mount: crate::workspace::Mount, code: &str, message: String) {
315        self.quarantined.push(super::QuarantinedMem {
316            mount,
317            reason_code: code.to_string(),
318            reason_message: message,
319        });
320    }
321
322    /// Unmount one writable mem atomically: every derived structure for it
323    /// (store slice, schema entry, router slot, load warnings, pending
324    /// change notices, community and search memos, its quarantine entry)
325    /// is gone afterwards, or nothing is touched and the error names why.
326    /// The mem is remembered as recently unmounted so an operation naming
327    /// it refuses with `MEM_UNMOUNTED` rather than a bare unknown-mem.
328    pub(crate) fn unmount_mem(&mut self, mem: &str) -> Result<(), EngineError> {
329        #[cfg(test)]
330        if self.inject_unmount_failure.as_deref() == Some(mem) {
331            return Err(EngineError::Backend(crate::backend::BackendError::Other(
332                format!("injected unmount failure for mem `{mem}`"),
333            )));
334        }
335        let removed = self.unregister_writable_mem(mem)?;
336        if removed.is_none() {
337            // Not mounted: a quarantined entry leaving the roster.
338            self.quarantined.retain(|q| q.mount.mem != mem);
339        }
340        self.pending_mem_changed.retain(|n| n.mem != mem);
341        self.labelling_memo = std::cell::OnceCell::new();
342        self.recently_unmounted.insert(mem.to_string());
343        Ok(())
344    }
345
346    /// Whether `mem` left the roster during this engine's lifetime and has
347    /// not returned — the typed-refusal memory behind `MEM_UNMOUNTED`.
348    pub fn recently_unmounted(&self, mem: &str) -> bool {
349        self.recently_unmounted.contains(mem)
350    }
351
352    /// Subscribe to applied roster changes. Returns the subscription id;
353    /// pass it to [`Self::unsubscribe_roster_changes`] to stop.
354    pub fn subscribe_roster_changes(&self, callback: RosterCallback) -> u64 {
355        let mut subs = self
356            .roster_subscribers
357            .lock()
358            .expect("roster subscriber registry mutex must not be poisoned");
359        let id = subs.0 + 1;
360        subs.0 = id;
361        subs.1.push((id, callback));
362        id
363    }
364
365    /// Drop a roster subscription; a no-op for an unknown id.
366    pub fn unsubscribe_roster_changes(&self, id: u64) {
367        let mut subs = self
368            .roster_subscribers
369            .lock()
370            .expect("roster subscriber registry mutex must not be poisoned");
371        subs.1.retain(|(slot, _)| *slot != id);
372    }
373
374    fn emit_roster_changed(&self, change: &RosterChange) {
375        if change.is_empty() {
376            return;
377        }
378        let callbacks: Vec<RosterCallback> = self
379            .roster_subscribers
380            .lock()
381            .expect("roster subscriber registry mutex must not be poisoned")
382            .1
383            .iter()
384            .map(|(_, cb)| cb.clone())
385            .collect();
386        for cb in callbacks {
387            cb(change);
388        }
389    }
390
391    /// The set of mems this engine serves as writable, for tests and
392    /// consumers that compare rosters.
393    pub fn writable_mem_set(&self) -> HashSet<String> {
394        self.mounts
395            .iter()
396            .filter(|m| m.mount.capability == crate::workspace::MountCapability::Write)
397            .map(|m| m.mount.mem.clone())
398            .collect()
399    }
400}