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