bynk_project/schema_registry.rs
1//! Events track, slice 3c (#980): the cross-build schema registry's document
2//! shape and (de)serialisation.
3//!
4//! P4.0 (#1113, [DECISION A]): this module used to also hold `reconcile` —
5//! the `bynk_check`-coupled half that diffs a project's live event shapes
6//! against this document (it reads `UnitTable`, which stays in `bynk-emit`
7//! pending P4.1's `bynk-check` entry point). Only the pure, disk-free
8//! document shape and its parse/serialize moved here; `reconcile` and its
9//! helpers (`snapshot`, `canon_type`, `Reconciled`, …) stay in `bynk-emit`'s
10//! own `project/schema_registry.rs`, and reach `SchemaRegistry`'s otherwise-
11//! private `version`/`events` only through [`SchemaRegistry::new`],
12//! [`SchemaRegistry::get`], and [`SchemaRegistry::insert`] — never raw field
13//! access across the crate boundary.
14//!
15//! #1078: this module touches no disk. `parse`/`serialize` are pure —
16//! `bynk.schema.lock`'s content comes in through
17//! `CompileOptions::schema_registry`'s `SchemaLock::On { existing }` and goes
18//! out through `ProjectOutput::schema_lock`; `bynk-driver`'s `schema_lock`
19//! module owns the actual read/atomic-write. `parse` takes a
20//! `project_root: &Path` (#1085 review) purely to name the file in a
21//! corruption message — never for I/O.
22//!
23//! State-migrations S0 (#2204): the lock is `version = 2` and also records
24//! each agent class's stored state shape under `[agents]` (the retired
25//! track's summary in `design/archive/retired-tracks.md`, §3.1). A v1 lock
26//! reads as v2 with no agents; the version bump exists so an older toolchain
27//! *refuses* a v2 lock instead of parsing it, dropping the unknown `[agents]`
28//! table (there is no `deny_unknown_fields`) and writing the lock back
29//! without it.
30
31use std::collections::BTreeMap;
32use std::path::Path;
33
34use serde::{Deserialize, Serialize};
35
36pub fn lock_version() -> u32 {
37 2
38}
39
40/// The last lock version without `[agents]`. [`parse`] reads it as the
41/// current version with an empty agent table; the next build writes it back
42/// at [`lock_version`]. `check`/`test` read it and never write (ADR 0493).
43const LEGACY_EVENTS_ONLY_VERSION: u32 = 1;
44
45#[derive(Debug, Default, Serialize, Deserialize, PartialEq, Eq)]
46pub struct SchemaRegistry {
47 // No serde `default`: a registry with no `version` is not a fresh
48 // project, it is corruption (a truncated write), and must fail the read
49 // rather than silently re-baseline every event's history — the same
50 // argument `bynk.deploy.lock`'s `DeployLock` makes for the identical
51 // field.
52 version: u32,
53 #[serde(default)]
54 events: BTreeMap<String, EventEntry>,
55 /// Keyed `<unit>.<Agent>`. Skipped when empty, so a project with no
56 /// agents writes exactly the events-only document it always did, apart
57 /// from the version line.
58 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
59 agents: BTreeMap<String, AgentEntry>,
60}
61
62impl SchemaRegistry {
63 /// A fresh, empty registry at the current lock version — what
64 /// `bynk-emit`'s `reconcile` starts from and fills in per-event via
65 /// [`Self::insert`] as it walks the project's units. [DECISION A]: kept
66 /// private-fielded so `version`/`events` stay encapsulated across the
67 /// `bynk-emit` ↔ `bynk-project` boundary the way they always were
68 /// in-crate.
69 pub fn new() -> Self {
70 SchemaRegistry {
71 version: lock_version(),
72 events: BTreeMap::new(),
73 agents: BTreeMap::new(),
74 }
75 }
76
77 /// This registry's entry for `key` (`<unit>.<EventName>`), when one
78 /// exists — what `reconcile` diffs a unit's live event shape against.
79 pub fn get(&self, key: &str) -> Option<&EventEntry> {
80 self.events.get(key)
81 }
82
83 /// Record `entry` under `key`, overwriting any prior entry — what
84 /// `reconcile` calls once per event as it rebuilds the updated document.
85 pub fn insert(&mut self, key: String, entry: EventEntry) {
86 self.events.insert(key, entry);
87 }
88
89 /// This registry's entry for agent class `key` (`<unit>.<Agent>`).
90 pub fn get_agent(&self, key: &str) -> Option<&AgentEntry> {
91 self.agents.get(key)
92 }
93
94 /// Record agent class `entry` under `key`, overwriting any prior entry.
95 pub fn insert_agent(&mut self, key: String, entry: AgentEntry) {
96 self.agents.insert(key, entry);
97 }
98
99 /// Raise agent class `key`'s floor to `floor`, dropping the snapshots
100 /// below it (state-migrations S4, #2259 Decision F). The floor only rises:
101 /// a `floor` at or below the recorded one changes nothing and returns
102 /// `Ok(false)`. A `floor` above the class's current version, or a class the
103 /// registry does not record, is refused.
104 pub fn raise_floor(&mut self, key: &str, floor: i64) -> Result<bool, String> {
105 let Some(entry) = self.agents.get_mut(key) else {
106 return Err(format!("`bynk.schema.lock` records no agent `{key}`"));
107 };
108 if floor > entry.version {
109 return Err(format!(
110 "cannot raise agent `{key}`'s floor to {floor}: its current version is {}",
111 entry.version
112 ));
113 }
114 if floor <= entry.floor {
115 return Ok(false);
116 }
117 entry.floor = floor;
118 entry.shapes.retain(|s| s.version >= floor);
119 Ok(true)
120 }
121
122 /// Every recorded agent class, in key order — what the agent reconcile
123 /// walks to find classes that disappeared from source.
124 pub fn agents(&self) -> impl Iterator<Item = (&String, &AgentEntry)> {
125 self.agents.iter()
126 }
127}
128
129/// One agent class's recorded state history (track §3.1).
130///
131/// `version` is the class's current shape version: every accepted change
132/// bumps it, additive or not, so the S1 `__v` marker always names exactly one
133/// entry in `shapes`. `floor` is the oldest version any deployed instance may
134/// still hold; only a migration sweep (S4) raises it, and `shapes` keeps one
135/// snapshot per version from `floor` to `version`.
136#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
137pub struct AgentEntry {
138 pub version: i64,
139 pub floor: i64,
140 pub shapes: Vec<AgentShape>,
141 /// State-migrations S3 (#2248, #2253 review): the old names this class was
142 /// renamed from (`agent New replaces Old`), once a build moved their
143 /// entries here. While the declaration stays in source, it tells an
144 /// already-applied rename from a mistyped one. Additive and omitted when
145 /// empty, so the lock format is unchanged for every class never renamed.
146 #[serde(default, skip_serializing_if = "Vec::is_empty")]
147 pub renamed_from: Vec<String>,
148}
149
150impl AgentEntry {
151 /// The entry's own invariants: `1 <= floor <= version`, and exactly one
152 /// snapshot for every version from `floor` to `version`, in order. A
153 /// hand-edit or a bad merge of two branches that each bumped the class can
154 /// break them; reconciling against such an entry would compare with the
155 /// wrong shape (#2204 review), so [`parse`] refuses it as corruption.
156 fn validate(&self) -> Result<(), String> {
157 if self.floor < 1 || self.floor > self.version {
158 return Err(format!(
159 "has floor {} outside 1..={}",
160 self.floor, self.version
161 ));
162 }
163 let versions: Vec<i64> = self.shapes.iter().map(|s| s.version).collect();
164 let expected: Vec<i64> = (self.floor..=self.version).collect();
165 if versions != expected {
166 return Err(format!(
167 "records shapes for versions {versions:?}, not one per version {}..={}",
168 self.floor, self.version
169 ));
170 }
171 Ok(())
172 }
173
174 /// The oldest stored version a build at this entry's `version` can read
175 /// forward without a migration step: the smallest `m >= floor` such that
176 /// every snapshot after `m`, up to `version`, was an additive change
177 /// (state-migrations S1, #2211 Decision B). A record at `m` or later loads
178 /// by zero-merge (ADR 0124 D4); one below it has no path.
179 pub fn oldest_readable(&self) -> i64 {
180 self.oldest_readable_to(self.version)
181 }
182
183 /// [`Self::oldest_readable`] measured against `target` instead of the
184 /// current version: the oldest version whose path to `target` is entirely
185 /// additive. A `migrate from target` step covers every version from there
186 /// up to `target` (state-migrations S2, #2224 Decision C).
187 pub fn oldest_readable_to(&self, target: i64) -> i64 {
188 let mut m = target;
189 while m > self.floor && self.shapes.iter().any(|s| s.version == m && s.additive) {
190 m -= 1;
191 }
192 m
193 }
194
195 /// The snapshot at the entry's current `version`.
196 pub fn current(&self) -> Option<&AgentShape> {
197 self.shape(self.version)
198 }
199
200 /// The snapshot recorded at `version`, if the entry still holds it.
201 pub fn shape(&self, version: i64) -> Option<&AgentShape> {
202 self.shapes.iter().find(|s| s.version == version)
203 }
204}
205
206/// The stored shape of one agent class at one version.
207#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
208pub struct AgentShape {
209 pub version: i64,
210 /// Whether the change *into* this version was additive (a baseline is
211 /// not: nothing preceded it).
212 pub additive: bool,
213 pub fields: Vec<StoreShape>,
214}
215
216/// One `store` field's stored shape. `ty` is the structural rendering of the
217/// field's type with every refinement predicate stripped; `refinement` is
218/// the same walk with predicates kept (an opaque type's included). A change
219/// to `ty` is non-additive; a change to `refinement` alone is not.
220#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
221pub struct StoreShape {
222 pub name: String,
223 pub kind: String,
224 #[serde(rename = "type")]
225 pub ty: String,
226 pub refinement: String,
227 /// #2676 (Decision B): one node per position in the stored value, so the
228 /// reconcile can tell a record field added with a default (additive) from
229 /// any other structural change. Optional (Decision D): a lock written
230 /// before it reads with none, and an unchanged build fills them in
231 /// (Decision C).
232 #[serde(default, skip_serializing_if = "Vec::is_empty")]
233 pub paths: Vec<PathShape>,
234}
235
236/// #2676: one position in a stored value. `path` starts at the `store` field's
237/// name and appends `.field` for a record field, `|Variant` for a sum variant,
238/// `[]` for a `List`/`Set` element, `?` for an `Option`'s value, `{}` for a
239/// `Map`'s value and `|Ok`/`|Err` for a `Result`'s arms. `ty` is the node's own
240/// shallow structure (`{}` a record, `|` a sum, `variant`, `List`, `Map[String]`,
241/// a base type, `@N` a recursion back-reference), so two values have the same
242/// structure exactly when their path sets agree. `default` is set on a record
243/// field that declares one.
244#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
245pub struct PathShape {
246 pub path: String,
247 #[serde(rename = "type")]
248 pub ty: String,
249 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
250 pub default: bool,
251 /// The node with its predicates kept (a refined or opaque base's, or a
252 /// field's inline refinement), when that differs from `ty`. A change here
253 /// alone leaves stored data readable, as for [`StoreShape::refinement`].
254 #[serde(default, skip_serializing_if = "String::is_empty")]
255 pub refinement: String,
256}
257
258#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
259pub struct EventEntry {
260 pub schema: i64,
261 pub fields: Vec<FieldShape>,
262}
263
264/// A shallow, per-field snapshot of an event's current shape — deliberately
265/// **not** `bynk-check/src/contract.rs`'s `canon_named_in`: that renders a
266/// field as `name: type` with no signal for default-presence, so an additive
267/// change (new field, has a default) and a breaking one (new field, no
268/// default) perturb it identically. This snapshot exists to tell those two
269/// apart, one field at a time.
270#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
271pub struct FieldShape {
272 pub name: String,
273 #[serde(rename = "type")]
274 pub ty: String,
275 pub default: bool,
276}
277
278/// Parse `bynk.schema.lock`'s content. `existing: None` means the project
279/// has no lock file yet — a fresh project's first reconciliation, baselined
280/// rather than compared, exactly as a missing file always meant back when
281/// this function read the file itself. It must mean *verified absent*, never
282/// "content unavailable" for some other reason — see `SchemaLock::On`'s doc
283/// comment, which states that invariant on the type the caller constructs.
284///
285/// `Some(text)` that is empty/unparseable/a different lock version is
286/// corruption, not a fresh project, and fails hard (`ledger.rs`'s own
287/// argument for the identical case) — never silently re-baselines.
288///
289/// `project_root` is used only to name the file in an error message — #1078
290/// made this function disk-free (and so path-blind) for the content itself;
291/// #1085 review restored the location context a corruption diagnostic lost
292/// as a result, without reintroducing any `fs`/`Path` I/O here.
293pub fn parse(existing: Option<&str>, project_root: &Path) -> Result<SchemaRegistry, String> {
294 let Some(text) = existing else {
295 return Ok(SchemaRegistry::new());
296 };
297 let path = project_root.join("bynk.schema.lock");
298 if text.trim().is_empty() {
299 return Err(format!(
300 "schema registry `{}` is empty or truncated (corrupt); refusing \
301 to treat it as a fresh project — restore it from version control",
302 path.display()
303 ));
304 }
305 let reg: SchemaRegistry = toml::from_str(text).map_err(|e| {
306 format!(
307 "schema registry `{}` is corrupt ({e}) — restore it from version control",
308 path.display()
309 )
310 })?;
311 let mut reg = reg;
312 if reg.version == LEGACY_EVENTS_ONLY_VERSION && reg.agents.is_empty() {
313 reg.version = lock_version();
314 }
315 if reg.version != lock_version() {
316 return Err(format!(
317 "unsupported schema registry version {} (`{}`)",
318 reg.version,
319 path.display()
320 ));
321 }
322 for (key, entry) in ®.agents {
323 if let Err(why) = entry.validate() {
324 return Err(format!(
325 "schema registry `{}` is corrupt: agent `{key}` {why} — restore it from \
326 version control",
327 path.display()
328 ));
329 }
330 }
331 Ok(reg)
332}
333
334/// Serialize a reconciled registry to `bynk.schema.lock`'s TOML form —
335/// what `bynk-driver` writes to disk, atomically, only on a fully clean
336/// build (`compile_project`'s own gate). No disk access here; see this
337/// module's doc comment for why. Cannot fail for this data shape (string
338/// keys, no floats) — `toml::to_string_pretty` only errors on inputs this
339/// struct never produces.
340pub fn serialize(reg: &SchemaRegistry) -> String {
341 toml::to_string_pretty(reg).expect("SchemaRegistry always serializes")
342}
343
344#[cfg(test)]
345mod tests {
346 use super::*;
347
348 fn shape(name: &str, ty: &str, default: bool) -> FieldShape {
349 FieldShape {
350 name: name.to_string(),
351 ty: ty.to_string(),
352 default,
353 }
354 }
355
356 fn test_root() -> &'static Path {
357 Path::new("/project")
358 }
359
360 #[test]
361 fn new_registry_is_empty_at_the_current_lock_version() {
362 let reg = SchemaRegistry::new();
363 assert_eq!(reg.version, lock_version());
364 assert!(reg.events.is_empty());
365 }
366
367 #[test]
368 fn insert_then_get_round_trips_an_entry() {
369 let mut reg = SchemaRegistry::new();
370 let entry = EventEntry {
371 schema: 2,
372 fields: vec![shape("orderId", "String", false)],
373 };
374 reg.insert("commerce.order.PaymentConfirmed".to_string(), entry.clone());
375 assert_eq!(reg.get("commerce.order.PaymentConfirmed"), Some(&entry));
376 assert_eq!(reg.get("no.such.key"), None);
377 }
378
379 #[test]
380 fn parse_of_absent_content_is_an_empty_registry() {
381 let reg = parse(None, test_root()).unwrap();
382 assert!(reg.events.is_empty());
383 }
384
385 #[test]
386 fn parse_round_trips_serialized_content() {
387 let mut reg = SchemaRegistry::new();
388 reg.insert(
389 "commerce.order.PaymentConfirmed".to_string(),
390 EventEntry {
391 schema: 2,
392 fields: vec![shape("orderId", "String", false)],
393 },
394 );
395 let body = serialize(®);
396 assert_eq!(parse(Some(&body), test_root()).unwrap(), reg);
397 }
398
399 #[test]
400 fn a_truncated_file_is_corruption_not_a_fresh_project() {
401 let err = parse(Some(" \n"), test_root()).unwrap_err();
402 assert!(err.contains("restore it from version control"));
403 // Not a full path match (`\` vs `/` makes that Windows-fragile) —
404 // just proving the filename made it into the message at all.
405 assert!(err.contains("bynk.schema.lock"));
406 }
407
408 #[test]
409 fn an_unparseable_file_is_corruption() {
410 let err = parse(Some("not valid toml {{{"), test_root()).unwrap_err();
411 assert!(err.contains("corrupt"));
412 assert!(err.contains("bynk.schema.lock"));
413 }
414
415 #[test]
416 fn a_v1_lock_reads_as_the_current_version_with_no_agents() {
417 let v1 = "version = 1\n\n[events]\n";
418 let reg = parse(Some(v1), test_root()).unwrap();
419 assert_eq!(reg.version, lock_version());
420 assert!(reg.agents.is_empty());
421 assert!(serialize(®).starts_with("version = 2"));
422 }
423
424 #[test]
425 fn a_v1_lock_that_somehow_carries_agents_is_refused() {
426 let text = "version = 1\n\n[agents.\"u.A\"]\nversion = 1\nfloor = 1\nshapes = []\n";
427 let err = parse(Some(text), test_root()).unwrap_err();
428 assert!(err.contains("unsupported schema registry version 1"));
429 }
430
431 #[test]
432 fn agent_entries_round_trip() {
433 let mut reg = SchemaRegistry::new();
434 reg.insert_agent(
435 "shop.Cart".to_string(),
436 AgentEntry {
437 version: 2,
438 floor: 1,
439 shapes: vec![
440 AgentShape {
441 version: 1,
442 additive: false,
443 fields: vec![StoreShape {
444 name: "owner".to_string(),
445 kind: "Cell".to_string(),
446 ty: "String".to_string(),
447 refinement: "String".to_string(),
448 paths: Vec::new(),
449 }],
450 },
451 AgentShape {
452 version: 2,
453 additive: true,
454 fields: vec![],
455 },
456 ],
457 renamed_from: Vec::new(),
458 },
459 );
460 let body = serialize(®);
461 assert_eq!(parse(Some(&body), test_root()).unwrap(), reg);
462 assert_eq!(
463 reg.get_agent("shop.Cart")
464 .unwrap()
465 .current()
466 .unwrap()
467 .version,
468 2
469 );
470 }
471
472 #[test]
473 fn an_agent_entry_with_no_snapshot_for_its_version_is_corruption() {
474 let text = "version = 2\n\n[agents.\"u.A\"]\nversion = 2\nfloor = 1\n\n\
475 [[agents.\"u.A\".shapes]]\nversion = 1\nadditive = false\nfields = []\n";
476 let err = parse(Some(text), test_root()).unwrap_err();
477 assert!(err.contains("corrupt"), "{err}");
478 assert!(err.contains("agent `u.A`"), "{err}");
479 }
480
481 #[test]
482 fn an_agent_entry_with_its_floor_above_its_version_is_corruption() {
483 let text = "version = 2\n\n[agents.\"u.A\"]\nversion = 1\nfloor = 2\nshapes = []\n";
484 let err = parse(Some(text), test_root()).unwrap_err();
485 assert!(err.contains("floor 2"), "{err}");
486 }
487
488 #[test]
489 fn oldest_readable_walks_back_over_additive_snapshots_only() {
490 let shape = |version, additive| AgentShape {
491 version,
492 additive,
493 fields: vec![],
494 };
495 let entry = |version, floor, shapes| AgentEntry {
496 version,
497 floor,
498 shapes,
499 renamed_from: Vec::new(),
500 };
501 // Baseline only.
502 assert_eq!(entry(1, 1, vec![shape(1, false)]).oldest_readable(), 1);
503 // 1 -> 2 -> 3, all additive: everything back to the floor reads.
504 let all = entry(3, 1, vec![shape(1, false), shape(2, true), shape(3, true)]);
505 assert_eq!(all.oldest_readable(), 1);
506 // 2 -> 3 non-additive (an S2 step): only 3 reads without one.
507 let broken = entry(3, 1, vec![shape(1, false), shape(2, true), shape(3, false)]);
508 assert_eq!(broken.oldest_readable(), 3);
509 // 1 -> 2 non-additive, 2 -> 3 additive: 2 and 3 read.
510 let mid = entry(3, 1, vec![shape(1, false), shape(2, false), shape(3, true)]);
511 assert_eq!(mid.oldest_readable(), 2);
512 // A raised floor bounds the walk.
513 let floored = entry(3, 2, vec![shape(2, true), shape(3, true)]);
514 assert_eq!(floored.oldest_readable(), 2);
515 }
516
517 #[test]
518 fn raising_the_floor_drops_older_snapshots_and_stays_valid() {
519 let snap = |version| AgentShape {
520 version,
521 additive: false,
522 fields: Vec::new(),
523 };
524 let mut reg = SchemaRegistry::new();
525 reg.insert_agent(
526 "u.A".to_string(),
527 AgentEntry {
528 version: 3,
529 floor: 1,
530 shapes: vec![snap(1), snap(2), snap(3)],
531 renamed_from: Vec::new(),
532 },
533 );
534 assert_eq!(reg.raise_floor("u.A", 3), Ok(true));
535 let entry = reg.get_agent("u.A").unwrap();
536 assert_eq!(entry.floor, 3);
537 assert_eq!(entry.shapes, vec![snap(3)]);
538 // The edited lock reads back as valid.
539 let text = serialize(®);
540 assert_eq!(parse(Some(&text), test_root()).unwrap(), reg);
541 // The floor never falls, and never passes the current version.
542 assert_eq!(reg.raise_floor("u.A", 2), Ok(false));
543 assert!(
544 reg.raise_floor("u.A", 4)
545 .unwrap_err()
546 .contains("current version is 3")
547 );
548 assert!(reg.raise_floor("u.B", 1).is_err());
549 }
550
551 #[test]
552 fn a_registry_with_no_agents_writes_no_agents_table() {
553 assert!(!serialize(&SchemaRegistry::new()).contains("agents"));
554 }
555
556 #[test]
557 fn an_unsupported_lock_version_is_corruption() {
558 let err = parse(Some("version = 99\n"), test_root()).unwrap_err();
559 assert!(err.contains("unsupported schema registry version 99"));
560 }
561}