Skip to main content

bynk_check/
schema_registry.rs

1//! Events track, slice 3c (#980): the cross-build schema registry's
2//! reconciliation logic — verifying a project's live event shapes against a
3//! committed `bynk.schema.lock`, keyed by qualified event name, storing each
4//! event's field shape (name, type, whether the field has a default) and its
5//! current schema version. Every build reconciles the live shape against the
6//! stored one and either leaves the version alone, bumps it (a purely
7//! additive change), or fails the build (a change that isn't safely
8//! additive).
9//!
10//! P4.0 (#1113, [DECISION A]): the document shape itself — `SchemaRegistry`,
11//! `EventEntry`, `FieldShape`, and their `parse`/`serialize` — moved to
12//! `bynk_project::schema_registry`; `bynk-emit/src/project/schema_registry.rs`
13//! re-exports it there, unchanged, for every existing `schema_registry::X`
14//! call site in `project.rs`.
15//!
16//! P5.3 (`design/tracks/semantics-in-the-checker.md` §6): [`reconcile`] and
17//! its helpers moved here from that same `bynk-emit` module — category 1 of
18//! `bynk-check/src/analysis.rs`'s own seven-category residual-gap accounting
19//! ("gap in name only" at the time: `reconcile` only ever ran under
20//! `SchemaLock::On`, and the analyse path always passed `SchemaLock::Off`, so
21//! relocating it changed nothing observable — see that module's doc for why
22//! R3.5 still required the move; #2081 later gave the analyse path the
23//! caller's lock). `bynk-emit`'s `run_checks` is now this function's caller, not its
24//! owner, the same way P4.0/P4.1 turned `project.rs` into a caller of
25//! `bynk-project`/`bynk-check` throughout.
26//!
27//! P5.5 (§6, §3.2's "eighth site"): [`parse_or_diagnose`] moved here too —
28//! `bynk.project.schema_registry_corrupt`, a real `CompileError::new`
29//! construction the seven-category accounting above didn't cover (it isn't a
30//! whole-project *check*, it's the read step immediately before
31//! [`reconcile`]), found and scoped by name in §3.2 rather than left for a
32//! future sweep to rediscover. `bynk_project::schema_registry::parse` itself
33//! — the document-shape parse — stays in `bynk-project` (P4.0); only the
34//! diagnostic construction on its error path moves, the same split
35//! `reconcile`'s own move drew between document shape and checking.
36
37use std::collections::BTreeMap;
38
39use bynk_syntax::ast::{
40    AgentDecl, EventDecl, Expr, ExprKind, MigrateDecl, MigrateItem, TypeBody, TypeRef,
41};
42use bynk_syntax::error::CompileError;
43use bynk_syntax::span::Span;
44
45use bynk_project::schema_registry::{
46    AgentEntry, AgentShape, EventEntry, FieldShape, PathShape, SchemaRegistry, StoreShape,
47};
48
49use crate::symbols::UnitTable;
50
51/// Parse `bynk.schema.lock`'s content, diagnosing a corrupt file as
52/// `bynk.project.schema_registry_corrupt` rather than handing the caller a
53/// bare `String` to wrap itself. `existing`/`project_root` are exactly
54/// `bynk_project::schema_registry::parse`'s own parameters — `None` (no lock
55/// file yet) always succeeds with a fresh, empty registry.
56pub fn parse_or_diagnose(
57    existing: Option<&str>,
58    project_root: &std::path::Path,
59) -> Result<SchemaRegistry, CompileError> {
60    bynk_project::schema_registry::parse(existing, project_root).map_err(|msg| {
61        CompileError::new("bynk.project.schema_registry_corrupt", Span::default(), msg)
62    })
63}
64
65/// A shallow, per-field snapshot of an event's current shape — deliberately
66/// **not** `bynk-check/src/contract.rs`'s `canon_named_in`: that renders a
67/// field as `name: type` with no signal for default-presence, so an additive
68/// change (new field, has a default) and a breaking one (new field, no
69/// default) perturb it identically. This snapshot exists to tell those two
70/// apart, one field at a time.
71fn snapshot(event: &EventDecl) -> Vec<FieldShape> {
72    let mut fields: Vec<FieldShape> = event
73        .body
74        .fields
75        .iter()
76        .map(|f| FieldShape {
77            name: f.name.name.clone(),
78            ty: canon_type(&f.type_ref),
79            default: f.init.is_some(),
80        })
81        .collect();
82    fields.sort_by(|a, b| a.name.cmp(&b.name));
83    fields
84}
85
86/// A stable surface-form rendering of a `TypeRef`, for the registry's own
87/// stored shape only. Deliberately **not** `bynk-fmt`'s `type_ref_to_string`
88/// (private to the printer, and neither `bynk-emit` nor `bynk-check` depends on `bynk-fmt`)
89/// — and deliberately not required to match either the formatter's or the
90/// checker's own rendering byte-for-byte: this string is compared only
91/// against itself, across builds, never displayed to a user. Exhaustive, no
92/// wildcard arm, so a new `TypeRef` variant is a compile error here rather
93/// than a silent "no signal" gap in the registry's diffing.
94fn canon_type(t: &TypeRef) -> String {
95    match t {
96        TypeRef::Base(b, _) => b.name().to_string(),
97        TypeRef::Named(id) => id.name.clone(),
98        TypeRef::Result(a, b, _) => format!("Result[{}, {}]", canon_type(a), canon_type(b)),
99        TypeRef::Option(t, _) => format!("Option[{}]", canon_type(t)),
100        TypeRef::Effect(t, _) => format!("Effect[{}]", canon_type(t)),
101        TypeRef::HttpResult(t, _) => format!("HttpResult[{}]", canon_type(t)),
102        TypeRef::QueueResult(_) => "QueueResult".to_string(),
103        TypeRef::Asset(_) => "Asset".to_string(),
104        TypeRef::RequestHeaders(_) => "RequestHeaders".to_string(),
105        TypeRef::RequestQuery(_) => "RequestQuery".to_string(),
106        TypeRef::RequestCookies(_) => "RequestCookies".to_string(),
107        TypeRef::TokenClaims(_) => "TokenClaims".to_string(),
108        TypeRef::BoundaryRejection(_) => "BoundaryRejection".to_string(),
109        TypeRef::List(t, _) => format!("List[{}]", canon_type(t)),
110        TypeRef::Set(t, _) => format!("Set[{}]", canon_type(t)),
111        TypeRef::Map(k, v, _) => format!("Map[{}, {}]", canon_type(k), canon_type(v)),
112        TypeRef::Query(t, _) => format!("Query[{}]", canon_type(t)),
113        TypeRef::Stream(t, _) => format!("Stream[{}]", canon_type(t)),
114        TypeRef::Connection(t, _) => format!("Connection[{}]", canon_type(t)),
115        TypeRef::History(t, _) => format!("History[{}]", canon_type(t)),
116        TypeRef::ValidationError(_) => "ValidationError".to_string(),
117        TypeRef::DecodeError(_) => "DecodeError".to_string(),
118        TypeRef::Unit(_) => "()".to_string(),
119        TypeRef::Fn(params, ret, _) => format!(
120            "({}) -> {}",
121            params.iter().map(canon_type).collect::<Vec<_>>().join(", "),
122            canon_type(ret)
123        ),
124        TypeRef::App { name, args, .. } => format!(
125            "{}[{}]",
126            name.name,
127            args.iter().map(canon_type).collect::<Vec<_>>().join(", ")
128        ),
129    }
130}
131
132/// The outcome of reconciling one event against its (possibly absent)
133/// registry entry.
134enum Reconciled {
135    /// No prior entry: baseline silently at `declared` (the event's current
136    /// `@schema(N)`, or `1`).
137    Baseline { fields: Vec<FieldShape> },
138    /// Shape unchanged since the stored entry.
139    Unchanged {
140        fields: Vec<FieldShape>,
141        stored: i64,
142    },
143    /// Every added field carries a default; nothing removed or retyped.
144    Additive {
145        fields: Vec<FieldShape>,
146        bumped: i64,
147    },
148    /// A field was removed, retyped, added without a default, or lost a
149    /// default it previously had.
150    NonAdditive {
151        removed: Vec<String>,
152        retyped: Vec<String>,
153        added_without_default: Vec<String>,
154        lost_default: Vec<String>,
155    },
156}
157
158fn reconcile_one(current: &[FieldShape], stored: Option<&EventEntry>) -> Reconciled {
159    let Some(stored) = stored else {
160        return Reconciled::Baseline {
161            fields: current.to_vec(),
162        };
163    };
164    if current == stored.fields.as_slice() {
165        return Reconciled::Unchanged {
166            fields: current.to_vec(),
167            stored: stored.schema,
168        };
169    }
170
171    fn by_name(fields: &[FieldShape]) -> BTreeMap<&str, &FieldShape> {
172        fields.iter().map(|f| (f.name.as_str(), f)).collect()
173    }
174    let old = by_name(&stored.fields);
175    let new = by_name(current);
176
177    let removed: Vec<String> = old
178        .keys()
179        .filter(|n| !new.contains_key(*n))
180        .map(|n| n.to_string())
181        .collect();
182    let retyped: Vec<String> = old
183        .iter()
184        .filter_map(|(n, old_field)| {
185            new.get(n)
186                .filter(|new_field| new_field.ty != old_field.ty)
187                .map(|_| n.to_string())
188        })
189        .collect();
190    let added_without_default: Vec<String> = new
191        .iter()
192        .filter(|(n, f)| !old.contains_key(*n) && !f.default)
193        .map(|(n, _)| n.to_string())
194        .collect();
195    // A field present in both, same type, that had a default and no longer
196    // does: an older wire event that omitted this key (relying on the
197    // default) can no longer decode — the same forward-compatibility break
198    // as a field added without one, just approached from the other side.
199    let lost_default: Vec<String> = old
200        .iter()
201        .filter_map(|(n, old_field)| {
202            new.get(n).filter(|new_field| {
203                new_field.ty == old_field.ty && old_field.default && !new_field.default
204            })
205        })
206        .map(|f| f.name.clone())
207        .collect();
208
209    if removed.is_empty()
210        && retyped.is_empty()
211        && added_without_default.is_empty()
212        && lost_default.is_empty()
213    {
214        Reconciled::Additive {
215            fields: current.to_vec(),
216            bumped: stored.schema + 1,
217        }
218    } else {
219        Reconciled::NonAdditive {
220            removed,
221            retyped,
222            lost_default,
223            added_without_default,
224        }
225    }
226}
227
228/// Reconcile every event across every unit against the given registry.
229/// Returns the updated registry document and the effective schema version
230/// for each event, keyed the same way as the document itself
231/// (`<unit>.<EventName>`). Diagnostics for a mismatched `@schema(N)` or a
232/// non-additive change are pushed onto `errors`.
233pub fn reconcile(
234    existing: &SchemaRegistry,
235    unit_tables: &std::collections::HashMap<String, UnitTable>,
236    errors: &mut Vec<CompileError>,
237) -> (SchemaRegistry, std::collections::HashMap<String, i64>) {
238    let mut updated = SchemaRegistry::new();
239    let mut effective = std::collections::HashMap::new();
240
241    let mut units: Vec<_> = unit_tables.iter().collect();
242    units.sort_by_key(|(name, _)| *name);
243
244    for (unit_name, table) in units {
245        let mut events: Vec<_> = table.events.iter().collect();
246        events.sort_by_key(|(name, _)| *name);
247        for (event_name, event) in events {
248            let key = format!("{unit_name}.{event_name}");
249            let fields = snapshot(event);
250            let declared = event.schema_version();
251            let annotation_span = event
252                .annotations
253                .iter()
254                .find(|a| a.name.name == "schema")
255                .map(|a| a.span);
256            let has_annotation = annotation_span.is_some();
257
258            let (effective_version, entry) = match reconcile_one(&fields, existing.get(&key)) {
259                Reconciled::Baseline { fields } => (
260                    declared,
261                    EventEntry {
262                        schema: declared,
263                        fields,
264                    },
265                ),
266                Reconciled::Unchanged { fields, stored } => {
267                    if has_annotation && declared != stored {
268                        errors.push(mismatch_error(
269                            event_name,
270                            annotation_span.unwrap(),
271                            declared,
272                            stored,
273                        ));
274                    }
275                    (
276                        stored,
277                        EventEntry {
278                            schema: stored,
279                            fields,
280                        },
281                    )
282                }
283                Reconciled::Additive { fields, bumped } => {
284                    if has_annotation && declared != bumped {
285                        errors.push(mismatch_error(
286                            event_name,
287                            annotation_span.unwrap(),
288                            declared,
289                            bumped,
290                        ));
291                    }
292                    (
293                        bumped,
294                        EventEntry {
295                            schema: bumped,
296                            fields,
297                        },
298                    )
299                }
300                Reconciled::NonAdditive {
301                    removed,
302                    retyped,
303                    added_without_default,
304                    lost_default,
305                } => {
306                    errors.push(non_additive_error(
307                        event,
308                        event_name,
309                        &removed,
310                        &retyped,
311                        &added_without_default,
312                        &lost_default,
313                    ));
314                    // Keep the old entry as-is: a build that fails here
315                    // must not perturb the registry (`compile_project`
316                    // skips the write on any error too — this just keeps
317                    // the in-memory document consistent with that).
318                    let old = existing
319                        .get(&key)
320                        .expect("a NonAdditive verdict only fires against a stored entry")
321                        .clone();
322                    (old.schema, old)
323                }
324            };
325
326            effective.insert(key.clone(), effective_version);
327            updated.insert(key, entry);
328        }
329    }
330
331    (updated, effective)
332}
333
334fn mismatch_error(
335    event_name: &str,
336    span: bynk_syntax::span::Span,
337    declared: i64,
338    computed: i64,
339) -> CompileError {
340    CompileError::new(
341        "bynk.event.schema_version_mismatch",
342        span,
343        format!(
344            "`{event_name}`'s `@schema({declared})` disagrees with the schema \
345             registry, which computes version {computed} from the event's \
346             build history"
347        ),
348    )
349    .with_note(format!(
350        "update the annotation to `@schema({computed})`, or remove it to let \
351         the compiler track the version automatically"
352    ))
353}
354
355/// The clauses of a non-additive event change, as the diagnostic and the
356/// contract diff (#2467) both word them.
357fn describe_non_additive_event(
358    removed: &[String],
359    retyped: &[String],
360    added_without_default: &[String],
361    lost_default: &[String],
362) -> String {
363    let mut parts = Vec::new();
364    if !removed.is_empty() {
365        parts.push(format!("field(s) removed: {}", removed.join(", ")));
366    }
367    if !retyped.is_empty() {
368        parts.push(format!("field(s) retyped: {}", retyped.join(", ")));
369    }
370    if !added_without_default.is_empty() {
371        parts.push(format!(
372            "field(s) added without a default: {}",
373            added_without_default.join(", ")
374        ));
375    }
376    if !lost_default.is_empty() {
377        parts.push(format!(
378            "field(s) lost their default: {}",
379            lost_default.join(", ")
380        ));
381    }
382    parts.join("; ")
383}
384
385fn non_additive_error(
386    event: &EventDecl,
387    event_name: &str,
388    removed: &[String],
389    retyped: &[String],
390    added_without_default: &[String],
391    lost_default: &[String],
392) -> CompileError {
393    let parts = describe_non_additive_event(removed, retyped, added_without_default, lost_default);
394    CompileError::new(
395        "bynk.event.non_additive_schema_change",
396        event.span,
397        format!(
398            "`{event_name}` changed in a way the schema registry cannot \
399             evolve additively — {parts}"
400        ),
401    )
402    .with_note(
403        "an additive change adds only fields that carry a default; give a \
404         breaking change a new event type name instead",
405    )
406}
407
408// ---------------------------------------------------------------------------
409// State-migrations S0 (#2204; the retired track's summary in
410// `design/archive/retired-tracks.md`, §3.1, §3.4): the agent-state half of the
411// registry. Every agent class's stored shape is
412// recorded per version under `[agents]`, and a change deployed data cannot be
413// read through is refused here, before it can orphan anything.
414// ---------------------------------------------------------------------------
415
416/// The stored shape of one agent class: one [`StoreShape`] per `store` field,
417/// sorted by name (stored state is a JSON object, so order is invisible).
418/// Each type is rendered twice by `contract.rs`'s canonical walk (track
419/// §3.1, #2204 Decision A): structurally, and with refinements.
420fn agent_snapshot(
421    agent: &AgentDecl,
422    types: &std::collections::HashMap<String, std::sync::Arc<bynk_syntax::ast::TypeDecl>>,
423) -> Vec<StoreShape> {
424    let mut fields: Vec<StoreShape> = agent
425        .store_fields
426        .iter()
427        .map(|f| {
428            let (structure, full): (Vec<String>, Vec<String>) = f
429                .kind
430                .args
431                .iter()
432                .map(|a| crate::contract::canon_storage_type(a, types))
433                .unzip();
434            // #2676 (Decision B): one argument roots its paths at the
435            // field's name; a kind with several (`Map[K, V]`) numbers them.
436            let args = &f.kind.args;
437            let paths = args
438                .iter()
439                .enumerate()
440                .flat_map(|(i, a)| {
441                    let root = if args.len() == 1 {
442                        f.name.name.clone()
443                    } else {
444                        format!("{}#{i}", f.name.name)
445                    };
446                    crate::contract::storage_paths(a, &root, types)
447                })
448                .map(|p| PathShape {
449                    refinement: if p.full == p.structure {
450                        String::new()
451                    } else {
452                        p.full
453                    },
454                    path: p.path,
455                    ty: p.structure,
456                    default: p.default,
457                })
458                .collect();
459            StoreShape {
460                name: f.name.name.clone(),
461                kind: f.kind.head.name.clone(),
462                ty: structure.join(", "),
463                refinement: full.join(", "),
464                paths,
465            }
466        })
467        .collect();
468    fields.sort_by(|a, b| a.name.cmp(&b.name));
469    fields
470}
471
472/// How one agent class's live shape relates to its recorded current shape.
473#[derive(Debug, PartialEq, Eq)]
474enum AgentChange {
475    Unchanged,
476    /// Fields added, record fields added with a default inside a stored value
477    /// (#2676), and/or refinements changed with the structure intact.
478    Additive {
479        refined: Vec<String>,
480        /// #2676: what changed inside a stored value, path by path
481        /// ("prefs.size added with a default").
482        nested: Vec<String>,
483    },
484    NonAdditive {
485        removed: Vec<String>,
486        added: Vec<String>,
487        /// A retyped field, with the paths that broke when the lock recorded
488        /// them (`prefs (prefs.size added without a default)`).
489        retyped: Vec<String>,
490        rekinded: Vec<String>,
491        /// #2676 (Decision C): a field was retyped against a snapshot written
492        /// before the lock recorded paths, so the change could not be judged
493        /// path by path.
494        unrecorded: bool,
495    },
496}
497
498/// #2676 (Decision C), per field: a stored field written before the lock
499/// recorded paths (`paths.is_empty()`) takes them from the unchanged
500/// declaration, matched by name, so the next change can be judged path by
501/// path. The structure is the same and defaults were never recorded, so
502/// nothing is invented. A field whose paths are already recorded is never
503/// touched, so a later classifier change cannot silently rewrite history.
504fn backfill_paths(stored: &mut [StoreShape], current: &[StoreShape]) {
505    for f in stored.iter_mut().filter(|f| f.paths.is_empty()) {
506        if let Some(c) = current.iter().find(|c| c.name == f.name) {
507            f.paths = c.paths.clone();
508        }
509    }
510}
511
512fn classify_agent_change(current: &[StoreShape], stored: &[StoreShape]) -> AgentChange {
513    if current == stored {
514        return AgentChange::Unchanged;
515    }
516    let old: BTreeMap<&str, &StoreShape> = stored.iter().map(|f| (f.name.as_str(), f)).collect();
517    let new: BTreeMap<&str, &StoreShape> = current.iter().map(|f| (f.name.as_str(), f)).collect();
518    let mut removed = Vec::new();
519    let mut retyped = Vec::new();
520    let mut rekinded = Vec::new();
521    let mut refined = Vec::new();
522    let mut nested = Vec::new();
523    let mut unrecorded = false;
524    for (name, o) in &old {
525        let Some(n) = new.get(name) else {
526            removed.push(name.to_string());
527            continue;
528        };
529        if n.kind != o.kind {
530            rekinded.push(name.to_string());
531            continue;
532        }
533        if o.paths.is_empty() {
534            // Decision C: no recorded paths, so only the strings can be
535            // compared, as before #2676. An unchanged one is backfilled by the
536            // reconcile.
537            if n.ty != o.ty {
538                retyped.push(name.to_string());
539                unrecorded = true;
540            } else if n.refinement != o.refinement {
541                refined.push(name.to_string());
542            }
543            continue;
544        }
545        let paths = compare_paths(&o.paths, &n.paths);
546        if !paths.problems.is_empty() {
547            retyped.push(format!("{name} ({})", paths.problems.join(", ")));
548            continue;
549        }
550        if n.ty != o.ty && paths.added.is_empty() && paths.variants.is_empty() {
551            // The strings differ but no path explains it: never guess.
552            retyped.push(name.to_string());
553            continue;
554        }
555        nested.extend(
556            paths
557                .added
558                .iter()
559                .map(|p| format!("{p} added with a default")),
560        );
561        nested.extend(paths.gained.iter().map(|p| format!("{p} gained a default")));
562        nested.extend(paths.variants.iter().map(|p| format!("{p} variant added")));
563        // The whole-value strings differ whenever a field is added, so a
564        // refinement change is read position by position.
565        if paths.refined {
566            refined.push(name.to_string());
567        }
568    }
569    let added: Vec<String> = new
570        .keys()
571        .filter(|n| !old.contains_key(*n))
572        .map(|n| n.to_string())
573        .collect();
574    if !removed.is_empty() || !retyped.is_empty() || !rekinded.is_empty() {
575        return AgentChange::NonAdditive {
576            removed,
577            added,
578            retyped,
579            rekinded,
580            unrecorded,
581        };
582    }
583    if added.is_empty() && refined.is_empty() && nested.is_empty() {
584        // Equal but for paths a pre-#2676 snapshot never recorded.
585        return AgentChange::Unchanged;
586    }
587    AgentChange::Additive { refined, nested }
588}
589
590/// #2676: how one stored field's recorded paths relate to its live ones.
591#[derive(Debug, Default, PartialEq, Eq)]
592struct PathChange {
593    /// What makes the change non-additive, one clause per path.
594    problems: Vec<String>,
595    /// The topmost new paths, each a record field that declares a default.
596    added: Vec<String>,
597    /// Existing record fields that gained a default.
598    gained: Vec<String>,
599    /// #2691: the topmost new sum variants. No stored value names one, so each
600    /// is additive, payload fields included.
601    variants: Vec<String>,
602    /// Whether a position both shapes have changed its predicates only.
603    refined: bool,
604}
605
606/// #2676 (Decisions A and E). Every recorded path must still exist with the
607/// same shallow structure, and must not lose its default (a record stored
608/// before the field existed would no longer decode). Every new path must sit
609/// under a new record field that declares a default: that field is absent from
610/// every stored record and decodes to its default, and whatever lies beneath it
611/// comes with it. Anything else (a removed or retyped position, a field added
612/// without a default) is a problem. A new sum variant is additive (#2691): a
613/// value stored before it cannot name it, and a newer record is stopped on
614/// rollback by the `__v` marker.
615fn compare_paths(stored: &[PathShape], live: &[PathShape]) -> PathChange {
616    let old: BTreeMap<&str, &PathShape> = stored.iter().map(|p| (p.path.as_str(), p)).collect();
617    let new: BTreeMap<&str, &PathShape> = live.iter().map(|p| (p.path.as_str(), p)).collect();
618    let mut change = PathChange::default();
619    for (path, o) in &old {
620        match new.get(path) {
621            None => change.problems.push(format!("{path} removed")),
622            Some(n) if n.ty != o.ty => change.problems.push(format!("{path} retyped")),
623            Some(n) if o.default && !n.default => {
624                change.problems.push(format!("{path} lost its default"));
625            }
626            Some(n) => {
627                if !o.default && n.default {
628                    change.gained.push(path.to_string());
629                }
630                if path_refinement(n) != path_refinement(o) {
631                    change.refined = true;
632                }
633            }
634        }
635    }
636    let fresh: Vec<&str> = new
637        .keys()
638        .copied()
639        .filter(|p| !old.contains_key(p))
640        .collect();
641    for path in &fresh {
642        // Only the topmost new position is judged; what lies under it comes
643        // with it.
644        if fresh.iter().any(|q| q != path && is_under(path, q)) {
645            continue;
646        }
647        let node = new[path];
648        if node.default {
649            change.added.push(path.to_string());
650        } else if node.ty == "variant" {
651            change.variants.push(path.to_string());
652        } else {
653            change
654                .problems
655                .push(format!("{path} added without a default"));
656        }
657    }
658    change
659}
660
661/// A path's rendering with predicates kept (recorded only where it differs from
662/// its structure).
663fn path_refinement(p: &PathShape) -> &str {
664    if p.refinement.is_empty() {
665        &p.ty
666    } else {
667        &p.refinement
668    }
669}
670
671/// Whether `path` lies strictly beneath `ancestor`: it extends it at a segment
672/// boundary (`prefs.size` is under `prefs`, `prefs.sizes` is not under
673/// `prefs.size`).
674fn is_under(path: &str, ancestor: &str) -> bool {
675    path.strip_prefix(ancestor)
676        .and_then(|rest| rest.chars().next())
677        .is_some_and(|c| matches!(c, '.' | '[' | '?' | '{' | '|' | '#'))
678}
679
680/// The rename the author most likely made, when it is unambiguous: exactly
681/// one removed field and exactly one added field share a storage kind and a
682/// structure, and neither matches any other candidate. Never applied — only
683/// named in the diagnostic's help (track §3.4: a pairing is never guessed).
684fn unambiguous_rename<'a>(
685    removed: &'a [String],
686    added: &'a [String],
687    stored: &[StoreShape],
688    current: &[StoreShape],
689) -> RenameHint<'a> {
690    let shape_of = |fields: &[StoreShape], name: &str| {
691        fields
692            .iter()
693            .find(|f| f.name == name)
694            .map(|f| (f.kind.clone(), f.ty.clone()))
695    };
696    let mut pairs = Vec::new();
697    let mut ambiguous = false;
698    for r in removed {
699        let r_shape = shape_of(stored, r);
700        let candidates: Vec<&String> = added
701            .iter()
702            .filter(|a| shape_of(current, a) == r_shape)
703            .collect();
704        match candidates.as_slice() {
705            [] => {}
706            [a] => {
707                let rivals = removed
708                    .iter()
709                    .filter(|other| shape_of(stored, other) == r_shape)
710                    .count();
711                if rivals == 1 {
712                    pairs.push((r.as_str(), a.as_str()));
713                } else {
714                    ambiguous = true;
715                }
716            }
717            _ => ambiguous = true,
718        }
719    }
720    match (ambiguous, pairs.as_slice()) {
721        (true, _) => RenameHint::Ambiguous,
722        (false, [one]) => RenameHint::One(one.0, one.1),
723        _ => RenameHint::None,
724    }
725}
726
727#[derive(Debug, PartialEq, Eq)]
728enum RenameHint<'a> {
729    None,
730    One(&'a str, &'a str),
731    Ambiguous,
732}
733
734/// The way past a refusal until the migration slices land (#2204 Decision C).
735/// The toolchain cannot know whether a class was ever deployed — the deploy
736/// ledger records no Durable Object classes (ADR 0194 D1, ADR 0443) — so the
737/// note asks the author.
738fn never_deployed_note(key: &str) -> String {
739    format!(
740        "if this class was never deployed, delete its `[agents.\"{key}\"]` entry from \
741         `bynk.schema.lock` to record the new shape as a fresh baseline; if it was deployed, \
742         widen rather than narrow, or stage the change through a new field (ADR 0124 D3), or \
743         declare a `migrate from N` step that carries the old data forward"
744    )
745}
746
747/// The two facts the emitter needs to stamp and check an agent's stored
748/// state (state-migrations S1, #2211 Decision B): the class's lock `version`,
749/// and the oldest stored version it reads forward without a migration step.
750#[derive(Debug, Clone, PartialEq, Eq)]
751pub struct AgentVersions {
752    pub version: i64,
753    pub oldest_readable: i64,
754    /// State-migrations S2 (#2224 Decision C): each valid `migrate from N`
755    /// step, sorted by `N`.
756    pub steps: Vec<MigrationStep>,
757}
758
759/// What the emitter needs to run one `migrate from N` step (#2224 Decision D).
760#[derive(Debug, Clone, PartialEq, Eq)]
761pub struct MigrationStep {
762    /// The stored versions the step covers: `from` and every older version,
763    /// down to `lo`, whose path to `from` is entirely additive (Decision C).
764    pub lo: i64,
765    pub from: i64,
766    /// Version `from`'s fields the current shape keeps with the same
767    /// structure: carried over as they are.
768    pub carried: Vec<String>,
769    /// Every field version `from` recorded: a stored key outside this set
770    /// (and `__v`) is an unknown key, kept rather than dropped.
771    pub known: Vec<String>,
772    /// The old type's `Map[K, V]` fields that read a store `Map` (persisted as
773    /// a `Record`), rather than a `Cell` holding a map value.
774    pub store_maps: Vec<String>,
775}
776
777/// The storage kinds a migration step can neither read nor assign: they have
778/// no value type (#2224 Decision A).
779fn kind_has_no_value(kind: &str) -> bool {
780    matches!(kind, "Set" | "Log" | "Cache")
781}
782
783/// The fields a step reads off its `old` parameter (`old.f` in its body).
784fn step_reads(step: &MigrateDecl) -> std::collections::BTreeSet<String> {
785    fn walk(e: &Expr, old: &str, out: &mut std::collections::BTreeSet<String>) {
786        if let ExprKind::FieldAccess { receiver, field } = &e.kind
787            && matches!(&receiver.kind, ExprKind::Ident(id) if id.name == old)
788        {
789            out.insert(field.name.clone());
790        }
791        for c in bynk_syntax::ast::expr_children(e) {
792            walk(c, old, out);
793        }
794    }
795    let mut out = std::collections::BTreeSet::new();
796    if let Some(old) = &step.old {
797        for item in &step.items {
798            match item {
799                MigrateItem::Let(l) => walk(&l.value, &old.name.name, &mut out),
800                MigrateItem::Assign(a) => walk(&a.value, &old.name.name, &mut out),
801                MigrateItem::Drop(_) => {}
802            }
803        }
804    }
805    out
806}
807
808/// Check one `migrate from N` step against the lock (#2224 Decisions A, C): its
809/// version is recorded and below the current one, each field of its old type
810/// matches version N's recorded field on structure (refinement-only
811/// differences warn), each `drop` names a real field, and it accounts for
812/// every change from version N to the current shape. Returns whether it holds;
813/// diagnostics go onto `errors`.
814fn check_step(
815    agent: &AgentDecl,
816    step: &MigrateDecl,
817    entry: &AgentEntry,
818    current: &[StoreShape],
819    types: &std::collections::HashMap<String, std::sync::Arc<bynk_syntax::ast::TypeDecl>>,
820    errors: &mut Vec<CompileError>,
821) -> Option<StepPlanParts> {
822    let n = step.from;
823    // State-migrations S4 (#2259 Decision G): a complete sweep raised the
824    // floor past N. Versions are numbered contiguously from 1, so N was
825    // recorded once, but no stored instance can hold it now: the step is dead
826    // code, not an error. Its snapshot was dropped with the floor rise.
827    if n >= 1 && n < entry.floor {
828        errors.push(
829            CompileError::new(
830                "bynk.agent.migrate_below_floor",
831                step.from_span,
832                format!(
833                    "`migrate from {n}`: agent `{}`'s floor is {}, so no stored instance can \
834                     hold version {n}; this step can be deleted",
835                    agent.name.name, entry.floor
836                ),
837            )
838            .with_note("`bynk migrate sweep` raised the floor; the step emits nothing"),
839        );
840        return None;
841    }
842    let Some(snapshot) = entry
843        .shape(n)
844        .filter(|_| n >= entry.floor && n < entry.version)
845    else {
846        errors.push(
847            CompileError::new(
848                "bynk.agent.migrate_unknown_version",
849                step.from_span,
850                format!(
851                    "`migrate from {n}`: the lock records agent `{}` at versions {}..={}, so a \
852                     step can read a version from {} to {}",
853                    agent.name.name,
854                    entry.floor,
855                    entry.version,
856                    entry.floor,
857                    entry.version - 1
858                ),
859            )
860            .with_note("a step reads an older recorded version; the current version needs no step"),
861        );
862        return None;
863    };
864    let stored: BTreeMap<&str, &StoreShape> = snapshot
865        .fields
866        .iter()
867        .map(|f| (f.name.as_str(), f))
868        .collect();
869    let now: BTreeMap<&str, &StoreShape> = current.iter().map(|f| (f.name.as_str(), f)).collect();
870    let mut ok = true;
871    // The old type's fields that read a store `Map` (a `Record` on disk), as
872    // opposed to a `Cell` holding a map value (already in its value wire form).
873    let mut store_maps: Vec<String> = Vec::new();
874
875    // The old type's fields against version N, on structure.
876    if let Some(old) = &step.old
877        && let TypeRef::Named(id) = &old.type_ref
878        && let Some(decl) = types.get(&id.name)
879        && let TypeBody::Record(r) = &decl.body
880    {
881        for f in &r.fields {
882            // A `Map[K, V]` field names either a store `Map` of `K, V` or a
883            // `Cell` whose value is a map: version N's recorded kind decides
884            // (#2243 review). Every other type names a `Cell`.
885            let recorded_kind = stored.get(f.name.name.as_str()).map(|s| s.kind.as_str());
886            let (kind, ty, full) = match &f.type_ref {
887                TypeRef::Map(k, v, _) if recorded_kind != Some("Cell") => {
888                    let (ks, kf) = crate::contract::canon_storage_type(k, types);
889                    let (vs, vf) = crate::contract::canon_storage_type(v, types);
890                    ("Map", format!("{ks}, {vs}"), format!("{kf}, {vf}"))
891                }
892                other => {
893                    let (s, full) = crate::contract::canon_storage_type(other, types);
894                    ("Cell", s, full)
895                }
896            };
897            if kind == "Map" {
898                store_maps.push(f.name.name.clone());
899            }
900            match stored.get(f.name.name.as_str()) {
901                Some(s) if s.kind == kind && s.ty == ty => {
902                    if s.refinement != full {
903                        errors.push(
904                            CompileError::new(
905                                "bynk.agent.refinement_changed",
906                                f.span,
907                                format!(
908                                    "`{}.{}` differs from version {n}'s recorded field only in \
909                                     its refinement",
910                                    id.name, f.name.name
911                                ),
912                            )
913                            .with_note(
914                                "the step still reads the stored value; its output is validated \
915                                 against the current type on load",
916                            ),
917                        );
918                    }
919                }
920                Some(s) => {
921                    ok = false;
922                    errors.push(
923                        CompileError::new(
924                            "bynk.agent.migrate_shape_mismatch",
925                            f.span,
926                            format!(
927                                "`{}.{}` is declared as `{kind}` of `{ty}`, but version {n} \
928                                 recorded it as `{}` of `{}`",
929                                id.name, f.name.name, s.kind, s.ty
930                            ),
931                        )
932                        .with_note(
933                            "declare the old field exactly as version N stored it, \
934                             declaring a copy of any nested type that has changed since",
935                        ),
936                    );
937                }
938                None => {
939                    ok = false;
940                    errors.push(CompileError::new(
941                        "bynk.agent.migrate_shape_mismatch",
942                        f.span,
943                        format!(
944                            "`{}.{}`: agent `{}` had no field `{}` at version {n}",
945                            id.name, f.name.name, agent.name.name, f.name.name
946                        ),
947                    ));
948                }
949            }
950        }
951    }
952
953    let mut dropped = std::collections::BTreeSet::new();
954    let mut assigned = std::collections::BTreeSet::new();
955    for item in &step.items {
956        match item {
957            MigrateItem::Drop(d) => {
958                let name = d.field.name.as_str();
959                if !stored.contains_key(name) && !now.contains_key(name) {
960                    ok = false;
961                    errors.push(CompileError::new(
962                        "bynk.agent.migrate_shape_mismatch",
963                        d.field.span,
964                        format!(
965                            "`drop {name}`: agent `{}` has no field `{name}` at version {n} or now",
966                            agent.name.name
967                        ),
968                    ));
969                }
970                dropped.insert(name.to_string());
971            }
972            MigrateItem::Assign(a) => {
973                assigned.insert(a.target.name.clone());
974            }
975            MigrateItem::Let(_) => {}
976        }
977    }
978    let reads = step_reads(step);
979
980    // Coverage against the current shape (#2224 Decision C).
981    let mut unread: Vec<String> = Vec::new();
982    let mut unassigned: Vec<String> = Vec::new();
983    for (name, s) in &stored {
984        match now.get(name) {
985            None => {
986                if !reads.contains(*name) && !dropped.contains(*name) {
987                    unread.push(name.to_string());
988                }
989            }
990            Some(c) if c.kind != s.kind || c.ty != s.ty => {
991                let no_value = kind_has_no_value(&c.kind) || kind_has_no_value(&s.kind);
992                let covered = assigned.contains(*name) || (no_value && dropped.contains(*name));
993                if !covered {
994                    unassigned.push(name.to_string());
995                }
996            }
997            Some(_) => {}
998        }
999    }
1000    if !unread.is_empty() || !unassigned.is_empty() {
1001        ok = false;
1002        let mut parts = Vec::new();
1003        if !unread.is_empty() {
1004            parts.push(format!(
1005                "removed field(s) neither read (`old.f`) nor dropped: {}",
1006                unread.join(", ")
1007            ));
1008        }
1009        if !unassigned.is_empty() {
1010            parts.push(format!(
1011                "changed field(s) not assigned: {}",
1012                unassigned.join(", ")
1013            ));
1014        }
1015        errors.push(
1016            CompileError::new(
1017                "bynk.agent.migrate_incomplete",
1018                step.keyword.merge(step.from_span),
1019                format!(
1020                    "`migrate from {n}` does not account for every change from version {n} to \
1021                     the current shape — {}",
1022                    parts.join("; ")
1023                ),
1024            )
1025            .with_note(
1026                "read a removed field through `old` or `drop` it; assign a changed field (a \
1027                 `Set`, `Log` or `Cache` field can only be dropped, which starts it afresh)",
1028            ),
1029        );
1030    }
1031    if !ok {
1032        return None;
1033    }
1034    let carried = stored
1035        .iter()
1036        .filter(|(name, s)| {
1037            now.get(*name)
1038                .is_some_and(|c| c.kind == s.kind && c.ty == s.ty)
1039        })
1040        .map(|(name, _)| name.to_string())
1041        .collect();
1042    let known = stored.keys().map(|n| n.to_string()).collect();
1043    Some(StepPlanParts {
1044        carried,
1045        known,
1046        store_maps,
1047    })
1048}
1049
1050/// What a passing [`check_step`] hands to [`MigrationStep`].
1051#[derive(Debug, Clone, Default)]
1052struct StepPlanParts {
1053    carried: Vec<String>,
1054    known: Vec<String>,
1055    store_maps: Vec<String>,
1056}
1057
1058/// Reconcile every agent class across every unit against `existing`, writing
1059/// each class's entry into `updated` (the document [`reconcile`] already
1060/// rebuilt for events). Diagnostics go onto `errors`; a refused change keeps
1061/// the class's stored entry untouched, as a refused event change does.
1062///
1063/// Returns each live class's [`AgentVersions`], keyed `<unit>.<Agent>`, read
1064/// from the *reconciled* entry — so a read-only `check`/`test` reports the
1065/// version the next build will record.
1066pub fn reconcile_agents(
1067    existing: &SchemaRegistry,
1068    updated: &mut SchemaRegistry,
1069    unit_tables: &std::collections::HashMap<String, UnitTable>,
1070    unit_uses: &std::collections::HashMap<String, Vec<String>>,
1071    errors: &mut Vec<CompileError>,
1072) -> std::collections::HashMap<String, AgentVersions> {
1073    let mut versions = std::collections::HashMap::new();
1074    let mut live = std::collections::BTreeSet::new();
1075    // State-migrations S3 (#2248, Decision C): recorded classes a declaration
1076    // accounts for — renamed away, or removed — so they are not reported
1077    // `class_removed` and are not carried forward under their old key.
1078    let mut accounted = std::collections::BTreeSet::new();
1079    let mut units: Vec<_> = unit_tables.iter().collect();
1080    units.sort_by_key(|(name, _)| *name);
1081    for (unit_name, table) in units {
1082        let types = crate::symbols::combined_types_for(unit_name, unit_tables, unit_uses);
1083        // A `removed agent` accounts for its recorded entry, which is dropped.
1084        // A name the lock doesn't record needs nothing: after the build that
1085        // drops it the lock can't tell "already removed" from "never
1086        // recorded", and Cloudflare treats a `deleted` tombstone for a
1087        // namespace that doesn't exist as stale, with no effect.
1088        for r in &table.removed_agents {
1089            let key = format!("{unit_name}.{}", r.name.name);
1090            if existing.get_agent(&key).is_some() {
1091                accounted.insert(key);
1092            }
1093        }
1094        let mut agents: Vec<_> = table.agents.iter().collect();
1095        agents.sort_by_key(|(name, _)| *name);
1096        for (agent_name, agent) in agents {
1097            let key = format!("{unit_name}.{agent_name}");
1098            live.insert(key.clone());
1099            let current = agent_snapshot(agent, &types);
1100            // The step that carries the stored version across this build's
1101            // non-additive change, when one is declared and checked here.
1102            let mut transition_step: Option<(i64, Option<StepPlanParts>)> = None;
1103            // State-migrations S3 (#2248, Decisions B, C): a rename takes the
1104            // old class's recorded history as this class's own.
1105            let mut history = existing.get_agent(&key);
1106            let mut renamed_now: Option<String> = None;
1107            if let Some(old) = &agent.replaces
1108                && !table.agents.contains_key(&old.name)
1109            {
1110                let old_key = format!("{unit_name}.{}", old.name);
1111                match (existing.get_agent(&old_key), history) {
1112                    // Already applied: an earlier build moved the entry here,
1113                    // and the declaration stays until Cloudflare reports its
1114                    // tombstone stale. `renamed_from` tells that apart from a
1115                    // mistyped old name (#2253 review).
1116                    (None, Some(h)) if h.renamed_from.contains(&old.name) => {}
1117                    (None, _) => errors.push(
1118                        CompileError::new(
1119                            "bynk.agent.replaces_unknown",
1120                            old.span,
1121                            format!(
1122                                "agent `{agent_name}` replaces `{}`, but `bynk.schema.lock` \
1123                                 records no class `{old_key}`",
1124                                old.name
1125                            ),
1126                        )
1127                        .with_note(
1128                            "a rename moves a recorded class's data and history; check the old \
1129                             name, and that it was built with this context",
1130                        ),
1131                    ),
1132                    (Some(_), Some(_)) => errors.push(
1133                        CompileError::new(
1134                            "bynk.agent.class_conflict",
1135                            agent.name.span,
1136                            format!(
1137                                "agent `{agent_name}` replaces `{}`, but `{key}` already has its \
1138                                 own recorded history",
1139                                old.name
1140                            ),
1141                        )
1142                        .with_note(
1143                            "renaming onto a recorded class would merge two histories (and \
1144                             Cloudflare refuses a rename onto an existing namespace)",
1145                        ),
1146                    ),
1147                    (Some(old_entry), None) => {
1148                        accounted.insert(old_key);
1149                        history = Some(old_entry);
1150                        renamed_now = Some(old.name.clone());
1151                    }
1152                }
1153            }
1154            let entry = match history {
1155                None => AgentEntry {
1156                    version: 1,
1157                    floor: 1,
1158                    shapes: vec![AgentShape {
1159                        version: 1,
1160                        additive: false,
1161                        fields: current.clone(),
1162                    }],
1163                    renamed_from: Vec::new(),
1164                },
1165                Some(stored_entry) => {
1166                    // `parse` refuses an entry whose `version` names no
1167                    // snapshot (`bynk.project.schema_registry_corrupt`), so
1168                    // there is always one to compare against.
1169                    let stored = stored_entry
1170                        .current()
1171                        .map(|s| s.fields.as_slice())
1172                        .expect("a parsed agent entry has a snapshot at its version");
1173                    match classify_agent_change(&current, stored) {
1174                        AgentChange::Unchanged => {
1175                            // #2676 (Decision C): see `backfill_paths`.
1176                            let mut entry = stored_entry.clone();
1177                            let version = entry.version;
1178                            if let Some(snapshot) =
1179                                entry.shapes.iter_mut().find(|s| s.version == version)
1180                            {
1181                                backfill_paths(&mut snapshot.fields, &current);
1182                            }
1183                            entry
1184                        }
1185                        AgentChange::Additive { refined, .. } => {
1186                            for name in &refined {
1187                                errors.push(refinement_changed_warning(agent, name));
1188                            }
1189                            let mut next = stored_entry.clone();
1190                            next.version += 1;
1191                            next.shapes.push(AgentShape {
1192                                version: next.version,
1193                                additive: true,
1194                                fields: current.clone(),
1195                            });
1196                            next
1197                        }
1198                        AgentChange::NonAdditive {
1199                            removed,
1200                            added,
1201                            retyped,
1202                            rekinded,
1203                            unrecorded,
1204                        } => {
1205                            // State-migrations S2 (#2224 Decision C): a
1206                            // `migrate from <stored version>` step that checks
1207                            // against the lock carries the change.
1208                            let from = stored_entry.version;
1209                            match agent.migrations.iter().find(|m| m.from == from) {
1210                                Some(step) => {
1211                                    let mut probe = stored_entry.clone();
1212                                    probe.version += 1;
1213                                    let plan =
1214                                        check_step(agent, step, &probe, &current, &types, errors);
1215                                    let accepted = plan.is_some();
1216                                    transition_step = Some((from, plan));
1217                                    if accepted {
1218                                        probe.shapes.push(AgentShape {
1219                                            version: probe.version,
1220                                            additive: false,
1221                                            fields: current.clone(),
1222                                        });
1223                                        probe
1224                                    } else {
1225                                        stored_entry.clone()
1226                                    }
1227                                }
1228                                None => {
1229                                    let hint =
1230                                        unambiguous_rename(&removed, &added, stored, &current);
1231                                    let mut err = non_additive_state_error(
1232                                        agent, &key, from, stored, &removed, &retyped, &rekinded,
1233                                        &hint,
1234                                    );
1235                                    if unrecorded {
1236                                        err = err.with_note(
1237                                            "this lock predates per-path shapes, so a change \
1238                                             inside a stored value can't be judged field by \
1239                                             field: build once with the definition the lock \
1240                                             records, before this change, so the lock records \
1241                                             which fields have defaults; a record field added \
1242                                             with a default is then additive",
1243                                        );
1244                                    }
1245                                    errors.push(err);
1246                                    stored_entry.clone()
1247                                }
1248                            }
1249                        }
1250                    }
1251                }
1252            };
1253            // A rename applied by this build is remembered on the entry.
1254            let mut entry = entry;
1255            if let Some(old) = renamed_now
1256                && !entry.renamed_from.contains(&old)
1257            {
1258                entry.renamed_from.push(old);
1259            }
1260            // Every other step is checked against the reconciled entry and
1261            // the current shape; each valid one covers a range of versions.
1262            let mut steps = Vec::new();
1263            for step in &agent.migrations {
1264                let plan = match &transition_step {
1265                    Some((from, parts)) if *from == step.from => {
1266                        parts.clone().filter(|_| entry.version > step.from)
1267                    }
1268                    _ => check_step(agent, step, &entry, &current, &types, errors),
1269                };
1270                if let Some(parts) = plan {
1271                    steps.push(MigrationStep {
1272                        lo: entry.oldest_readable_to(step.from),
1273                        from: step.from,
1274                        carried: parts.carried,
1275                        known: parts.known,
1276                        store_maps: parts.store_maps,
1277                    });
1278                }
1279            }
1280            steps.sort_by_key(|s| s.from);
1281            let oldest_readable = entry.oldest_readable();
1282            for v in entry.floor..entry.version {
1283                let covered =
1284                    v >= oldest_readable || steps.iter().any(|s| s.lo <= v && v <= s.from);
1285                if !covered {
1286                    errors.push(
1287                        CompileError::new(
1288                            "bynk.agent.version_without_path",
1289                            agent.name.span,
1290                            format!(
1291                                "agent `{}`'s stored version {v} has no path to version {}: no \
1292                                 `migrate` step covers it, and its changes since were not all \
1293                                 additive",
1294                                agent.name.name, entry.version
1295                            ),
1296                        )
1297                        .with_note(format!(
1298                            "a stored record at version {v} faults on load (`NoMigrationPath`); \
1299                             add a `migrate from {v}` step, or ignore this if no instance can \
1300                             still hold it"
1301                        )),
1302                    );
1303                }
1304            }
1305            versions.insert(
1306                key.clone(),
1307                AgentVersions {
1308                    version: entry.version,
1309                    oldest_readable,
1310                    steps,
1311                },
1312            );
1313            updated.insert_agent(key, entry);
1314        }
1315    }
1316
1317    for (key, entry) in existing.agents() {
1318        if live.contains(key) || accounted.contains(key) {
1319            continue;
1320        }
1321        errors.push(
1322            CompileError::new(
1323                "bynk.agent.class_removed",
1324                Span::default(),
1325                format!(
1326                    "agent class `{key}` is recorded in `bynk.schema.lock` but no longer \
1327                     declared — a deployment's stored instances of it would be orphaned"
1328                ),
1329            )
1330            .with_note(format!(
1331                "declare what became of it: `agent New replaces {class}` renames it (its data \
1332                 moves), `removed agent {class}` deletes its data; if `{key}` was never \
1333                 deployed, you can instead delete its `[agents.\"{key}\"]` entry from \
1334                 `bynk.schema.lock`",
1335                class = key.rsplit('.').next().unwrap_or(key)
1336            )),
1337        );
1338        updated.insert_agent(key.clone(), entry.clone());
1339    }
1340    versions
1341}
1342
1343// ---------------------------------------------------------------------------
1344// #2467: the contract diff. What the editor lists as "every boundary change
1345// since the lock" is not a second classifier: events go through
1346// [`reconcile_one`] and agents through [`classify_agent_change`] and
1347// [`reconcile_agents`] themselves, the functions `bynk check`, the deploy
1348// build and the lock refresh run (ADR 0491's gate and `reconcile` share the
1349// one meaning of "breaking"). This module only reports their verdicts.
1350// ---------------------------------------------------------------------------
1351
1352/// What kind of boundary type a [`BoundaryChange`] is about.
1353#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
1354pub enum ChangeKind {
1355    Event,
1356    Agent,
1357}
1358
1359/// The classifier's verdict on one change since the lock.
1360#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1361pub enum ChangeClass {
1362    /// A build accepts it and the lock refresh records the next version
1363    /// (additive, or carried by a declared `migrate from N` step).
1364    Compatible,
1365    /// A build refuses it: `bynk check` reports the non-additive diagnostic.
1366    Breaking,
1367}
1368
1369/// One event or agent class whose live shape differs from `bynk.schema.lock`.
1370#[derive(Debug, Clone, PartialEq, Eq)]
1371pub struct BoundaryChange {
1372    pub kind: ChangeKind,
1373    /// The declaring unit.
1374    pub unit: String,
1375    /// The event or agent class name.
1376    pub name: String,
1377    pub class: ChangeClass,
1378    /// The schema version (event) or state version (agent) the lock records.
1379    pub locked_version: i64,
1380    /// The change, in the diagnostic's words.
1381    pub detail: String,
1382}
1383
1384/// Every event and agent class in `unit_tables` whose shape differs from
1385/// `existing`, classified. Unchanged and not-yet-recorded types are omitted
1386/// (a type the lock does not record is a baseline, not a change). Sorted by
1387/// kind, then qualified name.
1388pub fn diff_against_lock(
1389    existing: &SchemaRegistry,
1390    unit_tables: &std::collections::HashMap<String, UnitTable>,
1391    unit_uses: &std::collections::HashMap<String, Vec<String>>,
1392) -> Vec<BoundaryChange> {
1393    let mut out = Vec::new();
1394
1395    for (unit_name, table) in unit_tables {
1396        for (event_name, event) in &table.events {
1397            let key = format!("{unit_name}.{event_name}");
1398            let Some(stored) = existing.get(&key) else {
1399                continue;
1400            };
1401            let current = snapshot(event);
1402            let (class, detail) = match reconcile_one(&current, Some(stored)) {
1403                Reconciled::Baseline { .. } | Reconciled::Unchanged { .. } => continue,
1404                Reconciled::Additive { .. } => {
1405                    let old: Vec<&str> = stored.fields.iter().map(|f| f.name.as_str()).collect();
1406                    let added: Vec<&str> = current
1407                        .iter()
1408                        .map(|f| f.name.as_str())
1409                        .filter(|n| !old.contains(n))
1410                        .collect();
1411                    // Additive also covers a reorder and a field gaining a
1412                    // default, where nothing is added.
1413                    let detail = if added.is_empty() {
1414                        "changed additively (a field gained a default, or fields were reordered)"
1415                            .to_string()
1416                    } else {
1417                        format!("field(s) added with a default: {}", added.join(", "))
1418                    };
1419                    (ChangeClass::Compatible, detail)
1420                }
1421                Reconciled::NonAdditive {
1422                    removed,
1423                    retyped,
1424                    added_without_default,
1425                    lost_default,
1426                } => (
1427                    ChangeClass::Breaking,
1428                    describe_non_additive_event(
1429                        &removed,
1430                        &retyped,
1431                        &added_without_default,
1432                        &lost_default,
1433                    ),
1434                ),
1435            };
1436            out.push(BoundaryChange {
1437                kind: ChangeKind::Event,
1438                unit: unit_name.clone(),
1439                name: event_name.clone(),
1440                class,
1441                locked_version: stored.schema,
1442                detail,
1443            });
1444        }
1445    }
1446
1447    // Agents: the real reconcile decides whether a build would accept the
1448    // change (an additive one, or one a `migrate from N` step carries, bumps
1449    // the version); the diagnostics it would raise are discarded.
1450    let mut scratch = SchemaRegistry::new();
1451    let mut ignored = Vec::new();
1452    reconcile_agents(existing, &mut scratch, unit_tables, unit_uses, &mut ignored);
1453    for (unit_name, table) in unit_tables {
1454        let types = crate::symbols::combined_types_for(unit_name, unit_tables, unit_uses);
1455        for (agent_name, agent) in &table.agents {
1456            let key = format!("{unit_name}.{agent_name}");
1457            let Some(stored_entry) = existing.get_agent(&key) else {
1458                continue;
1459            };
1460            let Some(stored) = stored_entry.current() else {
1461                continue;
1462            };
1463            let current = agent_snapshot(agent, &types);
1464            let change = classify_agent_change(&current, &stored.fields);
1465            if change == AgentChange::Unchanged {
1466                continue;
1467            }
1468            let advanced = scratch
1469                .get_agent(&key)
1470                .is_some_and(|e| e.version > stored_entry.version);
1471            let (class, detail) = match change {
1472                AgentChange::Unchanged => continue,
1473                AgentChange::Additive { nested, .. } => (
1474                    ChangeClass::Compatible,
1475                    // #2676 (Decision G): name what changed inside a value.
1476                    if nested.is_empty() {
1477                        "stored state changed additively".to_string()
1478                    } else {
1479                        format!("stored state changed additively ({})", nested.join(", "))
1480                    },
1481                ),
1482                AgentChange::NonAdditive {
1483                    removed,
1484                    retyped,
1485                    rekinded,
1486                    ..
1487                } => {
1488                    let mut parts = Vec::new();
1489                    if !removed.is_empty() {
1490                        parts.push(format!("field(s) removed: {}", removed.join(", ")));
1491                    }
1492                    if !retyped.is_empty() {
1493                        parts.push(format!("field(s) retyped: {}", retyped.join(", ")));
1494                    }
1495                    if !rekinded.is_empty() {
1496                        parts.push(format!(
1497                            "field(s) changed storage kind: {}",
1498                            rekinded.join(", ")
1499                        ));
1500                    }
1501                    if advanced {
1502                        parts.push("carried by a `migrate` step".to_string());
1503                        (ChangeClass::Compatible, parts.join("; "))
1504                    } else {
1505                        (ChangeClass::Breaking, parts.join("; "))
1506                    }
1507                }
1508            };
1509            out.push(BoundaryChange {
1510                kind: ChangeKind::Agent,
1511                unit: unit_name.clone(),
1512                name: agent_name.clone(),
1513                class,
1514                locked_version: stored_entry.version,
1515                detail,
1516            });
1517        }
1518    }
1519
1520    // A recorded class no declaration accounts for: the real reconcile
1521    // reports `bynk.agent.class_removed`.
1522    for (key, entry) in existing.agents() {
1523        let live = unit_tables
1524            .iter()
1525            .any(|(u, t)| t.agents.keys().any(|a| format!("{u}.{a}") == *key));
1526        if live
1527            || !ignored.iter().any(|e| {
1528                e.category == "bynk.agent.class_removed" && e.message.contains(&format!("`{key}`"))
1529            })
1530        {
1531            continue;
1532        }
1533        let (unit, name) = key.rsplit_once('.').unwrap_or(("", key));
1534        out.push(BoundaryChange {
1535            kind: ChangeKind::Agent,
1536            unit: unit.to_string(),
1537            name: name.to_string(),
1538            class: ChangeClass::Breaking,
1539            locked_version: entry.version,
1540            detail: "recorded in the lock but no longer declared".to_string(),
1541        });
1542    }
1543
1544    out.sort_by(|a, b| (a.kind, &a.unit, &a.name).cmp(&(b.kind, &b.unit, &b.name)));
1545    out
1546}
1547
1548fn refinement_changed_warning(agent: &AgentDecl, field: &str) -> CompileError {
1549    let span = agent
1550        .store_fields
1551        .iter()
1552        .find(|f| f.name.name == field)
1553        .map_or(agent.name.span, |f| f.span);
1554    CompileError::new(
1555        "bynk.agent.refinement_changed",
1556        span,
1557        format!(
1558            "the refinement on `{}.{field}`'s stored type changed; a stored value that no \
1559             longer satisfies it faults on load (`RehydrationViolation`)",
1560            agent.name.name
1561        ),
1562    )
1563    .with_note(
1564        "widening a refinement is safe; if this narrows it, migrate the stored data before \
1565         deploying",
1566    )
1567}
1568
1569#[allow(clippy::too_many_arguments)]
1570fn non_additive_state_error(
1571    agent: &AgentDecl,
1572    key: &str,
1573    stored_version: i64,
1574    stored_fields: &[StoreShape],
1575    removed: &[String],
1576    retyped: &[String],
1577    rekinded: &[String],
1578    hint: &RenameHint<'_>,
1579) -> CompileError {
1580    let mut parts = Vec::new();
1581    if !removed.is_empty() {
1582        parts.push(format!("field(s) removed: {}", removed.join(", ")));
1583    }
1584    if !retyped.is_empty() {
1585        parts.push(format!("field(s) retyped: {}", retyped.join(", ")));
1586    }
1587    if !rekinded.is_empty() {
1588        parts.push(format!(
1589            "field(s) changed storage kind: {}",
1590            rekinded.join(", ")
1591        ));
1592    }
1593    let mut err = CompileError::new(
1594        "bynk.agent.non_additive_state_change",
1595        agent.name.span,
1596        format!(
1597            "agent `{}`'s stored state changed in a way deployed data cannot be read \
1598             through — {}",
1599            agent.name.name,
1600            parts.join("; ")
1601        ),
1602    );
1603    match hint {
1604        RenameHint::One(from, to) => {
1605            err = err.with_note(format!(
1606                "`{from}` was removed and `{to}` added with the same stored shape: if this \
1607                 is a rename, deployed `{from}` values are not carried over to `{to}` — they \
1608                 would read as `{to}`'s zero"
1609            ));
1610            // State-migrations S2 (#2224): name the step that carries it. A
1611            // `Cell` whose stored type is a plain name spells the old type
1612            // exactly; anything structural is described instead.
1613            let old_ty = format!("{}V{stored_version}", agent.name.name);
1614            let shape = stored_fields.iter().find(|f| f.name == *from);
1615            err = err.with_note(match shape {
1616                Some(s) if s.kind == "Cell" && s.ty.chars().all(|c| c.is_alphanumeric()) => {
1617                    format!(
1618                        "to carry it, declare `type {old_ty} = {{ {from}: {} }}` and add \
1619                     `migrate from {stored_version} (old: {old_ty}) {{ {to} := old.{from} }}` to \
1620                     the agent",
1621                        s.ty
1622                    )
1623                }
1624                _ => format!(
1625                    "to carry it, declare a record type `{old_ty}` with `{from}` as version \
1626                     {stored_version} stored it, and add `migrate from {stored_version} (old: \
1627                     {old_ty}) {{ {to} := old.{from} }}` to the agent"
1628                ),
1629            });
1630        }
1631        RenameHint::Ambiguous => {
1632            err = err.with_note(
1633                "several removed and added fields share a stored shape, so which became \
1634                 which cannot be inferred; it will have to be declared",
1635            );
1636        }
1637        RenameHint::None => {}
1638    }
1639    err.with_note(never_deployed_note(key))
1640}
1641
1642#[cfg(test)]
1643mod path_tests {
1644    use super::*;
1645
1646    fn at(path: &str, ty: &str, default: bool) -> PathShape {
1647        PathShape {
1648            path: path.to_string(),
1649            ty: ty.to_string(),
1650            default,
1651            refinement: String::new(),
1652        }
1653    }
1654
1655    #[test]
1656    fn is_under_needs_a_segment_boundary() {
1657        assert!(is_under("prefs.size", "prefs"));
1658        assert!(is_under("items[].note", "items"));
1659        assert!(is_under("byId#1.label", "byId"));
1660        assert!(is_under("last?|Added.sku", "last?|Added"));
1661        assert!(!is_under("prefs.sizes", "prefs.size"));
1662        assert!(!is_under("prefs", "prefs"));
1663    }
1664
1665    #[test]
1666    fn only_a_topmost_new_defaulted_field_is_additive() {
1667        let old = [at("p", "{}", false), at("p.theme", "String", false)];
1668        let added = [
1669            at("p", "{}", false),
1670            at("p.extra", "{}", true),
1671            at("p.extra.note", "String", false),
1672            at("p.theme", "String", false),
1673        ];
1674        let change = compare_paths(&old, &added);
1675        assert!(change.problems.is_empty(), "{change:?}");
1676        assert_eq!(change.added, ["p.extra"]);
1677
1678        let undefaulted = [
1679            at("p", "{}", false),
1680            at("p.dark", "Bool", false),
1681            at("p.theme", "String", false),
1682        ];
1683        assert_eq!(
1684            compare_paths(&old, &undefaulted).problems,
1685            ["p.dark added without a default"]
1686        );
1687    }
1688
1689    #[test]
1690    fn removal_retype_lost_default_and_a_variant_are_problems() {
1691        let old = [
1692            at("p", "{}", false),
1693            at("p.size", "Int", true),
1694            at("p.theme", "String", false),
1695        ];
1696        let new = [at("p", "{}", false), at("p.size", "String", false)];
1697        assert_eq!(
1698            compare_paths(&old, &new).problems,
1699            ["p.size retyped", "p.theme removed"]
1700        );
1701        let lost = [
1702            at("p", "{}", false),
1703            at("p.size", "Int", false),
1704            at("p.theme", "String", false),
1705        ];
1706        assert_eq!(
1707            compare_paths(&old, &lost).problems,
1708            ["p.size lost its default"]
1709        );
1710    }
1711
1712    #[test]
1713    fn a_new_variant_is_additive_but_a_removed_one_is_not() {
1714        let sum = [at("e", "|", false), at("e|A", "variant", false)];
1715        let more = [
1716            at("e", "|", false),
1717            at("e|A", "variant", false),
1718            at("e|B", "variant", false),
1719            at("e|B.sku", "String", false),
1720        ];
1721        let change = compare_paths(&sum, &more);
1722        assert!(change.problems.is_empty(), "{change:?}");
1723        assert_eq!(change.variants, ["e|B"]);
1724        // Removal (and so a rename) stays refused.
1725        assert_eq!(
1726            compare_paths(&more, &sum).problems,
1727            ["e|B removed", "e|B.sku removed"]
1728        );
1729        // An existing variant gaining a payload field stays refused.
1730        let grown = [
1731            at("e", "|", false),
1732            at("e|A", "variant", false),
1733            at("e|A.x", "Int", false),
1734        ];
1735        assert_eq!(
1736            compare_paths(&sum, &grown).problems,
1737            ["e|A.x added without a default"]
1738        );
1739        // The accepted variant is recorded, so the change bumps the version.
1740        let old = vec![store("|", sum.to_vec())];
1741        let new = vec![store("|", more.to_vec())];
1742        match classify_agent_change(&new, &old) {
1743            AgentChange::Additive { nested, .. } => assert_eq!(nested, ["e|B variant added"]),
1744            other => panic!("expected Additive, got {other:?}"),
1745        }
1746    }
1747
1748    fn store(ty: &str, paths: Vec<PathShape>) -> StoreShape {
1749        StoreShape {
1750            name: "p".to_string(),
1751            kind: "Cell".to_string(),
1752            ty: ty.to_string(),
1753            refinement: String::new(),
1754            paths,
1755        }
1756    }
1757
1758    #[test]
1759    fn backfill_leaves_a_recorded_snapshot_with_reordered_paths_alone() {
1760        // #2688: the paths come back in another order, which classifies as
1761        // Unchanged; the stored bytes must not be rewritten.
1762        let a = vec![at("p", "{}", false), at("p.size", "Int", false)];
1763        let b = vec![at("p.size", "Int", false), at("p", "{}", false)];
1764        let stored = vec![store("{size: Int}", a)];
1765        let current = vec![store("{size: Int}", b)];
1766        assert_eq!(
1767            classify_agent_change(&current, &stored),
1768            AgentChange::Unchanged
1769        );
1770        let mut after = stored.clone();
1771        backfill_paths(&mut after, &current);
1772        assert_eq!(after, stored);
1773    }
1774
1775    #[test]
1776    fn backfill_fills_only_the_field_with_no_recorded_paths() {
1777        let recorded = vec![at("p", "{}", false), at("p.size", "Int", false)];
1778        let reordered = vec![at("p.size", "Int", false), at("p", "{}", false)];
1779        let mut old = store("{size: Int}", recorded.clone());
1780        old.name = "p".to_string();
1781        let mut legacy = store("Int", Vec::new());
1782        legacy.name = "q".to_string();
1783        let mut cur_p = store("{size: Int}", reordered);
1784        cur_p.name = "p".to_string();
1785        let mut cur_q = store("Int", vec![at("q", "Int", false)]);
1786        cur_q.name = "q".to_string();
1787        let mut stored = vec![old, legacy];
1788        backfill_paths(&mut stored, &[cur_p, cur_q]);
1789        assert_eq!(stored[0].paths, recorded, "recorded field untouched");
1790        assert_eq!(stored[1].paths, [at("q", "Int", false)]);
1791    }
1792
1793    #[test]
1794    fn a_type_string_difference_no_path_explains_is_refused() {
1795        // #2688: the recorded paths agree, yet the structure strings differ.
1796        // Never guess: the change is non-additive.
1797        let paths = vec![at("p", "{}", false), at("p.size", "Int", false)];
1798        let old = [store("{size: Int}", paths.clone())];
1799        let new = [store("{size: Int, ghost: Int}", paths)];
1800        match classify_agent_change(&new, &old) {
1801            AgentChange::NonAdditive { retyped, .. } => assert_eq!(retyped, ["p"]),
1802            other => panic!("expected NonAdditive, got {other:?}"),
1803        }
1804    }
1805}
1806
1807#[cfg(test)]
1808mod tests {
1809    use super::*;
1810    use bynk_syntax::ast::{
1811        Annotation, AnnotationArg, BaseType, Expr, ExprId, ExprKind, Ident, RecordBody, Trivia,
1812    };
1813    use bynk_syntax::span::Span;
1814    use std::collections::HashMap as StdHashMap;
1815
1816    fn ident(name: &str) -> Ident {
1817        Ident {
1818            name: name.to_string(),
1819            span: Span::default(),
1820        }
1821    }
1822
1823    fn int_lit(value: i64) -> Expr {
1824        Expr {
1825            id: ExprId::SYNTHETIC,
1826            kind: ExprKind::IntLit {
1827                value,
1828                lexeme: value.to_string(),
1829            },
1830            span: Span::default(),
1831        }
1832    }
1833
1834    fn field(name: &str, ty: TypeRef, has_default: bool) -> bynk_syntax::ast::RecordField {
1835        bynk_syntax::ast::RecordField {
1836            annotations: Vec::new(),
1837            documentation: None,
1838            trivia: Default::default(),
1839            name: ident(name),
1840            type_ref: ty,
1841            refinement: None,
1842            init: has_default.then(|| int_lit(0)),
1843            span: Span::default(),
1844        }
1845    }
1846
1847    fn schema_annotation(n: i64) -> Annotation {
1848        Annotation {
1849            name: ident("schema"),
1850            args: vec![AnnotationArg {
1851                label: None,
1852                value: int_lit(n),
1853                span: Span::default(),
1854                from_const: None,
1855            }],
1856            span: Span::default(),
1857        }
1858    }
1859
1860    fn event(
1861        name: &str,
1862        annotations: Vec<Annotation>,
1863        fields: Vec<bynk_syntax::ast::RecordField>,
1864    ) -> EventDecl {
1865        EventDecl {
1866            name: ident(name),
1867            annotations,
1868            body: RecordBody {
1869                trailing_comments: Default::default(),
1870                fields,
1871                span: Span::default(),
1872            },
1873            documentation: None,
1874            span: Span::default(),
1875            trivia: Trivia::default(),
1876        }
1877    }
1878
1879    fn int_ty() -> TypeRef {
1880        TypeRef::Base(BaseType::Int, Span::default())
1881    }
1882    fn string_ty() -> TypeRef {
1883        TypeRef::Base(BaseType::String, Span::default())
1884    }
1885
1886    fn shape(name: &str, ty: &str, default: bool) -> FieldShape {
1887        FieldShape {
1888            name: name.to_string(),
1889            ty: ty.to_string(),
1890            default,
1891        }
1892    }
1893
1894    // -- canon_type -----------------------------------------------------
1895
1896    #[test]
1897    fn canon_type_renders_base_and_generic_shapes() {
1898        assert_eq!(canon_type(&int_ty()), "Int");
1899        assert_eq!(
1900            canon_type(&TypeRef::Option(Box::new(string_ty()), Span::default())),
1901            "Option[String]"
1902        );
1903        assert_eq!(
1904            canon_type(&TypeRef::List(Box::new(int_ty()), Span::default())),
1905            "List[Int]"
1906        );
1907    }
1908
1909    // -- reconcile_one ----------------------------------------------------
1910
1911    #[test]
1912    fn no_entry_baselines_silently() {
1913        let current = vec![shape("orderId", "String", false)];
1914        match reconcile_one(&current, None) {
1915            Reconciled::Baseline { fields } => assert_eq!(fields, current),
1916            _ => panic!("expected Baseline"),
1917        }
1918    }
1919
1920    #[test]
1921    fn unchanged_shape_keeps_stored_version() {
1922        let current = vec![shape("orderId", "String", false)];
1923        let stored = EventEntry {
1924            schema: 2,
1925            fields: current.clone(),
1926        };
1927        match reconcile_one(&current, Some(&stored)) {
1928            Reconciled::Unchanged { stored: v, .. } => assert_eq!(v, 2),
1929            _ => panic!("expected Unchanged"),
1930        }
1931    }
1932
1933    #[test]
1934    fn additive_field_with_default_bumps_version() {
1935        let old = vec![shape("orderId", "String", false)];
1936        let new = vec![
1937            shape("orderId", "String", false),
1938            shape("region", "Region", true),
1939        ];
1940        let stored = EventEntry {
1941            schema: 1,
1942            fields: old,
1943        };
1944        match reconcile_one(&new, Some(&stored)) {
1945            Reconciled::Additive { bumped, .. } => assert_eq!(bumped, 2),
1946            _ => panic!("expected Additive"),
1947        }
1948    }
1949
1950    #[test]
1951    fn field_removed_is_non_additive() {
1952        let old = vec![
1953            shape("orderId", "String", false),
1954            shape("region", "Region", false),
1955        ];
1956        let new = vec![shape("orderId", "String", false)];
1957        let stored = EventEntry {
1958            schema: 1,
1959            fields: old,
1960        };
1961        match reconcile_one(&new, Some(&stored)) {
1962            Reconciled::NonAdditive { removed, .. } => {
1963                assert_eq!(removed, vec!["region".to_string()])
1964            }
1965            _ => panic!("expected NonAdditive"),
1966        }
1967    }
1968
1969    #[test]
1970    fn field_retyped_is_non_additive() {
1971        let old = vec![shape("orderId", "String", false)];
1972        let new = vec![shape("orderId", "Int", false)];
1973        let stored = EventEntry {
1974            schema: 1,
1975            fields: old,
1976        };
1977        match reconcile_one(&new, Some(&stored)) {
1978            Reconciled::NonAdditive { retyped, .. } => {
1979                assert_eq!(retyped, vec!["orderId".to_string()])
1980            }
1981            _ => panic!("expected NonAdditive"),
1982        }
1983    }
1984
1985    #[test]
1986    fn field_added_without_default_is_non_additive() {
1987        let old = vec![shape("orderId", "String", false)];
1988        let new = vec![
1989            shape("orderId", "String", false),
1990            shape("region", "Region", false),
1991        ];
1992        let stored = EventEntry {
1993            schema: 1,
1994            fields: old,
1995        };
1996        match reconcile_one(&new, Some(&stored)) {
1997            Reconciled::NonAdditive {
1998                added_without_default,
1999                ..
2000            } => assert_eq!(added_without_default, vec!["region".to_string()]),
2001            _ => panic!("expected NonAdditive"),
2002        }
2003    }
2004
2005    #[test]
2006    fn a_field_losing_its_default_is_non_additive() {
2007        // An older wire event that omitted `region` (relying on the default)
2008        // could no longer decode once the default is gone — the same
2009        // forward-compatibility break as adding a field without one, from
2010        // the other direction.
2011        let old = vec![
2012            shape("orderId", "String", false),
2013            shape("region", "String", true),
2014        ];
2015        let new = vec![
2016            shape("orderId", "String", false),
2017            shape("region", "String", false),
2018        ];
2019        let stored = EventEntry {
2020            schema: 1,
2021            fields: old,
2022        };
2023        match reconcile_one(&new, Some(&stored)) {
2024            Reconciled::NonAdditive { lost_default, .. } => {
2025                assert_eq!(lost_default, vec!["region".to_string()])
2026            }
2027            _ => panic!("expected NonAdditive"),
2028        }
2029    }
2030
2031    // -- reconcile (full pipeline, with real EventDecls) -------------------
2032
2033    fn table_with(events: Vec<(&str, EventDecl)>) -> UnitTable {
2034        UnitTable {
2035            exec_plan: Default::default(),
2036            kind: None,
2037            removed_agents: Vec::new(),
2038            types: StdHashMap::new(),
2039            fns: StdHashMap::new(),
2040            methods: StdHashMap::new(),
2041            capabilities: StdHashMap::new(),
2042            providers: StdHashMap::new(),
2043            services: StdHashMap::new(),
2044            agents: StdHashMap::new(),
2045            actors: StdHashMap::new(),
2046            exported_capabilities: Default::default(),
2047            events: events
2048                .into_iter()
2049                .map(|(n, e)| (n.to_string(), e))
2050                .collect(),
2051            flattened_caps: StdHashMap::new(),
2052            consumed_type_aliases: StdHashMap::new(),
2053            unselected_consumed_types: Default::default(),
2054            unlisted_consumed_types: Default::default(),
2055            assets: StdHashMap::new(),
2056            embeds: StdHashMap::new(),
2057            consts: StdHashMap::new(),
2058            derived: StdHashMap::new(),
2059        }
2060    }
2061
2062    #[test]
2063    fn diff_against_lock_describes_an_additive_change_that_adds_no_field() {
2064        // `region` gains a default: `Additive` to the classifier, but no
2065        // field is added, so the detail must not claim one.
2066        let e = event(
2067            "Paid",
2068            vec![],
2069            vec![
2070                field("orderId", string_ty(), false),
2071                field("region", string_ty(), true),
2072            ],
2073        );
2074        let mut units = StdHashMap::new();
2075        units.insert("shop.order".to_string(), table_with(vec![("Paid", e)]));
2076        let mut existing = SchemaRegistry::new();
2077        existing.insert(
2078            "shop.order.Paid".to_string(),
2079            EventEntry {
2080                schema: 1,
2081                fields: vec![
2082                    shape("orderId", "String", false),
2083                    shape("region", "String", false),
2084                ],
2085            },
2086        );
2087        let diff = diff_against_lock(&existing, &units, &StdHashMap::new());
2088        assert_eq!(diff.len(), 1);
2089        assert_eq!(diff[0].class, ChangeClass::Compatible);
2090        assert!(
2091            !diff[0].detail.ends_with(": "),
2092            "no dangling field list: {}",
2093            diff[0].detail
2094        );
2095    }
2096
2097    #[test]
2098    fn reconcile_baselines_a_brand_new_event_at_its_declared_annotation() {
2099        let e = event(
2100            "PaymentConfirmed",
2101            vec![schema_annotation(3)],
2102            vec![field("orderId", string_ty(), false)],
2103        );
2104        let mut units = StdHashMap::new();
2105        units.insert(
2106            "commerce.order".to_string(),
2107            table_with(vec![("PaymentConfirmed", e)]),
2108        );
2109        let existing = SchemaRegistry::new();
2110        let mut errors = Vec::new();
2111        let (updated, effective) = reconcile(&existing, &units, &mut errors);
2112        assert!(errors.is_empty(), "a first-ever compile must not error");
2113        assert_eq!(effective.get("commerce.order.PaymentConfirmed"), Some(&3));
2114        assert_eq!(
2115            updated
2116                .get("commerce.order.PaymentConfirmed")
2117                .unwrap()
2118                .schema,
2119            3
2120        );
2121    }
2122
2123    #[test]
2124    fn reconcile_rejects_a_mismatched_schema_annotation_on_an_unchanged_event() {
2125        let e = event(
2126            "PaymentConfirmed",
2127            vec![schema_annotation(5)],
2128            vec![field("orderId", string_ty(), false)],
2129        );
2130        let mut units = StdHashMap::new();
2131        units.insert(
2132            "commerce.order".to_string(),
2133            table_with(vec![("PaymentConfirmed", e)]),
2134        );
2135        let mut existing = SchemaRegistry::new();
2136        existing.insert(
2137            "commerce.order.PaymentConfirmed".to_string(),
2138            EventEntry {
2139                schema: 2,
2140                fields: vec![shape("orderId", "String", false)],
2141            },
2142        );
2143        let mut errors = Vec::new();
2144        let (_, effective) = reconcile(&existing, &units, &mut errors);
2145        assert_eq!(errors.len(), 1);
2146        assert_eq!(errors[0].category, "bynk.event.schema_version_mismatch");
2147        // The registry's computed version wins as the effective one, not the
2148        // author's stale annotation.
2149        assert_eq!(effective.get("commerce.order.PaymentConfirmed"), Some(&2));
2150    }
2151
2152    #[test]
2153    fn reconcile_auto_bumps_an_unannotated_additive_change() {
2154        let e = event(
2155            "OrderCancelled",
2156            vec![],
2157            vec![
2158                field("orderId", string_ty(), false),
2159                field("reason", string_ty(), true),
2160            ],
2161        );
2162        let mut units = StdHashMap::new();
2163        units.insert(
2164            "commerce.order".to_string(),
2165            table_with(vec![("OrderCancelled", e)]),
2166        );
2167        let mut existing = SchemaRegistry::new();
2168        existing.insert(
2169            "commerce.order.OrderCancelled".to_string(),
2170            EventEntry {
2171                schema: 1,
2172                fields: vec![shape("orderId", "String", false)],
2173            },
2174        );
2175        let mut errors = Vec::new();
2176        let (updated, effective) = reconcile(&existing, &units, &mut errors);
2177        assert!(errors.is_empty());
2178        assert_eq!(effective.get("commerce.order.OrderCancelled"), Some(&2));
2179        assert_eq!(
2180            updated.get("commerce.order.OrderCancelled").unwrap().schema,
2181            2
2182        );
2183    }
2184
2185    #[test]
2186    fn reconcile_rejects_a_non_additive_change_and_keeps_the_old_entry() {
2187        let e = event(
2188            "OrderCancelled",
2189            vec![],
2190            vec![field("orderId", string_ty(), false)],
2191        );
2192        let mut units = StdHashMap::new();
2193        units.insert(
2194            "commerce.order".to_string(),
2195            table_with(vec![("OrderCancelled", e)]),
2196        );
2197        let mut existing = SchemaRegistry::new();
2198        existing.insert(
2199            "commerce.order.OrderCancelled".to_string(),
2200            EventEntry {
2201                schema: 4,
2202                fields: vec![
2203                    shape("orderId", "String", false),
2204                    shape("reason", "String", false),
2205                ],
2206            },
2207        );
2208        let mut errors = Vec::new();
2209        let (updated, effective) = reconcile(&existing, &units, &mut errors);
2210        assert_eq!(errors.len(), 1);
2211        assert_eq!(errors[0].category, "bynk.event.non_additive_schema_change");
2212        assert_eq!(effective.get("commerce.order.OrderCancelled"), Some(&4));
2213        assert_eq!(
2214            updated.get("commerce.order.OrderCancelled").unwrap().schema,
2215            4
2216        );
2217    }
2218
2219    #[test]
2220    fn a_stale_key_for_a_renamed_event_is_dropped_silently() {
2221        // The old table had `PaymentConfirmed`; the new one only has
2222        // `PaymentConfirmedV2` (the track's prescribed rename-for-breaking-
2223        // change path). No diagnostic, and the old key does not survive into
2224        // the updated document.
2225        let e = event(
2226            "PaymentConfirmedV2",
2227            vec![],
2228            vec![field("orderId", string_ty(), false)],
2229        );
2230        let mut units = StdHashMap::new();
2231        units.insert(
2232            "commerce.order".to_string(),
2233            table_with(vec![("PaymentConfirmedV2", e)]),
2234        );
2235        let mut existing = SchemaRegistry::new();
2236        existing.insert(
2237            "commerce.order.PaymentConfirmed".to_string(),
2238            EventEntry {
2239                schema: 3,
2240                fields: vec![shape("orderId", "String", false)],
2241            },
2242        );
2243        let mut errors = Vec::new();
2244        let (updated, _) = reconcile(&existing, &units, &mut errors);
2245        assert!(errors.is_empty());
2246        assert!(updated.get("commerce.order.PaymentConfirmed").is_none());
2247        assert!(updated.get("commerce.order.PaymentConfirmedV2").is_some());
2248    }
2249
2250    // `serialize`, and `parse`'s own parsing rules, are
2251    // `bynk_project::schema_registry`'s (P4.0, #1113) — covered by that
2252    // crate's own tests; nothing left to duplicate here.
2253
2254    // -- parse_or_diagnose (P5.5) ------------------------------------------
2255
2256    #[test]
2257    fn parse_or_diagnose_passes_through_a_valid_registry() {
2258        let mut reg = SchemaRegistry::new();
2259        reg.insert(
2260            "commerce.order.PaymentConfirmed".to_string(),
2261            EventEntry {
2262                schema: 1,
2263                fields: vec![shape("orderId", "String", false)],
2264            },
2265        );
2266        let text = bynk_project::schema_registry::serialize(&reg);
2267        let parsed = parse_or_diagnose(Some(&text), std::path::Path::new("/tmp"))
2268            .expect("a freshly serialized registry must parse");
2269        assert_eq!(
2270            parsed
2271                .get("commerce.order.PaymentConfirmed")
2272                .map(|e| e.schema),
2273            Some(1)
2274        );
2275    }
2276
2277    #[test]
2278    fn parse_or_diagnose_reports_a_corrupt_registry_under_its_own_code() {
2279        let err = parse_or_diagnose(Some("not valid toml {{{"), std::path::Path::new("/tmp"))
2280            .expect_err("garbage content must not parse");
2281        assert_eq!(err.category, "bynk.project.schema_registry_corrupt");
2282    }
2283
2284    #[test]
2285    fn parse_or_diagnose_with_no_existing_content_baselines_empty() {
2286        let parsed = parse_or_diagnose(None, std::path::Path::new("/tmp"))
2287            .expect("no lock file yet is not corruption");
2288        assert!(parsed.get("anything.at_all").is_none());
2289    }
2290}