memstead_base/engine/lifecycle/mounts.rs
1//! Mount registration: registering and unregistering writable mems and read mounts, the load-warning channel, the full refresh and the state persist.
2
3use super::*;
4
5impl Engine {
6 /// Unregister a writable mem at runtime. Engine-level
7 /// primitive that `memstead_mem_delete` builds on.
8 ///
9 /// Removes the named mount from [`Self::mounts`], drops the
10 /// mem's entities from the store, refreshes the
11 /// [`MemRouterSnapshot`] via `Arc::make_mut` (COW swap so
12 /// readers holding a pre-swap snapshot see the pre-state for
13 /// their lifetime), and invalidates the community + search
14 /// memos. Does NOT touch the backend's on-disk state — the
15 /// caller (`delete_mem` orchestrator) decides whether to
16 /// remove the directory / gitdir after this returns.
17 ///
18 /// Returns `Ok(Some(backend))` when the mem was present and
19 /// unregistered — the caller can drive any backend-specific
20 /// follow-up cleanup (`backend.delete_artifacts()` for the
21 /// mem-repo branch + `__MEMSTEAD` config when `delete_files=true`).
22 /// Returns `Ok(None)` when no mount named the mem (idempotent —
23 /// repeated calls are safe).
24 pub fn unregister_writable_mem(
25 &mut self,
26 mem_name: &str,
27 ) -> Result<Option<Box<dyn MemBackend>>, EngineError> {
28 let pos = self.mounts.iter().position(|m| m.mount.mem == mem_name);
29 let Some(idx) = pos else {
30 return Ok(None);
31 };
32
33 // Drop the mount first — releases all engine-side state that
34 // referenced the backend. The `Box<dyn MemBackend>` itself
35 // travels back to the caller so backend-side cleanup
36 // (`delete_artifacts`) can run after the engine snapshot
37 // settled.
38 let mount = self.mounts.remove(idx);
39
40 // Drop the schema entry for this mem (kept in lockstep
41 // with `self.mounts`).
42 self.schemas_remove(&mount.mount.mem);
43
44 // Drop entities. The store's mem index is the
45 // authoritative count; the return value (number of
46 // entities removed) is informational only — the caller
47 // already knows the mem and doesn't need the count.
48 let _removed = self.store.remove_entities_by_mem(mem_name);
49
50 // Purge load-time warnings attributed to the removed mem.
51 // `health()` merges `self.load_warnings` unconditionally, so
52 // a skipped purge leaves phantom warnings citing entities the
53 // store no longer holds — for the whole engine lifetime, since
54 // nothing else clears the accumulator on the MCP path.
55 // Attribution is by SOURCE mem only (`WarningHint::source_mem`):
56 // a warning whose source entity lives in a surviving mem stays
57 // even when its target pointed into the deleted mem — the
58 // invalid row still exists in that survivor's markdown and
59 // remains visible drift (recover-worthy), not stale state.
60 self.load_warnings
61 .retain(|w| w.source_mem() != Some(mem_name));
62
63 // COW snapshot swap on the mem_router. `Arc::make_mut`
64 // clones the inner snapshot when other Arcs exist; if this
65 // is the only handle (typical for the engine's lifetime),
66 // it returns the existing inner directly without cloning.
67 // Readers that captured an `Arc` before this call observe
68 // the pre-swap state — the in-flight handler's
69 // `mem_router()` borrow is unaffected by this mutation.
70 Arc::make_mut(&mut self.mem_router).remove_writable(mem_name);
71
72 // Invalidate dependent memos — community detection + search
73 // indexes were computed over the pre-removal store and are
74 // now stale. Mutation paths already invalidate; this
75 // matches the contract.
76 self.invalidate_communities();
77 self.invalidate_search_indexes();
78
79 Ok(Some(mount.backend))
80 }
81
82 /// Register a read-only mount at runtime — the install path's
83 /// engine primitive. Same registration pipeline as
84 /// [`Self::register_writable_mem`] (collision probe, config read,
85 /// schema resolution, entity load, router swap); the router branch
86 /// lands the mount in the read-only slot for
87 /// `capability: ReadOnly` + `Archive` storage, so `is_writable`
88 /// stays false and `archive_path_for_mem` resolves.
89 pub fn register_read_mount(
90 &mut self,
91 mount: Mount,
92 backend: Box<dyn MemBackend>,
93 origin: MemOrigin,
94 ) -> Result<(), EngineError> {
95 self.register_writable_mem_inner(mount, backend, origin, true)
96 }
97
98 /// Unregister a read-only mount at runtime — the uninstall path's
99 /// engine primitive, mirroring [`Self::unregister_writable_mem`]
100 /// for the read-only slot. Returns `Ok(None)` when the name is
101 /// not a registered read-only mount (writable mems are the
102 /// delete/unregister verbs' business, deliberately not this
103 /// one's). Registration removal only — the backing archive file
104 /// (global cache) is never touched.
105 pub fn unregister_read_mount(
106 &mut self,
107 mem_name: &str,
108 ) -> Result<Option<Box<dyn MemBackend>>, EngineError> {
109 let pos = self.mounts.iter().position(|m| {
110 m.mount.mem == mem_name
111 && m.mount.capability == crate::workspace::MountCapability::ReadOnly
112 });
113 let Some(idx) = pos else {
114 return Ok(None);
115 };
116 let mount = self.mounts.remove(idx);
117 self.schemas_remove(&mount.mount.mem);
118 let _removed = self.store.remove_entities_by_mem(mem_name);
119 self.load_warnings
120 .retain(|w| w.source_mem() != Some(mem_name));
121 Arc::make_mut(&mut self.mem_router).remove_read_only(mem_name);
122 self.invalidate_communities();
123 self.invalidate_search_indexes();
124 Ok(Some(mount.backend))
125 }
126
127 /// Append a typed load-time warning from outside the engine's own
128 /// load pipeline — the boot orchestrators (which live in the full
129 /// crate) use this to surface one-time migrations they perform
130 /// around engine construction.
131 pub fn push_load_warning(&mut self, warning: crate::ops::WarningHint) {
132 self.load_warnings.push(warning);
133 }
134
135 /// Register a writable mem at runtime. Engine-level primitive
136 /// that `memstead_mem_create` builds on.
137 ///
138 /// Steps:
139 /// 1. Name collision probe against the current `mem_router`
140 /// snapshot. Writable AND read-only entries collide; the
141 /// error surfaces the colliding source so the orchestrator
142 /// can render a recovery hint.
143 /// 2. Schema resolution via the built-in catalogue (mirrors
144 /// [`Self::from_mounts`]; workspace-authored schema
145 /// resolution lifts later).
146 /// 3. Per-mem config load (folder backends only; git-branch /
147 /// archive return None — same contract as
148 /// [`Self::from_mounts`]).
149 /// 4. Entity load via the backend, parse, push into the engine's
150 /// store with a `LoadCollector` so drift warnings forward to
151 /// `self.load_warnings`.
152 /// 5. Insert schema into [`Self::schemas`].
153 /// 6. Push the [`MountedBackend`] into [`Self::mounts`].
154 /// 7. COW snapshot swap on [`Self::mem_router`] via
155 /// `Arc::make_mut` + `add_writable(name, dir, origin, mem_path)`.
156 /// Folder mounts surface their on-disk path; other backends
157 /// register with `dir: None` (matches full's contract).
158 /// `mem_path` carries the create-time organisational `path`
159 /// component (mirrors `MemCreateParams.path`) — the
160 /// delete-side lifecycle composer reads it back to rebuild the
161 /// `<mem_path>/<name>` candidate the create-side composer
162 /// matched against. Caller threads `None` for flat-layout
163 /// registrations and `Some(p)` for hierarchical ones.
164 /// 8. Invalidate community + search memos.
165 ///
166 /// Returns `Err(EngineError::MemNameCollision)` when the name
167 /// is already registered. Other failures (schema-not-found,
168 /// backend read errors) propagate as their typed variants. On
169 /// failure no engine mutation happens: every potentially-
170 /// mutating step runs only after the collision probe succeeds,
171 /// and intermediate failures propagate before the mount /
172 /// router are touched.
173 pub fn register_writable_mem(
174 &mut self,
175 mount: Mount,
176 backend: Box<dyn MemBackend>,
177 origin: MemOrigin,
178 ) -> Result<(), EngineError> {
179 self.register_writable_mem_inner(mount, backend, origin, true)
180 }
181
182 /// [`Self::register_writable_mem`] with the workspace-global
183 /// passes (relation validation, alias remap, memo invalidation)
184 /// made optional: `run_global_passes: false` lets a batch caller
185 /// ([`Self::full_refresh`]) attach N mounts and run the global
186 /// passes ONCE afterwards instead of N times under the engine
187 /// lock. A `false` caller MUST run
188 /// [`Self::finish_batched_registrations`] after its loop, or
189 /// loaded relations skip validation and alias edges stay
190 /// unmapped.
191 fn register_writable_mem_inner(
192 &mut self,
193 mount: Mount,
194 backend: Box<dyn MemBackend>,
195 origin: MemOrigin,
196 run_global_passes: bool,
197 ) -> Result<(), EngineError> {
198 // Step 1: name collision probe.
199 if let Some(existing) = self.mem_router.origin_for_mem(&mount.mem) {
200 return Err(EngineError::MemNameCollision {
201 name: mount.mem.clone(),
202 source_origin: existing.render_source(),
203 });
204 }
205 if self.mem_router.archive_path_for_mem(&mount.mem).is_some() {
206 return Err(EngineError::MemNameCollision {
207 name: mount.mem.clone(),
208 source_origin: "attached read mem".to_string(),
209 });
210 }
211
212 // Step 2: per-mem config load via the backend trait. Read
213 // before resolving the schema — the mem's own config carries
214 // the authoritative pin (mirrors the boot path), so a mem
215 // re-registered or mounted from another machine resolves from
216 // its own backend, not this workspace's mount expectation.
217 let mem_config = backend.read_mem_config().ok().flatten().and_then(|bytes| {
218 let value: serde_json::Value = serde_json::from_slice(&bytes).ok()?;
219 memstead_schema::config::parse_mem_config(&value).ok()
220 });
221
222 // Step 3: schema resolution. `MemConfig.schema` is the
223 // authoritative settled pin; `Mount.schema` is the fallback when
224 // the config carries none, and an expectation assertion when it
225 // does — a disagreement surfaces `SchemaPinMismatch` (config
226 // wins, neither silently dropped). Mirrors `from_mounts_inner`.
227 // Resolve against the engine's full loaded catalogue (already-
228 // loaded workspace/local-storage schemas layered over built-ins)
229 // so a mem registered against a backend-installed (e.g.
230 // git-branch `__MEMSTEAD:schemas/` ref) schema resolves.
231 let mut builtin_schemas: Vec<std::sync::Arc<memstead_schema::Schema>> =
232 self.workspace_schemas().to_vec();
233 // An archive-backed mount's own sealed vocabulary sits between
234 // the workspace tier and the built-ins, for this resolution
235 // only — see `from_mounts_inner` for why it never joins the
236 // shared catalogue.
237 builtin_schemas.extend(crate::engine::boot::embedded_archive_schemas(&mount));
238 builtin_schemas.extend(
239 memstead_schema::builtins::load_builtin_schemas()
240 .map_err(|e| EngineError::SchemaResolverInit(e.to_string()))?,
241 );
242 let config_pin = mem_config.as_ref().and_then(|c| c.schema.as_ref());
243 let mount_pin = mount.schema.as_ref();
244 if let (Some(cfg), Some(mp)) = (config_pin, mount_pin)
245 && cfg != mp
246 {
247 self.load_warnings
248 .push(crate::ops::WarningHint::SchemaPinMismatch {
249 mem: mount.mem.clone(),
250 config_pin: cfg.as_display(),
251 mount_pin: mp.as_display(),
252 });
253 }
254 let settled_pin = config_pin.or(mount_pin);
255 let effective_pin = mount
256 .migration_target
257 .as_ref()
258 .or(settled_pin)
259 .ok_or_else(|| EngineError::MemConfigIncomplete {
260 mem: mount.mem.clone(),
261 missing_fields: vec!["schema".to_string()],
262 })?
263 .clone();
264 let schema = crate::engine::SchemaResolver::new(&builtin_schemas)
265 .resolve(&effective_pin)
266 .map_err(|sources| {
267 EngineError::SchemaNotFound {
268 mem: mount.mem.clone(),
269 pin: effective_pin.as_display(),
270 sources,
271 install_hint: None,
272 }
273 .with_schema_install_probe(self.workspace_root())
274 })?;
275
276 // Step 4: load entities via the backend, push into the
277 // engine's store with a LoadCollector so drift warnings
278 // forward into `self.load_warnings`. Derive the mem
279 // roster + last-segment suffixes from the POST-registration
280 // view (new mem included) so cross-mem references
281 // targeting the new mem resolve correctly during this
282 // load.
283 let (entries, read_errors) = collect_source_entries(backend.as_ref())?;
284 if let Some(w) = crate::engine::boot::unbacked_mount_warning(
285 &mount,
286 backend.as_ref(),
287 Some(entries.len()),
288 ) {
289 self.load_warnings.push(w);
290 }
291 let load_result = parse_entries(entries, read_errors, &mount.mem, schema.as_ref());
292
293 let mut mem_names: Vec<String> = self.mounts.iter().map(|m| m.mount.mem.clone()).collect();
294 mem_names.push(mount.mem.clone());
295 let known_suffixes: Vec<String> = mem_names
296 .iter()
297 .map(|n| crate::entity::store_builder::last_segment_suffix(n).to_string())
298 .collect();
299 let fallback = engine_fallback_type();
300 push_entities_into_store(
301 &mut self.store,
302 load_result.entities,
303 fallback.as_ref(),
304 Some(crate::entity::store_builder::LoadCollector {
305 warnings: &mut self.load_warnings,
306 known_suffixes: &known_suffixes,
307 mem_names: &mem_names,
308 }),
309 );
310 self.load_errors.extend(load_result.errors);
311
312 // Step 5: insert schema (kept in lockstep with `self.mounts`).
313 self.schemas_insert(mount.mem.clone(), schema);
314
315 // Re-run the parse-time relation validator now that the new
316 // mem's schema is in `self.schemas`. Mirrors the boot path
317 // (`Engine::from_mounts_inner`) — hand-edited or externally-
318 // generated markdown in the newly-attached mount goes through
319 // the same gauntlet (grammar / unknown_rel_type / shape /
320 // cycle) and offending relations are dropped with typed
321 // `PARSED_RELATION_INVALID` warnings on `self.load_warnings`.
322 // The newly-pushed mount isn't in `self.mounts` yet (that's
323 // Step 6 below), so build the map from `self.mounts` plus the
324 // about-to-be-attached mount we're still holding.
325 if run_global_passes {
326 let mut mount_caps: std::collections::HashMap<
327 String,
328 crate::workspace::MountCapability,
329 > = self
330 .mounts
331 .iter()
332 .map(|m| (m.mount.mem.clone(), m.mount.capability))
333 .collect();
334 mount_caps.insert(mount.mem.clone(), mount.capability);
335 crate::entity::store_builder::validate_loaded_relations(
336 &mut self.store,
337 &self.schemas,
338 &mount_caps,
339 &mut self.load_warnings,
340 );
341 crate::entity::store_builder::remap_alias_target_edge_sources(
342 &mut self.store,
343 &self.schemas,
344 );
345 }
346
347 // Step 6: push the MountedBackend.
348 let last_known_head = backend.current_head().ok().flatten();
349 let mem_name_for_router = mount.mem.clone();
350 let storage_for_router = mount.storage.clone();
351 let mount_capability_for_router = mount.capability;
352 self.mounts.push(MountedBackend {
353 mount,
354 backend,
355 last_known_head,
356 mem_config,
357 // A runtime-created mem is authored live, not installed from
358 // an archive — it carries no archive-borne provenance payload
359 // and no sealed check records.
360 archive_provenance: None,
361 archive_checks: None,
362 // Registered live and loaded in this call — never deferred.
363 deferred: false,
364 });
365
366 // Step 7: COW snapshot swap on mem_router, branched on the
367 // mount's capability — a read-only archive mount registers in
368 // the router's read-only slot (so `is_writable` stays false
369 // and `archive_path_for_mem` resolves), everything else in the
370 // writable slot. Folder mounts surface their on-disk path;
371 // other backends register with `dir: None` (mem-repo-backed
372 // mounts have no working tree).
373 match (&mount_capability_for_router, &storage_for_router) {
374 (crate::workspace::MountCapability::ReadOnly, MountStorage::Archive { path }) => {
375 Arc::make_mut(&mut self.mem_router)
376 .add_read_only(mem_name_for_router, path.clone());
377 }
378 _ => {
379 let dir: Option<PathBuf> = match &storage_for_router {
380 MountStorage::Folder { path } => Some(path.clone()),
381 MountStorage::GitBranch { .. }
382 | MountStorage::Archive { .. }
383 | MountStorage::InMemory => None,
384 };
385 Arc::make_mut(&mut self.mem_router).add_writable(mem_name_for_router, dir, origin);
386 }
387 }
388
389 // Step 8: invalidate dependent memos.
390 if run_global_passes {
391 self.invalidate_communities();
392 self.invalidate_search_indexes();
393 }
394
395 Ok(())
396 }
397
398 /// The batched tail of `register_writable_mem_inner(...,
399 /// run_global_passes: false)`: one workspace-global relation
400 /// validation, one alias remap, one memo invalidation for the
401 /// whole batch of registrations.
402 /// [`Self::register_writable_mem`] without the workspace-global
403 /// passes — the batch form the roster reconciliation uses; the
404 /// caller runs [`Self::finish_batched_registrations`] once after.
405 pub(crate) fn register_writable_mem_batched(
406 &mut self,
407 mount: Mount,
408 backend: Box<dyn MemBackend>,
409 origin: MemOrigin,
410 ) -> Result<(), EngineError> {
411 self.register_writable_mem_inner(mount, backend, origin, false)
412 }
413
414 pub(crate) fn finish_batched_registrations(&mut self) {
415 let mount_caps: std::collections::HashMap<String, crate::workspace::MountCapability> = self
416 .mounts
417 .iter()
418 .map(|m| (m.mount.mem.clone(), m.mount.capability))
419 .collect();
420 crate::entity::store_builder::validate_loaded_relations(
421 &mut self.store,
422 &self.schemas,
423 &mount_caps,
424 &mut self.load_warnings,
425 );
426 crate::entity::store_builder::remap_alias_target_edge_sources(
427 &mut self.store,
428 &self.schemas,
429 );
430 self.invalidate_communities();
431 self.invalidate_search_indexes();
432 }
433
434 /// Additive full refresh — the warm-server half of "restart the
435 /// process": re-scan the schema sources and the mount manifest,
436 /// making newly installed schema versions resolvable and newly
437 /// registered mems usable, WITHOUT applying removals. The
438 /// asymmetry is deliberate and is the whole safety argument:
439 /// adding extends what the in-memory store can answer, while
440 /// removing can strand entities, in-flight handles, and cached
441 /// hashes the process is still serving. Removals are skipped and
442 /// reported; a restart applies them.
443 ///
444 /// Failure model is per-item: a schema source or a mount that
445 /// fails to refresh lands in `failures` and never surfaces as
446 /// newly available; the others proceed. Each mount registration
447 /// is all-or-nothing (every fallible step runs before the store
448 /// is touched), so a failed item leaves no half-updated state.
449 /// The workspace-global passes (relation validation, alias remap,
450 /// memo invalidation) run ONCE per refresh regardless of how many
451 /// mounts attached.
452 ///
453 /// A newly mounted mem starts cold and loads like any other
454 /// mount. Content reload of pre-existing mems is NOT part of this
455 /// method — callers that want both (the `memstead_reload
456 /// full=true` surface) run the existing content-reload sweep
457 /// alongside.
458 pub fn full_refresh(&mut self) -> crate::ops::FullRefreshReport {
459 let started = std::time::Instant::now();
460 let mut report = crate::ops::FullRefreshReport::default();
461
462 let Some(_root) = self.workspace_root.clone() else {
463 report.failures.push(crate::ops::RefreshFailure {
464 item: "workspace".to_string(),
465 error: "engine has no workspace root (ad-hoc mount-list construction) — \
466 nothing to re-scan"
467 .to_string(),
468 });
469 report.elapsed_ms = started.elapsed().as_millis() as u64;
470 return report;
471 };
472
473 // Workspace policy — same best-effort refresh the
474 // workspace-wide content reload performs.
475 self.refresh_workspace_settings_if_possible();
476
477 // --- Schema sources, additively. ---
478 self.refresh_schema_sources(&mut report);
479
480 // --- Mount roster: the same reconciliation every operation runs
481 // (roster.rs), forced here even when the fingerprint says
482 // unchanged so the report is authoritative. Removals APPLY. ---
483 match self.reconcile_roster_forced() {
484 Ok(change) => {
485 report.mems_mounted = change.added;
486 report.mems_unmounted = change.removed;
487 report.mems_quarantined = change.quarantined;
488 report.failures.extend(change.failures);
489 }
490 Err(e) => report.failures.push(crate::ops::RefreshFailure {
491 item: "mount-manifest".to_string(),
492 error: e.to_string(),
493 }),
494 }
495 report.mems_mounted.sort();
496 report.mems_unmounted.sort();
497 report.mems_quarantined.sort();
498
499 report.elapsed_ms = started.elapsed().as_millis() as u64;
500 report
501 }
502
503 /// Re-scan the schema sources additively into `report`
504 /// (`schemas_added`, `schema_removals_skipped`, per-source failures).
505 pub(crate) fn refresh_schema_sources(&mut self, report: &mut crate::ops::FullRefreshReport) {
506 let Some(root) = self.workspace_root.clone() else {
507 return;
508 };
509 use crate::schema_source::SchemaSource as _;
510 let mut fresh: Vec<std::sync::Arc<memstead_schema::Schema>> = Vec::new();
511 let mut sources_complete = true;
512 match crate::schema_source::FolderSchemaSource::for_workspace(&root).read_schemas() {
513 Ok(mut s) => fresh.append(&mut s),
514 Err(e) => {
515 sources_complete = false;
516 report.failures.push(crate::ops::RefreshFailure {
517 item: "schema-source:folder".to_string(),
518 error: e.to_string(),
519 });
520 }
521 }
522 if let Some(ops) = self.git_branch_ops() {
523 match (ops.read_ref_schemas)(&root) {
524 Ok(mut s) => fresh.append(&mut s),
525 Err(e) => {
526 sources_complete = false;
527 report.failures.push(crate::ops::RefreshFailure {
528 item: "schema-source:memstead-ref".to_string(),
529 error: e.to_string(),
530 });
531 }
532 }
533 }
534 let key = |s: &memstead_schema::Schema| {
535 let (name, version) = s.id();
536 format!("{name}@{version}")
537 };
538 let existing: std::collections::HashSet<String> =
539 self.workspace_schemas.iter().map(|s| key(s)).collect();
540 let fresh_keys: std::collections::HashSet<String> = fresh.iter().map(|s| key(s)).collect();
541 for schema in fresh {
542 let k = key(&schema);
543 if !existing.contains(&k) && !report.schemas_added.contains(&k) {
544 report.schemas_added.push(k);
545 self.workspace_schemas.push(schema);
546 }
547 }
548 report.schemas_added.sort();
549 // Removal detection is only meaningful when every source was
550 // actually readable — otherwise an unreadable source would
551 // masquerade as a mass removal.
552 if sources_complete {
553 report.schema_removals_skipped = existing
554 .difference(&fresh_keys)
555 .cloned()
556 .collect::<Vec<_>>();
557 report.schema_removals_skipped.sort();
558 }
559 }
560
561 /// Override the workspace root after construction. The full
562 /// boot helper `memstead_git_branch::engine_from_workspace_root`
563 /// calls this so the engine knows the path even when the boot
564 /// route runs through the full adapter rather than
565 /// [`Self::from_workspace_root`].
566 pub fn set_workspace_root(&mut self, root: PathBuf) {
567 self.workspace_root = Some(root);
568 self.capture_roster_fingerprint();
569 }
570
571 /// Persist the engine's current mount list to the workspace
572 /// store so a freshly-booted sibling process observes the same
573 /// mem membership. Called by
574 /// [`crate::mem_management::create_mem`] /
575 /// [`crate::mem_management::delete_mem`] after the in-memory
576 /// router mutation lands — without this, the per-mem content
577 /// (branch + `__MEMSTEAD` config blob, or folder + `.memstead/config.json`)
578 /// is already on disk, but the next process boot reads an empty
579 /// `.memstead/state/mounts.json` and the engine starts with zero
580 /// writable mems.
581 ///
582 /// No-op when `workspace_root` is unset (tests / ad-hoc
583 /// consumers that build the engine directly from a mount list).
584 /// Production boot paths (`Engine::from_workspace_root` and the
585 /// full counterpart) always set the root, so the engine-side
586 /// fix covers every caller — in-process embedders included
587 /// — by construction.
588 ///
589 /// Hardcoded against [`crate::FileWorkspaceStore`] because that
590 /// is the only V1 adapter; a future SQLite or remote adapter
591 /// would install through a setter mirroring
592 /// [`Self::set_backend_factory`].
593 pub fn persist_state(&self) -> Result<(), EngineError> {
594 let Some(root) = self.workspace_root.as_ref() else {
595 return Ok(());
596 };
597 use crate::workspace_store::WorkspaceStoreAdapter as _;
598 let store = crate::FileWorkspaceStore::new();
599 let map = |e: crate::workspace_store::StoreError| {
600 EngineError::Mem(format!("persist workspace state: {e}"))
601 };
602
603 // Publish THIS engine's changes, not its whole cached view. An
604 // earlier version serialized `self.mounts` wholesale, so a
605 // long-lived process silently dropped every mount a sibling
606 // process had registered since the cache was taken — the same
607 // condition the mem-config writers close by re-reading, reaching
608 // the workspace roster through the one writer they did not cover.
609 // The delta is computed against `mounts_baseline` (what this
610 // engine last read or wrote) rather than against a clock: a
611 // single-writer workspace has an identical on-disk roster, so
612 // the merge is a no-op there.
613 // The roster this engine speaks for is the attached mounts PLUS
614 // the quarantined ones: a quarantined mem's retained Mount is
615 // what lets `reload` re-attempt the attach after a repair, and
616 // dropping it from the file is how "degrade, never disappear"
617 // turns into "disappear". It is also the record the
618 // quarantine-repair path repins before asking for a state write.
619 let ours: Vec<crate::workspace::Mount> = self
620 .mounts
621 .iter()
622 .map(|m| m.mount.clone())
623 .chain(self.quarantined.iter().map(|q| q.mount.clone()))
624 .collect();
625
626 for attempt in 0..8 {
627 let expected = store.read_state_bytes(root).map_err(map)?;
628 let on_disk: Vec<crate::workspace::Mount> = match expected.as_deref() {
629 Some(bytes) => store.parse_state_bytes(root, bytes).map_err(map)?,
630 None => Vec::new(),
631 };
632
633 let merged = {
634 let baseline = self.mounts_baseline.borrow();
635 merge_mount_rosters(&baseline, &ours, on_disk)
636 };
637 let workspace = crate::workspace::Workspace {
638 mounts: merged,
639 settings: self.settings.clone(),
640 };
641
642 if store
643 .save_state_cas(root, &workspace, expected.as_deref())
644 .map_err(map)?
645 {
646 *self.mounts_baseline.borrow_mut() = ours;
647 return Ok(());
648 }
649 if attempt == 7 {
650 return Err(EngineError::Mem(
651 "workspace state is being written concurrently: eight compare-and-set \
652 attempts all lost the race. Retry, or find the writer that is not \
653 backing off."
654 .to_string(),
655 ));
656 }
657 }
658 unreachable!("the loop returns on success and on exhaustion")
659 }
660}
661
662/// Three-way merge of a mount roster for a state write.
663///
664/// `baseline` is what the writing engine last read or wrote, `ours` is
665/// its roster now, `on_disk` is what the file holds at this instant.
666/// The result keeps every on-disk mount the writer did not touch (so a
667/// sibling's registration survives), drops the ones the writer removed
668/// since its baseline, and applies the ones it added or changed.
669///
670/// A mount present in `ours` unchanged since the baseline does NOT
671/// overwrite the on-disk record of the same name: if a sibling edited
672/// it and we did not, the sibling's edit is the newer statement about
673/// it, and republishing our stale copy is exactly the loss this merge
674/// exists to prevent.
675fn merge_mount_rosters(
676 baseline: &[crate::workspace::Mount],
677 ours: &[crate::workspace::Mount],
678 on_disk: Vec<crate::workspace::Mount>,
679) -> Vec<crate::workspace::Mount> {
680 use std::collections::{HashMap, HashSet};
681
682 let ours_names: HashSet<&str> = ours.iter().map(|m| m.mem.as_str()).collect();
683 let removed_by_us: HashSet<&str> = baseline
684 .iter()
685 .map(|m| m.mem.as_str())
686 .filter(|n| !ours_names.contains(n))
687 .collect();
688 let baseline_by_name: HashMap<&str, &crate::workspace::Mount> =
689 baseline.iter().map(|m| (m.mem.as_str(), m)).collect();
690
691 let mut merged: Vec<crate::workspace::Mount> = on_disk
692 .into_iter()
693 .filter(|m| !removed_by_us.contains(m.mem.as_str()))
694 .collect();
695
696 for mount in ours {
697 let untouched_by_us = baseline_by_name
698 .get(mount.mem.as_str())
699 .is_some_and(|b| *b == mount);
700 match merged.iter_mut().find(|d| d.mem == mount.mem) {
701 Some(slot) => {
702 if !untouched_by_us {
703 *slot = mount.clone();
704 }
705 }
706 None => merged.push(mount.clone()),
707 }
708 }
709 merged
710}