Skip to main content

memstead_base/engine/lifecycle/
schema_pin.rs

1//! The mem schema pin and its migration: setting the pin, reading the stamped generation, persisting it, and bumping the backend's copy.
2
3use super::reload::changed_config_fields;
4use super::*;
5
6impl Engine {
7    /// Set a mem's schema pin — the conformance-gated schema-migration
8    /// trigger. Behaviour per the pinned contract:
9    ///
10    /// - requested == current pin → `Noop`, no state change.
11    /// - requested != pin, mem integral against the target →
12    ///   atomic switch (`schema_pin = target`, migration state
13    ///   cleared) in one workspace-store write → `Switched`.
14    /// - requested != pin, mem NOT integral → enter (or stay in)
15    ///   dual-pin: `migration_target = target`, writes validate
16    ///   against the target from this call on, `findings` carries
17    ///   the non-integral entities → `MigrationStarted`
18    ///   (first call) / `MigrationPending` (same target re-issued).
19    /// - re-issued with the in-flight target once every entity is
20    ///   integral → atomic switch → `Switched`.
21    ///
22    /// The trigger is a label change gated by the conformance check —
23    /// no content hashing. The response hands the agent findings and
24    /// nothing else (no migration scripts, no hints); each repair
25    /// write is validated strictly against the target.
26    pub fn set_mem_schema(
27        &mut self,
28        mem: &str,
29        target: &memstead_schema::SchemaRef,
30    ) -> Result<crate::engine::SetSchemaOutcome, EngineError> {
31        use crate::engine::{SetSchemaOutcome, SetSchemaResult};
32        // A mem mounted read-only refuses before any lock is taken, as
33        // an entity write into it does: the refusal lays nothing where
34        // the mem lives. (A quarantined mem is not mounted and goes on
35        // to its repair path below.)
36        let _ = self.settle_roster_before_locking();
37        if self.mounts.iter().any(|m| {
38            m.mount.mem == mem && m.mount.capability != crate::workspace::MountCapability::Write
39        }) {
40            return Err(EngineError::ReadOnlyMount(mem.to_string()));
41        }
42        // A pin switch waits for a write in progress in any mem; the
43        // subject may be unreadable (a repin is how it is repaired).
44        let (_write_lock, _) = self.lock_workspace_for_mem_operation(mem)?;
45        // A quarantined mem's set-schema IS the repair path (an
46        // unresolvable pin is the commonest quarantine cause): repin
47        // the retained mount, then re-attempt the attach — the same
48        // in-process recovery `reload` performs after an external
49        // repair. Ordinary mounts proceed below unchanged.
50        if self.quarantine_reason(mem).is_some() {
51            return self.set_schema_on_quarantined(mem, target);
52        }
53        // Capability gate, identical in shape and position to the six
54        // sibling setters (`set_mem_version` … `set_mem_sync_state`):
55        // a schema-pin change starts a migration — the one lifecycle
56        // mutation a read-only mount must be able to refuse like any
57        // other. Judged on the roster as it stands now.
58        let (mount_idx, _roster_notice) = self.writable_mount_on_current_roster(mem)?;
59
60        // The requested target must resolve before anything else —
61        // an unknown ref is an error, not a migration into nowhere.
62        let target_schema = self.resolve_schema_by_ref(target).ok_or_else(|| {
63            // The migration resolver consulted workspace-authored
64            // schemas layered over the built-ins (`resolve_schema_by_ref`).
65            let consulted: Vec<_> = self
66                .workspace_schemas
67                .iter()
68                .chain(self.builtin_schemas.iter())
69                .cloned()
70                .collect();
71            EngineError::SchemaNotFound {
72                mem: mem.to_string(),
73                pin: target.as_display(),
74                sources: crate::engine::error::SchemaSourceDiagnostic::for_failed_pin(
75                    &target.name,
76                    &target.version,
77                    &consulted,
78                ),
79                install_hint: None,
80            }
81            .with_schema_install_probe(self.workspace_root())
82        })?;
83
84        // `Mount.schema` is now the optional assertion; for a mem the
85        // operator is actively re-pinning it is normally `Some` (and kept
86        // in sync with the config by the switch below). `<unset>` covers a
87        // mount that carried no assertion.
88        let current_pin = self.mounts[mount_idx].mount.schema.clone();
89        let current_pin_display = current_pin
90            .as_ref()
91            .map(|p| p.as_display())
92            .unwrap_or_else(|| "<unset>".to_string());
93        let in_flight = self.mounts[mount_idx].mount.migration_target.clone();
94
95        // The noop question is asked of the pin the engine actually
96        // serves (the loaded schema, resolved from the authoritative
97        // backend config at boot), never of the mount's expectation
98        // alone. With a `SCHEMA_PIN_MISMATCH` (mount says 0.4.0, config
99        // says 0.1.0) the old comparison against the mount answered
100        // "noop" for a target of 0.4.0 and the config stayed at 0.1.0
101        // forever: the one command meant to repair the mismatch could
102        // not. When the served pin already equals the target and only
103        // the mount expectation lags, the expectation is aligned in
104        // place and reported as switched.
105        let served_pin: Option<memstead_schema::SchemaRef> = self.schemas.get(mem).map(|s| {
106            let (name, version) = s.id();
107            memstead_schema::SchemaRef::new(name, version)
108        });
109        // During a dual-pin migration the served schema IS the target
110        // (writes validate against it) while the config still pins the
111        // old generation, so the shortcut applies only with no migration
112        // in flight; an in-flight target falls through to the
113        // conformance gate that completes it.
114        if served_pin.as_ref() == Some(target) && in_flight.is_none() {
115            if current_pin.as_ref() == Some(target) {
116                return Ok(SetSchemaOutcome {
117                    mem: mem.to_string(),
118                    schema_pin: current_pin_display,
119                    migration_target: in_flight.map(|t| t.as_display()),
120                    outcome: SetSchemaResult::Noop,
121                    findings: Vec::new(),
122                    stamped_schema: self.stamped_schema_of(mount_idx),
123                });
124            }
125            self.mounts[mount_idx].mount.schema = Some(target.clone());
126            self.mounts[mount_idx].mount.migration_target = None;
127            self.persist_state()?;
128            return Ok(SetSchemaOutcome {
129                mem: mem.to_string(),
130                schema_pin: target.as_display(),
131                migration_target: None,
132                outcome: SetSchemaResult::Switched,
133                findings: Vec::new(),
134                stamped_schema: self.stamped_schema_of(mount_idx),
135            });
136        }
137
138        // Conformance gate against the requested target. The full
139        // integrity definition includes the consistency axis, but the
140        // schema-switch gate is conformance: consistency breaks are
141        // schema-independent (they neither block nor are caused by a
142        // pin change) and keep their always-available repair paths.
143        let findings = crate::ops::integrity::conformance_findings(
144            &self.store,
145            mem,
146            target_schema.as_ref(),
147            &self.schemas,
148        );
149
150        if findings.is_empty() {
151            // Atomic switch. The pin's authoritative home is the backend
152            // config (boot resolution prefers it over `Mount.schema`), so
153            // persist there FIRST — if that write fails, every other piece
154            // of state stays untouched and the switch is a clean no-op.
155            // Without this the new pin landed only in `mounts.json` and was
156            // silently reverted on the next process boot for any
157            // config-present mem.
158            self.persist_mem_schema_pin(mount_idx, target)?;
159            self.mounts[mount_idx].mount.schema = Some(target.clone());
160            self.mounts[mount_idx].mount.migration_target = None;
161            self.schemas_insert(mem.to_string(), target_schema);
162            self.invalidate_communities();
163            // The index field set derives from the pinned schema — the
164            // schema-switch staleness the whole-map drop used to mask:
165            // this mem's index must be
166            // rebuilt against the new field set.
167            self.invalidate_search_indexes();
168            self.persist_state()?;
169            // The completed migration re-stamps the mutation stamp (the
170            // marker `ENGINE_VERSION_SKEW` reads) with the generation
171            // the mem now sits on. Without this the marker kept naming
172            // the old pin until the next entity write, and an agent
173            // reading it after the migration re-derived from a stale
174            // generation. The stamp
175            // writer's equality guard keeps a no-move write from
176            // happening; its warnings ride entity mutations and have no
177            // channel on this outcome, the same standing as the sweep.
178            let _stamp_warnings_have_no_channel_here = self.stamp_mutation_versions(mount_idx);
179            return Ok(SetSchemaOutcome {
180                mem: mem.to_string(),
181                schema_pin: target.as_display(),
182                migration_target: None,
183                outcome: SetSchemaResult::Switched,
184                findings: Vec::new(),
185                stamped_schema: self.stamped_schema_of(mount_idx),
186            });
187        }
188
189        let outcome = if in_flight.as_ref() == Some(target) {
190            SetSchemaResult::MigrationPending
191        } else {
192            SetSchemaResult::MigrationStarted
193        };
194        self.mounts[mount_idx].mount.migration_target = Some(target.clone());
195        // Writes validate against the target from this point on —
196        // the load-bearing dual-pin semantic.
197        self.schemas_insert(mem.to_string(), target_schema);
198        self.invalidate_communities();
199        // Same field-set dependency as the atomic-switch branch above.
200        self.invalidate_search_indexes();
201        self.persist_state()?;
202        // A dual-pin entry never moves the marker: the mem still sits
203        // on the old generation until every entity is integral, and
204        // the outcome says which generation the marker carries.
205        Ok(SetSchemaOutcome {
206            mem: mem.to_string(),
207            schema_pin: current_pin_display,
208            migration_target: Some(target.as_display()),
209            outcome,
210            findings,
211            stamped_schema: self.stamped_schema_of(mount_idx),
212        })
213    }
214
215    /// The resolved schema the mem's mutation stamp names, from the
216    /// engine's cached config (kept current by the shared config
217    /// writer), or `None` when the mem carries no stamp.
218    pub(super) fn stamped_schema_of(&self, mount_idx: usize) -> Option<String> {
219        self.mounts
220            .get(mount_idx)
221            .and_then(|m| m.mem_config.as_ref())
222            .and_then(|c| c.mutation_stamp.as_ref())
223            .map(|st| st.schema.clone())
224    }
225
226    /// Persist a mem's new schema pin into the authoritative backend
227    /// config (`.memstead/config.json` for folder, the `__MEMSTEAD`
228    /// mem-config blob for git-branch).
229    ///
230    /// Boot resolution treats the backend config as the authoritative
231    /// settled pin and `Mount.schema` (the `mounts.json` copy) as a
232    /// cross-checked assertion. A schema switch that updated only
233    /// `mounts.json` would therefore be silently reverted on the next
234    /// process boot — the config still names the old pin. This keeps the
235    /// authoritative home in sync at switch time.
236    ///
237    /// Value-level field bump: only the `"schema"` string is rewritten;
238    /// every other config field (`readMems`, write guidance, …) is
239    /// preserved verbatim. Config-absent mems (no `config.json`) keep
240    /// `Mount.schema` as their settled pin, so there is nothing to update
241    /// — a clean no-op.
242    /// **The one way this engine writes a mem config.** Every config-writing
243    /// operation goes through it; none serializes its cached struct.
244    ///
245    /// The defect it removes: a long-lived MCP server reads each mem's config
246    /// once at boot and holds it for days. Eight operations used to clone that
247    /// cached struct, set one field, and write the whole thing back, so
248    /// anything a sibling process changed in between was gone. The
249    /// reload-before-operation invariant did not save them, because the
250    /// staleness probe watches the entity branch (git-branch) or the change
251    /// log (folder) and a config-only write advances neither.
252    ///
253    /// What this does instead is what the schema-pin writer next door already
254    /// did: read the config the backend HAS, mutate the one field on that
255    /// JSON, write it back. A field this call did not set cannot be reverted,
256    /// because this call never had an opinion about it.
257    ///
258    /// `apply` receives the freshly-read config, PARSED. It deliberately does
259    /// not receive raw JSON: an earlier draft handed out the `Value` and each
260    /// closure wrote its own key name, which put `review_mark` in the file
261    /// where the struct reads `reviewMark` and lost the field on the next
262    /// read. Serde owns the wire names; the closures must not restate them.
263    /// Unknown fields survive because `MemConfig` flattens them into `extra`.
264    ///
265    /// `apply` runs again on a re-read if the file moved between the read and
266    /// the write, so it must be a pure function of the config it is handed,
267    /// never of the engine's cache.
268    ///
269    /// Returns the parsed new config plus, when the stored config had moved on
270    /// from what this engine last observed, the fields the intervening writer
271    /// had changed. The caller rides that on its own response as
272    /// `CONFIG_WRITE_INTERVENED`.
273    pub(crate) fn write_mem_config_merged(
274        &mut self,
275        mount_idx: usize,
276        mem_name: &str,
277        tool: &'static str,
278        note: Option<&str>,
279        apply: &dyn Fn(&mut memstead_schema::config::MemConfig),
280    ) -> Result<(memstead_schema::config::MemConfig, Vec<String>), EngineError> {
281        // The config-write commit carries the operation's provenance
282        // like every other commit: the tool that caused it, the
283        // session's actor, client, role and identity, and the note.
284        let ctx = self.session_commit_context(Some(tool), note.map(String::from));
285        let backend = self.mounts[mount_idx].backend.as_ref();
286        let read = |b: &dyn crate::backend::MemBackend| -> Result<Vec<u8>, EngineError> {
287            b.read_mem_config()
288                .map_err(|e| EngineError::Mem(format!("read mem config for update: {e}")))?
289                .ok_or_else(|| {
290                    EngineError::InvalidInput(format!(
291                        "mem '{mem_name}' has no stored MemConfig (initialize the mem via \
292                         `memstead init` or `memstead mem create` first)"
293                    ))
294                })
295        };
296
297        let stored = read(backend)?;
298        // What the intervening writer changed, if anyone did. Compared against
299        // the engine's cached copy, never against a clock: the rule forbids
300        // reacting to cache age, and a single-writer workspace has an
301        // identical cache, so this is empty there.
302        let intervened = match self.mounts[mount_idx].mem_config.as_ref() {
303            Some(cached) => changed_config_fields(cached, &stored),
304            None => Vec::new(),
305        };
306
307        let render =
308            |raw: &[u8]| -> Result<(memstead_schema::config::MemConfig, Vec<u8>), EngineError> {
309                let value: serde_json::Value = serde_json::from_slice(raw)
310                    .map_err(|e| EngineError::Mem(format!("parse mem config for update: {e}")))?;
311                let mut cfg = memstead_schema::config::parse_mem_config(&value)
312                    .map_err(|e| EngineError::Mem(format!("parse mem config for update: {e}")))?;
313                apply(&mut cfg);
314                let mut bytes = serde_json::to_vec_pretty(&cfg)
315                    .map_err(|e| EngineError::Mem(format!("serialize mem config: {e}")))?;
316                bytes.push(b'\n');
317                Ok((cfg, bytes))
318            };
319        let (mut parsed, mut bytes) = render(&stored)?;
320
321        // Compare-and-set, done by the backend so the check and the write are
322        // one step. An earlier draft re-read here and then wrote, which is
323        // check-then-write and leaves exactly the lost-update window
324        // open. On a mismatch the loop re-reads, re-applies onto what is
325        // there, and retries: the intervening writer's change is merged, never
326        // overwritten. Bounded, because an unbounded retry against a hot
327        // writer is a hang, and reaching the bound is a real contention
328        // problem the caller should hear about rather than a state to spin in.
329        let mut expected = stored;
330        for attempt in 0..8 {
331            let wrote = self.mounts[mount_idx].backend.write_mem_config_cas(
332                Some(&expected),
333                &bytes,
334                &ctx,
335            )?;
336            if wrote {
337                break;
338            }
339            if attempt == 7 {
340                return Err(EngineError::Mem(format!(
341                    "mem '{mem_name}' config is being written concurrently: eight \
342                     compare-and-set attempts all lost the race. Retry, or find the \
343                     writer that is not backing off."
344                )));
345            }
346            expected = read(self.mounts[mount_idx].backend.as_ref())?;
347            let rendered = render(&expected)?;
348            parsed = rendered.0;
349            bytes = rendered.1;
350        }
351
352        let mounted = &mut self.mounts[mount_idx];
353        mounted.mem_config = Some(parsed.clone());
354        // Refresh the head cursor so the next drift probe does not surface
355        // MEM_RELOADED for the commit this call just produced.
356        if let Some(sha) = mounted.backend.current_head().ok().flatten() {
357            let before = mounted
358                .last_known_head
359                .replace(sha.clone())
360                .unwrap_or_default();
361            // The config write is the current caller's own.
362            self.caller_saw_own_write(mem_name, &before, &sha);
363        }
364        Ok((parsed, intervened))
365    }
366
367    fn persist_mem_schema_pin(
368        &mut self,
369        mount_idx: usize,
370        target: &memstead_schema::SchemaRef,
371    ) -> Result<(), EngineError> {
372        let ctx = self.session_commit_context(Some("set_mem_schema"), None);
373        let value = bump_backend_schema_pin(self.mounts[mount_idx].backend.as_ref(), target, &ctx)?;
374        // Refresh the cached parsed config so in-session reads observe the
375        // new pin without a reload.
376        if let Some(value) = value
377            && let Ok(cfg) = memstead_schema::config::parse_mem_config(&value)
378        {
379            self.mounts[mount_idx].mem_config = Some(cfg);
380        }
381        Ok(())
382    }
383}
384
385pub fn bump_backend_schema_pin(
386    backend: &dyn crate::backend::MemBackend,
387    target: &memstead_schema::SchemaRef,
388    ctx: &crate::vcs::CommitContext<'_>,
389) -> Result<Option<serde_json::Value>, EngineError> {
390    // Compare-and-set against the bytes this call read, re-read and re-applied
391    // on a mismatch: a config field another writer changed in between
392    // survives, and the pin lands on top of it. Bounded like
393    // `write_mem_config_merged`.
394    for _ in 0..8 {
395        let Some(bytes) = backend
396            .read_mem_config()
397            .map_err(|e| EngineError::Mem(format!("read mem config for pin update: {e}")))?
398        else {
399            return Ok(None);
400        };
401        let mut value: serde_json::Value = serde_json::from_slice(&bytes)
402            .map_err(|e| EngineError::Mem(format!("parse mem config for pin update: {e}")))?;
403        value["schema"] = serde_json::Value::String(target.as_display());
404        let new_bytes = serde_json::to_vec_pretty(&value)
405            .map_err(|e| EngineError::Mem(format!("serialize mem config for pin update: {e}")))?;
406        if backend
407            .write_mem_config_cas(Some(&bytes), &new_bytes, ctx)
408            .map_err(|e| EngineError::Mem(format!("write mem config for pin update: {e}")))?
409        {
410            return Ok(Some(value));
411        }
412    }
413    Err(EngineError::Mem(format!(
414        "mem config is being written concurrently: eight compare-and-set attempts to \
415         pin {} all lost the race. Retry.",
416        target.as_display()
417    )))
418}