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, remounts the entries whose
13//! capability changed (every row counts, read-only ones included: a read
14//! that was withdrawn must stop being served), re-scans the schema sources,
15//! and reports the change (`MEM_ROSTER_CHANGED`) so an agent drops the cached
16//! hashes of the mems that left.
17//!
18//! The probe is a `stat` plus, only when size or mtime moved, a hash of the
19//! file — the same cost band as the branch-tip probe, never a boot.
20
21use std::collections::{BTreeMap, BTreeSet, HashSet};
22use std::path::PathBuf;
23use std::sync::Arc;
24
25use serde::{Deserialize, Serialize};
26
27use super::{Engine, EngineError};
28
29/// What the engine last saw of the roster file: size and mtime for the
30/// cheap comparison, the content hash for the decision.
31#[derive(Debug, Clone, PartialEq, Eq)]
32pub struct RosterFingerprint {
33 len: u64,
34 modified: Option<std::time::SystemTime>,
35 hash: u64,
36}
37
38/// One applied roster reconciliation.
39#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
40pub struct RosterChange {
41 /// Mems the roster gained and the engine mounted cold, ready to serve.
42 /// A mem whose capability changed is here and under `removed`: it was
43 /// unmounted and mounted again under the roster's capability.
44 pub added: Vec<String>,
45 /// Mems the roster lost and the engine unmounted: their entities,
46 /// search index, community partition and derived views are gone.
47 pub removed: Vec<String>,
48 /// Mems the roster gained that failed to mount and are quarantined
49 /// under the boot rules (each with its reason on the quarantine
50 /// roster); the other mems keep serving.
51 pub quarantined: Vec<String>,
52 /// Per-item failures that were not a quarantine: the schema-source
53 /// re-scan, or an unmount that could not complete (the roster change
54 /// for that mem is not applied and it stays fully served).
55 pub failures: Vec<crate::ops::RefreshFailure>,
56}
57
58/// What makes a roster row the mount it is: under one name, a row with
59/// another capability, storage or pin is another mount.
60#[derive(Debug, Clone, PartialEq, Eq)]
61struct RowIdentity {
62 capability: crate::workspace::MountCapability,
63 storage: crate::workspace::MountStorage,
64 schema: Option<memstead_schema::SchemaRef>,
65}
66
67impl RowIdentity {
68 fn of(mount: &crate::workspace::Mount) -> Self {
69 use crate::workspace::MountStorage;
70 // One spelling per place: the row a verb built and the row the
71 // roster file gives back name the same directory in two ways.
72 let canonical = |p: &std::path::Path| p.canonicalize().unwrap_or_else(|_| p.to_path_buf());
73 let storage = match &mount.storage {
74 MountStorage::Folder { path } => MountStorage::Folder {
75 path: canonical(path),
76 },
77 MountStorage::GitBranch { gitdir, branch } => MountStorage::GitBranch {
78 gitdir: canonical(gitdir),
79 branch: crate::workspace::branch_full_ref(branch),
80 },
81 MountStorage::Archive { path } => MountStorage::Archive {
82 path: canonical(path),
83 },
84 MountStorage::InMemory => MountStorage::InMemory,
85 };
86 Self {
87 capability: mount.capability,
88 storage,
89 schema: mount.schema.clone(),
90 }
91 }
92
93 /// Same storage and pin, whatever the capability.
94 fn same_place_as(&self, other: &Self) -> bool {
95 self.storage == other.storage && self.schema == other.schema
96 }
97}
98
99impl RosterChange {
100 /// Whether anything at all changed or failed.
101 pub fn is_empty(&self) -> bool {
102 self.added.is_empty()
103 && self.removed.is_empty()
104 && self.quarantined.is_empty()
105 && self.failures.is_empty()
106 }
107}
108
109/// The event a roster subscriber receives — the applied change.
110pub type RosterChangedEvent = RosterChange;
111
112/// Callback shape for roster subscribers, mirroring
113/// [`super::events::EventCallback`].
114pub type RosterCallback = Arc<dyn Fn(&RosterChangedEvent) + Send + Sync + 'static>;
115
116/// The roster subscriber registry: the next id, then `(id, callback)`.
117pub(crate) type RosterSubscribers = std::sync::Mutex<(u64, Vec<(u64, RosterCallback)>)>;
118
119fn hash_bytes(bytes: &[u8]) -> u64 {
120 use std::hash::{Hash, Hasher};
121 let mut h = std::collections::hash_map::DefaultHasher::new();
122 bytes.hash(&mut h);
123 h.finish()
124}
125
126impl Engine {
127 /// The roster file this engine's membership is read from, when the
128 /// engine knows its workspace root.
129 fn roster_path(&self) -> Option<PathBuf> {
130 self.workspace_root.as_ref().map(|root| {
131 root.join(crate::workspace_store::WORKSPACE_STORE_DIR)
132 .join("state")
133 .join("mounts.json")
134 })
135 }
136
137 /// The roster's current fingerprint. `Ok(None)` when the engine has no
138 /// workspace root or the file does not exist (an ad-hoc mount list, a
139 /// standalone folder mem). Size and mtime unchanged from the cached
140 /// fingerprint short-circuits without reading the file.
141 fn roster_fingerprint_now(&self) -> Result<Option<RosterFingerprint>, std::io::Error> {
142 let Some(path) = self.roster_path() else {
143 return Ok(None);
144 };
145 let meta = match std::fs::metadata(&path) {
146 Ok(m) => m,
147 Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None),
148 Err(e) => return Err(e),
149 };
150 let len = meta.len();
151 let modified = meta.modified().ok();
152 if let Some(cached) = &self.roster_fingerprint
153 && cached.len == len
154 && cached.modified == modified
155 {
156 return Ok(Some(cached.clone()));
157 }
158 let bytes = std::fs::read(&path)?;
159 Ok(Some(RosterFingerprint {
160 len,
161 modified,
162 hash: hash_bytes(&bytes),
163 }))
164 }
165
166 /// Capture the roster as it stands as the reconciliation baseline —
167 /// what boot and every applied reconcile leave behind.
168 pub(crate) fn capture_roster_fingerprint(&mut self) {
169 self.roster_fingerprint = self.roster_fingerprint_now().ok().flatten();
170 }
171
172 /// Reconcile membership with the roster file: `Ok(None)` when the roster
173 /// did not change since the last reconcile; `Ok(Some(change))` after
174 /// applying a change; `Err` only when the roster could not be read or
175 /// parsed at all (the baseline is kept, so the next operation retries).
176 ///
177 /// A roster file that did not exist at boot (a workspace whose first
178 /// mem is created by another process after this engine started) is a
179 /// change like any other: the first observation is applied, never
180 /// swallowed as a baseline. Boot captures its own baseline through
181 /// [`Engine::capture_roster_fingerprint`], so an engine that saw the
182 /// file at boot is not re-mounted here.
183 ///
184 /// Per mem the change is atomic: an unmount that cannot complete leaves
185 /// that mem fully served, is reported under `failures`, and keeps the
186 /// baseline where it was so it is retried next time; a cold mount that
187 /// fails quarantines the mem exactly as boot would. Every roster row
188 /// counts, read-only ones included; a row whose capability changed is
189 /// unmounted and mounted again under the new capability.
190 pub fn reconcile_roster(&mut self) -> Result<Option<RosterChange>, EngineError> {
191 let now = self.roster_fingerprint_now().map_err(|e| {
192 EngineError::Backend(crate::backend::BackendError::Other(format!(
193 "roster unreadable: {e}"
194 )))
195 })?;
196 let Some(now) = now else {
197 return Ok(None);
198 };
199 let Some(cached) = self.roster_fingerprint.clone() else {
200 // No baseline: the file appeared after boot. Mount what it names.
201 return self.apply_roster(now).map(Some);
202 };
203 if cached.hash == now.hash {
204 // The same rows, written again (a name taken off the roster
205 // and put back unchanged between two operations): nothing
206 // moved for the mems that serve, and a quarantined row is
207 // tried again, as after any write of the roster.
208 let written_again = cached.modified != now.modified;
209 if written_again && !self.quarantined.is_empty() {
210 return self.apply_roster(now).map(Some);
211 }
212 self.roster_fingerprint = Some(now);
213 return Ok(None);
214 }
215 self.apply_roster(now).map(Some)
216 }
217
218 /// The reconciliation without the fingerprint gate — what
219 /// `full_refresh` runs so its report is authoritative even when the
220 /// roster file did not move (a first observation, a probe that was
221 /// skipped). An engine without a roster file yields an empty change.
222 pub(crate) fn reconcile_roster_forced(&mut self) -> Result<RosterChange, EngineError> {
223 let now = self.roster_fingerprint_now().map_err(|e| {
224 EngineError::Backend(crate::backend::BackendError::Other(format!(
225 "roster unreadable: {e}"
226 )))
227 })?;
228 match now {
229 Some(now) => self.apply_roster(now),
230 None => Ok(RosterChange::default()),
231 }
232 }
233
234 fn apply_roster(&mut self, now: RosterFingerprint) -> Result<RosterChange, EngineError> {
235 let root = self
236 .workspace_root
237 .clone()
238 .expect("a roster fingerprint implies a workspace root");
239 let workspace = crate::workspace_store::WorkspaceStoreAdapter::load(
240 &crate::workspace_store::FileWorkspaceStore::new(),
241 &root,
242 )
243 .map_err(|e| {
244 EngineError::Backend(crate::backend::BackendError::Other(format!(
245 "roster under {} unreadable: {e}",
246 root.display()
247 )))
248 })?;
249
250 let cross_mem_links = workspace.settings.cross_mem_links.clone();
251 // Every roster row counts, whatever its capability: a read-only
252 // mount another process added or withdrew is membership like a
253 // writable one, and a row whose capability changed is a mount to
254 // take down and bring up again under the new capability.
255 // A row is the same mount only while its capability, its storage
256 // and its pin stand: a name unregistered and mounted again onto
257 // another branch, another git directory or another pin between
258 // two operations is another mount under an old name, and serving
259 // the old one would read and write a store the roster no longer
260 // names.
261 let manifest: BTreeMap<String, RowIdentity> = workspace
262 .mounts
263 .iter()
264 .map(|m| (m.mem.clone(), RowIdentity::of(m)))
265 .collect();
266 let mounted: BTreeMap<String, RowIdentity> = self
267 .mounts
268 .iter()
269 .map(|m| (m.mount.mem.clone(), RowIdentity::of(&m.mount)))
270 .collect();
271 // Every quarantined row the roster still names is tried again:
272 // the roster was written, and what kept the row out of service
273 // (a git directory that was away, a schema not yet installed)
274 // may be gone. One whose row names the storage and pin it had
275 // and that fails again is no news and is not reported again;
276 // one that now names another storage or pin is another mount.
277 let mut retried_in_place: BTreeSet<String> = BTreeSet::new();
278 let mut requeued: BTreeSet<String> = BTreeSet::new();
279 for q in &self.quarantined {
280 if let Some(row) = manifest.get(&q.mount.mem) {
281 requeued.insert(q.mount.mem.clone());
282 if row.same_place_as(&RowIdentity::of(&q.mount)) {
283 retried_in_place.insert(q.mount.mem.clone());
284 }
285 }
286 }
287 if !requeued.is_empty() {
288 self.quarantined
289 .retain(|q| !requeued.contains(&q.mount.mem));
290 }
291 let quarantined_now: BTreeSet<String> = self
292 .quarantined
293 .iter()
294 .map(|q| q.mount.mem.clone())
295 .collect();
296
297 let mut change = RosterChange::default();
298 let mut all_applied = true;
299
300 // The schema catalogue first: a mem that arrived may pin a schema
301 // installed since boot, or one installed in the git directory it
302 // arrives from, and a cold mount resolves against the catalogue
303 // as it stands.
304 let mut schema_report = crate::ops::FullRefreshReport::default();
305 self.refresh_schema_sources_for(&mut schema_report, &workspace.mounts);
306 change.failures.extend(schema_report.failures);
307
308 // Removals first, each atomic: the mems the roster no longer
309 // names, and the ones it names under another capability. The
310 // latter are mounted again below, so a capability change is
311 // reported the way it happened, under removed and under added.
312 let mut remounting: BTreeSet<String> = BTreeSet::new();
313 for (name, identity) in &mounted {
314 let roster_identity = manifest.get(name);
315 if roster_identity == Some(identity) {
316 continue;
317 }
318 match self.unmount_mem(name) {
319 Ok(()) => {
320 change.removed.push(name.clone());
321 if roster_identity.is_some() {
322 remounting.insert(name.clone());
323 }
324 }
325 Err(e) => {
326 all_applied = false;
327 change.failures.push(crate::ops::RefreshFailure {
328 item: format!("unmount:{name}"),
329 error: e.to_string(),
330 });
331 }
332 }
333 }
334 // A gone quarantined entry just leaves the quarantine roster: it
335 // served nothing. One that stays follows its row's capability, so
336 // a later attach never restores an access the roster withdrew.
337 let gone_quarantined: Vec<String> = quarantined_now
338 .iter()
339 .filter(|name| !manifest.contains_key(*name))
340 .cloned()
341 .collect();
342 if !gone_quarantined.is_empty() {
343 self.quarantined
344 .retain(|q| !gone_quarantined.contains(&q.mount.mem));
345 change.removed.extend(gone_quarantined);
346 }
347
348 // Additions: cold mount under the boot quarantine rules.
349 let mut any_mounted = false;
350 for mount in workspace.mounts {
351 if (mounted.contains_key(&mount.mem) && !remounting.contains(&mount.mem))
352 || quarantined_now.contains(&mount.mem)
353 {
354 continue;
355 }
356 let name = mount.mem.clone();
357 // A mem that is mounted again under another capability was
358 // never away for the caller: it must not read as unmounted
359 // if the remount ends in quarantine.
360 if remounting.contains(&name) {
361 self.recently_unmounted.remove(&name);
362 }
363 let backend = match (self.backend_factory)(&mount) {
364 Ok(b) => b,
365 Err(e) => {
366 // Boot's reason for a mount that cannot be
367 // instantiated: a missing installed archive says
368 // what to install.
369 let (code, message) =
370 super::boot::instantiate_failure_reason(&mount, e.code(), e.to_string());
371 self.quarantine_mount(mount, &code, message);
372 if !retried_in_place.contains(&name) {
373 change.quarantined.push(name);
374 }
375 continue;
376 }
377 };
378 // Boot's rule for storage that is gone (a branch the mem-repo
379 // lacks, a folder that does not exist): quarantine under
380 // MOUNT_UNBACKED rather than serving an empty graph.
381 if let Some(crate::ops::WarningHint::MountUnbacked { reason, .. }) =
382 super::boot::unbacked_mount_warning(&mount, backend.as_ref())
383 && reason != crate::ops::MountUnbackedReason::Empty
384 {
385 let (code, message) = super::boot::missing_storage_reason(&mount);
386 self.quarantine_mount(mount, &code, message);
387 if !retried_in_place.contains(&name) {
388 change.quarantined.push(name);
389 }
390 continue;
391 }
392 match self.register_writable_mem_batched(
393 mount.clone(),
394 backend,
395 crate::mem::MemOrigin::ExplicitToml,
396 ) {
397 Ok(()) => {
398 any_mounted = true;
399 self.recently_unmounted.remove(&name);
400 change.added.push(name);
401 }
402 Err(e) => {
403 self.quarantine_mount(mount, e.code(), e.to_string());
404 if !retried_in_place.contains(&name) {
405 change.quarantined.push(name);
406 }
407 }
408 }
409 }
410 if any_mounted {
411 self.finish_batched_registrations();
412 }
413
414 // The cross-mem grants come from the same load. They are the one
415 // policy that names mems, so they move with the roster (a rename
416 // rewrites them with the mount) and must govern the next write as
417 // the mounts do. The rest of the policy keeps its own refresh path.
418 let mut current = self.settings().clone();
419 current.cross_mem_links = cross_mem_links;
420 self.set_settings(current);
421 if all_applied {
422 self.roster_fingerprint = Some(now);
423 }
424 self.invalidate_communities();
425 self.invalidate_search_indexes();
426 self.emit_roster_changed(&change);
427 Ok(change)
428 }
429
430 fn quarantine_mount(&mut self, mount: crate::workspace::Mount, code: &str, message: String) {
431 self.quarantined.push(super::QuarantinedMem {
432 mount,
433 reason_code: code.to_string(),
434 reason_message: message,
435 });
436 }
437
438 /// Unmount one mem, writable or read-only, atomically: every derived structure for it
439 /// (store slice, schema entry, router slot, load warnings, pending
440 /// change notices, community and search memos, its quarantine entry)
441 /// is gone afterwards, or nothing is touched and the error names why.
442 /// The mem is remembered as recently unmounted so an operation naming
443 /// it refuses with `MEM_UNMOUNTED` rather than a bare unknown-mem.
444 pub(crate) fn unmount_mem(&mut self, mem: &str) -> Result<(), EngineError> {
445 #[cfg(test)]
446 if self.inject_unmount_failure.as_deref() == Some(mem) {
447 return Err(EngineError::Backend(crate::backend::BackendError::Other(
448 format!("injected unmount failure for mem `{mem}`"),
449 )));
450 }
451 // The read-only slot has its own unregistration: it clears the
452 // router's read-only entry, which the writable one leaves alone.
453 let read_only = self.mounts.iter().any(|m| {
454 m.mount.mem == mem && m.mount.capability == crate::workspace::MountCapability::ReadOnly
455 });
456 let removed = if read_only {
457 self.unregister_read_mount(mem)?
458 } else {
459 self.unregister_writable_mem(mem)?
460 };
461 if removed.is_none() {
462 // Not mounted: a quarantined entry leaving the roster.
463 self.quarantined.retain(|q| q.mount.mem != mem);
464 }
465 self.pending_mem_changed.retain(|n| n.mem != mem);
466 self.callers.forget_mem(mem);
467 self.labelling_memo = std::cell::OnceCell::new();
468 self.recently_unmounted.insert(mem.to_string());
469 Ok(())
470 }
471
472 /// Resolve `mem` for a write on the roster as it stands now: the
473 /// roster is reconciled first, so a verb that judges writability
474 /// before it takes the write lock never refuses on a capability the
475 /// roster has since changed, and never accepts one it has withdrawn.
476 /// Returns the mount index and the roster notice the reconciliation
477 /// produced, for the caller's response.
478 pub(in crate::engine) fn writable_mount_on_current_roster(
479 &mut self,
480 mem: &str,
481 ) -> Result<(usize, Vec<crate::ops::WarningHint>), EngineError> {
482 let notice = self.roster_warnings();
483 let idx = self
484 .mounts
485 .iter()
486 .position(|m| m.mount.mem == mem)
487 .ok_or_else(|| self.unknown_mem_error(mem))?;
488 if self.mounts[idx].mount.capability != crate::workspace::MountCapability::Write {
489 return Err(EngineError::ReadOnlyMount(mem.to_string()));
490 }
491 Ok((idx, notice))
492 }
493
494 /// The capability the roster file gives `mem` at this instant, read
495 /// without reconciling: for the one caller that attaches a mount the
496 /// reconciliation does not touch (a quarantined mem on its way back
497 /// into service) and must not attach it under a capability the roster
498 /// has since changed. `None` when there is no roster file, it cannot
499 /// be read, or it does not name the mem.
500 pub(in crate::engine) fn roster_capability_on_disk(
501 &self,
502 mem: &str,
503 ) -> Option<crate::workspace::MountCapability> {
504 let root = self.workspace_root.as_ref()?;
505 self.roster_path().filter(|p| p.is_file())?;
506 let workspace = crate::workspace_store::WorkspaceStoreAdapter::load(
507 &crate::workspace_store::FileWorkspaceStore::new(),
508 root,
509 )
510 .ok()?;
511 workspace
512 .mounts
513 .iter()
514 .find(|m| m.mem == mem)
515 .map(|m| m.capability)
516 }
517
518 /// Whether `mem` left the roster during this engine's lifetime and has
519 /// not returned — the typed-refusal memory behind `MEM_UNMOUNTED`.
520 pub fn recently_unmounted(&self, mem: &str) -> bool {
521 self.recently_unmounted.contains(mem)
522 }
523
524 /// Subscribe to applied roster changes. Returns the subscription id;
525 /// pass it to [`Self::unsubscribe_roster_changes`] to stop.
526 pub fn subscribe_roster_changes(&self, callback: RosterCallback) -> u64 {
527 let mut subs = self
528 .roster_subscribers
529 .lock()
530 .expect("roster subscriber registry mutex must not be poisoned");
531 let id = subs.0 + 1;
532 subs.0 = id;
533 subs.1.push((id, callback));
534 id
535 }
536
537 /// Drop a roster subscription; a no-op for an unknown id.
538 pub fn unsubscribe_roster_changes(&self, id: u64) {
539 let mut subs = self
540 .roster_subscribers
541 .lock()
542 .expect("roster subscriber registry mutex must not be poisoned");
543 subs.1.retain(|(slot, _)| *slot != id);
544 }
545
546 fn emit_roster_changed(&self, change: &RosterChange) {
547 if change.is_empty() {
548 return;
549 }
550 let callbacks: Vec<RosterCallback> = self
551 .roster_subscribers
552 .lock()
553 .expect("roster subscriber registry mutex must not be poisoned")
554 .1
555 .iter()
556 .map(|(_, cb)| cb.clone())
557 .collect();
558 for cb in callbacks {
559 cb(change);
560 }
561 }
562
563 /// The set of mems this engine serves as writable, for tests and
564 /// consumers that compare rosters.
565 pub fn writable_mem_set(&self) -> HashSet<String> {
566 self.mounts
567 .iter()
568 .filter(|m| m.mount.capability == crate::workspace::MountCapability::Write)
569 .map(|m| m.mount.mem.clone())
570 .collect()
571 }
572}