Skip to main content

meerkat_machine_codegen/
artifacts.rs

1use std::cell::{Cell, RefCell};
2use std::collections::{BTreeMap, BTreeSet};
3use std::fmt::Write;
4use std::rc::Rc;
5
6struct InfallibleWrite;
7
8impl InfallibleWrite {
9    fn expect(self, _message: &str) {}
10}
11
12fn push_fmt(out: &mut String, args: std::fmt::Arguments<'_>) {
13    let _ignored = out.write_fmt(args);
14}
15
16fn push_line(out: &mut String, args: std::fmt::Arguments<'_>) {
17    push_fmt(out, args);
18    out.push('\n');
19}
20
21macro_rules! pushln {
22    ($out:expr) => {{
23        $out.push('\n');
24    }};
25    ($out:expr, $($arg:tt)*) => {{
26        push_line($out, format_args!($($arg)*));
27    }};
28}
29
30macro_rules! writeln {
31    ($dst:expr) => {{
32        let _ignored = ::std::writeln!($dst);
33        InfallibleWrite
34    }};
35    ($dst:expr, $($arg:tt)*) => {{
36        let _ignored = ::std::writeln!($dst, $($arg)*);
37        InfallibleWrite
38    }};
39}
40
41const TLA_RUST_U64_MAX_CONSTANT: &str = "RustU64Max";
42const TLC_SAFE_RUST_U64_MAX_VALUE: u64 = 2_147_483_647;
43const SESSION_ID_STRING_BRIDGE_HELPER: &str = "meerkat_machine_session_id_matches_string";
44const TLC_REPRESENTATIVE_DOMAIN_HELPER: &str = "TlcRepresentativeDomain";
45
46/// Rust's `Option` order over the model's option records: `None` sorts below
47/// every `Some`, and two `Some`s compare their values. TLC cannot order
48/// records, so an ordering comparison with an option operand renders through
49/// these operators (`a > b` as `OptionLt(b, a)`, `a >= b` as `OptionLe(b, a)`).
50/// A module defines them only when it uses them, and its ASSUMEs re-check the
51/// order on every TLC run of that module.
52///
53/// The operators branch with `IF`, never `\/`: TLC evaluates every disjunct of
54/// an action-level `\/` to enumerate successors (see
55/// `render_or_short_circuit`), and a `None` record's `value` is the string
56/// `"none"`, which TLC cannot order against a number. An `IF` evaluates only
57/// the branch its condition selects, so a `.value` is read only after both
58/// `tag`s say `"some"`.
59const TLA_OPTION_ORDER_DEFINITIONS: &str = concat!(
60    "OptionLt(a, b) == IF b.tag = \"none\" THEN FALSE ELSE IF a.tag = \"none\" THEN TRUE ELSE a.value < b.value\n",
61    "OptionLe(a, b) == IF a.tag = \"none\" THEN TRUE ELSE IF b.tag = \"none\" THEN FALSE ELSE a.value <= b.value\n",
62    "ASSUME ~OptionLt(None, None) /\\ OptionLt(None, Some(0)) /\\ ~OptionLt(Some(0), None) /\\ ",
63    "OptionLt(Some(0), Some(1)) /\\ ~OptionLt(Some(1), Some(1)) /\\ ~OptionLt(Some(1), Some(0))\n",
64    "ASSUME OptionLe(None, None) /\\ OptionLe(None, Some(0)) /\\ ~OptionLe(Some(0), None) /\\ ",
65    "OptionLe(Some(0), Some(1)) /\\ OptionLe(Some(1), Some(1)) /\\ ~OptionLe(Some(1), Some(0))\n",
66    "\n",
67);
68
69use meerkat_machine_schema::{
70    CompositionCoverageManifest, CompositionInvariantKind, CompositionSchema,
71    CompositionStateLimits, CompositionWitness, CoverageAnchor, CoverageSchemaTarget,
72    DriverRefusalFieldSource, EntryInput, EnumSchema, Expr, FeedbackFieldSource, FeedbackInputRef,
73    Guard, HelperSchema, MachineCoverageManifest, MachineSchema, Quantifier, Route,
74    RouteBindingSource, RouteDelivery, RouteTarget, RouteTargetKind, SchedulerRule,
75    TransitionSchema, TriggerMatch, TypePathEnumPayloadAtom, TypePathEnumStructuralVariant,
76    TypePathStructField, TypePathStructFieldAtom, TypeRef, Update, VariantSchema,
77    canonical_machine_schemas,
78};
79
80/// Fail-closed error for composition/machine TLA model generation.
81///
82/// The composition CASE builders and helper ordering used to silently emit
83/// sentinel strings (`"unknown_actor"`, `"unknown_machine"`, …) and swallow
84/// compiler construction errors into `String::new()`. That turned a malformed
85/// composition (a route referencing an undeclared machine/effect/input, or a
86/// helper-call cycle) into a broken-but-passing model. Generation now returns
87/// this typed error so `machine-generate` / `machine-check-drift` fail closed
88/// on malformed input. For every currently-valid schema the resolution checks
89/// pass, so generated output is unchanged.
90/// How a machine's named-type bindings depart from the canonical machine
91/// that shares its id.
92#[derive(Debug, Clone, Copy, PartialEq, Eq)]
93pub enum CanonicalNamedTypeMismatchKind {
94    /// A canonical struct binding is missing.
95    MissingStructBinding,
96    /// The binding's generated domain shape differs from the canonical one.
97    DomainShape,
98}
99
100impl std::fmt::Display for CanonicalNamedTypeMismatchKind {
101    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
102        f.write_str(match self {
103            Self::MissingStructBinding => "is missing the canonical struct binding",
104            Self::DomainShape => "has a different domain shape than the canonical binding",
105        })
106    }
107}
108
109#[derive(Debug, thiserror::Error)]
110pub enum CompositionTlaError {
111    #[error("machine `{machine}`: invalid finite TLC model: {reason}")]
112    InvalidTlcModel { machine: String, reason: String },
113    /// A route's `from_machine` is not a declared machine instance.
114    #[error(
115        "composition `{composition}`: route `{route}` source machine `{machine}` is not a declared machine instance"
116    )]
117    UnknownRouteSourceMachine {
118        composition: String,
119        route: String,
120        machine: String,
121    },
122    /// A route's `to.machine` is not a declared machine instance.
123    #[error(
124        "composition `{composition}`: route `{route}` target machine `{machine}` is not a declared machine instance"
125    )]
126    UnknownRouteTargetMachine {
127        composition: String,
128        route: String,
129        machine: String,
130    },
131    /// A route's `effect_variant` is not a declared effect on its source machine.
132    #[error(
133        "composition `{composition}`: route `{route}` effect `{effect}` is not a declared effect on source machine instance `{machine}`"
134    )]
135    UnknownRouteEffect {
136        composition: String,
137        route: String,
138        machine: String,
139        effect: String,
140    },
141    /// A route's `to.input_variant` is not a declared input on its target machine.
142    #[error(
143        "composition `{composition}`: route `{route}` target input `{input}` is not a declared input on target machine instance `{machine}`"
144    )]
145    UnknownRouteTargetInput {
146        composition: String,
147        route: String,
148        machine: String,
149        input: String,
150    },
151    /// A route's `to.input_variant` is not a declared signal on its target machine.
152    #[error(
153        "composition `{composition}`: route `{route}` target signal `{signal}` is not a declared signal on target machine instance `{machine}`"
154    )]
155    UnknownRouteTargetSignal {
156        composition: String,
157        route: String,
158        machine: String,
159        signal: String,
160    },
161    /// An obligation field on a handoff protocol is absent from the matching
162    /// effect payload (used to be papered over with an `"unknown_<field>"`
163    /// sentinel literal in the generated TLA record).
164    #[error(
165        "composition `{composition}`: handoff protocol `{protocol}` obligation field `{field}` is absent from effect `{effect}` payload"
166    )]
167    UnknownObligationField {
168        composition: String,
169        protocol: String,
170        effect: String,
171        field: String,
172    },
173    /// A generated composition `CASE` operator over a route component could
174    /// not resolve a non-empty mapping for a composition that declares the
175    /// corresponding routes/machines. The previous behaviour laundered this
176    /// into an `OTHER -> "unknown_*"` sentinel, so a model that referenced an
177    /// undeclared actor/machine/effect/input still type-checked. Fail closed
178    /// instead: the operator's `OTHER` catch-all is dropped and an empty
179    /// mapping for a populated composition is a hard codegen error.
180    #[error(
181        "composition `{composition}`: route component `{component}` operator has no resolvable mapping despite declared routes/machines"
182    )]
183    UnknownRouteComponent {
184        composition: String,
185        component: &'static str,
186    },
187    /// A witness references a machine instance that is not part of the
188    /// composition. The renderer must not fall back to an arbitrary schema,
189    /// because that can make a liveness witness weaker than its catalog claim.
190    #[error(
191        "composition `{composition}`: witness `{witness}` references unknown machine instance `{machine}`"
192    )]
193    UnknownWitnessMachine {
194        composition: String,
195        witness: String,
196        machine: String,
197    },
198    /// A witness references a transition that is not declared on its machine.
199    /// Dropping the transition silently would let the generated witness omit
200    /// required progress while still rendering.
201    #[error(
202        "composition `{composition}`: witness `{witness}` references unknown transition `{transition}` on machine instance `{machine}`"
203    )]
204    UnknownWitnessTransition {
205        composition: String,
206        witness: String,
207        machine: String,
208        transition: String,
209    },
210    /// A machine declares a helper-call cycle, so no topological helper order
211    /// exists. The previous fallback silently emitted the cyclic helpers in an
212    /// arbitrary order, producing a model that references helpers before they
213    /// are defined.
214    #[error("machine `{machine}`: helper-call cycle detected: {cycle}")]
215    HelperCycle { machine: String, cycle: String },
216    /// Two distinct UNCHANGED frames derived the same generated operator name.
217    /// Disambiguating with a counter would be order-dependent and would hand
218    /// one action a frame condition it did not have, so this fails the render.
219    #[error("composition `{composition}`: {collision}")]
220    UnchangedFrameCollision {
221        composition: String,
222        collision: UnchangedFrameCollision,
223    },
224    /// Two distinct UNCHANGED frames derived the same generated operator name
225    /// while rendering a per-machine model.
226    #[error("machine `{machine}`: {collision}")]
227    MachineUnchangedFrameCollision {
228        machine: String,
229        collision: UnchangedFrameCollision,
230    },
231    /// Lower-level TLA compiler construction/render failure (e.g. an unknown
232    /// machine schema for a composition instance).
233    #[error("composition TLA compilation failed: {0}")]
234    Compile(String),
235    /// A supplied machine schema fails its own validation.
236    #[error("supplied machine `{machine}` is invalid: {error}")]
237    InvalidSuppliedMachine { machine: String, error: String },
238    /// A supplied catalog lists the same machine id twice.
239    #[error("supplied machine catalog lists machine `{machine}` more than once")]
240    DuplicateSuppliedMachine { machine: String },
241    /// A supplied machine reuses a canonical Meerkat machine id with a
242    /// different schema. A caller's catalog may include a canonical machine
243    /// unchanged, but never a shadow of it.
244    #[error(
245        "supplied machine `{machine}` shares its id with a canonical Meerkat machine but has a different schema"
246    )]
247    ShadowsCanonicalMachine { machine: String },
248    /// A machine that shares a canonical machine's id omits a canonical
249    /// struct named-type binding, or binds a shared named type with a
250    /// different generated domain shape.
251    #[error("machine `{machine}`: named type `{named_type}` {reason}")]
252    CanonicalNamedTypeMismatch {
253        machine: String,
254        named_type: String,
255        reason: CanonicalNamedTypeMismatchKind,
256    },
257    /// Two machines of one composition bind the same named type with
258    /// different generated domain shapes.
259    #[error(
260        "composition `{composition}`: named type `{named_type}` is bound with different domain shapes"
261    )]
262    DivergentNamedTypeBinding {
263        composition: String,
264        named_type: String,
265    },
266    /// The composition does not validate against the supplied catalog.
267    #[error("composition `{composition}` does not validate against the supplied catalog: {error}")]
268    InvalidCompositionForCatalog { composition: String, error: String },
269}
270
271impl From<String> for CompositionTlaError {
272    fn from(message: String) -> Self {
273        CompositionTlaError::Compile(message)
274    }
275}
276
277fn route_target_variant<'a>(
278    machine: &'a MachineSchema,
279    target: &RouteTarget,
280) -> Option<&'a VariantSchema> {
281    match target.kind {
282        RouteTargetKind::Input => machine
283            .inputs
284            .variant_named(target.input_variant.as_str())
285            .ok(),
286        RouteTargetKind::Signal => machine
287            .signals
288            .variant_named(target.input_variant.as_str())
289            .ok(),
290    }
291}
292
293fn transition_trigger_variant<'a>(
294    schema: &'a MachineSchema,
295    transition: &TransitionSchema,
296) -> Option<&'a VariantSchema> {
297    match &transition.on {
298        meerkat_machine_schema::TriggerMatch::Input { variant, .. } => {
299            schema.inputs.variant_named(variant.as_str()).ok()
300        }
301        meerkat_machine_schema::TriggerMatch::Signal { variant, .. } => {
302            schema.signals.variant_named(variant.as_str()).ok()
303        }
304    }
305}
306
307/// Boolean input literals that every enabled instance of `transition` must
308/// carry.
309///
310/// Machine `Next` is an existential disjunction over input domains. Naively
311/// enumerating a large set of boolean validation facts creates a `2^N`
312/// cross-product even when the transition guard immediately requires each fact
313/// to be one literal. Replacing those existential bindings with the forced
314/// literals preserves the exact action relation: assignments carrying the
315/// opposite value cannot satisfy the existing conjunctive guard and therefore
316/// cannot produce a successor state.
317///
318/// Keep the analysis deliberately conservative. Only a whole conjunct that is
319/// structurally a binding, its negation, or a binding/literal equality is
320/// specialized. Values mentioned under disjunctions, helper calls, or other
321/// expressions retain their complete domains. Contradictory requirements also
322/// fall back to full enumeration so codegen never guesses about an
323/// unsatisfiable guard.
324fn transition_forced_bool_literals(
325    transition: &TransitionSchema,
326    binding_types: &BTreeMap<String, TypeRef>,
327) -> BTreeMap<String, bool> {
328    let mut requirements = BTreeMap::<String, Option<bool>>::new();
329    for guard in &transition.guards {
330        collect_conjunctive_bool_requirements(&guard.expr, &mut requirements);
331    }
332    requirements
333        .into_iter()
334        .filter_map(|(binding, required)| {
335            if matches!(binding_types.get(&binding), Some(TypeRef::Bool)) {
336                required.map(|value| (binding, value))
337            } else {
338                None
339            }
340        })
341        .collect()
342}
343
344fn transition_uses_tlc_representative_payload(
345    schema: &MachineSchema,
346    transition: &TransitionSchema,
347) -> bool {
348    match &transition.on {
349        meerkat_machine_schema::TriggerMatch::Input { variant, .. } => schema
350            .tlc_representative_inputs
351            .iter()
352            .any(|candidate| candidate == variant),
353        meerkat_machine_schema::TriggerMatch::Signal { .. } => false,
354    }
355}
356
357fn tlc_representative_domain(domain: String) -> String {
358    format!("{TLC_REPRESENTATIVE_DOMAIN_HELPER}({domain})")
359}
360
361fn collect_conjunctive_bool_requirements(
362    expr: &Expr,
363    requirements: &mut BTreeMap<String, Option<bool>>,
364) {
365    if let Expr::And(items) = expr {
366        for item in items {
367            collect_conjunctive_bool_requirements(item, requirements);
368        }
369        return;
370    }
371
372    let requirement = match expr {
373        Expr::Binding(binding) => Some((binding.as_str(), true)),
374        Expr::Not(inner) => match inner.as_ref() {
375            Expr::Binding(binding) => Some((binding.as_str(), false)),
376            _ => None,
377        },
378        Expr::Eq(left, right) => bool_binding_literal_equality(left, right, false),
379        Expr::Neq(left, right) => bool_binding_literal_equality(left, right, true),
380        _ => None,
381    };
382    let Some((binding, value)) = requirement else {
383        return;
384    };
385
386    match requirements.get(binding).copied() {
387        None => {
388            requirements.insert(binding.to_owned(), Some(value));
389        }
390        Some(Some(existing)) if existing != value => {
391            requirements.insert(binding.to_owned(), None);
392        }
393        Some(_) => {}
394    }
395}
396
397fn bool_binding_literal_equality<'a>(
398    left: &'a Expr,
399    right: &'a Expr,
400    negate: bool,
401) -> Option<(&'a str, bool)> {
402    let (binding, value) = match (left, right) {
403        (Expr::Binding(binding), Expr::Bool(value))
404        | (Expr::Bool(value), Expr::Binding(binding)) => (binding.as_str(), *value),
405        _ => return None,
406    };
407    Some((binding, if negate { !value } else { value }))
408}
409
410fn tla_bool_literal(value: bool) -> &'static str {
411    if value { "TRUE" } else { "FALSE" }
412}
413
414fn collect_helper_calls(expr: &Expr, calls: &mut BTreeSet<String>) {
415    match expr {
416        Expr::Bool(_)
417        | Expr::U64(_)
418        | Expr::U64Max
419        | Expr::String(_)
420        | Expr::NamedVariant { .. }
421        | Expr::EmptySet
422        | Expr::EmptyMap
423        | Expr::CurrentPhase
424        | Expr::Phase(_)
425        | Expr::Field(_)
426        | Expr::Binding(_)
427        | Expr::Variant(_)
428        | Expr::None => {}
429        Expr::SeqLiteral(items) | Expr::And(items) | Expr::Or(items) => {
430            for item in items {
431                collect_helper_calls(item, calls);
432            }
433        }
434        Expr::IfElse {
435            condition,
436            then_expr,
437            else_expr,
438        } => {
439            collect_helper_calls(condition, calls);
440            collect_helper_calls(then_expr, calls);
441            collect_helper_calls(else_expr, calls);
442        }
443        Expr::Not(inner)
444        | Expr::SeqElements(inner)
445        | Expr::Len(inner)
446        | Expr::Head(inner)
447        | Expr::MapKeys(inner)
448        | Expr::Some(inner)
449        | Expr::FieldAccess { base: inner, .. }
450        | Expr::EnumVariantIs { value: inner, .. }
451        | Expr::EnumStringSetPayload { value: inner, .. } => collect_helper_calls(inner, calls),
452        Expr::Eq(left, right)
453        | Expr::Neq(left, right)
454        | Expr::Add(left, right)
455        | Expr::Sub(left, right)
456        | Expr::Gt(left, right)
457        | Expr::Gte(left, right)
458        | Expr::Lt(left, right)
459        | Expr::Lte(left, right)
460        | Expr::SeqStartsWith {
461            seq: left,
462            prefix: right,
463        } => {
464            collect_helper_calls(left, calls);
465            collect_helper_calls(right, calls);
466        }
467        Expr::Contains { collection, value } => {
468            collect_helper_calls(collection, calls);
469            collect_helper_calls(value, calls);
470        }
471        Expr::Count { collection, value } => {
472            collect_helper_calls(collection, calls);
473            collect_helper_calls(value, calls);
474        }
475        Expr::MapContainsKey { map, key } => {
476            collect_helper_calls(map, calls);
477            collect_helper_calls(key, calls);
478        }
479        Expr::MapGet { map, key } | Expr::MapValue { map, key } => {
480            collect_helper_calls(map, calls);
481            collect_helper_calls(key, calls);
482        }
483        Expr::MapLiteral(entries) => {
484            for (key, value) in entries {
485                collect_helper_calls(key, calls);
486                collect_helper_calls(value, calls);
487            }
488        }
489        Expr::Call { helper, args } => {
490            calls.insert(helper.clone());
491            for arg in args {
492                collect_helper_calls(arg, calls);
493            }
494        }
495        Expr::Quantified { over, body, .. } => {
496            collect_helper_calls(over, calls);
497            collect_helper_calls(body, calls);
498        }
499    }
500}
501
502fn expr_uses_u64_max(expr: &Expr) -> bool {
503    match expr {
504        Expr::U64Max => true,
505        Expr::SeqLiteral(items) | Expr::And(items) | Expr::Or(items) => {
506            items.iter().any(expr_uses_u64_max)
507        }
508        Expr::IfElse {
509            condition,
510            then_expr,
511            else_expr,
512        } => {
513            expr_uses_u64_max(condition)
514                || expr_uses_u64_max(then_expr)
515                || expr_uses_u64_max(else_expr)
516        }
517        Expr::Not(inner)
518        | Expr::SeqElements(inner)
519        | Expr::Len(inner)
520        | Expr::Head(inner)
521        | Expr::MapKeys(inner)
522        | Expr::Some(inner)
523        | Expr::FieldAccess { base: inner, .. }
524        | Expr::EnumVariantIs { value: inner, .. }
525        | Expr::EnumStringSetPayload { value: inner, .. } => expr_uses_u64_max(inner),
526        Expr::Eq(left, right)
527        | Expr::Neq(left, right)
528        | Expr::Add(left, right)
529        | Expr::Sub(left, right)
530        | Expr::Gt(left, right)
531        | Expr::Gte(left, right)
532        | Expr::Lt(left, right)
533        | Expr::Lte(left, right) => expr_uses_u64_max(left) || expr_uses_u64_max(right),
534        Expr::Contains { collection, value } | Expr::Count { collection, value } => {
535            expr_uses_u64_max(collection) || expr_uses_u64_max(value)
536        }
537        Expr::MapContainsKey { map, key }
538        | Expr::MapGet { map, key }
539        | Expr::MapValue { map, key } => expr_uses_u64_max(map) || expr_uses_u64_max(key),
540        Expr::MapLiteral(entries) => entries
541            .iter()
542            .any(|(key, value)| expr_uses_u64_max(key) || expr_uses_u64_max(value)),
543        Expr::SeqStartsWith { seq, prefix } => expr_uses_u64_max(seq) || expr_uses_u64_max(prefix),
544        Expr::Call { helper, args } => {
545            native_helper_uses_u64_max(helper) || args.iter().any(expr_uses_u64_max)
546        }
547        Expr::Quantified { over, body, .. } => expr_uses_u64_max(over) || expr_uses_u64_max(body),
548        Expr::Bool(_)
549        | Expr::U64(_)
550        | Expr::String(_)
551        | Expr::NamedVariant { .. }
552        | Expr::EmptySet
553        | Expr::EmptyMap
554        | Expr::CurrentPhase
555        | Expr::Phase(_)
556        | Expr::Field(_)
557        | Expr::Binding(_)
558        | Expr::Variant(_)
559        | Expr::None => false,
560    }
561}
562
563fn expr_calls_helper(expr: &Expr, helper: &str) -> bool {
564    let mut calls = BTreeSet::new();
565    collect_helper_calls(expr, &mut calls);
566    calls.contains(helper)
567}
568
569fn native_helper_uses_u64_max(helper: &str) -> bool {
570    matches!(
571        helper,
572        "mob_machine_next_respawn_generation"
573            | "mob_machine_next_minted_generation"
574            | "mob_machine_u64_is_exact_successor"
575            | "mob_machine_optional_u64_is_exact_successor"
576    )
577}
578
579fn update_uses_u64_max(update: &Update) -> bool {
580    match update {
581        Update::Assign { expr, .. }
582        | Update::SetInsert { value: expr, .. }
583        | Update::SetRemove { value: expr, .. }
584        | Update::SeqAppend { value: expr, .. }
585        | Update::SeqPrepend { values: expr, .. }
586        | Update::SeqRemoveValue { value: expr, .. }
587        | Update::SeqRemoveAll { values: expr, .. } => expr_uses_u64_max(expr),
588        Update::MapInsert { key, value, .. } => expr_uses_u64_max(key) || expr_uses_u64_max(value),
589        Update::MapRemove { key, .. }
590        | Update::MapIncrement { key, .. }
591        | Update::MapDecrement { key, .. } => expr_uses_u64_max(key),
592        Update::Conditional {
593            condition,
594            then_updates,
595            else_updates,
596        } => {
597            expr_uses_u64_max(condition)
598                || then_updates.iter().any(update_uses_u64_max)
599                || else_updates.iter().any(update_uses_u64_max)
600        }
601        Update::ForEach { over, updates, .. } => {
602            expr_uses_u64_max(over) || updates.iter().any(update_uses_u64_max)
603        }
604        Update::Increment { .. } | Update::Decrement { .. } | Update::SeqPopFront { .. } => false,
605    }
606}
607
608fn update_calls_helper(update: &Update, helper: &str) -> bool {
609    match update {
610        Update::Assign { expr, .. }
611        | Update::SetInsert { value: expr, .. }
612        | Update::SetRemove { value: expr, .. }
613        | Update::SeqAppend { value: expr, .. }
614        | Update::SeqPrepend { values: expr, .. }
615        | Update::SeqRemoveValue { value: expr, .. }
616        | Update::SeqRemoveAll { values: expr, .. } => expr_calls_helper(expr, helper),
617        Update::MapInsert { key, value, .. } => {
618            expr_calls_helper(key, helper) || expr_calls_helper(value, helper)
619        }
620        Update::MapRemove { key, .. }
621        | Update::MapIncrement { key, .. }
622        | Update::MapDecrement { key, .. } => expr_calls_helper(key, helper),
623        Update::Conditional {
624            condition,
625            then_updates,
626            else_updates,
627        } => {
628            expr_calls_helper(condition, helper)
629                || then_updates
630                    .iter()
631                    .any(|update| update_calls_helper(update, helper))
632                || else_updates
633                    .iter()
634                    .any(|update| update_calls_helper(update, helper))
635        }
636        Update::ForEach { over, updates, .. } => {
637            expr_calls_helper(over, helper)
638                || updates
639                    .iter()
640                    .any(|update| update_calls_helper(update, helper))
641        }
642        Update::Increment { .. } | Update::Decrement { .. } | Update::SeqPopFront { .. } => false,
643    }
644}
645
646fn explicit_value_uses_u64_max(value: &meerkat_machine_schema::TlcValue) -> bool {
647    use meerkat_machine_schema::TlcValue;
648    match value {
649        TlcValue::U64(number) => *number == u64::MAX,
650        TlcValue::Some(value) => explicit_value_uses_u64_max(value),
651        TlcValue::Record(fields) => fields.values().any(explicit_value_uses_u64_max),
652        TlcValue::Set(values) => values.iter().any(explicit_value_uses_u64_max),
653        TlcValue::Bool(_) | TlcValue::String(_) | TlcValue::None => false,
654    }
655}
656
657fn machine_uses_u64_max(schema: &MachineSchema) -> bool {
658    schema.tlc_model.as_ref().is_some_and(|model| {
659        [&model.ci, &model.deep].iter().any(|profile| {
660            profile
661                .named_values
662                .values()
663                .flatten()
664                .any(explicit_value_uses_u64_max)
665        })
666    }) || schema
667        .state
668        .init
669        .fields
670        .iter()
671        .any(|field| expr_uses_u64_max(&field.expr))
672        || schema
673            .helpers
674            .iter()
675            .any(|helper| expr_uses_u64_max(&helper.body))
676        || schema
677            .derived
678            .iter()
679            .any(|helper| expr_uses_u64_max(&helper.body))
680        || schema
681            .invariants
682            .iter()
683            .any(|invariant| expr_uses_u64_max(&invariant.expr))
684        || schema.transitions.iter().any(|transition| {
685            transition
686                .guards
687                .iter()
688                .any(|guard| expr_uses_u64_max(&guard.expr))
689                || transition.updates.iter().any(update_uses_u64_max)
690                || transition
691                    .emit
692                    .iter()
693                    .any(|effect| effect.fields.values().any(expr_uses_u64_max))
694        })
695}
696
697fn machine_uses_session_id_string_bridge(schema: &MachineSchema) -> bool {
698    schema
699        .state
700        .init
701        .fields
702        .iter()
703        .any(|field| expr_calls_helper(&field.expr, SESSION_ID_STRING_BRIDGE_HELPER))
704        || schema
705            .helpers
706            .iter()
707            .chain(schema.derived.iter())
708            .any(|helper| expr_calls_helper(&helper.body, SESSION_ID_STRING_BRIDGE_HELPER))
709        || schema
710            .invariants
711            .iter()
712            .any(|invariant| expr_calls_helper(&invariant.expr, SESSION_ID_STRING_BRIDGE_HELPER))
713        || schema.transitions.iter().any(|transition| {
714            transition
715                .guards
716                .iter()
717                .any(|guard| expr_calls_helper(&guard.expr, SESSION_ID_STRING_BRIDGE_HELPER))
718                || transition
719                    .updates
720                    .iter()
721                    .any(|update| update_calls_helper(update, SESSION_ID_STRING_BRIDGE_HELPER))
722                || transition.emit.iter().any(|effect| {
723                    effect
724                        .fields
725                        .values()
726                        .any(|expr| expr_calls_helper(expr, SESSION_ID_STRING_BRIDGE_HELPER))
727                })
728        })
729}
730
731fn composition_uses_session_id_string_bridge(
732    machine_by_instance: &BTreeMap<&str, &MachineSchema>,
733) -> bool {
734    machine_by_instance
735        .values()
736        .copied()
737        .any(machine_uses_session_id_string_bridge)
738}
739
740fn composition_uses_u64_max(
741    schema: &CompositionSchema,
742    machine_by_instance: &BTreeMap<&str, &MachineSchema>,
743) -> bool {
744    machine_by_instance
745        .values()
746        .copied()
747        .any(machine_uses_u64_max)
748        || schema.routes.iter().any(|route| {
749            route.bindings.iter().any(|binding| match &binding.source {
750                RouteBindingSource::Literal(expr) => expr_uses_u64_max(expr),
751                RouteBindingSource::Field { .. } | RouteBindingSource::OwnerProvided => false,
752            })
753        })
754        || schema.witnesses.iter().any(|witness| {
755            witness.preload_inputs.iter().any(|input| {
756                input
757                    .fields
758                    .iter()
759                    .any(|field| expr_uses_u64_max(&field.expr))
760            }) || witness.expected_states.iter().any(|state| {
761                state
762                    .fields
763                    .iter()
764                    .any(|field| expr_uses_u64_max(&field.expr))
765            })
766        })
767}
768
769/// Detect a helper-call cycle via DFS over the helper-call dependency graph,
770/// using a visited set plus an explicit recursion stack to catch back-edges.
771///
772/// Returns the cycle path (in call order) the first time a back-edge is found,
773/// or `None` when the helper graph is acyclic. Only edges to declared helpers
774/// (`known`) are followed; self-references and calls to native/undeclared
775/// helpers are not dependency edges for ordering purposes.
776fn detect_helper_cycle(defs: &[&HelperSchema], known: &BTreeSet<String>) -> Option<Vec<String>> {
777    let deps_of = |helper: &HelperSchema| -> Vec<String> {
778        let mut calls = BTreeSet::new();
779        collect_helper_calls(&helper.body, &mut calls);
780        calls
781            .into_iter()
782            .filter(|dep| dep != &helper.name && known.contains(dep))
783            .collect()
784    };
785    let by_name: BTreeMap<&str, &HelperSchema> =
786        defs.iter().map(|h| (h.name.as_str(), *h)).collect();
787
788    let mut visited: BTreeSet<String> = BTreeSet::new();
789    let mut on_stack: BTreeSet<String> = BTreeSet::new();
790    let mut stack_path: Vec<String> = Vec::new();
791    // Explicit work stack of (node, next-dependency-index) frames so the DFS
792    // does not recurse on the (untrusted) helper graph depth.
793    let mut frames: Vec<(String, Vec<String>, usize)> = Vec::new();
794
795    for root in defs {
796        let root_name = root.name.clone();
797        if visited.contains(&root_name) {
798            continue;
799        }
800        frames.push((root_name.clone(), deps_of(root), 0));
801        on_stack.insert(root_name.clone());
802        stack_path.push(root_name);
803
804        while !frames.is_empty() {
805            // Read the next dependency (if any) from the top frame, advancing
806            // its cursor, then release the borrow before mutating `frames`.
807            let next_dep = {
808                let Some((_, deps, idx)) = frames.last_mut() else {
809                    break;
810                };
811                if *idx < deps.len() {
812                    let dep = deps[*idx].clone();
813                    *idx += 1;
814                    Some(dep)
815                } else {
816                    None
817                }
818            };
819
820            match next_dep {
821                Some(dep) => {
822                    if on_stack.contains(&dep) {
823                        // Back-edge: report the cycle path from `dep` onward,
824                        // closing the loop back to `dep`.
825                        let start = stack_path.iter().position(|n| n == &dep).unwrap_or(0);
826                        let mut cycle = stack_path[start..].to_vec();
827                        cycle.push(dep);
828                        return Some(cycle);
829                    }
830                    if visited.contains(&dep) {
831                        continue;
832                    }
833                    let dep_deps = match by_name.get(dep.as_str()) {
834                        Some(helper) => deps_of(helper),
835                        None => Vec::new(),
836                    };
837                    on_stack.insert(dep.clone());
838                    stack_path.push(dep.clone());
839                    frames.push((dep, dep_deps, 0));
840                }
841                None => {
842                    if let Some((node, _, _)) = frames.pop() {
843                        on_stack.remove(&node);
844                        visited.insert(node);
845                    }
846                    stack_path.pop();
847                }
848            }
849        }
850    }
851    None
852}
853
854fn helper_dependency_order(
855    schema: &MachineSchema,
856) -> std::result::Result<Vec<&HelperSchema>, CompositionTlaError> {
857    let defs = schema
858        .helpers
859        .iter()
860        .chain(schema.derived.iter())
861        .collect::<Vec<_>>();
862    let known = defs
863        .iter()
864        .map(|helper| &helper.name)
865        .cloned()
866        .collect::<BTreeSet<_>>();
867
868    // Fail closed: a helper-call cycle has no topological order. The previous
869    // fallback silently dumped the cyclic helpers in arbitrary order, emitting
870    // a model that references a helper before it is defined.
871    if let Some(cycle) = detect_helper_cycle(&defs, &known) {
872        return Err(CompositionTlaError::HelperCycle {
873            machine: schema.machine.as_str().to_owned(),
874            cycle: cycle.join(" -> "),
875        });
876    }
877
878    let mut remaining = defs;
879    let mut ordered = Vec::new();
880
881    while !remaining.is_empty() {
882        let remaining_names = remaining
883            .iter()
884            .map(|helper| &helper.name)
885            .cloned()
886            .collect::<BTreeSet<_>>();
887        let mut ready_indices = Vec::new();
888
889        for (index, helper) in remaining.iter().enumerate() {
890            let mut deps = BTreeSet::new();
891            collect_helper_calls(&helper.body, &mut deps);
892            let unresolved = deps.into_iter().filter(|dep| {
893                dep != &helper.name && known.contains(dep) && remaining_names.contains(dep)
894            });
895            if unresolved.count() == 0 {
896                ready_indices.push(index);
897            }
898        }
899
900        if ready_indices.is_empty() {
901            // Unreachable: `detect_helper_cycle` already failed closed on any
902            // cyclic helper graph above, so an acyclic graph always has at
903            // least one ready helper here. Fail closed defensively rather than
904            // re-introducing the silent arbitrary-order fallback.
905            let cycle = remaining
906                .iter()
907                .map(|helper| helper.name.clone())
908                .collect::<Vec<_>>()
909                .join(" -> ");
910            return Err(CompositionTlaError::HelperCycle {
911                machine: schema.machine.as_str().to_owned(),
912                cycle,
913            });
914        }
915
916        for index in ready_indices.into_iter().rev() {
917            ordered.push(remaining.remove(index));
918        }
919    }
920
921    Ok(ordered)
922}
923
924/// Render one coverage anchor as a generated contract-markdown bullet,
925/// surfacing its typed schema target so artifact drift is visible to the
926/// rerun-and-diff gate.
927fn render_contract_coverage_anchor_bullet(anchor: &CoverageAnchor) -> String {
928    let target = match &anchor.target {
929        CoverageSchemaTarget::Machine(machine) => format!("machine `{machine}`"),
930        CoverageSchemaTarget::Route(route) => format!("route `{route}`"),
931    };
932    format!(
933        "- `{}` ({}): `{}` — {}",
934        anchor.id,
935        target,
936        anchor.symbol.as_str(),
937        anchor.note
938    )
939}
940
941pub fn render_machine_contract_markdown(
942    schema: &MachineSchema,
943    coverage: &MachineCoverageManifest,
944) -> String {
945    let mut out = String::new();
946
947    pushln!(&mut out, "# {}", schema.machine);
948    pushln!(&mut out);
949    writeln!(
950        &mut out,
951        "_Generated from the Rust machine catalog. Do not edit by hand._"
952    )
953    .expect("write to string");
954    pushln!(&mut out);
955    pushln!(&mut out, "- Version: `{}`", schema.version);
956    writeln!(
957        &mut out,
958        "- Rust owner: `{}` / `{}`",
959        schema.rust.crate_name, schema.rust.module
960    )
961    .expect("write to string");
962    pushln!(&mut out);
963
964    render_state_markdown(&mut out, schema);
965    let runtime_internal_inputs: BTreeSet<&str> = schema
966        .runtime_internal_inputs
967        .iter()
968        .map(|input| input.as_str())
969        .collect();
970    render_input_subset(&mut out, "Inputs", &schema.inputs, |name| {
971        !runtime_internal_inputs.contains(name)
972    });
973    if !schema.surface_only_inputs.is_empty() {
974        pushln!(&mut out, "## Surface-only Inputs");
975        for input in &schema.surface_only_inputs {
976            pushln!(&mut out, "- `{input}`");
977        }
978        pushln!(&mut out);
979    }
980    if !runtime_internal_inputs.is_empty() {
981        render_input_subset(
982            &mut out,
983            "Runtime-Internal Inputs",
984            &schema.inputs,
985            |name| runtime_internal_inputs.contains(name),
986        );
987    }
988    render_ci_samples_markdown(&mut out, schema);
989    render_enum_markdown(&mut out, "Signals", &schema.signals);
990    render_enum_markdown(&mut out, "Effects", &schema.effects);
991
992    if !schema.helpers.is_empty() {
993        pushln!(&mut out, "## Helpers");
994        for helper in &schema.helpers {
995            writeln!(
996                &mut out,
997                "- `{}`({}) -> `{}`",
998                helper.name,
999                render_field_list(&helper.params),
1000                render_type_ref(&helper.returns)
1001            )
1002            .expect("write to string");
1003        }
1004        pushln!(&mut out);
1005    }
1006
1007    if !schema.derived.is_empty() {
1008        pushln!(&mut out, "## Derived");
1009        for derived in &schema.derived {
1010            writeln!(
1011                &mut out,
1012                "- `{}`({}) -> `{}`",
1013                derived.name,
1014                render_field_list(&derived.params),
1015                render_type_ref(&derived.returns)
1016            )
1017            .expect("write to string");
1018        }
1019        pushln!(&mut out);
1020    }
1021
1022    if !schema.command_plans.is_empty() {
1023        pushln!(&mut out, "## Command Plans");
1024        let transitions_by_name = schema
1025            .transitions
1026            .iter()
1027            .map(|transition| (transition.name.as_str(), transition))
1028            .collect::<BTreeMap<_, _>>();
1029        for plan in &schema.command_plans {
1030            pushln!(&mut out, "### `{}`", plan.name);
1031            pushln!(&mut out, "- Authority: `{}`", plan.authority_type);
1032            if !plan.source_inputs.is_empty() {
1033                writeln!(
1034                    &mut out,
1035                    "- Source Inputs: {}",
1036                    plan.source_inputs
1037                        .iter()
1038                        .map(|input| format!("`{input}`"))
1039                        .collect::<Vec<_>>()
1040                        .join(", ")
1041                )
1042                .expect("write to string");
1043            }
1044            if !plan.source_signals.is_empty() {
1045                writeln!(
1046                    &mut out,
1047                    "- Source Signals: {}",
1048                    plan.source_signals
1049                        .iter()
1050                        .map(|signal| format!("`{signal}`"))
1051                        .collect::<Vec<_>>()
1052                        .join(", ")
1053                )
1054                .expect("write to string");
1055            }
1056            if !plan.transitions.is_empty() {
1057                writeln!(
1058                    &mut out,
1059                    "- Transitions: {}",
1060                    plan.transitions
1061                        .iter()
1062                        .map(|transition| format!("`{transition}`"))
1063                        .collect::<Vec<_>>()
1064                        .join(", ")
1065                )
1066                .expect("write to string");
1067                pushln!(&mut out, "- Guard Expansion:");
1068                for transition_id in &plan.transitions {
1069                    if let Some(transition) = transitions_by_name.get(transition_id.as_str()) {
1070                        let guards = if transition.guards.is_empty() {
1071                            "`<none>`".to_owned()
1072                        } else {
1073                            transition
1074                                .guards
1075                                .iter()
1076                                .map(|guard| format!("`{}`", guard.name))
1077                                .collect::<Vec<_>>()
1078                                .join(", ")
1079                        };
1080                        pushln!(&mut out, "  - `{transition_id}`: {guards}");
1081                    }
1082                }
1083            }
1084            if !plan.effects.is_empty() {
1085                writeln!(
1086                    &mut out,
1087                    "- Command Effects: {}",
1088                    plan.effects
1089                        .iter()
1090                        .map(|effect| format!("`{effect}`"))
1091                        .collect::<Vec<_>>()
1092                        .join(", ")
1093                )
1094                .expect("write to string");
1095            }
1096            if !plan.effect_closures.is_empty() {
1097                pushln!(&mut out, "- Effect Closure:");
1098                for closure in &plan.effect_closures {
1099                    writeln!(
1100                        &mut out,
1101                        "  - `{}` via `{}` ({}) states: {}",
1102                        closure.effect,
1103                        closure.authority_type,
1104                        closure.closure_policy,
1105                        closure
1106                            .lifecycle
1107                            .iter()
1108                            .map(|state| format!("`{state}`"))
1109                            .collect::<Vec<_>>()
1110                            .join(", ")
1111                    )
1112                    .expect("write to string");
1113                }
1114            }
1115            let emitted_effects = plan
1116                .transitions
1117                .iter()
1118                .filter_map(|transition_id| transitions_by_name.get(transition_id.as_str()))
1119                .flat_map(|transition| transition.emit.iter().map(|effect| &effect.variant))
1120                .collect::<BTreeSet<_>>();
1121            if !emitted_effects.is_empty() {
1122                writeln!(
1123                    &mut out,
1124                    "- Emitted By Transitions: {}",
1125                    emitted_effects
1126                        .iter()
1127                        .map(|effect| format!("`{effect}`"))
1128                        .collect::<Vec<_>>()
1129                        .join(", ")
1130                )
1131                .expect("write to string");
1132            }
1133            pushln!(&mut out);
1134        }
1135    }
1136
1137    pushln!(&mut out, "## Invariants");
1138    for invariant in &schema.invariants {
1139        pushln!(&mut out, "- `{}`", invariant.name);
1140    }
1141    pushln!(&mut out);
1142
1143    pushln!(&mut out, "## Transitions");
1144    for transition in &schema.transitions {
1145        pushln!(&mut out, "### `{}`", transition.name);
1146        writeln!(
1147            &mut out,
1148            "- From: {}",
1149            transition
1150                .from
1151                .iter()
1152                .map(|item| format!("`{item}`"))
1153                .collect::<Vec<_>>()
1154                .join(", ")
1155        )
1156        .expect("write to string");
1157        writeln!(
1158            &mut out,
1159            "- On: `{}`({})",
1160            transition.on.variant_str(),
1161            transition
1162                .on
1163                .bindings()
1164                .iter()
1165                .map(meerkat_machine_schema::identity::FieldId::as_str)
1166                .collect::<Vec<_>>()
1167                .join(", ")
1168        )
1169        .expect("write to string");
1170        if !transition.guards.is_empty() {
1171            pushln!(&mut out, "- Guards:");
1172            for guard in &transition.guards {
1173                pushln!(&mut out, "  - `{}`", guard.name);
1174            }
1175        }
1176        if !transition.emit.is_empty() {
1177            writeln!(
1178                &mut out,
1179                "- Emits: {}",
1180                transition
1181                    .emit
1182                    .iter()
1183                    .map(|effect| format!("`{}`", effect.variant))
1184                    .collect::<Vec<_>>()
1185                    .join(", ")
1186            )
1187            .expect("write to string");
1188        }
1189        pushln!(&mut out, "- To: `{}`", transition.to);
1190        pushln!(&mut out);
1191    }
1192
1193    pushln!(&mut out, "## Coverage");
1194    pushln!(&mut out, "### Code Anchors");
1195    for anchor in &coverage.code_anchors {
1196        pushln!(
1197            &mut out,
1198            "{}",
1199            render_contract_coverage_anchor_bullet(anchor)
1200        );
1201    }
1202    pushln!(&mut out);
1203    pushln!(&mut out, "### Scenarios");
1204    for scenario in &coverage.scenarios {
1205        pushln!(&mut out, "- `{}` — {}", scenario.id, scenario.summary);
1206    }
1207
1208    out
1209}
1210
1211pub fn render_composition_contract_markdown(
1212    schema: &CompositionSchema,
1213    coverage: &CompositionCoverageManifest,
1214) -> String {
1215    let mut out = String::new();
1216
1217    pushln!(&mut out, "# {}", schema.name);
1218    pushln!(&mut out);
1219    writeln!(
1220        &mut out,
1221        "_Generated from the Rust composition catalog. Do not edit by hand._"
1222    )
1223    .expect("write to string");
1224    pushln!(&mut out);
1225
1226    pushln!(&mut out, "## Machines");
1227    for machine in &schema.machines {
1228        writeln!(
1229            &mut out,
1230            "- `{}`: `{}` @ actor `{}`",
1231            machine.instance_id, machine.machine_name, machine.actor
1232        )
1233        .expect("write to string");
1234    }
1235    pushln!(&mut out);
1236
1237    pushln!(&mut out, "## Routes");
1238    for route in &schema.routes {
1239        writeln!(
1240            &mut out,
1241            "- `{}`: `{}`.`{}` -> `{}`.`{}` [{}]",
1242            route.name,
1243            route.from_machine,
1244            route.effect_variant,
1245            route.to.machine,
1246            route.to.input_variant,
1247            render_route_delivery(route)
1248        )
1249        .expect("write to string");
1250    }
1251    pushln!(&mut out);
1252
1253    pushln!(&mut out, "## Target Selectors");
1254    if schema.route_target_selectors.is_empty() {
1255        pushln!(&mut out, "- `(none)`");
1256    } else {
1257        for selector in &schema.route_target_selectors {
1258            pushln!(
1259                &mut out,
1260                "- `{}` selects `{}` from `{:?}`",
1261                selector.route_name,
1262                selector.selector_field,
1263                selector.source
1264            );
1265        }
1266    }
1267    pushln!(&mut out);
1268
1269    pushln!(&mut out, "## Driver");
1270    if let Some(driver) = &schema.driver {
1271        pushln!(
1272            &mut out,
1273            "- `{}` (`{}` in `{}`)",
1274            driver.name,
1275            driver.rust.driver_type,
1276            driver.rust.module_path
1277        );
1278        if !driver.watched_effects.is_empty() {
1279            pushln!(&mut out, "  - watches:");
1280            for watched in &driver.watched_effects {
1281                pushln!(
1282                    &mut out,
1283                    "    - `{}::{}`",
1284                    watched.producer_instance,
1285                    watched.effect_variant
1286                );
1287            }
1288        }
1289        if !driver.dispatch_routes.is_empty() {
1290            pushln!(&mut out, "  - dispatches:");
1291            for dispatch in &driver.dispatch_routes {
1292                pushln!(
1293                    &mut out,
1294                    "    - `{}` → `{}::{}` ({:?})",
1295                    dispatch.name,
1296                    dispatch.target_instance,
1297                    dispatch.input_variant,
1298                    dispatch.target_kind
1299                );
1300            }
1301        }
1302        if !driver.refusal_closures.is_empty() {
1303            pushln!(&mut out, "  - consumer-refusal closures:");
1304            for closure in &driver.refusal_closures {
1305                pushln!(
1306                    &mut out,
1307                    "    - `{}` refusal → `{}::{}`",
1308                    closure.dispatch_route,
1309                    closure.feedback_instance,
1310                    closure.feedback_input
1311                );
1312            }
1313        }
1314    } else {
1315        pushln!(&mut out, "- `(none)`");
1316    }
1317    pushln!(&mut out);
1318
1319    pushln!(&mut out, "## Transaction Plans");
1320    if schema.transaction_plans.is_empty() {
1321        pushln!(&mut out, "- `(none)`");
1322    } else {
1323        for plan in &schema.transaction_plans {
1324            pushln!(
1325                &mut out,
1326                "- `{}` via `{}` / `{}` — {}",
1327                plan.name,
1328                plan.trigger,
1329                plan.store_primitive,
1330                plan.description
1331            );
1332        }
1333    }
1334    pushln!(&mut out);
1335
1336    pushln!(&mut out, "## Scheduler Rules");
1337    if schema.scheduler_rules.is_empty() {
1338        pushln!(&mut out, "- `(none)`");
1339    } else {
1340        for rule in &schema.scheduler_rules {
1341            pushln!(&mut out, "- `{}`", render_scheduler_rule(rule));
1342        }
1343    }
1344    pushln!(&mut out);
1345
1346    let structural_invariants = schema
1347        .invariants
1348        .iter()
1349        .filter(|invariant| invariant.kind.is_structural())
1350        .collect::<Vec<_>>();
1351    let behavioral_invariants = schema
1352        .invariants
1353        .iter()
1354        .filter(|invariant| invariant.kind.is_behavioral())
1355        .collect::<Vec<_>>();
1356
1357    pushln!(&mut out, "## Structural Requirements");
1358    if structural_invariants.is_empty() {
1359        pushln!(&mut out, "- `(none)`");
1360    } else {
1361        for invariant in &structural_invariants {
1362            pushln!(&mut out, "- `{}` — {}", invariant.name, invariant.statement);
1363        }
1364    }
1365    pushln!(&mut out);
1366
1367    writeln!(&mut out, "## Behavioral Invariants");
1368    if behavioral_invariants.is_empty() {
1369        pushln!(&mut out, "- `(none)`");
1370    } else {
1371        for invariant in &behavioral_invariants {
1372            pushln!(&mut out, "- `{}` — {}", invariant.name, invariant.statement);
1373        }
1374    }
1375    pushln!(&mut out);
1376
1377    writeln!(&mut out, "## Coverage");
1378    pushln!(&mut out, "### Code Anchors");
1379    for anchor in &coverage.code_anchors {
1380        pushln!(
1381            &mut out,
1382            "{}",
1383            render_contract_coverage_anchor_bullet(anchor)
1384        );
1385    }
1386    pushln!(&mut out);
1387    pushln!(&mut out, "### Scenarios");
1388    for scenario in &coverage.scenarios {
1389        pushln!(&mut out, "- `{}` — {}", scenario.id, scenario.summary);
1390    }
1391
1392    out
1393}
1394
1395pub fn render_machine_ci_cfg(
1396    schema: &MachineSchema,
1397    deep: bool,
1398) -> Result<String, CompositionTlaError> {
1399    if schema.tlc_model.is_some() {
1400        validate_machine_model(schema)?;
1401    }
1402    let mut out = String::new();
1403    let domains = collect_binding_domains(schema);
1404    let named_samples = collect_machine_named_type_samples(schema);
1405    let deep_named_samples = with_guard_binding_string_samples(&named_samples, schema);
1406    // The native SessionId/String bridge deliberately substitutes its sample
1407    // into a fixed-size Deep string pool; keep that bound for bridge machines.
1408    let deep_guard_string_samples = deep && !machine_uses_session_id_string_bridge(schema);
1409    let named_bindings = collect_machine_named_bindings(schema);
1410    let sample_cardinality = machine_cfg_sample_cardinality(schema, deep);
1411    let operator_suffix = if deep { "Deep" } else { "Ci" };
1412    let uses_u64_max = machine_uses_u64_max(schema);
1413    let session_id_cardinality = if deep {
1414        schema
1415            .deep_domain_overrides
1416            .get("SessionIdValues")
1417            .copied()
1418            .unwrap_or(sample_cardinality)
1419    } else {
1420        sample_cardinality
1421    };
1422    let session_id_string_bridge_sample = session_id_string_bridge_sample(
1423        deep && machine_uses_session_id_string_bridge(schema),
1424        &domains,
1425        session_id_cardinality,
1426        &named_samples,
1427        &named_bindings,
1428    );
1429    let input_samples = machine_input_sample_constants(schema);
1430    let typed_samples = machine_input_typed_sample_constants(schema);
1431
1432    pushln!(&mut out, "SPECIFICATION Spec");
1433    if !domains.is_empty() || uses_u64_max || !input_samples.is_empty() || !typed_samples.is_empty()
1434    {
1435        pushln!(&mut out, "CONSTANTS");
1436        if uses_u64_max {
1437            push_u64_max_cfg_assignment(&mut out);
1438        }
1439        for (name, ty) in domains {
1440            if matches!(
1441                ty,
1442                TypeRef::Seq(_) | TypeRef::Option(_) | TypeRef::Map(_, _)
1443            ) {
1444                continue;
1445            }
1446            if machine_explicit_values(schema, deep, &ty).is_some()
1447                || cfg_assignment_requires_model_operator(&ty, &named_bindings)
1448            {
1449                writeln!(
1450                    &mut out,
1451                    "  {} <- {}",
1452                    name,
1453                    cfg_assignment_operator_name(&name, operator_suffix),
1454                )
1455                .expect("write to string");
1456            } else {
1457                // Deep-profile per-domain override (machine analog of the
1458                // composition path): absent keys use the profile default.
1459                let domain_cardinality = if deep {
1460                    schema
1461                        .deep_domain_overrides
1462                        .get(name.as_str())
1463                        .copied()
1464                        .unwrap_or(sample_cardinality)
1465                } else {
1466                    sample_cardinality
1467                };
1468                writeln!(
1469                    &mut out,
1470                    "  {} = {}",
1471                    name,
1472                    render_cfg_domain_assignment(
1473                        &ty,
1474                        domain_cardinality,
1475                        if deep_guard_string_samples {
1476                            &deep_named_samples
1477                        } else {
1478                            &named_samples
1479                        },
1480                        &named_bindings,
1481                        deep_guard_string_samples,
1482                        session_id_string_bridge_sample.as_deref(),
1483                    )
1484                )
1485                .expect("write to string");
1486            }
1487        }
1488        // A `CiValues` input field: the CI profile explores exactly its
1489        // declared values, the Deep profile those and the default `0..2`.
1490        for (constant, ci_values) in &input_samples {
1491            let values: BTreeSet<u64> = if deep {
1492                broad_input_samples(ci_values)
1493            } else {
1494                ci_values.iter().copied().collect()
1495            };
1496            writeln!(&mut out, "  {} = {}", constant, render_u64_set(&values))
1497                .expect("write to string");
1498        }
1499        // A `CiSamples` input field: the CI profile explores exactly its
1500        // declared values, the Deep profile the field type's whole domain,
1501        // through the operators the generated model defines.
1502        for (constant, _, _) in &typed_samples {
1503            writeln!(
1504                &mut out,
1505                "  {} <- {}",
1506                constant,
1507                cfg_assignment_operator_name(constant, operator_suffix)
1508            )
1509            .expect("write to string");
1510        }
1511    }
1512    if !schema.invariants.is_empty() {
1513        pushln!(&mut out, "INVARIANTS");
1514        for invariant in &schema.invariants {
1515            pushln!(&mut out, "  {}", invariant.name);
1516        }
1517    }
1518    pushln!(&mut out, "CONSTRAINTS");
1519    writeln!(
1520        &mut out,
1521        "  {}",
1522        if deep {
1523            "DeepStateConstraint"
1524        } else {
1525            "CiStateConstraint"
1526        }
1527    )
1528    .expect("write to string");
1529
1530    Ok(out)
1531}
1532
1533pub fn render_composition_ci_cfg(schema: &CompositionSchema, deep: bool) -> String {
1534    render_composition_ci_cfg_from_catalog(schema, deep, &canonical_machine_schemas())
1535}
1536
1537/// [`render_composition_ci_cfg`] against an explicitly supplied machine
1538/// catalog, for compositions whose machines live outside Meerkat's catalog.
1539pub fn render_composition_ci_cfg_with_catalog(
1540    schema: &CompositionSchema,
1541    deep: bool,
1542    machine_catalog: &[MachineSchema],
1543) -> std::result::Result<String, CompositionTlaError> {
1544    validate_supplied_catalog(schema, machine_catalog)?;
1545    Ok(render_composition_ci_cfg_from_catalog(
1546        schema,
1547        deep,
1548        machine_catalog,
1549    ))
1550}
1551
1552fn render_composition_ci_cfg_from_catalog(
1553    schema: &CompositionSchema,
1554    deep: bool,
1555    machine_catalog: &[MachineSchema],
1556) -> String {
1557    let mut out = String::new();
1558    let machine_by_name = machine_catalog
1559        .iter()
1560        .map(|machine| (machine.machine.as_str(), machine))
1561        .collect::<BTreeMap<_, _>>();
1562    let machine_by_instance = schema
1563        .machines
1564        .iter()
1565        .filter_map(|instance| {
1566            machine_by_name
1567                .get(instance.machine_name.as_str())
1568                .copied()
1569                .map(|machine| (instance.instance_id.as_str(), machine))
1570        })
1571        .collect::<BTreeMap<_, _>>();
1572    let domains = collect_composition_binding_domains(schema, &machine_by_instance);
1573    let named_samples = collect_composition_named_type_samples(schema, &machine_by_instance);
1574    let named_bindings = collect_composition_named_bindings(machine_by_instance.values().copied());
1575    let operator_suffix = if deep { "Deep" } else { "Ci" };
1576    let mut instance_invariants = Vec::new();
1577    let mut obligation_invariants = Vec::new();
1578    let uses_u64_max = composition_uses_u64_max(schema, &machine_by_instance);
1579    let session_id_cardinality = if deep {
1580        schema
1581            .deep_domain_overrides
1582            .get("SessionIdValues")
1583            .copied()
1584            .unwrap_or(schema.deep_domain_cardinality)
1585    } else {
1586        default_sample_cardinality(false)
1587    };
1588    let session_id_string_bridge_sample = session_id_string_bridge_sample(
1589        deep && composition_uses_session_id_string_bridge(&machine_by_instance),
1590        &domains,
1591        session_id_cardinality,
1592        &named_samples,
1593        &named_bindings,
1594    );
1595
1596    for instance in &schema.machines {
1597        let Some(machine) = machine_by_instance
1598            .get(instance.instance_id.as_str())
1599            .copied()
1600        else {
1601            continue;
1602        };
1603        for invariant in &machine.invariants {
1604            instance_invariants.push(format!(
1605                "{}_{}",
1606                tla_ident(&instance.instance_id),
1607                tla_ident(&invariant.name)
1608            ));
1609        }
1610    }
1611    for protocol in &schema.handoff_protocols {
1612        let suffix = format!(
1613            "{}_{}",
1614            tla_ident(&protocol.producer_instance),
1615            tla_ident(&protocol.name)
1616        );
1617        if machine_by_instance
1618            .get(protocol.producer_instance.as_str())
1619            .is_some_and(|machine| terminal_closure_required(protocol, machine))
1620        {
1621            obligation_invariants.push(format!("NoOpenObligationsOnTerminal_{suffix}"));
1622        }
1623    }
1624    if schema
1625        .handoff_protocols
1626        .iter()
1627        .any(|protocol| !protocol.allowed_feedback_inputs.is_empty())
1628    {
1629        obligation_invariants.push("OwnerFeedbackHasProtocolProvenance".to_string());
1630    }
1631    pushln!(&mut out, "SPECIFICATION Spec");
1632    if !domains.is_empty() || uses_u64_max {
1633        pushln!(&mut out, "CONSTANTS");
1634        if uses_u64_max {
1635            push_u64_max_cfg_assignment(&mut out);
1636        }
1637        for (name, ty) in domains {
1638            if matches!(
1639                ty,
1640                TypeRef::Seq(_) | TypeRef::Option(_) | TypeRef::Map(_, _)
1641            ) {
1642                continue;
1643            }
1644            let cardinality = if deep {
1645                schema
1646                    .deep_domain_overrides
1647                    .get(name.as_str())
1648                    .copied()
1649                    .unwrap_or(schema.deep_domain_cardinality)
1650            } else {
1651                default_sample_cardinality(false)
1652            };
1653            if cfg_assignment_requires_model_operator(&ty, &named_bindings) {
1654                writeln!(
1655                    &mut out,
1656                    "  {} <- {}",
1657                    name,
1658                    cfg_assignment_operator_name(&name, operator_suffix),
1659                )
1660                .expect("write to string");
1661            } else {
1662                writeln!(
1663                    &mut out,
1664                    "  {} = {}",
1665                    name,
1666                    render_cfg_domain_assignment(
1667                        &ty,
1668                        cardinality,
1669                        &named_samples,
1670                        &named_bindings,
1671                        false,
1672                        session_id_string_bridge_sample.as_deref(),
1673                    )
1674                )
1675                .expect("write to string");
1676            }
1677        }
1678    }
1679    let behavioral_invariants = schema
1680        .invariants
1681        .iter()
1682        .filter(|invariant| invariant.kind.is_behavioral())
1683        .collect::<Vec<_>>();
1684    // Structural requirements (route/scheduler/priority presence, etc.) are
1685    // static, cheap-to-check predicates over the generated topology. They were
1686    // previously only validated in the Deep witness lane; emit them into the
1687    // standard INVARIANTS block unconditionally so the default (Ci) verify
1688    // profile fails closed on a missing structural requirement instead of
1689    // deferring the check to a Deep-only run.
1690    let structural_invariants = schema
1691        .invariants
1692        .iter()
1693        .filter(|invariant| invariant.kind.is_structural())
1694        .collect::<Vec<_>>();
1695    if !behavioral_invariants.is_empty()
1696        || !structural_invariants.is_empty()
1697        || !instance_invariants.is_empty()
1698        || !obligation_invariants.is_empty()
1699        || deep
1700    {
1701        pushln!(&mut out, "INVARIANTS");
1702        for invariant in behavioral_invariants {
1703            pushln!(&mut out, "  {}", invariant.name);
1704        }
1705        for invariant in structural_invariants {
1706            pushln!(&mut out, "  {}", invariant.name);
1707        }
1708        for invariant_name in instance_invariants {
1709            pushln!(&mut out, "  {}", invariant_name);
1710        }
1711        for invariant_name in obligation_invariants {
1712            pushln!(&mut out, "  {}", invariant_name);
1713        }
1714        if deep {
1715            pushln!(&mut out, "  CoverageInstrumentation");
1716        }
1717    }
1718    pushln!(&mut out, "CONSTRAINTS");
1719    writeln!(
1720        &mut out,
1721        "  {}",
1722        if deep {
1723            "DeepStateConstraint"
1724        } else {
1725            "CiStateConstraint"
1726        }
1727    )
1728    .expect("write to string");
1729
1730    out
1731}
1732
1733pub fn render_composition_witness_cfg(
1734    schema: &CompositionSchema,
1735    witness: &CompositionWitness,
1736) -> String {
1737    render_composition_witness_cfg_from_catalog(schema, witness, &canonical_machine_schemas())
1738}
1739
1740/// [`render_composition_witness_cfg`] against an explicitly supplied machine
1741/// catalog, for compositions whose machines live outside Meerkat's catalog.
1742pub fn render_composition_witness_cfg_with_catalog(
1743    schema: &CompositionSchema,
1744    witness: &CompositionWitness,
1745    machine_catalog: &[MachineSchema],
1746) -> std::result::Result<String, CompositionTlaError> {
1747    validate_supplied_catalog(schema, machine_catalog)?;
1748    Ok(render_composition_witness_cfg_from_catalog(
1749        schema,
1750        witness,
1751        machine_catalog,
1752    ))
1753}
1754
1755fn render_composition_witness_cfg_from_catalog(
1756    schema: &CompositionSchema,
1757    witness: &CompositionWitness,
1758    machine_catalog: &[MachineSchema],
1759) -> String {
1760    let mut out = String::new();
1761    let machine_by_name = machine_catalog
1762        .iter()
1763        .map(|machine| (machine.machine.as_str(), machine))
1764        .collect::<BTreeMap<_, _>>();
1765    let machine_by_instance = schema
1766        .machines
1767        .iter()
1768        .filter_map(|instance| {
1769            machine_by_name
1770                .get(instance.machine_name.as_str())
1771                .copied()
1772                .map(|machine| (instance.instance_id.as_str(), machine))
1773        })
1774        .collect::<BTreeMap<_, _>>();
1775    let domains = collect_composition_binding_domains(schema, &machine_by_instance);
1776    let named_samples =
1777        collect_composition_witness_named_type_samples(schema, witness, &machine_by_instance);
1778    let named_bindings = collect_composition_named_bindings(machine_by_instance.values().copied());
1779    let witness_sample_cardinality = schema
1780        .witness_domain_cardinality
1781        .max(max_named_sample_cardinality(&named_samples));
1782    let operator_suffix = witness_cfg_operator_suffix(witness);
1783    let mut instance_invariants = Vec::new();
1784    let mut obligation_invariants = Vec::new();
1785    let uses_u64_max = composition_uses_u64_max(schema, &machine_by_instance);
1786
1787    for instance in &schema.machines {
1788        let Some(machine) = machine_by_instance
1789            .get(instance.instance_id.as_str())
1790            .copied()
1791        else {
1792            continue;
1793        };
1794        for invariant in &machine.invariants {
1795            instance_invariants.push(format!(
1796                "{}_{}",
1797                tla_ident(&instance.instance_id),
1798                tla_ident(&invariant.name)
1799            ));
1800        }
1801    }
1802    for protocol in &schema.handoff_protocols {
1803        let suffix = format!(
1804            "{}_{}",
1805            tla_ident(&protocol.producer_instance),
1806            tla_ident(&protocol.name)
1807        );
1808        if machine_by_instance
1809            .get(protocol.producer_instance.as_str())
1810            .is_some_and(|machine| terminal_closure_required(protocol, machine))
1811        {
1812            obligation_invariants.push(format!("NoOpenObligationsOnTerminal_{suffix}"));
1813        }
1814    }
1815    if schema
1816        .handoff_protocols
1817        .iter()
1818        .any(|protocol| !protocol.allowed_feedback_inputs.is_empty())
1819    {
1820        obligation_invariants.push("OwnerFeedbackHasProtocolProvenance".to_string());
1821    }
1822
1823    writeln!(
1824        &mut out,
1825        "SPECIFICATION {}",
1826        composition_witness_spec_name(&witness.name)
1827    )
1828    .expect("write to string");
1829    if !domains.is_empty() || uses_u64_max {
1830        pushln!(&mut out, "CONSTANTS");
1831        if uses_u64_max {
1832            push_u64_max_cfg_assignment(&mut out);
1833        }
1834        for (name, ty) in domains {
1835            if matches!(
1836                ty,
1837                TypeRef::Seq(_) | TypeRef::Option(_) | TypeRef::Map(_, _)
1838            ) {
1839                continue;
1840            }
1841            if cfg_assignment_requires_model_operator(&ty, &named_bindings) {
1842                writeln!(
1843                    &mut out,
1844                    "  {} <- {}",
1845                    name,
1846                    cfg_assignment_operator_name(&name, &operator_suffix),
1847                )
1848                .expect("write to string");
1849            } else {
1850                writeln!(
1851                    &mut out,
1852                    "  {} = {}",
1853                    name,
1854                    render_default_domain_assignment(
1855                        &ty,
1856                        witness_sample_cardinality,
1857                        &named_samples,
1858                        &named_bindings,
1859                        true,
1860                    )
1861                )
1862                .expect("write to string");
1863            }
1864        }
1865    }
1866    let witness_properties = witness
1867        .expected_routes
1868        .iter()
1869        .map(|route| composition_witness_route_property_name(&witness.name, route))
1870        .chain(
1871            witness
1872                .expected_scheduler_rules
1873                .iter()
1874                .map(|rule| composition_witness_scheduler_property_name(&witness.name, rule)),
1875        )
1876        .chain(
1877            witness
1878                .expected_states
1879                .iter()
1880                .enumerate()
1881                .map(|(idx, _)| composition_witness_state_property_name(&witness.name, idx)),
1882        )
1883        .chain(witness.expected_transitions.iter().map(|transition| {
1884            composition_witness_transition_property_name(
1885                &witness.name,
1886                &transition.machine,
1887                &transition.transition,
1888            )
1889        }))
1890        .chain(
1891            witness
1892                .expected_transition_order
1893                .iter()
1894                .enumerate()
1895                .map(|(idx, _)| {
1896                    composition_witness_transition_order_property_name(&witness.name, idx)
1897                }),
1898        )
1899        .collect::<Vec<_>>();
1900    let explicit_witness = CompositionTlaCompiler::witness_has_explicit_progress(witness);
1901    if !schema.invariants.is_empty()
1902        || !instance_invariants.is_empty()
1903        || !obligation_invariants.is_empty()
1904        || (explicit_witness && !witness_properties.is_empty())
1905    {
1906        pushln!(&mut out, "INVARIANTS");
1907        for invariant in &schema.invariants {
1908            pushln!(&mut out, "  {}", invariant.name);
1909        }
1910        for invariant_name in instance_invariants {
1911            pushln!(&mut out, "  {}", invariant_name);
1912        }
1913        for invariant_name in obligation_invariants {
1914            pushln!(&mut out, "  {}", invariant_name);
1915        }
1916        pushln!(&mut out, "  CoverageInstrumentation");
1917        if explicit_witness {
1918            for property in &witness_properties {
1919                pushln!(&mut out, "  {property}");
1920            }
1921        }
1922    }
1923    if !explicit_witness && !witness_properties.is_empty() {
1924        pushln!(&mut out, "PROPERTIES");
1925        for property in witness_properties {
1926            pushln!(&mut out, "  {property}");
1927        }
1928    }
1929    if explicit_witness {
1930        pushln!(&mut out, "ACTION_CONSTRAINTS");
1931        pushln!(
1932            &mut out,
1933            "  {}",
1934            composition_witness_action_constraint_name(&witness.name)
1935        );
1936    }
1937    pushln!(&mut out, "CONSTRAINTS");
1938    writeln!(
1939        &mut out,
1940        "  {}",
1941        composition_witness_state_constraint_name(&witness.name)
1942    )
1943    .expect("write to string");
1944
1945    out
1946}
1947
1948pub fn composition_route_observed_operator_name(route_name: impl AsRef<str>) -> String {
1949    format!("RouteObserved_{}", tla_ident(route_name))
1950}
1951
1952pub fn composition_route_coverage_operator_name(route_name: impl AsRef<str>) -> String {
1953    format!("RouteCoverage_{}", tla_ident(route_name))
1954}
1955
1956pub fn composition_scheduler_triggered_operator_name(rule: &SchedulerRule) -> String {
1957    match rule {
1958        SchedulerRule::PreemptWhenReady { higher, lower } => format!(
1959            "SchedulerTriggered_PreemptWhenReady_{}_{}",
1960            tla_ident(higher),
1961            tla_ident(lower)
1962        ),
1963    }
1964}
1965
1966pub fn composition_scheduler_coverage_operator_name(rule: &SchedulerRule) -> String {
1967    match rule {
1968        SchedulerRule::PreemptWhenReady { higher, lower } => format!(
1969            "SchedulerCoverage_PreemptWhenReady_{}_{}",
1970            tla_ident(higher),
1971            tla_ident(lower)
1972        ),
1973    }
1974}
1975
1976fn max_named_sample_cardinality(named_samples: &BTreeMap<String, BTreeSet<String>>) -> usize {
1977    named_samples.values().map(BTreeSet::len).max().unwrap_or(1)
1978}
1979
1980struct CfgAssignmentOperatorProfile<'a> {
1981    suffix: String,
1982    explicit_values: Option<&'a meerkat_machine_schema::MachineTlcProfile>,
1983    sample_cardinality: usize,
1984    domain_overrides: Option<&'a BTreeMap<String, usize>>,
1985    named_samples: &'a BTreeMap<String, BTreeSet<String>>,
1986    include_string_samples: bool,
1987}
1988
1989fn cfg_assignment_operator_name(domain_name: &str, suffix: impl AsRef<str>) -> String {
1990    format!("{}{}", tla_ident(domain_name), tla_ident(suffix))
1991}
1992
1993fn push_u64_max_cfg_assignment(out: &mut String) {
1994    pushln!(
1995        out,
1996        "  \\* Rust u64::MAX, supplied as a finite TLC model-checking value."
1997    );
1998    writeln!(
1999        out,
2000        "  {} = {}",
2001        TLA_RUST_U64_MAX_CONSTANT, TLC_SAFE_RUST_U64_MAX_VALUE
2002    )
2003    .expect("write to string");
2004}
2005
2006fn witness_cfg_operator_suffix(witness: &CompositionWitness) -> String {
2007    format!("Witness{}", tla_ident(&witness.name))
2008}
2009
2010fn profile_sample_cardinality(
2011    profile: &CfgAssignmentOperatorProfile<'_>,
2012    domain_name: &str,
2013) -> usize {
2014    profile
2015        .domain_overrides
2016        .and_then(|overrides| overrides.get(domain_name).copied())
2017        .unwrap_or(profile.sample_cardinality)
2018}
2019
2020fn profile_sample_cardinality_for_domain(
2021    profile: &CfgAssignmentOperatorProfile<'_>,
2022    domain_name: &str,
2023    ty: &TypeRef,
2024    named_bindings: &BTreeMap<String, meerkat_machine_schema::RustTypeAtom>,
2025) -> usize {
2026    let sample_cardinality = profile_sample_cardinality(profile, domain_name);
2027    if profile.suffix == "Ci" && cfg_assignment_requires_model_operator(ty, named_bindings) {
2028        return 0;
2029    }
2030
2031    sample_cardinality
2032}
2033
2034fn machine_cfg_sample_cardinality(schema: &MachineSchema, deep: bool) -> usize {
2035    if !deep && schema.ci_step_limit == Some(1) {
2036        0
2037    } else {
2038        default_sample_cardinality(deep)
2039    }
2040}
2041
2042fn session_id_string_bridge_sample(
2043    enabled: bool,
2044    domains: &BTreeMap<String, TypeRef>,
2045    session_id_cardinality: usize,
2046    named_samples: &BTreeMap<String, BTreeSet<String>>,
2047    named_bindings: &BTreeMap<String, meerkat_machine_schema::RustTypeAtom>,
2048) -> Option<String> {
2049    if !enabled {
2050        return None;
2051    }
2052
2053    assert!(
2054        matches!(
2055            domains.get("SessionIdValues"),
2056            Some(TypeRef::Named(name)) if name.as_str() == "SessionId"
2057        ) && matches!(domains.get("StringValues"), Some(TypeRef::String)),
2058        "the SessionId/String native bridge requires both model domains"
2059    );
2060
2061    let sample = sample_values_for_named_type(
2062        "SessionId",
2063        session_id_cardinality.max(1),
2064        named_samples,
2065        named_bindings,
2066    )
2067    .into_iter()
2068    .next();
2069    assert!(
2070        sample.is_some(),
2071        "the SessionId/String native bridge requires a SessionId sample"
2072    );
2073    sample
2074}
2075
2076fn render_cfg_domain_assignment(
2077    ty: &TypeRef,
2078    sample_cardinality: usize,
2079    named_samples: &BTreeMap<String, BTreeSet<String>>,
2080    named_bindings: &BTreeMap<String, meerkat_machine_schema::RustTypeAtom>,
2081    include_string_samples: bool,
2082    session_id_string_bridge_sample: Option<&str>,
2083) -> String {
2084    let bridge_applies_to_session_id = matches!(
2085        ty,
2086        TypeRef::Named(name) if name.as_str() == "SessionId"
2087    );
2088    let effective_cardinality = if session_id_string_bridge_sample.is_some()
2089        && (matches!(ty, TypeRef::String) || bridge_applies_to_session_id)
2090    {
2091        sample_cardinality.max(1)
2092    } else {
2093        sample_cardinality
2094    };
2095
2096    if let (TypeRef::String, Some(bridge_sample)) = (ty, session_id_string_bridge_sample) {
2097        let mut samples =
2098            collected_string_samples(effective_cardinality, named_samples, include_string_samples)
2099                .into_iter()
2100                .map(|sample| tla_string(&sample))
2101                .collect::<Vec<_>>();
2102        let baseline_sample_count = samples.len();
2103        samples.retain(|sample| sample != bridge_sample);
2104        samples.insert(0, bridge_sample.to_owned());
2105        // Deep transition coverage makes the equality branch a non-vacuity
2106        // gate. Substitute the shared SessionId value into StringValues rather
2107        // than growing the renderer's actual baseline pool (which can be
2108        // smaller than a configured cardinality) and multiplying the explored
2109        // state space.
2110        if !include_string_samples {
2111            samples.truncate(baseline_sample_count);
2112        }
2113        return format!("{{{}}}", samples.join(", "));
2114    }
2115
2116    render_default_domain_assignment(
2117        ty,
2118        effective_cardinality,
2119        named_samples,
2120        named_bindings,
2121        include_string_samples,
2122    )
2123}
2124
2125fn push_cfg_assignment_operator_definitions(
2126    out: &mut String,
2127    domains: &BTreeMap<String, TypeRef>,
2128    named_bindings: &BTreeMap<String, meerkat_machine_schema::RustTypeAtom>,
2129    profile: &CfgAssignmentOperatorProfile<'_>,
2130) -> bool {
2131    let mut wrote = false;
2132    for (name, ty) in domains {
2133        let explicit = profile
2134            .explicit_values
2135            .and_then(|values| profile_explicit_values(values, ty));
2136        if cfg_domain_is_skipped_in_cfg(ty)
2137            || (explicit.is_none() && !cfg_assignment_requires_model_operator(ty, named_bindings))
2138        {
2139            continue;
2140        }
2141        let sample_cardinality =
2142            profile_sample_cardinality_for_domain(profile, name, ty, named_bindings);
2143        let assignment = explicit.map(render_explicit_values).unwrap_or_else(|| {
2144            render_default_domain_assignment(
2145                ty,
2146                sample_cardinality,
2147                profile.named_samples,
2148                named_bindings,
2149                profile.include_string_samples,
2150            )
2151        });
2152        writeln!(
2153            out,
2154            "{} == {}",
2155            cfg_assignment_operator_name(name, &profile.suffix),
2156            assignment
2157        )
2158        .expect("write to string");
2159        wrote = true;
2160    }
2161    if wrote {
2162        pushln!(out);
2163    }
2164    wrote
2165}
2166
2167fn validate_machine_model(schema: &MachineSchema) -> Result<(), CompositionTlaError> {
2168    let invalid = |reason| CompositionTlaError::InvalidTlcModel {
2169        machine: schema.machine.to_string(),
2170        reason,
2171    };
2172    schema
2173        .validate()
2174        .map_err(|error| invalid(error.to_string()))?;
2175    if let Some(model) = &schema.tlc_model {
2176        let domains = collect_binding_domains(schema);
2177        for profile in [&model.ci, &model.deep] {
2178            for name in profile.named_values.keys() {
2179                if !domains.values().any(|ty| match ty {
2180                    TypeRef::Named(id) => id == name,
2181                    TypeRef::Enum(id) => id.as_str() == name.as_str(),
2182                    _ => false,
2183                }) {
2184                    return Err(invalid(format!(
2185                        "explicit sample type {name} has no standalone model domain"
2186                    )));
2187                }
2188            }
2189        }
2190    }
2191    Ok(())
2192}
2193
2194fn profile_explicit_values<'a>(
2195    profile: &'a meerkat_machine_schema::MachineTlcProfile,
2196    ty: &TypeRef,
2197) -> Option<&'a [meerkat_machine_schema::TlcValue]> {
2198    let name = match ty {
2199        TypeRef::Named(name) => name.as_str(),
2200        TypeRef::Enum(name) => name.as_str(),
2201        _ => return None,
2202    };
2203    profile
2204        .named_values
2205        .iter()
2206        .find(|(id, _)| id.as_str() == name)
2207        .map(|(_, values)| values.as_slice())
2208}
2209
2210fn machine_explicit_values<'a>(
2211    schema: &'a MachineSchema,
2212    deep: bool,
2213    ty: &TypeRef,
2214) -> Option<&'a [meerkat_machine_schema::TlcValue]> {
2215    let model = schema.tlc_model.as_ref()?;
2216    profile_explicit_values(if deep { &model.deep } else { &model.ci }, ty)
2217}
2218
2219fn render_explicit_values(values: &[meerkat_machine_schema::TlcValue]) -> String {
2220    format!(
2221        "{{{}}}",
2222        values
2223            .iter()
2224            .map(render_explicit_value)
2225            .collect::<Vec<_>>()
2226            .join(", ")
2227    )
2228}
2229
2230fn render_explicit_value(value: &meerkat_machine_schema::TlcValue) -> String {
2231    use meerkat_machine_schema::TlcValue;
2232    match value {
2233        TlcValue::Bool(value) => if *value { "TRUE" } else { "FALSE" }.into(),
2234        TlcValue::U64(value) if *value == u64::MAX => TLA_RUST_U64_MAX_CONSTANT.to_owned(),
2235        TlcValue::U64(value) => value.to_string(),
2236        TlcValue::String(value) => tla_string(value),
2237        TlcValue::None => "None".into(),
2238        TlcValue::Some(value) => format!("Some({})", render_explicit_value(value)),
2239        TlcValue::Set(values) => render_explicit_values(values),
2240        TlcValue::Record(fields) => format!(
2241            "[{}]",
2242            fields
2243                .iter()
2244                .map(|(field, value)| format!(
2245                    "{} |-> {}",
2246                    tla_ident(field.as_str()),
2247                    render_explicit_value(value)
2248                ))
2249                .collect::<Vec<_>>()
2250                .join(", ")
2251        ),
2252    }
2253}
2254
2255fn cfg_domain_is_skipped_in_cfg(ty: &TypeRef) -> bool {
2256    matches!(
2257        ty,
2258        TypeRef::Seq(_) | TypeRef::Option(_) | TypeRef::Map(_, _)
2259    )
2260}
2261
2262fn cfg_assignment_requires_model_operator(
2263    ty: &TypeRef,
2264    named_bindings: &BTreeMap<String, meerkat_machine_schema::RustTypeAtom>,
2265) -> bool {
2266    match ty {
2267        TypeRef::Named(name) => {
2268            require_named_binding(named_bindings, name.as_str()).renders_cfg_hostile_record()
2269        }
2270        TypeRef::Enum(name) => {
2271            require_named_binding(named_bindings, name.as_str()).renders_cfg_hostile_record()
2272        }
2273        TypeRef::Set(inner) | TypeRef::Seq(inner) => {
2274            cfg_assignment_requires_model_operator(inner, named_bindings)
2275        }
2276        TypeRef::Option(_) | TypeRef::Map(_, _) => true,
2277        TypeRef::Bool | TypeRef::U32 | TypeRef::U64 | TypeRef::String => false,
2278    }
2279}
2280
2281trait CfgRecordRendering {
2282    fn renders_cfg_hostile_record(&self) -> bool;
2283}
2284
2285impl CfgRecordRendering for meerkat_machine_schema::RustTypeAtom {
2286    fn renders_cfg_hostile_record(&self) -> bool {
2287        match self {
2288            meerkat_machine_schema::RustTypeAtom::TypePathStruct { .. } => true,
2289            meerkat_machine_schema::RustTypeAtom::TypePathEnum {
2290                structural_variants,
2291                ..
2292            } => !structural_variants.is_empty(),
2293            _ => false,
2294        }
2295    }
2296}
2297
2298pub fn composition_witness_cfg_name(name: impl AsRef<str>) -> String {
2299    format!("witness-{}.cfg", tla_ident(name.as_ref()))
2300}
2301
2302fn composition_witness_route_property_name(
2303    witness: impl AsRef<str>,
2304    route_name: impl AsRef<str>,
2305) -> String {
2306    format!(
2307        "WitnessRouteObserved_{}_{}",
2308        tla_ident(witness.as_ref()),
2309        tla_ident(route_name)
2310    )
2311}
2312
2313fn composition_witness_scheduler_property_name(
2314    witness: impl AsRef<str>,
2315    rule: &SchedulerRule,
2316) -> String {
2317    format!(
2318        "WitnessSchedulerTriggered_{}_{}",
2319        tla_ident(witness.as_ref()),
2320        tla_ident(witness_scheduler_rule_label(rule))
2321    )
2322}
2323
2324fn composition_witness_state_property_name(witness: impl AsRef<str>, index: usize) -> String {
2325    format!(
2326        "WitnessStateObserved_{}_{}",
2327        tla_ident(witness.as_ref()),
2328        index + 1
2329    )
2330}
2331
2332fn composition_witness_transition_property_name(
2333    witness: impl AsRef<str>,
2334    machine: impl AsRef<str>,
2335    transition: impl AsRef<str>,
2336) -> String {
2337    format!(
2338        "WitnessTransitionObserved_{}_{}_{}",
2339        tla_ident(witness.as_ref()),
2340        tla_ident(machine),
2341        tla_ident(transition)
2342    )
2343}
2344
2345fn composition_witness_transition_order_property_name(
2346    witness: impl AsRef<str>,
2347    index: usize,
2348) -> String {
2349    format!(
2350        "WitnessTransitionOrder_{}_{}",
2351        tla_ident(witness.as_ref()),
2352        index + 1
2353    )
2354}
2355
2356fn witness_scheduler_rule_label(rule: &SchedulerRule) -> String {
2357    match rule {
2358        SchedulerRule::PreemptWhenReady { higher, lower } => {
2359            format!("PreemptWhenReady_{}_{}", higher, lower)
2360        }
2361    }
2362}
2363
2364fn composition_witness_init_name(name: impl AsRef<str>) -> String {
2365    format!("WitnessInit_{}", tla_ident(name.as_ref()))
2366}
2367
2368fn composition_witness_next_name(name: impl AsRef<str>) -> String {
2369    format!("WitnessNext_{}", tla_ident(name.as_ref()))
2370}
2371
2372fn composition_witness_spec_name(name: impl AsRef<str>) -> String {
2373    format!("WitnessSpec_{}", tla_ident(name.as_ref()))
2374}
2375
2376fn composition_witness_fairness_name(name: impl AsRef<str>, index: usize) -> String {
2377    format!("WitnessFairness_{}_{}", tla_ident(name.as_ref()), index + 1)
2378}
2379
2380fn composition_witness_completion_name(name: impl AsRef<str>) -> String {
2381    format!("WitnessScriptComplete_{}", tla_ident(name.as_ref()))
2382}
2383
2384fn composition_witness_action_constraint_name(name: impl AsRef<str>) -> String {
2385    format!("WitnessNoPrematureStutter_{}", tla_ident(name.as_ref()))
2386}
2387
2388fn composition_witness_state_constraint_name(name: impl AsRef<str>) -> String {
2389    format!("WitnessStateConstraint_{}", tla_ident(name.as_ref()))
2390}
2391
2392pub fn render_composition_semantic_model(
2393    schema: &CompositionSchema,
2394) -> std::result::Result<String, CompositionTlaError> {
2395    render_composition_semantic_model_from_catalog(schema, &canonical_machine_schemas())
2396}
2397
2398/// [`render_composition_semantic_model`] against an explicitly supplied
2399/// machine catalog, for compositions whose machines live outside Meerkat's
2400/// catalog.
2401pub fn render_composition_semantic_model_with_catalog(
2402    schema: &CompositionSchema,
2403    machine_catalog: &[MachineSchema],
2404) -> std::result::Result<String, CompositionTlaError> {
2405    validate_supplied_catalog(schema, machine_catalog)?;
2406    render_composition_semantic_model_from_catalog(schema, machine_catalog)
2407}
2408
2409fn render_composition_semantic_model_from_catalog(
2410    schema: &CompositionSchema,
2411    machine_catalog: &[MachineSchema],
2412) -> std::result::Result<String, CompositionTlaError> {
2413    // Fail closed: compiler construction (unknown machine schema, empty
2414    // catalog) and rendering (unresolved route component, helper-call cycle,
2415    // absent obligation field) used to be swallowed into `String::new()`,
2416    // producing a broken-but-passing model. Propagate the typed error so
2417    // `machine-generate` / `machine-check-drift` fail on malformed input.
2418    let compiler = CompositionTlaCompiler::new(schema, machine_catalog)
2419        .map_err(CompositionTlaError::Compile)?;
2420    compiler.render()
2421}
2422
2423/// Renders the generated per-composition Rust module (Track-B wave-b V2).
2424///
2425/// The emitted module is the typed seam between the composition's route
2426/// schema and the runtime composition dispatcher. It declares:
2427///
2428/// * generated producer/effect/input/signal/field identity facts,
2429/// * `TypedRoutedInput` / `TypedRoutedSignal` descriptors carrying typed
2430///   route targets and `(FieldId, FieldId)` binding pairs,
2431/// * a `route_to_input(instance, effect_variant) -> Option<TypedRoutedInput>`
2432///   fact resolver for input-kind routes, and
2433/// * a `route_to_signal(instance, effect_variant) -> Option<TypedRoutedSignal>`
2434///   fact resolver for signal-kind routes.
2435///
2436/// Returns `None` when the composition declares no driver descriptor; the
2437/// driver descriptor continues to carry the Rust emission path for xtask
2438/// consumers.
2439pub fn render_composition_driver(schema: &CompositionSchema) -> Option<String> {
2440    render_composition_driver_from_catalog(schema, &canonical_machine_schemas())
2441}
2442
2443/// [`render_composition_driver`] against an explicitly supplied machine
2444/// catalog, for compositions whose machines live outside Meerkat's catalog.
2445pub fn render_composition_driver_with_catalog(
2446    schema: &CompositionSchema,
2447    machine_catalog: &[MachineSchema],
2448) -> std::result::Result<Option<String>, CompositionTlaError> {
2449    validate_supplied_catalog(schema, machine_catalog)?;
2450    Ok(render_composition_driver_from_catalog(
2451        schema,
2452        machine_catalog,
2453    ))
2454}
2455
2456fn render_composition_driver_from_catalog(
2457    schema: &CompositionSchema,
2458    machine_catalog: &[MachineSchema],
2459) -> Option<String> {
2460    let driver = schema.driver.as_ref()?;
2461
2462    let machine_by_name = machine_catalog
2463        .iter()
2464        .map(|machine| (machine.machine.as_str(), machine))
2465        .collect::<BTreeMap<_, _>>();
2466
2467    let mut producers: Vec<(&str, &MachineSchema)> = Vec::new();
2468    let mut seen: BTreeSet<&str> = BTreeSet::new();
2469    for instance in &schema.machines {
2470        if !seen.insert(instance.instance_id.as_str()) {
2471            continue;
2472        }
2473        let Some(machine) = machine_by_name.get(instance.machine_name.as_str()).copied() else {
2474            continue;
2475        };
2476        producers.push((instance.instance_id.as_str(), machine));
2477    }
2478
2479    let composition_name = schema.name.as_str();
2480    let mut effect_variants_by_producer: BTreeMap<&str, BTreeSet<&str>> = BTreeMap::new();
2481    let mut input_variants: BTreeSet<&str> = BTreeSet::new();
2482    let mut signal_variants: BTreeSet<&str> = BTreeSet::new();
2483    let mut fields: BTreeSet<&str> = BTreeSet::new();
2484
2485    for route in &schema.routes {
2486        effect_variants_by_producer
2487            .entry(route.from_machine.as_str())
2488            .or_default()
2489            .insert(route.effect_variant.as_str());
2490
2491        match route.to.kind {
2492            RouteTargetKind::Input => {
2493                input_variants.insert(route.to.input_variant.as_str());
2494            }
2495            RouteTargetKind::Signal => {
2496                signal_variants.insert(route.to.input_variant.as_str());
2497            }
2498        }
2499
2500        for binding in &route.bindings {
2501            fields.insert(binding.to_field.as_str());
2502            if let RouteBindingSource::Field { from_field, .. } = &binding.source {
2503                fields.insert(from_field.as_str());
2504            }
2505        }
2506    }
2507    for closure in &driver.refusal_closures {
2508        input_variants.insert(closure.feedback_input.as_str());
2509        for binding in &closure.field_bindings {
2510            fields.insert(binding.input_field.as_str());
2511            if let DriverRefusalFieldSource::EffectField(source_field) = &binding.source {
2512                fields.insert(source_field.as_str());
2513            }
2514        }
2515    }
2516
2517    let mut out = String::new();
2518    pushln!(
2519        &mut out,
2520        "// @generated — composition module for `{composition_name}`"
2521    );
2522    pushln!(
2523        &mut out,
2524        "// DO NOT EDIT. Emitted by meerkat_machine_codegen::render_composition_driver."
2525    );
2526    pushln!(
2527        &mut out,
2528        "// Source of truth: catalog::compositions::{composition_name}"
2529    );
2530    pushln!(
2531        &mut out,
2532        "// Driver: `{}` (rust path: `{}`).",
2533        driver.name,
2534        driver.rust.module_path
2535    );
2536    pushln!(&mut out, "#![allow(clippy::expect_used)]");
2537    out.push('\n');
2538
2539    pushln!(
2540        &mut out,
2541        "use meerkat_machine_schema::identity::{{CompositionId, EffectVariantId, FieldId, InputVariantId, MachineId, MachineInstanceId, RouteId, SignalVariantId}};"
2542    );
2543    for import in &driver.rust.required_imports {
2544        pushln!(&mut out, "{import}");
2545    }
2546    out.push('\n');
2547
2548    pushln!(
2549        &mut out,
2550        "/// Typed route descriptor resolved from generated composition facts."
2551    );
2552    pushln!(&mut out, "///");
2553    pushln!(
2554        &mut out,
2555        "/// `bindings` lists producer-field → consumer-field pairs in the"
2556    );
2557    pushln!(&mut out, "/// order declared by the composition schema.");
2558    pushln!(&mut out, "#[derive(Debug, Clone, PartialEq, Eq)]");
2559    pushln!(&mut out, "pub struct TypedRoutedInput {{");
2560    pushln!(&mut out, "    pub route_id: RouteId,");
2561    pushln!(&mut out, "    pub instance_id: MachineInstanceId,");
2562    pushln!(&mut out, "    pub variant: InputVariantId,");
2563    pushln!(&mut out, "    pub bindings: Vec<(FieldId, FieldId)>,");
2564    pushln!(&mut out, "}}");
2565    out.push('\n');
2566
2567    pushln!(
2568        &mut out,
2569        "/// Typed signal-route descriptor resolved from generated composition facts."
2570    );
2571    pushln!(&mut out, "///");
2572    pushln!(
2573        &mut out,
2574        "/// `bindings` lists producer-field → consumer-field pairs in the"
2575    );
2576    pushln!(&mut out, "/// order declared by the composition schema.");
2577    pushln!(&mut out, "#[derive(Debug, Clone, PartialEq, Eq)]");
2578    pushln!(&mut out, "pub struct TypedRoutedSignal {{");
2579    pushln!(&mut out, "    pub route_id: RouteId,");
2580    pushln!(&mut out, "    pub instance_id: MachineInstanceId,");
2581    pushln!(&mut out, "    pub variant: SignalVariantId,");
2582    pushln!(&mut out, "    pub bindings: Vec<(FieldId, FieldId)>,");
2583    pushln!(&mut out, "}}");
2584    out.push('\n');
2585
2586    pushln!(
2587        &mut out,
2588        "/// Generated source for one consumer-refusal feedback field."
2589    );
2590    pushln!(&mut out, "#[derive(Debug, Clone, PartialEq, Eq)]");
2591    pushln!(&mut out, "pub enum GeneratedRefusalFieldSource {{");
2592    pushln!(&mut out, "    EffectField(FieldId),");
2593    pushln!(&mut out, "    ConsumerErrorCode,");
2594    pushln!(&mut out, "    ConsumerErrorMessage,");
2595    pushln!(&mut out, "}}");
2596    out.push('\n');
2597
2598    pushln!(
2599        &mut out,
2600        "/// Generated feedback closure for a consumer-refused dispatch."
2601    );
2602    pushln!(&mut out, "#[derive(Debug, Clone, PartialEq, Eq)]");
2603    pushln!(&mut out, "pub struct TypedDispatchRefusalClosure {{");
2604    pushln!(&mut out, "    pub route_id: RouteId,");
2605    pushln!(&mut out, "    pub producer_instance: MachineInstanceId,");
2606    pushln!(&mut out, "    pub effect_variant: EffectVariantId,");
2607    pushln!(&mut out, "    pub feedback_instance: MachineInstanceId,");
2608    pushln!(&mut out, "    pub feedback_input: InputVariantId,");
2609    pushln!(
2610        &mut out,
2611        "    pub field_bindings: Vec<(GeneratedRefusalFieldSource, FieldId)>,"
2612    );
2613    pushln!(&mut out, "}}");
2614    out.push('\n');
2615
2616    pushln!(
2617        &mut out,
2618        "/// Generated producer identity declared by this composition."
2619    );
2620    pushln!(&mut out, "#[derive(Debug, Clone, PartialEq, Eq)]");
2621    pushln!(&mut out, "pub struct ProducerFacts {{");
2622    pushln!(&mut out, "    pub instance_id: MachineInstanceId,");
2623    pushln!(&mut out, "    pub machine: MachineId,");
2624    pushln!(&mut out, "}}");
2625    out.push('\n');
2626
2627    pushln!(&mut out, "/// Composition id for this generated fact set.");
2628    pushln!(&mut out, "pub fn composition_id() -> CompositionId {{");
2629    pushln!(
2630        &mut out,
2631        "    CompositionId::parse(\"{composition_name}\").expect(\"composition slug\")"
2632    );
2633    pushln!(&mut out, "}}");
2634    out.push('\n');
2635
2636    pushln!(&mut out, "/// Generated producer instance facts.");
2637    pushln!(&mut out, "pub mod producers {{");
2638    pushln!(&mut out, "    use super::*;");
2639    for (instance_id, machine) in &producers {
2640        let fn_name = to_snake_case_local(instance_id);
2641        let machine_name = machine.machine.as_str();
2642        pushln!(&mut out);
2643        pushln!(&mut out, "    pub fn {fn_name}() -> ProducerFacts {{");
2644        pushln!(&mut out, "        ProducerFacts {{");
2645        pushln!(
2646            &mut out,
2647            "            instance_id: {fn_name}_instance_id(),"
2648        );
2649        pushln!(&mut out, "            machine: {fn_name}_machine_id(),");
2650        pushln!(&mut out, "        }}");
2651        pushln!(&mut out, "    }}");
2652        pushln!(&mut out);
2653        pushln!(
2654            &mut out,
2655            "    pub fn {fn_name}_instance_id() -> MachineInstanceId {{"
2656        );
2657        pushln!(
2658            &mut out,
2659            "        MachineInstanceId::parse(\"{instance_id}\").expect(\"producer instance slug\")"
2660        );
2661        pushln!(&mut out, "    }}");
2662        pushln!(&mut out);
2663        pushln!(
2664            &mut out,
2665            "    pub fn {fn_name}_machine_id() -> MachineId {{"
2666        );
2667        pushln!(
2668            &mut out,
2669            "        MachineId::parse(\"{machine_name}\").expect(\"producer machine slug\")"
2670        );
2671        pushln!(&mut out, "    }}");
2672    }
2673    pushln!(&mut out, "}}");
2674    out.push('\n');
2675
2676    pushln!(&mut out, "/// Generated producer-side effect variant ids.");
2677    pushln!(&mut out, "pub mod effects {{");
2678    for (instance_id, _) in &producers {
2679        let producer_mod = to_snake_case_local(instance_id);
2680        pushln!(&mut out);
2681        pushln!(&mut out, "    pub mod {producer_mod} {{");
2682        pushln!(&mut out, "        use super::super::*;");
2683        if let Some(effect_variants) = effect_variants_by_producer.get(instance_id) {
2684            for effect_variant in effect_variants {
2685                let fn_name = to_snake_case_local(effect_variant);
2686                pushln!(&mut out);
2687                pushln!(&mut out, "        pub fn {fn_name}() -> EffectVariantId {{");
2688                pushln!(
2689                    &mut out,
2690                    "            EffectVariantId::parse(\"{effect_variant}\").expect(\"effect variant slug\")"
2691                );
2692                pushln!(&mut out, "        }}");
2693            }
2694        }
2695        pushln!(&mut out, "    }}");
2696    }
2697    pushln!(&mut out, "}}");
2698    out.push('\n');
2699
2700    pushln!(&mut out, "/// Generated consumer input variant ids.");
2701    pushln!(&mut out, "pub mod inputs {{");
2702    pushln!(&mut out, "    use super::*;");
2703    for input_variant in &input_variants {
2704        let fn_name = to_snake_case_local(input_variant);
2705        pushln!(&mut out);
2706        pushln!(&mut out, "    pub fn {fn_name}() -> InputVariantId {{");
2707        pushln!(
2708            &mut out,
2709            "        InputVariantId::parse(\"{input_variant}\").expect(\"input variant slug\")"
2710        );
2711        pushln!(&mut out, "    }}");
2712    }
2713    pushln!(&mut out, "}}");
2714    out.push('\n');
2715
2716    pushln!(&mut out, "/// Generated consumer signal variant ids.");
2717    pushln!(&mut out, "pub mod signals {{");
2718    pushln!(&mut out, "    use super::*;");
2719    for signal_variant in &signal_variants {
2720        let fn_name = to_snake_case_local(signal_variant);
2721        pushln!(&mut out);
2722        pushln!(&mut out, "    pub fn {fn_name}() -> SignalVariantId {{");
2723        pushln!(
2724            &mut out,
2725            "        SignalVariantId::parse(\"{signal_variant}\").expect(\"signal variant slug\")"
2726        );
2727        pushln!(&mut out, "    }}");
2728    }
2729    pushln!(&mut out, "}}");
2730    out.push('\n');
2731
2732    pushln!(
2733        &mut out,
2734        "/// Generated field ids referenced by route bindings."
2735    );
2736    pushln!(&mut out, "pub mod fields {{");
2737    pushln!(&mut out, "    use super::*;");
2738    for field in &fields {
2739        let fn_name = to_snake_case_local(field);
2740        pushln!(&mut out);
2741        pushln!(&mut out, "    pub fn {fn_name}() -> FieldId {{");
2742        pushln!(
2743            &mut out,
2744            "        FieldId::parse(\"{field}\").expect(\"field slug\")"
2745        );
2746        pushln!(&mut out, "    }}");
2747    }
2748    pushln!(&mut out, "}}");
2749    out.push('\n');
2750
2751    for route in schema
2752        .routes
2753        .iter()
2754        .filter(|route| route.to.kind == RouteTargetKind::Input)
2755    {
2756        let route_fn = format!("route_{}", to_snake_case_local(route.name.as_str()));
2757        let target_machine = route.to.machine.as_str();
2758        let target_variant = route.to.input_variant.as_str();
2759        pushln!(
2760            &mut out,
2761            "/// Generated facts for input route `{}`.",
2762            route.name.as_str()
2763        );
2764        pushln!(&mut out, "pub fn {route_fn}() -> TypedRoutedInput {{");
2765        pushln!(&mut out, "    TypedRoutedInput {{");
2766        pushln!(
2767            &mut out,
2768            "        route_id: RouteId::parse(\"{}\").expect(\"route slug\"),",
2769            route.name.as_str()
2770        );
2771        pushln!(
2772            &mut out,
2773            "        instance_id: MachineInstanceId::parse(\"{target_machine}\").expect(\"composition instance slug\"),"
2774        );
2775        pushln!(
2776            &mut out,
2777            "        variant: InputVariantId::parse(\"{target_variant}\").expect(\"composition input slug\"),"
2778        );
2779        if route.bindings.is_empty() {
2780            pushln!(&mut out, "        bindings: Vec::new(),");
2781        } else {
2782            pushln!(&mut out, "        bindings: vec![");
2783            for binding in &route.bindings {
2784                let from_field = match &binding.source {
2785                    RouteBindingSource::Field { from_field, .. } => from_field.as_str(),
2786                    RouteBindingSource::Literal(_) | RouteBindingSource::OwnerProvided => {
2787                        continue;
2788                    }
2789                };
2790                let to_field = binding.to_field.as_str();
2791                pushln!(
2792                    &mut out,
2793                    "            (FieldId::parse(\"{from_field}\").expect(\"route producer field slug\"), FieldId::parse(\"{to_field}\").expect(\"route consumer field slug\")),"
2794                );
2795            }
2796            pushln!(&mut out, "        ],");
2797        }
2798        pushln!(&mut out, "    }}");
2799        pushln!(&mut out, "}}");
2800        out.push('\n');
2801    }
2802
2803    for closure in &driver.refusal_closures {
2804        let route = schema
2805            .routes
2806            .iter()
2807            .find(|route| route.name == closure.dispatch_route)?;
2808        let closure_fn = format!(
2809            "refusal_closure_{}",
2810            to_snake_case_local(closure.dispatch_route.as_str())
2811        );
2812        pushln!(
2813            &mut out,
2814            "/// Generated consumer-refusal closure for route `{}`.",
2815            closure.dispatch_route
2816        );
2817        pushln!(
2818            &mut out,
2819            "pub fn {closure_fn}() -> TypedDispatchRefusalClosure {{"
2820        );
2821        pushln!(&mut out, "    TypedDispatchRefusalClosure {{");
2822        pushln!(
2823            &mut out,
2824            "        route_id: RouteId::parse(\"{}\").expect(\"route slug\"),",
2825            closure.dispatch_route
2826        );
2827        pushln!(
2828            &mut out,
2829            "        producer_instance: MachineInstanceId::parse(\"{}\").expect(\"producer instance slug\"),",
2830            route.from_machine
2831        );
2832        pushln!(
2833            &mut out,
2834            "        effect_variant: EffectVariantId::parse(\"{}\").expect(\"effect variant slug\"),",
2835            route.effect_variant
2836        );
2837        pushln!(
2838            &mut out,
2839            "        feedback_instance: MachineInstanceId::parse(\"{}\").expect(\"feedback instance slug\"),",
2840            closure.feedback_instance
2841        );
2842        pushln!(
2843            &mut out,
2844            "        feedback_input: InputVariantId::parse(\"{}\").expect(\"feedback input slug\"),",
2845            closure.feedback_input
2846        );
2847        pushln!(&mut out, "        field_bindings: vec![");
2848        for binding in &closure.field_bindings {
2849            let source = match &binding.source {
2850                DriverRefusalFieldSource::EffectField(field) => format!(
2851                    "GeneratedRefusalFieldSource::EffectField(FieldId::parse(\"{}\").expect(\"effect field slug\"))",
2852                    field
2853                ),
2854                DriverRefusalFieldSource::ConsumerErrorCode => {
2855                    "GeneratedRefusalFieldSource::ConsumerErrorCode".to_owned()
2856                }
2857                DriverRefusalFieldSource::ConsumerErrorMessage => {
2858                    "GeneratedRefusalFieldSource::ConsumerErrorMessage".to_owned()
2859                }
2860            };
2861            pushln!(
2862                &mut out,
2863                "            ({source}, FieldId::parse(\"{}\").expect(\"feedback field slug\")),",
2864                binding.input_field
2865            );
2866        }
2867        pushln!(&mut out, "        ],");
2868        pushln!(&mut out, "    }}");
2869        pushln!(&mut out, "}}");
2870        out.push('\n');
2871    }
2872
2873    pushln!(
2874        &mut out,
2875        "/// Resolve a generated route to its consumer-refusal feedback closure."
2876    );
2877    pushln!(
2878        &mut out,
2879        "pub fn refusal_closure_for_route(route_id: &RouteId) -> Option<TypedDispatchRefusalClosure> {{"
2880    );
2881    for closure in &driver.refusal_closures {
2882        let closure_fn = format!(
2883            "refusal_closure_{}",
2884            to_snake_case_local(closure.dispatch_route.as_str())
2885        );
2886        pushln!(
2887            &mut out,
2888            "    if route_id == &RouteId::parse(\"{}\").expect(\"route slug\") {{",
2889            closure.dispatch_route
2890        );
2891        pushln!(&mut out, "        return Some({closure_fn}());");
2892        pushln!(&mut out, "    }}");
2893    }
2894    pushln!(&mut out, "    None");
2895    pushln!(&mut out, "}}");
2896    out.push('\n');
2897
2898    for route in schema
2899        .routes
2900        .iter()
2901        .filter(|route| route.to.kind == RouteTargetKind::Signal)
2902    {
2903        let route_fn = format!("route_{}", to_snake_case_local(route.name.as_str()));
2904        let target_machine = route.to.machine.as_str();
2905        let target_variant = route.to.input_variant.as_str();
2906        pushln!(
2907            &mut out,
2908            "/// Generated facts for signal route `{}`.",
2909            route.name.as_str()
2910        );
2911        pushln!(&mut out, "pub fn {route_fn}() -> TypedRoutedSignal {{");
2912        pushln!(&mut out, "    TypedRoutedSignal {{");
2913        pushln!(
2914            &mut out,
2915            "        route_id: RouteId::parse(\"{}\").expect(\"route slug\"),",
2916            route.name.as_str()
2917        );
2918        pushln!(
2919            &mut out,
2920            "        instance_id: MachineInstanceId::parse(\"{target_machine}\").expect(\"composition instance slug\"),"
2921        );
2922        pushln!(
2923            &mut out,
2924            "        variant: SignalVariantId::parse(\"{target_variant}\").expect(\"composition signal slug\"),"
2925        );
2926        if route.bindings.is_empty() {
2927            pushln!(&mut out, "        bindings: Vec::new(),");
2928        } else {
2929            pushln!(&mut out, "        bindings: vec![");
2930            for binding in &route.bindings {
2931                let from_field = match &binding.source {
2932                    RouteBindingSource::Field { from_field, .. } => from_field.as_str(),
2933                    RouteBindingSource::Literal(_) | RouteBindingSource::OwnerProvided => {
2934                        continue;
2935                    }
2936                };
2937                let to_field = binding.to_field.as_str();
2938                pushln!(
2939                    &mut out,
2940                    "            (FieldId::parse(\"{from_field}\").expect(\"route producer field slug\"), FieldId::parse(\"{to_field}\").expect(\"route consumer field slug\")),"
2941                );
2942            }
2943            pushln!(&mut out, "        ],");
2944        }
2945        pushln!(&mut out, "    }}");
2946        pushln!(&mut out, "}}");
2947        out.push('\n');
2948    }
2949
2950    pushln!(
2951        &mut out,
2952        "/// Resolve a producer `(instance, effect_variant)` to generated input-route facts."
2953    );
2954    pushln!(&mut out, "pub fn route_to_input(");
2955    pushln!(&mut out, "    producer_instance: &MachineInstanceId,");
2956    pushln!(&mut out, "    effect_variant: &EffectVariantId,");
2957    pushln!(&mut out, ") -> Option<TypedRoutedInput> {{");
2958    for route in schema
2959        .routes
2960        .iter()
2961        .filter(|route| route.to.kind == RouteTargetKind::Input)
2962    {
2963        let producer_mod = to_snake_case_local(route.from_machine.as_str());
2964        let effect_fn = to_snake_case_local(route.effect_variant.as_str());
2965        let route_fn = format!("route_{}", to_snake_case_local(route.name.as_str()));
2966        pushln!(
2967            &mut out,
2968            "    if producer_instance == &producers::{producer_mod}_instance_id() && effect_variant == &effects::{producer_mod}::{effect_fn}() {{"
2969        );
2970        pushln!(&mut out, "        return Some({route_fn}());");
2971        pushln!(&mut out, "    }}");
2972    }
2973    pushln!(&mut out, "    None");
2974    pushln!(&mut out, "}}");
2975    out.push('\n');
2976
2977    pushln!(
2978        &mut out,
2979        "/// Resolve a producer `(instance, effect_variant)` to generated signal-route facts."
2980    );
2981    pushln!(&mut out, "pub fn route_to_signal(");
2982    pushln!(&mut out, "    producer_instance: &MachineInstanceId,");
2983    pushln!(&mut out, "    effect_variant: &EffectVariantId,");
2984    pushln!(&mut out, ") -> Option<TypedRoutedSignal> {{");
2985    for route in schema
2986        .routes
2987        .iter()
2988        .filter(|route| route.to.kind == RouteTargetKind::Signal)
2989    {
2990        let producer_mod = to_snake_case_local(route.from_machine.as_str());
2991        let effect_fn = to_snake_case_local(route.effect_variant.as_str());
2992        let route_fn = format!("route_{}", to_snake_case_local(route.name.as_str()));
2993        pushln!(
2994            &mut out,
2995            "    if producer_instance == &producers::{producer_mod}_instance_id() && effect_variant == &effects::{producer_mod}::{effect_fn}() {{"
2996        );
2997        pushln!(&mut out, "        return Some({route_fn}());");
2998        pushln!(&mut out, "    }}");
2999    }
3000    pushln!(&mut out, "    None");
3001    pushln!(&mut out, "}}");
3002    out.push('\n');
3003
3004    let driver_type = driver.rust.driver_type.as_ref();
3005    let store_plan_type = driver.rust.store_plan_type.as_ref();
3006    let work_type = driver.rust.work_type.as_ref();
3007    let decision_type = driver.rust.decision_type.as_ref();
3008
3009    pushln!(
3010        &mut out,
3011        "/// Generated route target selected by `{driver_type}`."
3012    );
3013    pushln!(&mut out, "#[derive(Debug, Clone, PartialEq, Eq)]");
3014    pushln!(&mut out, "pub enum GeneratedRouteTarget {{");
3015    pushln!(&mut out, "    Input(TypedRoutedInput),");
3016    pushln!(&mut out, "    Signal(TypedRoutedSignal),");
3017    pushln!(&mut out, "}}");
3018    out.push('\n');
3019
3020    pushln!(
3021        &mut out,
3022        "/// Generated store plan emitted by `{driver_type}`."
3023    );
3024    pushln!(&mut out, "#[derive(Debug, Clone, PartialEq, Eq)]");
3025    pushln!(&mut out, "pub struct {store_plan_type} {{");
3026    pushln!(&mut out, "    pub target: GeneratedRouteTarget,");
3027    pushln!(&mut out, "}}");
3028    pushln!(&mut out);
3029    pushln!(&mut out, "impl {store_plan_type} {{");
3030    pushln!(
3031        &mut out,
3032        "    pub fn input(route: TypedRoutedInput) -> Self {{"
3033    );
3034    pushln!(
3035        &mut out,
3036        "        Self {{ target: GeneratedRouteTarget::Input(route) }}"
3037    );
3038    pushln!(&mut out, "    }}");
3039    pushln!(&mut out);
3040    pushln!(
3041        &mut out,
3042        "    pub fn signal(route: TypedRoutedSignal) -> Self {{"
3043    );
3044    pushln!(
3045        &mut out,
3046        "        Self {{ target: GeneratedRouteTarget::Signal(route) }}"
3047    );
3048    pushln!(&mut out, "    }}");
3049    pushln!(&mut out);
3050    pushln!(&mut out, "    pub fn route_id(&self) -> &RouteId {{");
3051    pushln!(&mut out, "        match &self.target {{");
3052    pushln!(
3053        &mut out,
3054        "            GeneratedRouteTarget::Input(route) => &route.route_id,"
3055    );
3056    pushln!(
3057        &mut out,
3058        "            GeneratedRouteTarget::Signal(route) => &route.route_id,"
3059    );
3060    pushln!(&mut out, "        }}");
3061    pushln!(&mut out, "    }}");
3062    pushln!(&mut out, "}}");
3063    out.push('\n');
3064
3065    pushln!(
3066        &mut out,
3067        "/// Generated work packet consumed by `{driver_type}`."
3068    );
3069    pushln!(&mut out, "#[derive(Debug, Clone, PartialEq, Eq)]");
3070    pushln!(&mut out, "pub struct {work_type} {{");
3071    pushln!(&mut out, "    pub producer_instance: MachineInstanceId,");
3072    pushln!(&mut out, "    pub effect_variant: EffectVariantId,");
3073    pushln!(&mut out, "}}");
3074    pushln!(&mut out);
3075    pushln!(&mut out, "impl {work_type} {{");
3076    pushln!(
3077        &mut out,
3078        "    pub fn new(producer_instance: MachineInstanceId, effect_variant: EffectVariantId) -> Self {{"
3079    );
3080    pushln!(
3081        &mut out,
3082        "        Self {{ producer_instance, effect_variant }}"
3083    );
3084    pushln!(&mut out, "    }}");
3085    pushln!(&mut out, "}}");
3086    out.push('\n');
3087
3088    pushln!(
3089        &mut out,
3090        "/// Generated routing decision emitted by `{driver_type}`."
3091    );
3092    pushln!(&mut out, "#[derive(Debug, Clone, PartialEq, Eq)]");
3093    pushln!(&mut out, "pub enum {decision_type} {{");
3094    pushln!(&mut out, "    DispatchInput(TypedRoutedInput),");
3095    pushln!(&mut out, "    DispatchSignal(TypedRoutedSignal),");
3096    pushln!(&mut out, "    NoRoute,");
3097    pushln!(&mut out, "}}");
3098    out.push('\n');
3099
3100    pushln!(
3101        &mut out,
3102        "/// Generated composition driver constrained by the catalog driver descriptor."
3103    );
3104    pushln!(&mut out, "#[derive(Debug, Clone, Copy, PartialEq, Eq)]");
3105    pushln!(&mut out, "pub struct {driver_type};");
3106    pushln!(&mut out);
3107    pushln!(&mut out, "impl {driver_type} {{");
3108    pushln!(
3109        &mut out,
3110        "    pub fn decide(work: &{work_type}) -> {decision_type} {{"
3111    );
3112    pushln!(
3113        &mut out,
3114        "        if let Some(route) = route_to_input(&work.producer_instance, &work.effect_variant) {{"
3115    );
3116    pushln!(
3117        &mut out,
3118        "            return {decision_type}::DispatchInput(route);"
3119    );
3120    pushln!(&mut out, "        }}");
3121    pushln!(
3122        &mut out,
3123        "        if let Some(route) = route_to_signal(&work.producer_instance, &work.effect_variant) {{"
3124    );
3125    pushln!(
3126        &mut out,
3127        "            return {decision_type}::DispatchSignal(route);"
3128    );
3129    pushln!(&mut out, "        }}");
3130    pushln!(&mut out, "        {decision_type}::NoRoute");
3131    pushln!(&mut out, "    }}");
3132    pushln!(&mut out);
3133    pushln!(
3134        &mut out,
3135        "    pub fn store_plan(decision: {decision_type}) -> Option<{store_plan_type}> {{"
3136    );
3137    pushln!(&mut out, "        match decision {{");
3138    pushln!(
3139        &mut out,
3140        "            {decision_type}::DispatchInput(route) => Some({store_plan_type}::input(route)),"
3141    );
3142    pushln!(
3143        &mut out,
3144        "            {decision_type}::DispatchSignal(route) => Some({store_plan_type}::signal(route)),"
3145    );
3146    pushln!(&mut out, "            {decision_type}::NoRoute => None,");
3147    pushln!(&mut out, "        }}");
3148    pushln!(&mut out, "    }}");
3149    pushln!(&mut out, "}}");
3150
3151    Some(out)
3152}
3153
3154fn to_snake_case_local(value: &str) -> String {
3155    let mut out = String::new();
3156    let mut previous_is_sep = true;
3157    for ch in value.chars() {
3158        if ch == '_' || ch == '-' || ch == ' ' {
3159            if !previous_is_sep {
3160                out.push('_');
3161                previous_is_sep = true;
3162            }
3163            continue;
3164        }
3165        if ch.is_ascii_uppercase() {
3166            if !out.is_empty() && !previous_is_sep {
3167                out.push('_');
3168            }
3169            out.push(ch.to_ascii_lowercase());
3170            previous_is_sep = false;
3171        } else {
3172            out.push(ch.to_ascii_lowercase());
3173            previous_is_sep = false;
3174        }
3175    }
3176    out.trim_matches('_').to_owned()
3177}
3178
3179pub fn render_machine_semantic_model(
3180    schema: &MachineSchema,
3181) -> std::result::Result<String, CompositionTlaError> {
3182    check_canonical_named_bindings(schema)?;
3183    if schema.tlc_model.is_some() {
3184        validate_machine_model(schema)?;
3185    }
3186    let mut compiler = MachineTlaCompiler::new(schema);
3187    compiler.render()
3188}
3189
3190fn render_state_markdown(out: &mut String, schema: &MachineSchema) {
3191    pushln!(out, "## State");
3192    writeln!(
3193        out,
3194        "- Phase enum: `{}`",
3195        schema
3196            .state
3197            .phase
3198            .variants
3199            .iter()
3200            .map(|variant| variant.name.as_str())
3201            .collect::<Vec<_>>()
3202            .join(" | ")
3203    )
3204    .expect("write to string");
3205    for field in &schema.state.fields {
3206        pushln!(out, "- `{}`: `{}`", field.name, render_type_ref(&field.ty));
3207    }
3208    pushln!(out);
3209}
3210
3211fn render_enum_markdown(out: &mut String, label: &str, schema: &EnumSchema) {
3212    writeln!(out, "## {label}");
3213    for variant in &schema.variants {
3214        if variant.fields.is_empty() {
3215            pushln!(out, "- `{}`", variant.name);
3216        } else {
3217            writeln!(
3218                out,
3219                "- `{}`({})",
3220                variant.name,
3221                render_field_list(&variant.fields)
3222            )
3223            .expect("write to string");
3224        }
3225    }
3226    pushln!(out);
3227}
3228
3229/// The input fields a machine's CI profile samples (`CiSamples`), in
3230/// declaration order, as one sentence of the generated contract; nothing for
3231/// a machine that declares none.
3232fn render_ci_samples_markdown(out: &mut String, schema: &MachineSchema) {
3233    let samples = schema
3234        .input_field_domains
3235        .iter()
3236        .filter_map(|declaration| match &declaration.domain {
3237            meerkat_machine_schema::InputFieldDomainKind::CiSamples(values) => Some(format!(
3238                "`{}`.`{}` as `{}`",
3239                declaration.input,
3240                declaration.field,
3241                render_explicit_values(values)
3242            )),
3243            meerkat_machine_schema::InputFieldDomainKind::AdditionalValues(_)
3244            | meerkat_machine_schema::InputFieldDomainKind::StateField(_)
3245            | meerkat_machine_schema::InputFieldDomainKind::CiValues(_) => None,
3246        })
3247        .collect::<Vec<_>>();
3248    let Some((last, rest)) = samples.split_last() else {
3249        return;
3250    };
3251    let listed = if rest.is_empty() {
3252        last.clone()
3253    } else {
3254        format!("{} and {last}", rest.join(", "))
3255    };
3256    pushln!(out, "## CI Profile Samples");
3257    writeln!(
3258        out,
3259        "The CI profile samples {listed}; the Deep profile and every composition explore each field's whole domain."
3260    )
3261    .expect("write to string");
3262    pushln!(out);
3263}
3264
3265/// Render a labelled subset of an input enum's variants, keeping only those whose
3266/// name satisfies `keep`. Used to split the public command surface from the
3267/// runtime-internal inputs in the generated machine contract.
3268fn render_input_subset(
3269    out: &mut String,
3270    label: &str,
3271    schema: &EnumSchema,
3272    keep: impl Fn(&str) -> bool,
3273) {
3274    writeln!(out, "## {label}");
3275    for variant in schema
3276        .variants
3277        .iter()
3278        .filter(|variant| keep(variant.name.as_str()))
3279    {
3280        if variant.fields.is_empty() {
3281            pushln!(out, "- `{}`", variant.name);
3282        } else {
3283            writeln!(
3284                out,
3285                "- `{}`({})",
3286                variant.name,
3287                render_field_list(&variant.fields)
3288            )
3289            .expect("write to string");
3290        }
3291    }
3292    pushln!(out);
3293}
3294
3295fn render_field_list(fields: &[meerkat_machine_schema::FieldSchema]) -> String {
3296    fields
3297        .iter()
3298        .map(|field| format!("{}: {}", field.name, render_type_ref(&field.ty)))
3299        .collect::<Vec<_>>()
3300        .join(", ")
3301}
3302
3303fn collect_binding_domains(schema: &MachineSchema) -> BTreeMap<String, TypeRef> {
3304    let mut domains = BTreeMap::new();
3305
3306    for field in &schema.state.fields {
3307        collect_type_domains(&field.ty, &mut domains);
3308    }
3309
3310    for transition in &schema.transitions {
3311        if let Some(variant) = transition_trigger_variant(schema, transition) {
3312            for binding in transition.on.bindings() {
3313                if let Some(field) = variant.fields.iter().find(|field| field.name == *binding) {
3314                    collect_type_domains(&field.ty, &mut domains);
3315                }
3316            }
3317        }
3318    }
3319
3320    for variant in &schema.effects.variants {
3321        for field in &variant.fields {
3322            collect_type_domains(&field.ty, &mut domains);
3323        }
3324    }
3325
3326    domains
3327}
3328
3329fn collect_composition_binding_domains(
3330    schema: &CompositionSchema,
3331    machine_by_instance: &BTreeMap<&str, &MachineSchema>,
3332) -> BTreeMap<String, TypeRef> {
3333    let mut domains = BTreeMap::new();
3334
3335    for machine in machine_by_instance.values() {
3336        for (name, ty) in collect_binding_domains(machine) {
3337            domains.entry(name).or_insert(ty);
3338        }
3339    }
3340
3341    for entry_input in &schema.entry_inputs {
3342        let Some(machine) = machine_by_instance
3343            .get(entry_input.machine.as_str())
3344            .copied()
3345        else {
3346            continue;
3347        };
3348        let Ok(variant) = machine.inputs.variant_named(&entry_input.input_variant) else {
3349            continue;
3350        };
3351        for field in &variant.fields {
3352            collect_type_domains(&field.ty, &mut domains);
3353        }
3354    }
3355
3356    domains
3357}
3358
3359fn collect_type_domains(ty: &TypeRef, domains: &mut BTreeMap<String, TypeRef>) {
3360    let name = domain_constant_name(ty);
3361    domains.entry(name).or_insert_with(|| ty.clone());
3362    match ty {
3363        TypeRef::Option(inner) | TypeRef::Seq(inner) | TypeRef::Set(inner) => {
3364            collect_type_domains(inner, domains);
3365        }
3366        TypeRef::Map(key, value) => {
3367            collect_type_domains(key, domains);
3368            collect_type_domains(value, domains);
3369        }
3370        TypeRef::Bool
3371        | TypeRef::U32
3372        | TypeRef::U64
3373        | TypeRef::String
3374        | TypeRef::Named(_)
3375        | TypeRef::Enum(_) => {}
3376    }
3377}
3378
3379/// Named samples for a machine Deep profile: every named bucket unchanged, but
3380/// the generic `String` bucket holds only the string literals a transition
3381/// guard requires an input binding to equal (`delivery_id == "terminal"`,
3382/// `claim_id == ""`). Without them a transition guarded on such a literal is
3383/// unreachable under the generic `"alpha"`/`"beta"` samples and Deep coverage
3384/// reports it as zero-hit. Literals from updates, effects or init (messages,
3385/// error codes) are deliberately not added, so unrelated machines keep their
3386/// sample domains.
3387fn with_guard_binding_string_samples(
3388    named_samples: &BTreeMap<String, BTreeSet<String>>,
3389    schema: &MachineSchema,
3390) -> BTreeMap<String, BTreeSet<String>> {
3391    let mut samples = named_samples.clone();
3392    let literals = collect_guard_binding_string_literals(schema);
3393    if literals.is_empty() {
3394        samples.remove("String");
3395    } else {
3396        samples.insert("String".to_owned(), literals);
3397    }
3398    samples
3399}
3400
3401fn collect_guard_binding_string_literals(schema: &MachineSchema) -> BTreeSet<String> {
3402    let mut literals = BTreeSet::new();
3403    for transition in &schema.transitions {
3404        let string_bindings = transition_trigger_variant(schema, transition)
3405            .map(|variant| {
3406                variant
3407                    .fields
3408                    .iter()
3409                    .filter(|field| {
3410                        matches!(field.ty, TypeRef::String)
3411                            && transition
3412                                .on
3413                                .bindings()
3414                                .iter()
3415                                .any(|binding| binding == &field.name)
3416                    })
3417                    .map(|field| field.name.as_str().to_owned())
3418                    .collect::<BTreeSet<_>>()
3419            })
3420            .unwrap_or_default();
3421        if string_bindings.is_empty() {
3422            continue;
3423        }
3424        for guard in &transition.guards {
3425            collect_binding_literal_comparisons(&guard.expr, &string_bindings, &mut literals);
3426        }
3427    }
3428    literals
3429}
3430
3431fn collect_binding_literal_comparisons(
3432    expr: &Expr,
3433    string_bindings: &BTreeSet<String>,
3434    literals: &mut BTreeSet<String>,
3435) {
3436    match expr {
3437        // Only equality makes a guard unreachable without its literal. An
3438        // inequality such as `attempt_id != ""` is already satisfied by the
3439        // generic samples, so its literal would only add rejection-path states.
3440        Expr::Eq(left, right) => {
3441            match (left.as_ref(), right.as_ref()) {
3442                (Expr::Binding(binding), Expr::String(literal))
3443                | (Expr::String(literal), Expr::Binding(binding))
3444                    if string_bindings.contains(binding) =>
3445                {
3446                    literals.insert(literal.clone());
3447                }
3448                _ => {}
3449            }
3450            collect_binding_literal_comparisons(left, string_bindings, literals);
3451            collect_binding_literal_comparisons(right, string_bindings, literals);
3452        }
3453        Expr::Neq(left, right) => {
3454            collect_binding_literal_comparisons(left, string_bindings, literals);
3455            collect_binding_literal_comparisons(right, string_bindings, literals);
3456        }
3457        Expr::Not(inner) => collect_binding_literal_comparisons(inner, string_bindings, literals),
3458        Expr::And(items) | Expr::Or(items) => {
3459            for item in items {
3460                collect_binding_literal_comparisons(item, string_bindings, literals);
3461            }
3462        }
3463        Expr::IfElse {
3464            condition,
3465            then_expr,
3466            else_expr,
3467        } => {
3468            for item in [condition, then_expr, else_expr] {
3469                collect_binding_literal_comparisons(item, string_bindings, literals);
3470            }
3471        }
3472        _ => {}
3473    }
3474}
3475
3476fn collect_machine_named_type_samples(
3477    schema: &MachineSchema,
3478) -> BTreeMap<String, BTreeSet<String>> {
3479    let field_types = schema
3480        .state
3481        .fields
3482        .iter()
3483        .map(|field| (field.name.as_str().to_owned(), field.ty.clone()))
3484        .collect::<BTreeMap<String, _>>();
3485    let helper_returns = schema
3486        .helpers
3487        .iter()
3488        .chain(schema.derived.iter())
3489        .map(|helper| (helper.name.clone(), helper.returns.clone()))
3490        .collect::<BTreeMap<String, _>>();
3491    let mut samples = BTreeMap::new();
3492
3493    for init in &schema.state.init.fields {
3494        if let Some(field_ty) = field_types.get(init.field.as_str()) {
3495            collect_named_literals_from_expr(
3496                &mut samples,
3497                &init.expr,
3498                Some(field_ty),
3499                &field_types,
3500                &helper_returns,
3501                &BTreeMap::new(),
3502            );
3503        }
3504    }
3505
3506    for helper in schema.helpers.iter().chain(schema.derived.iter()) {
3507        let bindings = helper
3508            .params
3509            .iter()
3510            .map(|field| (field.name.as_str().to_owned(), field.ty.clone()))
3511            .collect::<BTreeMap<String, _>>();
3512        collect_named_literals_from_expr(
3513            &mut samples,
3514            &helper.body,
3515            Some(&helper.returns),
3516            &field_types,
3517            &helper_returns,
3518            &bindings,
3519        );
3520    }
3521
3522    for invariant in &schema.invariants {
3523        collect_named_literals_from_expr(
3524            &mut samples,
3525            &invariant.expr,
3526            None,
3527            &field_types,
3528            &helper_returns,
3529            &BTreeMap::new(),
3530        );
3531    }
3532
3533    for transition in &schema.transitions {
3534        let binding_types = transition_trigger_variant(schema, transition)
3535            .map(|variant| {
3536                variant
3537                    .fields
3538                    .iter()
3539                    .filter(|field| {
3540                        transition
3541                            .on
3542                            .bindings()
3543                            .iter()
3544                            .any(|binding| binding == &field.name)
3545                    })
3546                    .map(|field| (field.name.as_str().to_owned(), field.ty.clone()))
3547                    .collect::<BTreeMap<_, _>>()
3548            })
3549            .unwrap_or_default();
3550
3551        for guard in &transition.guards {
3552            collect_named_literals_from_expr(
3553                &mut samples,
3554                &guard.expr,
3555                None,
3556                &field_types,
3557                &helper_returns,
3558                &binding_types,
3559            );
3560        }
3561        for update in &transition.updates {
3562            collect_named_literals_from_update(
3563                &mut samples,
3564                update,
3565                &field_types,
3566                &helper_returns,
3567                &binding_types,
3568            );
3569        }
3570        for effect in &transition.emit {
3571            let Ok(effect_variant) = schema.effects.variant_named(effect.variant.as_str()) else {
3572                continue;
3573            };
3574            for field in &effect_variant.fields {
3575                if let Some(expr) = effect.fields.get(&field.name) {
3576                    collect_named_literals_from_expr(
3577                        &mut samples,
3578                        expr,
3579                        Some(&field.ty),
3580                        &field_types,
3581                        &helper_returns,
3582                        &binding_types,
3583                    );
3584                }
3585            }
3586        }
3587    }
3588
3589    samples
3590}
3591
3592fn collect_composition_named_type_samples(
3593    schema: &CompositionSchema,
3594    machine_by_instance: &BTreeMap<&str, &MachineSchema>,
3595) -> BTreeMap<String, BTreeSet<String>> {
3596    let mut samples = BTreeMap::new();
3597    for machine in machine_by_instance.values() {
3598        merge_named_type_samples(&mut samples, collect_machine_named_type_samples(machine));
3599    }
3600
3601    for entry_input in &schema.entry_inputs {
3602        let Some(machine) = machine_by_instance
3603            .get(entry_input.machine.as_str())
3604            .copied()
3605        else {
3606            continue;
3607        };
3608        merge_named_type_samples(&mut samples, collect_machine_named_type_samples(machine));
3609    }
3610
3611    for route in &schema.routes {
3612        let Some(source_machine) = machine_by_instance
3613            .get(route.from_machine.as_str())
3614            .copied()
3615        else {
3616            continue;
3617        };
3618        let Ok(source_variant) = source_machine.effects.variant_named(&route.effect_variant) else {
3619            continue;
3620        };
3621        let source_field_types = source_variant
3622            .fields
3623            .iter()
3624            .map(|field| (field.name.as_str().to_owned(), field.ty.clone()))
3625            .collect::<BTreeMap<String, _>>();
3626        let Some(target_machine) = machine_by_instance.get(route.to.machine.as_str()).copied()
3627        else {
3628            continue;
3629        };
3630        let Some(target_variant) = route_target_variant(target_machine, &route.to) else {
3631            continue;
3632        };
3633        let field_types = target_variant
3634            .fields
3635            .iter()
3636            .map(|field| (field.name.as_str().to_owned(), field.ty.clone()))
3637            .collect::<BTreeMap<String, _>>();
3638
3639        for binding in &route.bindings {
3640            if let RouteBindingSource::Literal(expr) = &binding.source
3641                && let Some(field_ty) = field_types.get(binding.to_field.as_str())
3642            {
3643                collect_named_literals_from_expr(
3644                    &mut samples,
3645                    expr,
3646                    Some(field_ty),
3647                    &field_types,
3648                    &BTreeMap::new(),
3649                    &BTreeMap::new(),
3650                );
3651            }
3652            if let RouteBindingSource::Field { from_field, .. } = &binding.source
3653                && let (Some(source_ty), Some(target_ty)) = (
3654                    source_field_types.get(from_field.as_str()),
3655                    field_types.get(binding.to_field.as_str()),
3656                )
3657            {
3658                propagate_named_samples_between_types(&mut samples, source_ty, target_ty);
3659            }
3660        }
3661    }
3662
3663    for witness in &schema.witnesses {
3664        for preload in &witness.preload_inputs {
3665            let Some(machine) = machine_by_instance.get(preload.machine.as_str()).copied() else {
3666                continue;
3667            };
3668            let Ok(variant) = machine
3669                .inputs
3670                .variant_named(&preload.input_variant)
3671                .or_else(|_| machine.signals.variant_named(&preload.input_variant))
3672            else {
3673                continue;
3674            };
3675            let field_types = variant
3676                .fields
3677                .iter()
3678                .map(|field| (field.name.as_str().to_owned(), field.ty.clone()))
3679                .collect::<BTreeMap<String, _>>();
3680
3681            for field in &preload.fields {
3682                if let Some(field_ty) = field_types.get(field.field.as_str()) {
3683                    collect_named_literals_from_expr(
3684                        &mut samples,
3685                        &field.expr,
3686                        Some(field_ty),
3687                        &field_types,
3688                        &BTreeMap::new(),
3689                        &BTreeMap::new(),
3690                    );
3691                }
3692            }
3693        }
3694    }
3695
3696    samples
3697}
3698
3699fn collect_composition_witness_named_type_samples(
3700    schema: &CompositionSchema,
3701    witness: &CompositionWitness,
3702    machine_by_instance: &BTreeMap<&str, &MachineSchema>,
3703) -> BTreeMap<String, BTreeSet<String>> {
3704    let mut samples = BTreeMap::new();
3705
3706    for preload in &witness.preload_inputs {
3707        let Some(machine) = machine_by_instance.get(preload.machine.as_str()).copied() else {
3708            continue;
3709        };
3710        let Ok(variant) = machine
3711            .inputs
3712            .variant_named(&preload.input_variant)
3713            .or_else(|_| machine.signals.variant_named(&preload.input_variant))
3714        else {
3715            continue;
3716        };
3717        let field_types = variant
3718            .fields
3719            .iter()
3720            .map(|field| (field.name.as_str().to_owned(), field.ty.clone()))
3721            .collect::<BTreeMap<String, _>>();
3722
3723        for field in &preload.fields {
3724            if let Some(field_ty) = field_types.get(field.field.as_str()) {
3725                collect_named_literals_from_expr(
3726                    &mut samples,
3727                    &field.expr,
3728                    Some(field_ty),
3729                    &field_types,
3730                    &BTreeMap::new(),
3731                    &BTreeMap::new(),
3732                );
3733            }
3734        }
3735    }
3736
3737    let witness_routes = schema
3738        .routes
3739        .iter()
3740        .filter(|route| {
3741            witness
3742                .expected_routes
3743                .iter()
3744                .any(|name| name == &route.name)
3745        })
3746        .collect::<Vec<_>>();
3747    collect_route_binding_named_type_samples_to_fixpoint(
3748        &mut samples,
3749        &witness_routes,
3750        machine_by_instance,
3751    );
3752
3753    samples
3754}
3755
3756fn merge_named_type_samples(
3757    target: &mut BTreeMap<String, BTreeSet<String>>,
3758    source: BTreeMap<String, BTreeSet<String>>,
3759) {
3760    for (name, values) in source {
3761        target.entry(name).or_default().extend(values);
3762    }
3763}
3764
3765fn collect_route_binding_named_type_samples_to_fixpoint(
3766    samples: &mut BTreeMap<String, BTreeSet<String>>,
3767    routes: &[&Route],
3768    machine_by_instance: &BTreeMap<&str, &MachineSchema>,
3769) {
3770    loop {
3771        let mut changed = false;
3772        for route in routes {
3773            changed |=
3774                collect_route_binding_named_type_samples(samples, route, machine_by_instance);
3775        }
3776        if !changed {
3777            break;
3778        }
3779    }
3780}
3781
3782fn collect_route_binding_named_type_samples(
3783    samples: &mut BTreeMap<String, BTreeSet<String>>,
3784    route: &Route,
3785    machine_by_instance: &BTreeMap<&str, &MachineSchema>,
3786) -> bool {
3787    let Some(source_machine) = machine_by_instance
3788        .get(route.from_machine.as_str())
3789        .copied()
3790    else {
3791        return false;
3792    };
3793    let Ok(source_variant) = source_machine.effects.variant_named(&route.effect_variant) else {
3794        return false;
3795    };
3796    let source_field_types = source_variant
3797        .fields
3798        .iter()
3799        .map(|field| (field.name.as_str().to_owned(), field.ty.clone()))
3800        .collect::<BTreeMap<String, _>>();
3801    let Some(target_machine) = machine_by_instance.get(route.to.machine.as_str()).copied() else {
3802        return false;
3803    };
3804    let Some(target_variant) = route_target_variant(target_machine, &route.to) else {
3805        return false;
3806    };
3807    let target_field_types = target_variant
3808        .fields
3809        .iter()
3810        .map(|field| (field.name.as_str().to_owned(), field.ty.clone()))
3811        .collect::<BTreeMap<String, _>>();
3812
3813    let mut changed = false;
3814    for binding in &route.bindings {
3815        if let RouteBindingSource::Literal(expr) = &binding.source
3816            && let Some(field_ty) = target_field_types.get(binding.to_field.as_str())
3817        {
3818            let before = samples.clone();
3819            collect_named_literals_from_expr(
3820                samples,
3821                expr,
3822                Some(field_ty),
3823                &target_field_types,
3824                &BTreeMap::new(),
3825                &BTreeMap::new(),
3826            );
3827            changed |= *samples != before;
3828        }
3829        if let RouteBindingSource::Field { from_field, .. } = &binding.source
3830            && let (Some(source_ty), Some(target_ty)) = (
3831                source_field_types.get(from_field.as_str()),
3832                target_field_types.get(binding.to_field.as_str()),
3833            )
3834        {
3835            changed |= propagate_named_samples_between_types(samples, source_ty, target_ty);
3836        }
3837    }
3838
3839    changed
3840}
3841
3842fn propagate_named_samples_between_types(
3843    samples: &mut BTreeMap<String, BTreeSet<String>>,
3844    source_ty: &TypeRef,
3845    target_ty: &TypeRef,
3846) -> bool {
3847    match (source_ty, target_ty) {
3848        (TypeRef::Option(source_inner), TypeRef::Option(target_inner))
3849        | (TypeRef::Seq(source_inner), TypeRef::Seq(target_inner))
3850        | (TypeRef::Set(source_inner), TypeRef::Set(target_inner)) => {
3851            propagate_named_samples_between_types(samples, source_inner, target_inner)
3852        }
3853        _ => {
3854            let (Some(source_bucket), Some(target_bucket)) =
3855                (type_sample_bucket(source_ty), type_sample_bucket(target_ty))
3856            else {
3857                return false;
3858            };
3859            if let Some(source_samples) = samples.get(&source_bucket).cloned() {
3860                let target_samples = samples.entry(target_bucket).or_default();
3861                let before = target_samples.len();
3862                target_samples.extend(source_samples);
3863                target_samples.len() != before
3864            } else {
3865                false
3866            }
3867        }
3868    }
3869}
3870
3871fn collect_named_literals_from_update(
3872    samples: &mut BTreeMap<String, BTreeSet<String>>,
3873    update: &Update,
3874    field_types: &BTreeMap<String, TypeRef>,
3875    helper_returns: &BTreeMap<String, TypeRef>,
3876    binding_types: &BTreeMap<String, TypeRef>,
3877) {
3878    match update {
3879        Update::Assign { field, expr } => {
3880            collect_named_literals_from_expr(
3881                samples,
3882                expr,
3883                field_types.get(field.as_str()),
3884                field_types,
3885                helper_returns,
3886                binding_types,
3887            );
3888        }
3889        Update::MapInsert { field, key, value } => {
3890            if let Some(TypeRef::Map(key_ty, value_ty)) = field_types.get(field.as_str()) {
3891                collect_named_literals_from_expr(
3892                    samples,
3893                    key,
3894                    Some(key_ty),
3895                    field_types,
3896                    helper_returns,
3897                    binding_types,
3898                );
3899                collect_named_literals_from_expr(
3900                    samples,
3901                    value,
3902                    Some(value_ty),
3903                    field_types,
3904                    helper_returns,
3905                    binding_types,
3906                );
3907            }
3908        }
3909        Update::MapRemove { field, key } => {
3910            if let Some(TypeRef::Map(key_ty, _)) = field_types.get(field.as_str()) {
3911                collect_named_literals_from_expr(
3912                    samples,
3913                    key,
3914                    Some(key_ty),
3915                    field_types,
3916                    helper_returns,
3917                    binding_types,
3918                );
3919            }
3920        }
3921        Update::MapIncrement { field, key, .. } | Update::MapDecrement { field, key, .. } => {
3922            if let Some(TypeRef::Map(key_ty, _)) = field_types.get(field.as_str()) {
3923                collect_named_literals_from_expr(
3924                    samples,
3925                    key,
3926                    Some(key_ty),
3927                    field_types,
3928                    helper_returns,
3929                    binding_types,
3930                );
3931            }
3932        }
3933        Update::SetInsert { field, value } | Update::SetRemove { field, value } => {
3934            if let Some(TypeRef::Set(inner_ty)) = field_types.get(field.as_str()) {
3935                collect_named_literals_from_expr(
3936                    samples,
3937                    value,
3938                    Some(inner_ty),
3939                    field_types,
3940                    helper_returns,
3941                    binding_types,
3942                );
3943            }
3944        }
3945        Update::SeqAppend { field, value } | Update::SeqRemoveValue { field, value } => {
3946            if let Some(TypeRef::Seq(inner_ty)) = field_types.get(field.as_str()) {
3947                collect_named_literals_from_expr(
3948                    samples,
3949                    value,
3950                    Some(inner_ty),
3951                    field_types,
3952                    helper_returns,
3953                    binding_types,
3954                );
3955            }
3956        }
3957        Update::SeqPrepend { field, values } | Update::SeqRemoveAll { field, values } => {
3958            if let Some(field_ty) = field_types.get(field.as_str()) {
3959                collect_named_literals_from_expr(
3960                    samples,
3961                    values,
3962                    Some(field_ty),
3963                    field_types,
3964                    helper_returns,
3965                    binding_types,
3966                );
3967            }
3968        }
3969        Update::Conditional {
3970            condition,
3971            then_updates,
3972            else_updates,
3973        } => {
3974            collect_named_literals_from_expr(
3975                samples,
3976                condition,
3977                None,
3978                field_types,
3979                helper_returns,
3980                binding_types,
3981            );
3982            for nested in then_updates {
3983                collect_named_literals_from_update(
3984                    samples,
3985                    nested,
3986                    field_types,
3987                    helper_returns,
3988                    binding_types,
3989                );
3990            }
3991            for nested in else_updates {
3992                collect_named_literals_from_update(
3993                    samples,
3994                    nested,
3995                    field_types,
3996                    helper_returns,
3997                    binding_types,
3998                );
3999            }
4000        }
4001        Update::ForEach {
4002            binding,
4003            over,
4004            updates,
4005        } => {
4006            collect_named_literals_from_expr(
4007                samples,
4008                over,
4009                None,
4010                field_types,
4011                helper_returns,
4012                binding_types,
4013            );
4014            let mut nested_bindings = binding_types.clone();
4015            if let Some(over_ty) = infer_expr_type(over, field_types, helper_returns, binding_types)
4016            {
4017                match over_ty {
4018                    TypeRef::Seq(inner_ty) | TypeRef::Set(inner_ty) => {
4019                        nested_bindings.insert(binding.clone(), (*inner_ty).clone());
4020                    }
4021                    TypeRef::Map(key_ty, _) => {
4022                        nested_bindings.insert(binding.clone(), (*key_ty).clone());
4023                    }
4024                    _ => {}
4025                }
4026            }
4027            for nested in updates {
4028                collect_named_literals_from_update(
4029                    samples,
4030                    nested,
4031                    field_types,
4032                    helper_returns,
4033                    &nested_bindings,
4034                );
4035            }
4036        }
4037        Update::Increment { .. } | Update::Decrement { .. } | Update::SeqPopFront { .. } => {}
4038    }
4039}
4040
4041fn collect_named_literals_from_expr(
4042    samples: &mut BTreeMap<String, BTreeSet<String>>,
4043    expr: &Expr,
4044    expected_ty: Option<&TypeRef>,
4045    field_types: &BTreeMap<String, TypeRef>,
4046    helper_returns: &BTreeMap<String, TypeRef>,
4047    binding_types: &BTreeMap<String, TypeRef>,
4048) {
4049    if let Expr::String(value) = expr
4050        && let Some(bucket) = expected_ty.and_then(type_sample_bucket)
4051    {
4052        samples.entry(bucket).or_default().insert(value.clone());
4053    }
4054
4055    if let (Expr::NamedVariant { variant, .. }, Some(expected_ty)) = (expr, expected_ty)
4056        && let Some(bucket) = type_sample_bucket(expected_ty)
4057    {
4058        samples
4059            .entry(bucket)
4060            .or_default()
4061            .insert(variant.as_str().to_owned());
4062    }
4063
4064    match expr {
4065        Expr::Eq(left, right) | Expr::Neq(left, right) => {
4066            let left_ty = infer_expr_type(left, field_types, helper_returns, binding_types);
4067            let right_ty = infer_expr_type(right, field_types, helper_returns, binding_types);
4068            if let (Some(left_ty), Expr::String(value)) = (&left_ty, right.as_ref())
4069                && let Some(bucket) = type_sample_bucket(left_ty)
4070            {
4071                samples.entry(bucket).or_default().insert(value.clone());
4072            }
4073            if let (Some(right_ty), Expr::String(value)) = (&right_ty, left.as_ref())
4074                && let Some(bucket) = type_sample_bucket(right_ty)
4075            {
4076                samples.entry(bucket).or_default().insert(value.clone());
4077            }
4078            if let (Some(left_ty), Expr::NamedVariant { variant, .. }) = (&left_ty, right.as_ref())
4079                && let Some(bucket) = type_sample_bucket(left_ty)
4080            {
4081                samples
4082                    .entry(bucket)
4083                    .or_default()
4084                    .insert(variant.as_str().to_owned());
4085            }
4086            if let (Some(right_ty), Expr::NamedVariant { variant, .. }) = (&right_ty, left.as_ref())
4087                && let Some(bucket) = type_sample_bucket(right_ty)
4088            {
4089                samples
4090                    .entry(bucket)
4091                    .or_default()
4092                    .insert(variant.as_str().to_owned());
4093            }
4094            collect_named_literals_from_expr(
4095                samples,
4096                left,
4097                left_ty.as_ref(),
4098                field_types,
4099                helper_returns,
4100                binding_types,
4101            );
4102            collect_named_literals_from_expr(
4103                samples,
4104                right,
4105                right_ty.as_ref(),
4106                field_types,
4107                helper_returns,
4108                binding_types,
4109            );
4110        }
4111        Expr::IfElse {
4112            condition,
4113            then_expr,
4114            else_expr,
4115        } => {
4116            collect_named_literals_from_expr(
4117                samples,
4118                condition,
4119                Some(&TypeRef::Bool),
4120                field_types,
4121                helper_returns,
4122                binding_types,
4123            );
4124            collect_named_literals_from_expr(
4125                samples,
4126                then_expr,
4127                expected_ty,
4128                field_types,
4129                helper_returns,
4130                binding_types,
4131            );
4132            collect_named_literals_from_expr(
4133                samples,
4134                else_expr,
4135                expected_ty,
4136                field_types,
4137                helper_returns,
4138                binding_types,
4139            );
4140        }
4141        Expr::Not(inner)
4142        | Expr::SeqElements(inner)
4143        | Expr::Len(inner)
4144        | Expr::Head(inner)
4145        | Expr::MapKeys(inner)
4146        | Expr::Some(inner)
4147        | Expr::FieldAccess { base: inner, .. }
4148        | Expr::EnumVariantIs { value: inner, .. }
4149        | Expr::EnumStringSetPayload { value: inner, .. } => {
4150            let nested_ty = infer_expr_type(inner, field_types, helper_returns, binding_types);
4151            collect_named_literals_from_expr(
4152                samples,
4153                inner,
4154                nested_ty.as_ref(),
4155                field_types,
4156                helper_returns,
4157                binding_types,
4158            );
4159        }
4160        Expr::And(items) | Expr::Or(items) => {
4161            for item in items {
4162                collect_named_literals_from_expr(
4163                    samples,
4164                    item,
4165                    None,
4166                    field_types,
4167                    helper_returns,
4168                    binding_types,
4169                );
4170            }
4171        }
4172        Expr::SeqLiteral(items) => {
4173            let item_expected_ty = match expected_ty {
4174                Some(TypeRef::Seq(inner)) => Some(inner.as_ref()),
4175                _ => None,
4176            };
4177            for item in items {
4178                collect_named_literals_from_expr(
4179                    samples,
4180                    item,
4181                    item_expected_ty,
4182                    field_types,
4183                    helper_returns,
4184                    binding_types,
4185                );
4186            }
4187        }
4188        Expr::Add(left, right)
4189        | Expr::Sub(left, right)
4190        | Expr::Gt(left, right)
4191        | Expr::Gte(left, right)
4192        | Expr::Lt(left, right)
4193        | Expr::Lte(left, right) => {
4194            collect_named_literals_from_expr(
4195                samples,
4196                left,
4197                infer_expr_type(left, field_types, helper_returns, binding_types).as_ref(),
4198                field_types,
4199                helper_returns,
4200                binding_types,
4201            );
4202            collect_named_literals_from_expr(
4203                samples,
4204                right,
4205                infer_expr_type(right, field_types, helper_returns, binding_types).as_ref(),
4206                field_types,
4207                helper_returns,
4208                binding_types,
4209            );
4210        }
4211        Expr::Contains { collection, value } => {
4212            let collection_ty =
4213                infer_expr_type(collection, field_types, helper_returns, binding_types);
4214            let value_ty = match collection_ty {
4215                Some(TypeRef::Set(inner_ty) | TypeRef::Seq(inner_ty)) => Some(*inner_ty),
4216                Some(TypeRef::Map(key_ty, _)) => Some(*key_ty),
4217                _ => None,
4218            };
4219            collect_named_literals_from_expr(
4220                samples,
4221                collection,
4222                None,
4223                field_types,
4224                helper_returns,
4225                binding_types,
4226            );
4227            collect_named_literals_from_expr(
4228                samples,
4229                value,
4230                value_ty.as_ref(),
4231                field_types,
4232                helper_returns,
4233                binding_types,
4234            );
4235        }
4236        Expr::Count { collection, value } => {
4237            let collection_ty =
4238                infer_expr_type(collection, field_types, helper_returns, binding_types);
4239            let value_ty = match collection_ty {
4240                Some(TypeRef::Set(inner_ty) | TypeRef::Seq(inner_ty)) => Some(*inner_ty),
4241                Some(TypeRef::Map(key_ty, _)) => Some(*key_ty),
4242                _ => None,
4243            };
4244            collect_named_literals_from_expr(
4245                samples,
4246                collection,
4247                None,
4248                field_types,
4249                helper_returns,
4250                binding_types,
4251            );
4252            collect_named_literals_from_expr(
4253                samples,
4254                value,
4255                value_ty.as_ref(),
4256                field_types,
4257                helper_returns,
4258                binding_types,
4259            );
4260        }
4261        Expr::MapContainsKey { map, key } => {
4262            let map_ty = infer_expr_type(map, field_types, helper_returns, binding_types);
4263            let key_ty = match map_ty {
4264                Some(TypeRef::Map(key_ty, _)) => Some(*key_ty),
4265                _ => None,
4266            };
4267            collect_named_literals_from_expr(
4268                samples,
4269                map,
4270                None,
4271                field_types,
4272                helper_returns,
4273                binding_types,
4274            );
4275            collect_named_literals_from_expr(
4276                samples,
4277                key,
4278                key_ty.as_ref(),
4279                field_types,
4280                helper_returns,
4281                binding_types,
4282            );
4283        }
4284        Expr::SeqStartsWith { seq, prefix } => {
4285            let seq_ty = infer_expr_type(seq, field_types, helper_returns, binding_types);
4286            collect_named_literals_from_expr(
4287                samples,
4288                seq,
4289                seq_ty.as_ref(),
4290                field_types,
4291                helper_returns,
4292                binding_types,
4293            );
4294            collect_named_literals_from_expr(
4295                samples,
4296                prefix,
4297                seq_ty.as_ref(),
4298                field_types,
4299                helper_returns,
4300                binding_types,
4301            );
4302        }
4303        Expr::MapGet { map, key } | Expr::MapValue { map, key } => {
4304            let map_ty = infer_expr_type(map, field_types, helper_returns, binding_types);
4305            let key_ty = match map_ty {
4306                Some(TypeRef::Map(key_ty, _)) => Some(*key_ty),
4307                _ => None,
4308            };
4309            collect_named_literals_from_expr(
4310                samples,
4311                map,
4312                None,
4313                field_types,
4314                helper_returns,
4315                binding_types,
4316            );
4317            collect_named_literals_from_expr(
4318                samples,
4319                key,
4320                key_ty.as_ref(),
4321                field_types,
4322                helper_returns,
4323                binding_types,
4324            );
4325        }
4326        Expr::MapLiteral(entries) => {
4327            let (key_ty, value_ty) = match expected_ty {
4328                Some(TypeRef::Map(key_ty, value_ty)) => {
4329                    (Some(key_ty.as_ref()), Some(value_ty.as_ref()))
4330                }
4331                _ => (None, None),
4332            };
4333            for (key, value) in entries {
4334                collect_named_literals_from_expr(
4335                    samples,
4336                    key,
4337                    key_ty,
4338                    field_types,
4339                    helper_returns,
4340                    binding_types,
4341                );
4342                collect_named_literals_from_expr(
4343                    samples,
4344                    value,
4345                    value_ty,
4346                    field_types,
4347                    helper_returns,
4348                    binding_types,
4349                );
4350            }
4351        }
4352        Expr::Call { helper: _, args } => {
4353            for arg in args {
4354                collect_named_literals_from_expr(
4355                    samples,
4356                    arg,
4357                    infer_expr_type(arg, field_types, helper_returns, binding_types).as_ref(),
4358                    field_types,
4359                    helper_returns,
4360                    binding_types,
4361                );
4362            }
4363        }
4364        Expr::Quantified {
4365            binding,
4366            over,
4367            body,
4368            ..
4369        } => {
4370            collect_named_literals_from_expr(
4371                samples,
4372                over,
4373                None,
4374                field_types,
4375                helper_returns,
4376                binding_types,
4377            );
4378            // Thread the quantifier binding's element type into the body so
4379            // literals compared against the binding land in the element's
4380            // named sample domain (e.g. `exists(name in <Set<ToolName>>,
4381            // name == "view_image")` buckets the literal under `ToolName`).
4382            let element_ty = infer_expr_type(over, field_types, helper_returns, binding_types)
4383                .and_then(|ty| match ty {
4384                    TypeRef::Set(inner) | TypeRef::Seq(inner) => Some(*inner),
4385                    _ => None,
4386                });
4387            let mut body_binding_types = binding_types.clone();
4388            if let Some(element_ty) = element_ty {
4389                body_binding_types.insert(binding.clone(), element_ty);
4390            }
4391            collect_named_literals_from_expr(
4392                samples,
4393                body,
4394                Some(&TypeRef::Bool),
4395                field_types,
4396                helper_returns,
4397                &body_binding_types,
4398            );
4399        }
4400        Expr::Bool(_)
4401        | Expr::U64(_)
4402        | Expr::U64Max
4403        | Expr::String(_)
4404        | Expr::NamedVariant { .. }
4405        | Expr::EmptySet
4406        | Expr::EmptyMap
4407        | Expr::CurrentPhase
4408        | Expr::Phase(_)
4409        | Expr::Field(_)
4410        | Expr::Binding(_)
4411        | Expr::Variant(_)
4412        | Expr::None => {}
4413    }
4414}
4415
4416fn infer_expr_type(
4417    expr: &Expr,
4418    field_types: &BTreeMap<String, TypeRef>,
4419    helper_returns: &BTreeMap<String, TypeRef>,
4420    binding_types: &BTreeMap<String, TypeRef>,
4421) -> Option<TypeRef> {
4422    match expr {
4423        Expr::Bool(_) => Some(TypeRef::Bool),
4424        Expr::U64(_) | Expr::U64Max => Some(TypeRef::U64),
4425        Expr::String(_) | Expr::CurrentPhase | Expr::Phase(_) | Expr::Variant(_) => {
4426            Some(TypeRef::String)
4427        }
4428        Expr::NamedVariant { enum_name, .. } => Some(TypeRef::Enum(enum_name.clone())),
4429        Expr::FieldAccess { .. } => None,
4430        Expr::EnumVariantIs { .. } => Some(TypeRef::Bool),
4431        Expr::EnumStringSetPayload { .. } => Some(TypeRef::Set(Box::new(TypeRef::String))),
4432        Expr::Field(name) => field_types.get(name.as_str()).cloned(),
4433        Expr::Binding(name) => binding_types.get(name).cloned(),
4434        Expr::None => None,
4435        Expr::IfElse {
4436            then_expr,
4437            else_expr,
4438            ..
4439        } => {
4440            let then_ty = infer_expr_type(then_expr, field_types, helper_returns, binding_types);
4441            let else_ty = infer_expr_type(else_expr, field_types, helper_returns, binding_types);
4442            if then_ty == else_ty {
4443                then_ty
4444            } else {
4445                then_ty.or(else_ty)
4446            }
4447        }
4448        Expr::Not(_)
4449        | Expr::And(_)
4450        | Expr::Or(_)
4451        | Expr::Eq(_, _)
4452        | Expr::Neq(_, _)
4453        | Expr::Gt(_, _)
4454        | Expr::Gte(_, _)
4455        | Expr::Lt(_, _)
4456        | Expr::Lte(_, _)
4457        | Expr::Contains { .. }
4458        | Expr::MapContainsKey { .. }
4459        | Expr::SeqStartsWith { .. }
4460        | Expr::Quantified { .. } => Some(TypeRef::Bool),
4461        Expr::Add(_, _) | Expr::Sub(_, _) | Expr::Len(_) | Expr::Count { .. } => Some(TypeRef::U64),
4462        Expr::SeqElements(inner) => {
4463            match infer_expr_type(inner, field_types, helper_returns, binding_types) {
4464                Some(TypeRef::Seq(inner_ty)) => Some(TypeRef::Set(inner_ty)),
4465                _ => None,
4466            }
4467        }
4468        Expr::Head(inner) => {
4469            match infer_expr_type(inner, field_types, helper_returns, binding_types) {
4470                Some(TypeRef::Seq(inner_ty)) => Some(*inner_ty),
4471                _ => None,
4472            }
4473        }
4474        Expr::MapKeys(inner) => {
4475            match infer_expr_type(inner, field_types, helper_returns, binding_types) {
4476                Some(TypeRef::Map(key_ty, _)) => Some(TypeRef::Set(key_ty)),
4477                _ => None,
4478            }
4479        }
4480        Expr::MapGet { map, .. } | Expr::MapValue { map, .. } => {
4481            match infer_expr_type(map, field_types, helper_returns, binding_types) {
4482                Some(TypeRef::Map(_, value_ty)) => Some(*value_ty),
4483                _ => None,
4484            }
4485        }
4486        Expr::MapLiteral(entries) => entries.first().and_then(|(key, value)| {
4487            let key_ty = infer_expr_type(key, field_types, helper_returns, binding_types)?;
4488            let value_ty = infer_expr_type(value, field_types, helper_returns, binding_types)?;
4489            Some(TypeRef::Map(Box::new(key_ty), Box::new(value_ty)))
4490        }),
4491        Expr::Some(inner) => infer_expr_type(inner, field_types, helper_returns, binding_types)
4492            .map(|inner_ty| TypeRef::Option(Box::new(inner_ty))),
4493        Expr::Call { helper, .. } if helper == "mob_machine_step_status_from_frame_node_status" => {
4494            meerkat_machine_schema::identity::EnumTypeId::parse("StepRunStatus")
4495                .ok()
4496                .map(TypeRef::Enum)
4497        }
4498        Expr::Call { helper, args } if helper == "session_document_instruction_slot_after_set" => {
4499            args.first().and_then(|current| {
4500                infer_expr_type(current, field_types, helper_returns, binding_types)
4501            })
4502        }
4503        Expr::Call { helper, .. } if helper == "session_document_instruction_active_bytes" => {
4504            Some(TypeRef::U64)
4505        }
4506        // The Active entries of a slot map: the type of the map it filters.
4507        Expr::Call { helper, args } if helper == "session_document_instruction_active_slots" => {
4508            args.get(1).and_then(|values| {
4509                infer_expr_type(values, field_types, helper_returns, binding_types)
4510            })
4511        }
4512        // The retired count per activation key: the type of the row counts.
4513        Expr::Call { helper, args } if helper == "session_document_activation_retired_after" => {
4514            args.first()
4515                .and_then(|rows| infer_expr_type(rows, field_types, helper_returns, binding_types))
4516        }
4517        Expr::Call { helper, .. } if helper == "runtime_delivery_recipient_outcomes_after_set" => {
4518            Some(TypeRef::Map(
4519                Box::new(TypeRef::String),
4520                Box::new(TypeRef::Enum(
4521                    meerkat_machine_schema::identity::EnumTypeId::parse("DeliveryRecipientOutcome")
4522                        .ok()?,
4523                )),
4524            ))
4525        }
4526        Expr::Call { helper, .. } if helper == "mob_machine_run_step_status_after_set" => {
4527            Some(TypeRef::Map(
4528                Box::new(TypeRef::Named(
4529                    meerkat_machine_schema::identity::NamedTypeId::parse("RunId").ok()?,
4530                )),
4531                Box::new(TypeRef::Map(
4532                    Box::new(TypeRef::Named(
4533                        meerkat_machine_schema::identity::NamedTypeId::parse("StepId").ok()?,
4534                    )),
4535                    Box::new(TypeRef::Option(Box::new(TypeRef::Enum(
4536                        meerkat_machine_schema::identity::EnumTypeId::parse("StepRunStatus")
4537                            .ok()?,
4538                    )))),
4539                )),
4540            ))
4541        }
4542        Expr::Call { helper, .. }
4543            if helper == "mob_machine_run_step_status_after_cancel_unfinished" =>
4544        {
4545            Some(TypeRef::Map(
4546                Box::new(TypeRef::Named(
4547                    meerkat_machine_schema::identity::NamedTypeId::parse("RunId").ok()?,
4548                )),
4549                Box::new(TypeRef::Map(
4550                    Box::new(TypeRef::Named(
4551                        meerkat_machine_schema::identity::NamedTypeId::parse("StepId").ok()?,
4552                    )),
4553                    Box::new(TypeRef::Option(Box::new(TypeRef::Enum(
4554                        meerkat_machine_schema::identity::EnumTypeId::parse("StepRunStatus")
4555                            .ok()?,
4556                    )))),
4557                )),
4558            ))
4559        }
4560        Expr::Call { helper, .. } if helper == "mob_machine_run_step_bool_after_set" => {
4561            Some(TypeRef::Map(
4562                Box::new(TypeRef::Named(
4563                    meerkat_machine_schema::identity::NamedTypeId::parse("RunId").ok()?,
4564                )),
4565                Box::new(TypeRef::Map(
4566                    Box::new(TypeRef::Named(
4567                        meerkat_machine_schema::identity::NamedTypeId::parse("StepId").ok()?,
4568                    )),
4569                    Box::new(TypeRef::Bool),
4570                )),
4571            ))
4572        }
4573        Expr::Call { helper, .. }
4574            if helper == "mob_machine_run_step_condition_result_after_set" =>
4575        {
4576            Some(TypeRef::Map(
4577                Box::new(TypeRef::Named(
4578                    meerkat_machine_schema::identity::NamedTypeId::parse("RunId").ok()?,
4579                )),
4580                Box::new(TypeRef::Map(
4581                    Box::new(TypeRef::Named(
4582                        meerkat_machine_schema::identity::NamedTypeId::parse("StepId").ok()?,
4583                    )),
4584                    Box::new(TypeRef::Option(Box::new(TypeRef::Bool))),
4585                )),
4586            ))
4587        }
4588        Expr::Call { helper, .. }
4589            if helper == "mob_machine_run_step_u64_after_set"
4590                || helper == "mob_machine_run_step_u64_after_increment" =>
4591        {
4592            Some(TypeRef::Map(
4593                Box::new(TypeRef::Named(
4594                    meerkat_machine_schema::identity::NamedTypeId::parse("RunId").ok()?,
4595                )),
4596                Box::new(TypeRef::Map(
4597                    Box::new(TypeRef::Named(
4598                        meerkat_machine_schema::identity::NamedTypeId::parse("StepId").ok()?,
4599                    )),
4600                    Box::new(TypeRef::U64),
4601                )),
4602            ))
4603        }
4604        Expr::Call { helper, .. } if helper == "mob_machine_run_retry_count_after_increment" => {
4605            Some(TypeRef::Map(
4606                Box::new(TypeRef::Named(
4607                    meerkat_machine_schema::identity::NamedTypeId::parse("RunId").ok()?,
4608                )),
4609                Box::new(TypeRef::Map(
4610                    Box::new(TypeRef::String),
4611                    Box::new(TypeRef::U64),
4612                )),
4613            ))
4614        }
4615        Expr::Call { helper, .. } if helper == "mob_machine_frame_node_bool_after_set" => {
4616            Some(TypeRef::Map(
4617                Box::new(TypeRef::Named(
4618                    meerkat_machine_schema::identity::NamedTypeId::parse("FrameId").ok()?,
4619                )),
4620                Box::new(TypeRef::Map(
4621                    Box::new(TypeRef::Named(
4622                        meerkat_machine_schema::identity::NamedTypeId::parse("FlowNodeId").ok()?,
4623                    )),
4624                    Box::new(TypeRef::Bool),
4625                )),
4626            ))
4627        }
4628        Expr::Call { helper, .. } => helper_returns.get(helper).cloned(),
4629        Expr::SeqLiteral(items) => items.first().and_then(|item| {
4630            infer_expr_type(item, field_types, helper_returns, binding_types)
4631                .map(|inner_ty| TypeRef::Seq(Box::new(inner_ty)))
4632        }),
4633        Expr::EmptySet => None,
4634        Expr::EmptyMap => None,
4635    }
4636}
4637
4638fn default_sample_cardinality(deep: bool) -> usize {
4639    if deep { 2 } else { 1 }
4640}
4641
4642fn type_sample_bucket(ty: &TypeRef) -> Option<String> {
4643    match ty {
4644        TypeRef::String => Some("String".into()),
4645        TypeRef::Named(name) => Some(name.as_str().to_owned()),
4646        TypeRef::Enum(name) => Some(name.as_str().to_owned()),
4647        _ => None,
4648    }
4649}
4650
4651fn collected_sample_literals(
4652    bucket: &str,
4653    sample_cardinality: usize,
4654    named_samples: &BTreeMap<String, BTreeSet<String>>,
4655) -> Option<Vec<String>> {
4656    let samples = named_samples.get(bucket)?;
4657    let limit = sample_cardinality.max(1);
4658    let rendered = samples
4659        .iter()
4660        .take(limit)
4661        .map(tla_string)
4662        .collect::<Vec<_>>();
4663    (!rendered.is_empty()).then_some(rendered)
4664}
4665
4666fn generic_string_samples(sample_cardinality: usize) -> Vec<String> {
4667    if sample_cardinality > 1 {
4668        vec!["alpha".into(), "beta".into()]
4669    } else {
4670        vec!["alpha".into()]
4671    }
4672}
4673
4674fn collected_string_samples(
4675    sample_cardinality: usize,
4676    named_samples: &BTreeMap<String, BTreeSet<String>>,
4677    include_named_samples: bool,
4678) -> Vec<String> {
4679    let mut values = generic_string_samples(sample_cardinality);
4680    if include_named_samples && let Some(samples) = named_samples.get("String") {
4681        for sample in samples {
4682            if !values.iter().any(|existing| existing == sample) {
4683                values.push(sample.clone());
4684            }
4685        }
4686    }
4687    values
4688}
4689
4690fn render_default_domain_assignment(
4691    ty: &TypeRef,
4692    sample_cardinality: usize,
4693    named_samples: &BTreeMap<String, BTreeSet<String>>,
4694    named_bindings: &BTreeMap<String, meerkat_machine_schema::RustTypeAtom>,
4695    include_string_samples: bool,
4696) -> String {
4697    match ty {
4698        TypeRef::Bool => "{TRUE, FALSE}".into(),
4699        TypeRef::U32 | TypeRef::U64 => {
4700            if sample_cardinality > 1 {
4701                "{0, 1, 2}".into()
4702            } else {
4703                // CI uses {1} to avoid state explosion from zero-as-unlimited
4704                // semantics in scheduler guards (Or(max==0, count<max)).
4705                // Counter fields that start at 0 get it via Init, not NatValues.
4706                // Deep uses {0, 1} to cover the full range.
4707                "{1}".into()
4708            }
4709        }
4710        TypeRef::String if sample_cardinality == 0 => "{}".into(),
4711        TypeRef::String => format!(
4712            "{{{}}}",
4713            collected_string_samples(sample_cardinality, named_samples, include_string_samples)
4714                .into_iter()
4715                .map(|sample| tla_string(&sample))
4716                .collect::<Vec<_>>()
4717                .join(", ")
4718        ),
4719        TypeRef::Named(name) => render_named_type_domain_assignment(
4720            name.as_str(),
4721            sample_cardinality,
4722            named_samples,
4723            named_bindings,
4724        ),
4725        TypeRef::Enum(name) => render_enum_type_domain_assignment(
4726            name.as_str(),
4727            sample_cardinality,
4728            named_samples,
4729            named_bindings,
4730        ),
4731        TypeRef::Seq(inner) => {
4732            let samples = sample_values(
4733                inner,
4734                sample_cardinality,
4735                named_samples,
4736                named_bindings,
4737                include_string_samples,
4738            );
4739            if samples.len() >= 2 {
4740                format!(
4741                    "{{<<>>, <<{}>>, <<{}, {}>>}}",
4742                    samples[0], samples[0], samples[1]
4743                )
4744            } else if let Some(sample) = samples.first() {
4745                format!("{{<<>>, <<{}>>}}", sample)
4746            } else {
4747                "{<<>>}".into()
4748            }
4749        }
4750        TypeRef::Set(inner) => {
4751            let samples = sample_values(
4752                inner,
4753                sample_cardinality,
4754                named_samples,
4755                named_bindings,
4756                include_string_samples,
4757            );
4758            if samples.len() >= 2 {
4759                format!(
4760                    "{{{{}}, {{{}}}, {{{}, {}}}}}",
4761                    samples[0], samples[0], samples[1]
4762                )
4763            } else if let Some(sample) = samples.first() {
4764                format!("{{{{}}, {{{}}}}}", sample)
4765            } else {
4766                "{{}}".into()
4767            }
4768        }
4769        TypeRef::Option(inner) => {
4770            let samples = sample_values(
4771                inner,
4772                sample_cardinality,
4773                named_samples,
4774                named_bindings,
4775                include_string_samples,
4776            )
4777            .into_iter()
4778            .map(|sample| format!("[tag |-> {}, value |-> {}]", tla_string("some"), sample))
4779            .collect::<Vec<_>>();
4780            if samples.is_empty() {
4781                format!(
4782                    "{{[tag |-> {}, value |-> {}]}}",
4783                    tla_string("none"),
4784                    tla_string("none")
4785                )
4786            } else {
4787                format!(
4788                    "{{[tag |-> {}, value |-> {}], {}}}",
4789                    tla_string("none"),
4790                    tla_string("none"),
4791                    samples.join(", ")
4792                )
4793            }
4794        }
4795        TypeRef::Map(_, _) => "{}".into(),
4796    }
4797}
4798
4799fn render_named_type_domain_assignment(
4800    name: impl AsRef<str>,
4801    sample_cardinality: usize,
4802    named_samples: &BTreeMap<String, BTreeSet<String>>,
4803    named_bindings: &BTreeMap<String, meerkat_machine_schema::RustTypeAtom>,
4804) -> String {
4805    use meerkat_machine_schema::RustTypeAtom;
4806
4807    let name = name.as_ref();
4808    if name == "OperationSource" {
4809        return format!(
4810            "{{{}}}",
4811            operation_source_samples(sample_cardinality).join(", ")
4812        );
4813    }
4814    match require_named_binding(named_bindings, name) {
4815        RustTypeAtom::U64 | RustTypeAtom::U32 | RustTypeAtom::U16 | RustTypeAtom::U8 => {
4816            if sample_cardinality > 1 {
4817                "{1, 2}".into()
4818            } else {
4819                "{1}".into()
4820            }
4821        }
4822        RustTypeAtom::Bool => "{TRUE, FALSE}".into(),
4823        RustTypeAtom::StringEnum { variants } => {
4824            format!(
4825                "{{{}}}",
4826                string_enum_variant_samples(name, variants).join(", ")
4827            )
4828        }
4829        RustTypeAtom::TypePathEnum {
4830            unit_variants,
4831            structural_variants,
4832            ..
4833        } => format!(
4834            "{{{}}}",
4835            type_path_enum_variant_samples(
4836                unit_variants,
4837                structural_variants,
4838                sample_cardinality,
4839                named_samples,
4840                named_bindings,
4841            )
4842            .join(", ")
4843        ),
4844        RustTypeAtom::TypePathFieldPresenceSet { fields, .. } => format!(
4845            "{{{}}}",
4846            field_presence_set_samples(fields, sample_cardinality).join(", ")
4847        ),
4848        RustTypeAtom::TypePathStruct { fields, .. } => format!(
4849            "{{{}}}",
4850            type_path_struct_samples(fields, sample_cardinality, named_samples, named_bindings)
4851                .join(", ")
4852        ),
4853        RustTypeAtom::String | RustTypeAtom::TypePath(_) => {
4854            if sample_cardinality == 0 {
4855                return "{}".into();
4856            }
4857
4858            if let Some(rendered) =
4859                collected_sample_literals(name, sample_cardinality, named_samples)
4860            {
4861                return format!("{{{}}}", rendered.join(", "));
4862            }
4863
4864            let values = (1..=sample_cardinality.max(1))
4865                .map(|idx| tla_string(format!("{}_{}", tla_ident(name).to_lowercase(), idx)))
4866                .collect::<Vec<_>>()
4867                .join(", ");
4868            format!("{{{values}}}")
4869        }
4870    }
4871}
4872
4873#[allow(clippy::panic)]
4874fn render_enum_type_domain_assignment(
4875    name: impl AsRef<str>,
4876    sample_cardinality: usize,
4877    named_samples: &BTreeMap<String, BTreeSet<String>>,
4878    named_bindings: &BTreeMap<String, meerkat_machine_schema::RustTypeAtom>,
4879) -> String {
4880    use meerkat_machine_schema::RustTypeAtom;
4881
4882    let name = name.as_ref();
4883    match require_named_binding(named_bindings, name) {
4884        RustTypeAtom::StringEnum { variants } => {
4885            format!(
4886                "{{{}}}",
4887                string_enum_variant_samples(name, variants).join(", ")
4888            )
4889        }
4890        RustTypeAtom::TypePathEnum {
4891            unit_variants,
4892            structural_variants,
4893            ..
4894        } => format!(
4895            "{{{}}}",
4896            type_path_enum_variant_samples(
4897                unit_variants,
4898                structural_variants,
4899                sample_cardinality,
4900                named_samples,
4901                named_bindings,
4902            )
4903            .join(", ")
4904        ),
4905        other => {
4906            panic!(
4907                "generated enum domain `{name}` requires StringEnum or TypePathEnum binding, found {other:?}"
4908            );
4909        }
4910    }
4911}
4912
4913fn sample_values(
4914    ty: &TypeRef,
4915    sample_cardinality: usize,
4916    named_samples: &BTreeMap<String, BTreeSet<String>>,
4917    named_bindings: &BTreeMap<String, meerkat_machine_schema::RustTypeAtom>,
4918    include_string_samples: bool,
4919) -> Vec<String> {
4920    match ty {
4921        TypeRef::Bool => vec!["TRUE".into(), "FALSE".into()],
4922        TypeRef::U32 | TypeRef::U64 => {
4923            if sample_cardinality > 1 {
4924                vec!["1".into(), "2".into()]
4925            } else {
4926                vec!["1".into()]
4927            }
4928        }
4929        TypeRef::String if sample_cardinality == 0 => Vec::new(),
4930        TypeRef::String => {
4931            collected_string_samples(sample_cardinality, named_samples, include_string_samples)
4932                .into_iter()
4933                .map(|sample| tla_string(&sample))
4934                .collect()
4935        }
4936        TypeRef::Named(name) if named_type_uses_nat_domain(named_bindings, name.as_str()) => {
4937            if sample_cardinality > 1 {
4938                vec!["1".into(), "2".into()]
4939            } else {
4940                vec!["1".into()]
4941            }
4942        }
4943        TypeRef::Named(name) => {
4944            let name = name.as_str();
4945            sample_values_for_named_type(name, sample_cardinality, named_samples, named_bindings)
4946        }
4947        TypeRef::Enum(name) => {
4948            let name = name.as_str();
4949            sample_values_for_enum_type(name, sample_cardinality, named_samples, named_bindings)
4950        }
4951        TypeRef::Option(inner) => {
4952            let mut values = vec![format!(
4953                "[tag |-> {}, value |-> {}]",
4954                tla_string("none"),
4955                tla_string("none")
4956            )];
4957            values.extend(
4958                sample_values(
4959                    inner,
4960                    sample_cardinality,
4961                    named_samples,
4962                    named_bindings,
4963                    include_string_samples,
4964                )
4965                .into_iter()
4966                .map(|sample| format!("[tag |-> {}, value |-> {}]", tla_string("some"), sample)),
4967            );
4968            values
4969        }
4970        TypeRef::Seq(inner) => sample_values(
4971            inner,
4972            sample_cardinality,
4973            named_samples,
4974            named_bindings,
4975            include_string_samples,
4976        ),
4977        TypeRef::Set(inner) => sample_values(
4978            inner,
4979            sample_cardinality,
4980            named_samples,
4981            named_bindings,
4982            include_string_samples,
4983        ),
4984        TypeRef::Map(_, _) => vec![],
4985    }
4986}
4987
4988fn sample_values_for_named_type(
4989    name: &str,
4990    sample_cardinality: usize,
4991    named_samples: &BTreeMap<String, BTreeSet<String>>,
4992    bindings: &BTreeMap<String, meerkat_machine_schema::RustTypeAtom>,
4993) -> Vec<String> {
4994    use meerkat_machine_schema::RustTypeAtom;
4995
4996    if name == "OperationSource" {
4997        return operation_source_samples(sample_cardinality);
4998    }
4999    match require_named_binding(bindings, name) {
5000        RustTypeAtom::U64 | RustTypeAtom::U32 | RustTypeAtom::U16 | RustTypeAtom::U8 => {
5001            if sample_cardinality > 1 {
5002                vec!["1".into(), "2".into()]
5003            } else {
5004                vec!["1".into()]
5005            }
5006        }
5007        RustTypeAtom::Bool => vec!["TRUE".into(), "FALSE".into()],
5008        RustTypeAtom::StringEnum { variants } => string_enum_variant_samples(name, variants),
5009        RustTypeAtom::TypePathEnum {
5010            unit_variants,
5011            structural_variants,
5012            ..
5013        } => type_path_enum_variant_samples(
5014            unit_variants,
5015            structural_variants,
5016            sample_cardinality,
5017            named_samples,
5018            bindings,
5019        ),
5020        RustTypeAtom::TypePathFieldPresenceSet { fields, .. } => {
5021            field_presence_set_samples(fields, sample_cardinality)
5022        }
5023        RustTypeAtom::TypePathStruct { fields, .. } => {
5024            type_path_struct_samples(fields, sample_cardinality, named_samples, bindings)
5025        }
5026        RustTypeAtom::String | RustTypeAtom::TypePath(_) => {
5027            if sample_cardinality == 0 {
5028                return Vec::new();
5029            }
5030            if let Some(samples) = named_samples.get(name) {
5031                let limit = sample_cardinality.max(1);
5032                let rendered = samples
5033                    .iter()
5034                    .take(limit)
5035                    .map(tla_string)
5036                    .collect::<Vec<_>>();
5037                if !rendered.is_empty() {
5038                    return rendered;
5039                }
5040            }
5041            (1..=sample_cardinality.max(1))
5042                .map(|idx| tla_string(format!("{}_{}", tla_ident(name).to_lowercase(), idx)))
5043                .collect()
5044        }
5045    }
5046}
5047
5048#[allow(clippy::panic)]
5049fn sample_values_for_enum_type(
5050    name: &str,
5051    sample_cardinality: usize,
5052    named_samples: &BTreeMap<String, BTreeSet<String>>,
5053    bindings: &BTreeMap<String, meerkat_machine_schema::RustTypeAtom>,
5054) -> Vec<String> {
5055    use meerkat_machine_schema::RustTypeAtom;
5056
5057    match require_named_binding(bindings, name) {
5058        RustTypeAtom::StringEnum { variants } => string_enum_variant_samples(name, variants),
5059        RustTypeAtom::TypePathEnum {
5060            unit_variants,
5061            structural_variants,
5062            ..
5063        } => type_path_enum_variant_samples(
5064            unit_variants,
5065            structural_variants,
5066            sample_cardinality,
5067            named_samples,
5068            bindings,
5069        ),
5070        other => {
5071            panic!(
5072                "generated enum domain `{name}` requires StringEnum or TypePathEnum binding, found {other:?}"
5073            );
5074        }
5075    }
5076}
5077
5078#[allow(clippy::panic)]
5079fn require_named_binding<'a>(
5080    bindings: &'a BTreeMap<String, meerkat_machine_schema::RustTypeAtom>,
5081    name: &str,
5082) -> &'a meerkat_machine_schema::RustTypeAtom {
5083    bindings
5084        .get(name)
5085        .unwrap_or_else(|| panic!("missing NamedTypeBinding for generated domain `{name}`"))
5086}
5087
5088fn string_enum_variant_samples(
5089    name: &str,
5090    variants: &[meerkat_machine_schema::identity::EnumVariantId],
5091) -> Vec<String> {
5092    variants
5093        .iter()
5094        .map(|variant| tla_string(string_enum_wire_label(name, variant.as_str())))
5095        .collect()
5096}
5097
5098fn render_named_variant_value(
5099    enum_name: &str,
5100    variant: &str,
5101    named_bindings: &BTreeMap<String, meerkat_machine_schema::RustTypeAtom>,
5102) -> String {
5103    let label = tla_string(string_enum_wire_label(enum_name, variant));
5104    if named_bindings
5105        .get(enum_name)
5106        .is_some_and(CfgRecordRendering::renders_cfg_hostile_record)
5107    {
5108        format!("[tag |-> {label}]")
5109    } else {
5110        label
5111    }
5112}
5113
5114fn type_path_enum_variant_samples(
5115    unit_variants: &[meerkat_machine_schema::identity::EnumVariantId],
5116    structural_variants: &[TypePathEnumStructuralVariant],
5117    sample_cardinality: usize,
5118    named_samples: &BTreeMap<String, BTreeSet<String>>,
5119    named_bindings: &BTreeMap<String, meerkat_machine_schema::RustTypeAtom>,
5120) -> Vec<String> {
5121    let unit_variants_are_records = !structural_variants.is_empty();
5122    let mut samples = unit_variants
5123        .iter()
5124        .map(|variant| {
5125            let tag = tla_string(variant.as_str());
5126            if unit_variants_are_records {
5127                format!("[tag |-> {tag}]")
5128            } else {
5129                tag
5130            }
5131        })
5132        .collect::<Vec<_>>();
5133    if sample_cardinality > 0 {
5134        samples.extend(structural_variants.iter().flat_map(|variant| {
5135            render_type_path_enum_structural_samples(
5136                variant,
5137                sample_cardinality,
5138                named_samples,
5139                named_bindings,
5140            )
5141        }));
5142    }
5143    samples
5144}
5145
5146fn field_presence_set_samples(
5147    fields: &[meerkat_machine_schema::identity::FieldId],
5148    sample_cardinality: usize,
5149) -> Vec<String> {
5150    if sample_cardinality == 0 {
5151        return Vec::new();
5152    }
5153    let limit = sample_cardinality.max(1);
5154    let rendered_fields = fields
5155        .iter()
5156        .map(|field| tla_string(field.as_str()))
5157        .collect::<Vec<_>>();
5158    let mut samples = rendered_fields
5159        .iter()
5160        .take(limit)
5161        .map(|field| format!("{{{field}}}"))
5162        .collect::<Vec<_>>();
5163    if limit > rendered_fields.len() && rendered_fields.len() >= 2 {
5164        samples.push(format!("{{{}}}", rendered_fields.join(", ")));
5165    }
5166    samples
5167}
5168
5169fn operation_source_samples(sample_cardinality: usize) -> Vec<String> {
5170    let mut samples = vec![
5171        format!(
5172            "[kind |-> {}, session_id |-> Some({}), peer_id |-> None, address |-> None]",
5173            tla_string("SessionChild"),
5174            tla_string("sessionid_1")
5175        ),
5176        format!(
5177            "[kind |-> {}, session_id |-> None, peer_id |-> Some({}), address |-> Some({})]",
5178            tla_string("BackendPeer"),
5179            tla_string("peerid_1"),
5180            tla_string("peeraddress_1")
5181        ),
5182    ];
5183    if sample_cardinality > 2 {
5184        samples.push(format!(
5185            "[kind |-> {}, session_id |-> Some({}), peer_id |-> None, address |-> None]",
5186            tla_string("SessionChild"),
5187            tla_string("sessionid_2")
5188        ));
5189    }
5190    samples
5191}
5192
5193fn type_path_struct_samples(
5194    fields: &[TypePathStructField],
5195    sample_cardinality: usize,
5196    named_samples: &BTreeMap<String, BTreeSet<String>>,
5197    bindings: &BTreeMap<String, meerkat_machine_schema::RustTypeAtom>,
5198) -> Vec<String> {
5199    if sample_cardinality == 0 {
5200        return Vec::new();
5201    }
5202    if fields.is_empty() {
5203        return vec!["[]".to_owned()];
5204    }
5205
5206    let limit = sample_cardinality.max(1);
5207    let mut field_values = Vec::new();
5208    for field in fields {
5209        let values =
5210            type_path_struct_field_samples(field, sample_cardinality, named_samples, bindings);
5211        if values.is_empty() {
5212            return Vec::new();
5213        }
5214        field_values.push((field.name.as_str().to_owned(), values));
5215    }
5216
5217    (0..limit)
5218        .map(|idx| {
5219            let fields = field_values
5220                .iter()
5221                .map(|(name, values)| {
5222                    let value = &values[idx % values.len()];
5223                    format!("{name} |-> {value}")
5224                })
5225                .collect::<Vec<_>>();
5226            format!("[{}]", fields.join(", "))
5227        })
5228        .collect()
5229}
5230
5231fn type_path_struct_field_samples(
5232    field: &TypePathStructField,
5233    sample_cardinality: usize,
5234    named_samples: &BTreeMap<String, BTreeSet<String>>,
5235    bindings: &BTreeMap<String, meerkat_machine_schema::RustTypeAtom>,
5236) -> Vec<String> {
5237    match &field.atom {
5238        TypePathStructFieldAtom::String => {
5239            if sample_cardinality == 0 {
5240                Vec::new()
5241            } else {
5242                generic_string_samples(sample_cardinality)
5243                    .into_iter()
5244                    .map(tla_string)
5245                    .collect()
5246            }
5247        }
5248        TypePathStructFieldAtom::Named(name) => {
5249            sample_values_for_named_type(name.as_str(), sample_cardinality, named_samples, bindings)
5250        }
5251        TypePathStructFieldAtom::OptionalNamed(name) => {
5252            let mut values = vec!["None".to_owned()];
5253            values.extend(
5254                sample_values_for_named_type(
5255                    name.as_str(),
5256                    sample_cardinality,
5257                    named_samples,
5258                    bindings,
5259                )
5260                .into_iter()
5261                .map(|value| format!("Some({value})")),
5262            );
5263            values
5264        }
5265    }
5266}
5267
5268fn render_type_path_enum_structural_samples(
5269    variant: &TypePathEnumStructuralVariant,
5270    sample_cardinality: usize,
5271    named_samples: &BTreeMap<String, BTreeSet<String>>,
5272    named_bindings: &BTreeMap<String, meerkat_machine_schema::RustTypeAtom>,
5273) -> Vec<String> {
5274    let mut samples = vec![vec![format!(
5275        "tag |-> {}",
5276        tla_string(variant.variant.as_str())
5277    )]];
5278    for field in &variant.fields {
5279        let values = match &field.atom {
5280            TypePathEnumPayloadAtom::StringSet => string_set_payload_samples(sample_cardinality),
5281            TypePathEnumPayloadAtom::NamedSet(type_name) => named_set_payload_samples(
5282                type_name.as_str(),
5283                sample_cardinality,
5284                named_samples,
5285                named_bindings,
5286            ),
5287            TypePathEnumPayloadAtom::String => {
5288                if sample_cardinality == 0 {
5289                    Vec::new()
5290                } else {
5291                    generic_string_samples(sample_cardinality)
5292                        .into_iter()
5293                        .map(tla_string)
5294                        .collect()
5295                }
5296            }
5297            TypePathEnumPayloadAtom::OptionalString => {
5298                let mut values = vec![format!(
5299                    "[tag |-> {}, value |-> {}]",
5300                    tla_string("none"),
5301                    tla_string("none")
5302                )];
5303                if sample_cardinality > 0 {
5304                    values.extend(generic_string_samples(sample_cardinality).into_iter().map(
5305                        |sample| {
5306                            format!(
5307                                "[tag |-> {}, value |-> {}]",
5308                                tla_string("some"),
5309                                tla_string(&sample)
5310                            )
5311                        },
5312                    ));
5313                }
5314                values
5315            }
5316            TypePathEnumPayloadAtom::Named(type_name) => sample_values_for_named_type(
5317                type_name.as_str(),
5318                sample_cardinality,
5319                named_samples,
5320                named_bindings,
5321            ),
5322        };
5323        let mut next_samples = Vec::new();
5324        for sample in &samples {
5325            for value in &values {
5326                let mut next = sample.clone();
5327                next.push(format!("{} |-> {value}", field.name));
5328                next_samples.push(next);
5329            }
5330        }
5331        samples = next_samples;
5332    }
5333    samples
5334        .into_iter()
5335        .map(|fields| format!("[{}]", fields.join(", ")))
5336        .collect()
5337}
5338
5339/// TLA sample sets for a structural enum payload carrying a finite set of
5340/// values from a named value domain. Mirrors [`string_set_payload_samples`]
5341/// shape (empty / one-member / two-member sets) over the named domain's
5342/// sample pool so payload sets stay aligned with catalog key domains.
5343fn named_set_payload_samples(
5344    type_name: &str,
5345    sample_cardinality: usize,
5346    named_samples: &BTreeMap<String, BTreeSet<String>>,
5347    named_bindings: &BTreeMap<String, meerkat_machine_schema::RustTypeAtom>,
5348) -> Vec<String> {
5349    let mut values = if sample_cardinality == 0 {
5350        Vec::new()
5351    } else {
5352        sample_values_for_named_type(type_name, sample_cardinality, named_samples, named_bindings)
5353    };
5354    // Pad the payload element pool with synthetic domain members up to the
5355    // requested cardinality so the deep model still covers differing
5356    // same-variant multi-member payloads when the collected named-sample
5357    // pool is smaller than the cardinality.
5358    let mut synthetic_idx = 0usize;
5359    while sample_cardinality > 0 && values.len() < sample_cardinality {
5360        synthetic_idx += 1;
5361        let synthetic = tla_string(format!(
5362            "{}_{synthetic_idx}",
5363            tla_ident(type_name).to_lowercase()
5364        ));
5365        if !values.contains(&synthetic) {
5366            values.push(synthetic);
5367        }
5368    }
5369    let mut samples = vec!["{}".to_owned()];
5370    if let Some(first) = values.first() {
5371        samples.push(format!("{{{first}}}"));
5372    }
5373    if values.len() >= 2 {
5374        samples.push(format!("{{{}, {}}}", values[0], values[1]));
5375    }
5376    samples
5377}
5378
5379fn string_set_payload_samples(sample_cardinality: usize) -> Vec<String> {
5380    let values = if sample_cardinality == 0 {
5381        Vec::new()
5382    } else {
5383        generic_string_samples(sample_cardinality)
5384            .into_iter()
5385            .map(tla_string)
5386            .collect::<Vec<_>>()
5387    };
5388    let mut samples = vec!["{}".to_owned()];
5389    if let Some(first) = values.first() {
5390        samples.push(format!("{{{first}}}"));
5391    }
5392    if values.len() >= 2 {
5393        samples.push(format!("{{{}, {}}}", values[0], values[1]));
5394    }
5395    samples
5396}
5397
5398fn string_enum_wire_label(name: &str, variant: &str) -> String {
5399    if name == meerkat_core::turn_execution_authority::ContentShape::SCHEMA_TYPE_NAME
5400        && let Some(shape) =
5401            meerkat_core::turn_execution_authority::ContentShape::from_schema_variant(variant)
5402    {
5403        return shape.as_str().to_owned();
5404    }
5405
5406    variant.to_owned()
5407}
5408
5409/// Consult the schema's named-type binding table to decide whether a
5410/// named type's TLA domain is `Nat` (numeric) rather than string-like.
5411///
5412/// A named type resolves to a `Nat` TLA domain when its Rust atom lowers
5413/// to an unsigned integer width — the TLA projection mirrors the Rust
5414/// atom. Schemas reach codegen only after validation, so every
5415/// referenced named type has a binding; an unbound name here is a
5416/// codegen invariant violation.
5417fn named_type_uses_nat_domain(
5418    bindings: &BTreeMap<String, meerkat_machine_schema::RustTypeAtom>,
5419    name: &str,
5420) -> bool {
5421    use meerkat_machine_schema::RustTypeAtom;
5422    matches!(
5423        bindings.get(name),
5424        Some(RustTypeAtom::U64 | RustTypeAtom::U32 | RustTypeAtom::U16 | RustTypeAtom::U8)
5425    )
5426}
5427
5428/// Collect the `NamedTypeId → RustTypeAtom` map for a single machine.
5429fn collect_machine_named_bindings(
5430    schema: &MachineSchema,
5431) -> BTreeMap<String, meerkat_machine_schema::RustTypeAtom> {
5432    assert_machine_named_bindings_match_canonical(schema);
5433    schema
5434        .named_types
5435        .iter()
5436        .map(|binding| (binding.name.as_str().to_owned(), binding.rust.clone()))
5437        .collect()
5438}
5439
5440/// A machine that shares a canonical machine's id must bind every canonical
5441/// struct named type, and bind each shared named type with the canonical
5442/// generated domain shape.
5443fn check_canonical_named_bindings(schema: &MachineSchema) -> Result<(), CompositionTlaError> {
5444    let Some(canonical) = canonical_machine_schemas()
5445        .into_iter()
5446        .find(|canonical| canonical.machine == schema.machine)
5447    else {
5448        return Ok(());
5449    };
5450    let mismatch = |named_type: &str, reason| CompositionTlaError::CanonicalNamedTypeMismatch {
5451        machine: schema.machine.as_str().to_owned(),
5452        named_type: named_type.to_owned(),
5453        reason,
5454    };
5455    for canonical_binding in canonical.named_types.iter().filter(|binding| {
5456        matches!(
5457            binding.rust,
5458            meerkat_machine_schema::RustTypeAtom::TypePathStruct { .. }
5459        )
5460    }) {
5461        if !schema
5462            .named_types
5463            .iter()
5464            .any(|binding| binding.name == canonical_binding.name)
5465        {
5466            return Err(mismatch(
5467                canonical_binding.name.as_str(),
5468                CanonicalNamedTypeMismatchKind::MissingStructBinding,
5469            ));
5470        }
5471    }
5472    for binding in &schema.named_types {
5473        let Some(canonical_binding) = canonical
5474            .named_types
5475            .iter()
5476            .find(|candidate| candidate.name == binding.name)
5477        else {
5478            continue;
5479        };
5480        if !canonical_binding
5481            .rust
5482            .has_same_composition_domain_shape(&binding.rust)
5483        {
5484            return Err(mismatch(
5485                binding.name.as_str(),
5486                CanonicalNamedTypeMismatchKind::DomainShape,
5487            ));
5488        }
5489    }
5490    Ok(())
5491}
5492
5493/// Internal invariant for the infallible renderers, whose callers pass
5494/// canonical machines; the public fallible entry points check first.
5495fn assert_machine_named_bindings_match_canonical(schema: &MachineSchema) {
5496    if let Err(CompositionTlaError::CanonicalNamedTypeMismatch {
5497        machine,
5498        named_type,
5499        reason,
5500    }) = check_canonical_named_bindings(schema)
5501    {
5502        assert!(
5503            reason != CanonicalNamedTypeMismatchKind::MissingStructBinding,
5504            "generated machine `{machine}` missing canonical named-type `{named_type}` binding"
5505        );
5506        assert!(
5507            reason != CanonicalNamedTypeMismatchKind::DomainShape,
5508            "generated machine `{machine}` named-type `{named_type}` binding must match canonical domain shape"
5509        );
5510    }
5511}
5512
5513/// Validate a caller-supplied machine catalog before rendering a composition
5514/// against it: every machine validates, ids are unique, no machine shadows a
5515/// canonical Meerkat machine with a different schema, the composition's
5516/// machines agree on shared named types, and the composition validates
5517/// against the catalog. The render paths behind this never panic on a
5518/// supplied catalog.
5519fn validate_supplied_catalog(
5520    schema: &CompositionSchema,
5521    machine_catalog: &[MachineSchema],
5522) -> Result<(), CompositionTlaError> {
5523    let canonical = canonical_machine_schemas();
5524    let mut seen = BTreeSet::new();
5525    for machine in machine_catalog {
5526        machine
5527            .validate()
5528            .map_err(|error| CompositionTlaError::InvalidSuppliedMachine {
5529                machine: machine.machine.as_str().to_owned(),
5530                error: error.to_string(),
5531            })?;
5532        if !seen.insert(machine.machine.as_str()) {
5533            return Err(CompositionTlaError::DuplicateSuppliedMachine {
5534                machine: machine.machine.as_str().to_owned(),
5535            });
5536        }
5537        if canonical
5538            .iter()
5539            .any(|candidate| candidate.machine == machine.machine && candidate != machine)
5540        {
5541            return Err(CompositionTlaError::ShadowsCanonicalMachine {
5542                machine: machine.machine.as_str().to_owned(),
5543            });
5544        }
5545    }
5546    let mut merged: BTreeMap<&str, &meerkat_machine_schema::RustTypeAtom> = BTreeMap::new();
5547    for instance in &schema.machines {
5548        let Some(machine) = machine_catalog
5549            .iter()
5550            .find(|machine| machine.machine.as_str() == instance.machine_name.as_str())
5551        else {
5552            continue;
5553        };
5554        for binding in &machine.named_types {
5555            match merged.get(binding.name.as_str()) {
5556                Some(existing) if !existing.has_same_composition_domain_shape(&binding.rust) => {
5557                    return Err(CompositionTlaError::DivergentNamedTypeBinding {
5558                        composition: schema.name.as_str().to_owned(),
5559                        named_type: binding.name.as_str().to_owned(),
5560                    });
5561                }
5562                Some(_) => {}
5563                None => {
5564                    merged.insert(binding.name.as_str(), &binding.rust);
5565                }
5566            }
5567        }
5568    }
5569    let machines = machine_catalog.iter().collect::<Vec<_>>();
5570    schema.validate_against(&machines).map_err(|error| {
5571        CompositionTlaError::InvalidCompositionForCatalog {
5572            composition: schema.name.as_str().to_owned(),
5573            error: error.to_string(),
5574        }
5575    })
5576}
5577
5578/// Merge every machine's named-type bindings into one map for
5579/// composition-level TLA rendering. Duplicate names must agree on generated
5580/// domain shape across machines (validation enforces this by construction).
5581fn collect_composition_named_bindings<'a>(
5582    machines_by_instance: impl IntoIterator<Item = &'a MachineSchema>,
5583) -> BTreeMap<String, meerkat_machine_schema::RustTypeAtom> {
5584    let mut merged: BTreeMap<String, meerkat_machine_schema::RustTypeAtom> = BTreeMap::new();
5585    for machine in machines_by_instance {
5586        assert_machine_named_bindings_match_canonical(machine);
5587        for binding in &machine.named_types {
5588            let slug = binding.name.as_str().to_owned();
5589            if let Some(existing) = merged.get(&slug) {
5590                assert!(
5591                    existing.has_same_composition_domain_shape(&binding.rust),
5592                    "composition named-type `{slug}` binding must agree across machine schemas"
5593                );
5594            } else {
5595                merged.insert(slug, binding.rust.clone());
5596            }
5597        }
5598    }
5599    merged
5600}
5601
5602#[cfg(test)]
5603mod tests {
5604    use super::*;
5605
5606    /// A populated witness map literal renders as a TLC function in both the
5607    /// witness-literal path and the expression path, never as the `None`
5608    /// fallback (#1811).
5609    #[test]
5610    fn a_witness_map_literal_renders_as_a_tlc_function() {
5611        let machines = meerkat_machine_schema::canonical_machine_schemas();
5612        let compositions = meerkat_machine_schema::canonical_composition_schemas();
5613        let composition = compositions
5614            .iter()
5615            .find(|candidate| candidate.name.as_str() == "job_runtime_delivery")
5616            .expect("job_runtime_delivery composition");
5617        let compiler =
5618            CompositionTlaCompiler::new(composition, &machines).expect("composition compiler");
5619        let literal = Expr::MapLiteral(vec![
5620            (
5621                Expr::String("alpha".into()),
5622                Expr::String("member-a".into()),
5623            ),
5624            (Expr::String("beta".into()), Expr::U64(2)),
5625        ]);
5626        assert_eq!(
5627            compiler.render_literal_expr(&literal),
5628            "(\"alpha\" :> \"member-a\" @@ \"beta\" :> 2)"
5629        );
5630        assert_eq!(
5631            crate::render::render_expr_for_tests(&literal),
5632            "(\"alpha\" :> \"member-a\" @@ \"beta\" :> 2)"
5633        );
5634    }
5635
5636    /// Every quantified Next disjunct leads with its transition's source-phase
5637    /// guard, so TLC rejects the whole disjunct in other phases instead of
5638    /// enumerating each parameter tuple per state (#1499 measured 464 s
5639    /// unhoisted against 158 s hoisted on work_graph_lifecycle ci, identical
5640    /// state counts).
5641    #[test]
5642    fn quantified_next_disjuncts_lead_with_the_source_phase_guard() {
5643        let model =
5644            render_machine_semantic_model(&meerkat_machine()).expect("render MeerkatMachine model");
5645        let next = model
5646            .split_once("\nNext ==\n")
5647            .map(|(_, rest)| rest.split("\n\n").next().unwrap_or(""))
5648            .expect("Next block");
5649        let quantified = next
5650            .lines()
5651            .filter(|line| line.contains("\\E "))
5652            .collect::<Vec<_>>();
5653        assert!(
5654            !quantified.is_empty(),
5655            "MeerkatMachine has quantified transitions"
5656        );
5657        for line in &quantified {
5658            assert!(
5659                line.starts_with("    \\/ (phase = "),
5660                "quantified Next disjunct without a leading phase guard: {line}"
5661            );
5662        }
5663        assert!(
5664            next.contains("    \\/ (phase = \"Running\") /\\ \\E run_id \\in RunIdValues : RequestCancelAfterBoundary(run_id)"),
5665            "the guard is the transition's own source phase"
5666        );
5667    }
5668
5669    fn next_disjunct_for<'a>(model: &'a str, action: &str) -> &'a str {
5670        let next = model
5671            .split_once("\nNext ==\n")
5672            .map(|(_, rest)| rest.split("\n\n").next().unwrap_or(""))
5673            .expect("Next block");
5674        next.lines()
5675            .find(|line| line.contains(&format!(" {action}(")))
5676            .expect("Next disjunct for the action")
5677    }
5678
5679    /// A declared domain, not a binding name, decides an input field's TLC
5680    /// domain: additional values extend the default unsigned range, a state
5681    /// binding explores exactly the state field, and an undeclared
5682    /// `expected_revision` gets the plain default (the old name match is gone).
5683    #[test]
5684    fn declared_input_field_domains_decide_the_rendered_domain() {
5685        use meerkat_machine_schema::catalog::dsl::dsl_workgraph_lifecycle_machine;
5686        use meerkat_machine_schema::identity::{FieldId, InputVariantId};
5687        use meerkat_machine_schema::{InputFieldDomain, InputFieldDomainKind};
5688
5689        let shipped = dsl_workgraph_lifecycle_machine();
5690        let model = render_machine_semantic_model(&shipped).expect("render workgraph model");
5691        assert!(
5692            next_disjunct_for(&model, "UpdateOpen")
5693                .contains("\\E expected_revision \\in {revision} : "),
5694            "a state-bound declaration explores exactly the state field"
5695        );
5696
5697        let mut sampled = shipped.clone();
5698        sampled.input_field_domains.push(InputFieldDomain {
5699            input: InputVariantId::parse("CreateOpen").expect("input slug"),
5700            field: FieldId::parse("unresolved_blocker_count").expect("field slug"),
5701            domain: InputFieldDomainKind::AdditionalValues([3, 8].into_iter().collect()),
5702        });
5703        let model = render_machine_semantic_model(&sampled).expect("render sampled model");
5704        assert!(
5705            next_disjunct_for(&model, "CreateOpen")
5706                .contains("\\E arg_unresolved_blocker_count \\in (0..2 \\cup {3, 8}) : "),
5707            "additional values extend the default unsigned domain"
5708        );
5709
5710        let mut undeclared = shipped;
5711        undeclared.input_field_domains.clear();
5712        let model = render_machine_semantic_model(&undeclared).expect("render undeclared model");
5713        assert!(
5714            next_disjunct_for(&model, "UpdateOpen").contains("\\E expected_revision \\in 0..2 : "),
5715            "without a declaration the binding name no longer selects a domain"
5716        );
5717    }
5718
5719    /// A `CiValues` declaration ranges the field over a model constant: the
5720    /// CI config assigns it exactly the declared values, the Deep config those
5721    /// and the default unsigned domain.
5722    #[test]
5723    fn ci_values_narrow_the_ci_profile_alone() {
5724        use meerkat_machine_schema::catalog::dsl::dsl_workgraph_lifecycle_machine;
5725        use meerkat_machine_schema::identity::{FieldId, InputVariantId};
5726        use meerkat_machine_schema::{InputFieldDomain, InputFieldDomainKind};
5727
5728        let mut sampled = dsl_workgraph_lifecycle_machine();
5729        sampled.input_field_domains.push(InputFieldDomain {
5730            input: InputVariantId::parse("CreateOpen").expect("input slug"),
5731            field: FieldId::parse("unresolved_blocker_count").expect("field slug"),
5732            domain: InputFieldDomainKind::CiValues([0, 5].into_iter().collect()),
5733        });
5734        let constant = "InputSamples_CreateOpen_unresolved_blocker_count";
5735        let model = render_machine_semantic_model(&sampled).expect("render sampled model");
5736        assert!(
5737            next_disjunct_for(&model, "CreateOpen").contains(&format!(
5738                "\\E arg_unresolved_blocker_count \\in {constant} : "
5739            )),
5740            "the field ranges over its samples constant"
5741        );
5742        let constants_line = model
5743            .lines()
5744            .find(|line| line.starts_with("CONSTANTS "))
5745            .expect("model constants");
5746        assert!(
5747            constants_line.contains(constant),
5748            "the model declares the samples constant: {constants_line}"
5749        );
5750        assert!(
5751            next_disjunct_for(&model, "UpdateOpen")
5752                .contains("\\E expected_revision \\in {revision} : "),
5753            "the machine's other declarations are unchanged"
5754        );
5755
5756        let ci = render_machine_ci_cfg(&sampled, false).expect("valid CI CFG");
5757        assert!(
5758            ci.contains(&format!("\n  {constant} = {{0, 5}}\n")),
5759            "the CI config assigns exactly the declared values:\n{ci}"
5760        );
5761        let deep = render_machine_ci_cfg(&sampled, true).expect("valid Deep CFG");
5762        assert!(
5763            deep.contains(&format!("\n  {constant} = {{0, 1, 2, 5}}\n")),
5764            "the Deep config keeps the default domain beside the declared values:\n{deep}"
5765        );
5766        assert_eq!(
5767            broad_input_samples(&[0, 5].into_iter().collect::<BTreeSet<u64>>()),
5768            [0, 1, 2, 5].into_iter().collect::<BTreeSet<u64>>(),
5769            "outside the CI profile the field keeps the default domain beside its values"
5770        );
5771    }
5772
5773    /// A `CiSamples` declaration ranges a field of any type over a model
5774    /// constant that each profile's config assigns through an operator of
5775    /// the model: the CI profile the declared values, the Deep profile the
5776    /// field type's whole domain. DurableDecisionMachine's carried
5777    /// presentation is the shipped case; Present declares nothing, so it
5778    /// keeps every link a presentation's link can serve.
5779    #[test]
5780    fn ci_samples_narrow_the_ci_profile_alone_for_a_field_of_any_type() {
5781        let schema = meerkat_machine_schema::catalog::dsl::dsl_durable_decision_machine();
5782        let model = render_machine_semantic_model(&schema).expect("render DurableDecisionMachine");
5783        let ci = render_machine_ci_cfg(&schema, false).expect("valid CI CFG");
5784        let deep = render_machine_ci_cfg(&schema, true).expect("valid Deep CFG");
5785        let next = model
5786            .split_once("\nNext ==\n")
5787            .map(|(_, rest)| rest.split("\n\n").next().unwrap_or(""))
5788            .expect("Next block");
5789        let constants_line = model
5790            .lines()
5791            .find(|line| line.starts_with("CONSTANTS "))
5792            .expect("model constants");
5793        let decide = next
5794            .lines()
5795            .filter(|line| line.contains(": Decide"))
5796            .collect::<Vec<_>>();
5797        assert!(!decide.is_empty(), "Decide has Next disjuncts");
5798        for (field, ci_values, deep_domain) in [
5799            (
5800                "carried_audience",
5801                "{Some(\"alpha\")}",
5802                "OptionDecisionPartyValues",
5803            ),
5804            (
5805                "carried_digest",
5806                "{Some(\"alpha\")}",
5807                "OptionDecisionDigestValues",
5808            ),
5809            ("carried_complete", "{FALSE}", "BOOLEAN"),
5810            (
5811                "carried_link_served_digest",
5812                "{Some(\"alpha\")}",
5813                "OptionDecisionDigestValues",
5814            ),
5815        ] {
5816            let constant = format!("InputSamples_Decide_{field}");
5817            for line in &decide {
5818                assert!(
5819                    line.contains(&format!("\\E {field} \\in {constant} : ")),
5820                    "Decide.{field} ranges over {constant}: {line}"
5821                );
5822            }
5823            assert!(
5824                constants_line.contains(&constant),
5825                "the model declares {constant}: {constants_line}"
5826            );
5827            assert!(
5828                model.contains(&format!("\n{constant}Ci == {ci_values}\n")),
5829                "the model defines the CI samples of Decide.{field}"
5830            );
5831            assert!(
5832                model.contains(&format!("\n{constant}Deep == {deep_domain}\n")),
5833                "the model defines the Deep domain of Decide.{field}"
5834            );
5835            assert!(
5836                ci.contains(&format!("\n  {constant} <- {constant}Ci\n")),
5837                "the CI config samples Decide.{field}:\n{ci}"
5838            );
5839            assert!(
5840                deep.contains(&format!("\n  {constant} <- {constant}Deep\n")),
5841                "the Deep config keeps the whole domain of Decide.{field}:\n{deep}"
5842            );
5843        }
5844        let present = next
5845            .lines()
5846            .filter(|line| line.contains(": Present"))
5847            .collect::<Vec<_>>();
5848        assert!(!present.is_empty(), "Present has Next disjuncts");
5849        for line in present {
5850            assert!(
5851                line.contains("\\E link_served_digest \\in OptionDecisionDigestValues : "),
5852                "Present keeps every served link: {line}"
5853            );
5854        }
5855    }
5856
5857    /// SessionDocumentMachine's CI bound: under a step bound of 5 the CI
5858    /// profile explores the samples it declares, in every Next disjunct of
5859    /// the input's transitions; the Deep profile keeps `0..2` for each of
5860    /// them and its step bound of 8.
5861    #[test]
5862    fn session_document_narrows_its_ci_samples_only() {
5863        let schema = meerkat_machine_schema::catalog::dsl::dsl_session_document_machine();
5864        let model = render_machine_semantic_model(&schema).expect("render SessionDocumentMachine");
5865        let ci = render_machine_ci_cfg(&schema, false).expect("valid CI CFG");
5866        let deep = render_machine_ci_cfg(&schema, true).expect("valid Deep CFG");
5867        let next = model
5868            .split_once("\nNext ==\n")
5869            .map(|(_, rest)| rest.split("\n\n").next().unwrap_or(""))
5870            .expect("Next block");
5871        for (input, field, ci_values) in [
5872            ("ClassifyDurableTail", "dangling_tool_use_count", "{0}"),
5873            ("ClassifyDurableTail", "orphan_tool_result_count", "{0}"),
5874            ("RecoverSessionInstructionState", "target_generation", "{2}"),
5875            ("RecoverSessionInstructionState", "entry_sequence", "{0}"),
5876            ("RecoverSessionInstructionEffective", "generation", "{0}"),
5877            (
5878                "RecoverSessionInstructionEffective",
5879                "last_entry_sequence",
5880                "{0, 1}",
5881            ),
5882            ("SetSessionInstruction", "body_bytes", "{1}"),
5883        ] {
5884            let constant = format!("InputSamples_{input}_{field}");
5885            let disjuncts = next
5886                .lines()
5887                .filter(|line| line.contains(&format!(": {input}")))
5888                .collect::<Vec<_>>();
5889            assert!(!disjuncts.is_empty(), "{input} has Next disjuncts");
5890            for line in disjuncts {
5891                assert!(
5892                    line.contains(&format!("\\E {field} \\in {constant} : ")),
5893                    "{input}.{field} ranges over {constant}: {line}"
5894                );
5895            }
5896            assert!(
5897                ci.contains(&format!("\n  {constant} = {ci_values}\n")),
5898                "the CI config samples {input}.{field} as {ci_values}:\n{ci}"
5899            );
5900            assert!(
5901                deep.contains(&format!("\n  {constant} = {{0, 1, 2}}\n")),
5902                "the Deep config keeps 0..2 for {input}.{field}:\n{deep}"
5903            );
5904        }
5905        assert!(
5906            model.contains("\nCiStateConstraint == /\\ model_step_count <= 5 "),
5907            "the CI step bound is 5"
5908        );
5909        assert!(
5910            model.contains("\nDeepStateConstraint == /\\ model_step_count <= 8 "),
5911            "the Deep step bound stays 8"
5912        );
5913    }
5914
5915    #[test]
5916    fn substituted_compound_values_are_delimited_and_atoms_are_not() {
5917        for atom in [
5918            "x",
5919            "packet.payload.run_id",
5920            "Some(run_id)",
5921            "MapSet(m, k, v)",
5922            "m[k]",
5923            "f(a)[b](c)",
5924            "(a + 1)",
5925            "\"a(b\"",
5926            "42",
5927        ] {
5928            assert_eq!(tla_delimited(atom), atom, "{atom} is already an operand");
5929        }
5930        for compound in [
5931            "IF c THEN a ELSE b",
5932            "x + 1",
5933            "s \\cup {x}",
5934            "(a) + (b)",
5935            "f(a) = b",
5936            "~x",
5937        ] {
5938            assert_eq!(
5939                tla_delimited(compound),
5940                format!("({compound})"),
5941                "{compound} must be delimited before splicing"
5942            );
5943        }
5944    }
5945
5946    /// A field assigned by a conditional update earlier in the same block is
5947    /// read through its pending value, a bare `IF c THEN a ELSE b`. Spliced
5948    /// unparenthesized into a later expression, TLA+ precedence captured the
5949    /// surrounding operator. Shipped instance: the meerkat_mob_seam
5950    /// `TurnRunFailed` payload unwraps the conditionally updated
5951    /// `terminal_cause_kind` as `IF "value" \in DOMAIN v THEN v["value"] ELSE
5952    /// None`; with `v` bare, `["value"]` applied to v's ELSE branch only, so
5953    /// the THEN branch emitted the Option record instead of its value.
5954    #[test]
5955    fn a_conditionally_updated_field_read_later_in_the_block_splices_as_one_operand() {
5956        let model = render_composition_semantic_model(&meerkat_mob_seam_composition())
5957            .expect("render meerkat_mob_seam model");
5958        assert!(
5959            model.contains(
5960                "terminal_cause_kind |-> (IF \"value\" \\in DOMAIN (IF (IF (meerkat_terminal_cause_kind = None)"
5961            ),
5962            "the TurnRunFailed unwrap must test the whole conditional value"
5963        );
5964        assert!(
5965            !model.contains("ELSE meerkat_terminal_cause_kind[\"value\"]"),
5966            "no index may bind to one branch of a spliced conditional"
5967        );
5968    }
5969
5970    /// A set insert or remove of a field that a conditional update already
5971    /// changed earlier in the same block takes the field's pending value, a
5972    /// bare `IF c THEN a ELSE b`, as its left operand. Spliced unparenthesized,
5973    /// the ELSE branch captured the set operator, so the THEN branch lost the
5974    /// second update. Shipped instance: MobMachine's topology convergence
5975    /// removes both absent identities from `pending_respawn_topology`; the
5976    /// model removed only `a_identity` when both were absent.
5977    #[test]
5978    fn a_set_update_after_a_conditional_update_takes_the_whole_conditional() {
5979        let model = render_machine_semantic_model(&mob_machine()).expect("render MobMachine model");
5980        assert!(
5981            model.contains(
5982                "((IF ((a_identity \\in DOMAIN identity_to_runtime) = FALSE) THEN (pending_respawn_topology \\ {a_identity}) ELSE pending_respawn_topology) \\ {b_identity})"
5983            ),
5984            "the second removal must apply to the whole conditional value"
5985        );
5986        assert!(
5987            !model.contains("ELSE pending_respawn_topology \\ {b_identity}"),
5988            "no set operator may bind to one branch of a spliced conditional"
5989        );
5990    }
5991
5992    /// Every update kind that reads a field's pending value must splice it so
5993    /// no operator after it can bind into one branch of a pending conditional
5994    /// (`IF c THEN a ELSE b`, left by an earlier conditional update in the
5995    /// same block): each occurrence must close an operand, followed only by
5996    /// `)`, `,` or the end of the value. The match is exhaustive, so a new
5997    /// `Update` kind must be classified here.
5998    #[test]
5999    fn every_update_kind_splices_a_pending_conditional_as_one_operand() {
6000        use meerkat_machine_schema::identity::FieldId;
6001        const PENDING: &str = "IF c THEN a ELSE b";
6002        let field = || FieldId::parse("f").expect("field slug");
6003        let x = || Expr::Binding("x".to_owned());
6004        let samples = vec![
6005            Update::Increment {
6006                field: field(),
6007                amount: 1,
6008            },
6009            Update::Decrement {
6010                field: field(),
6011                amount: 1,
6012            },
6013            Update::MapInsert {
6014                field: field(),
6015                key: x(),
6016                value: x(),
6017            },
6018            Update::MapIncrement {
6019                field: field(),
6020                key: x(),
6021                amount: 1,
6022            },
6023            Update::MapDecrement {
6024                field: field(),
6025                key: x(),
6026                amount: 1,
6027            },
6028            Update::MapRemove {
6029                field: field(),
6030                key: x(),
6031            },
6032            Update::SetInsert {
6033                field: field(),
6034                value: x(),
6035            },
6036            Update::SetRemove {
6037                field: field(),
6038                value: x(),
6039            },
6040            Update::SeqAppend {
6041                field: field(),
6042                value: x(),
6043            },
6044            Update::SeqPrepend {
6045                field: field(),
6046                values: x(),
6047            },
6048            Update::SeqPopFront { field: field() },
6049            Update::SeqRemoveValue {
6050                field: field(),
6051                value: x(),
6052            },
6053            Update::SeqRemoveAll {
6054                field: field(),
6055                values: x(),
6056            },
6057            Update::Conditional {
6058                condition: Expr::Binding("d".to_owned()),
6059                then_updates: vec![Update::SetInsert {
6060                    field: field(),
6061                    value: x(),
6062                }],
6063                else_updates: vec![Update::SetRemove {
6064                    field: field(),
6065                    value: x(),
6066                }],
6067            },
6068            Update::ForEach {
6069                binding: "y".to_owned(),
6070                over: x(),
6071                updates: vec![Update::SetInsert {
6072                    field: field(),
6073                    value: Expr::Binding("y".to_owned()),
6074                }],
6075            },
6076        ];
6077        let schema = mob_machine();
6078        for update in &samples {
6079            // Exhaustive: classify every kind. `Assign` does not read the
6080            // field's pending value, so it cannot splice it.
6081            match update {
6082                Update::Assign { .. } => continue,
6083                Update::Increment { .. }
6084                | Update::Decrement { .. }
6085                | Update::MapInsert { .. }
6086                | Update::MapIncrement { .. }
6087                | Update::MapDecrement { .. }
6088                | Update::MapRemove { .. }
6089                | Update::SetInsert { .. }
6090                | Update::SetRemove { .. }
6091                | Update::SeqAppend { .. }
6092                | Update::SeqPrepend { .. }
6093                | Update::SeqPopFront { .. }
6094                | Update::SeqRemoveValue { .. }
6095                | Update::SeqRemoveAll { .. }
6096                | Update::Conditional { .. }
6097                | Update::ForEach { .. } => {}
6098            }
6099            let mut compiler = MachineTlaCompiler::new(&schema);
6100            let mut env = BTreeMap::from([("f".to_owned(), PENDING.to_owned())]);
6101            let binding_types =
6102                BTreeMap::from([("x".to_owned(), TypeRef::Set(Box::new(TypeRef::U64)))]);
6103            compiler.apply_update("Probe", &mut env, &BTreeMap::new(), &binding_types, update);
6104            let rendered = env.get("f").expect("the update writes f");
6105            assert!(
6106                rendered.contains(PENDING),
6107                "{update:?} must read the pending value: {rendered}"
6108            );
6109            for (at, _) in rendered.match_indices(PENDING) {
6110                let after = rendered[at + PENDING.len()..].chars().next();
6111                assert!(
6112                    matches!(after, None | Some(')' | ',')),
6113                    "{update:?} lets {after:?} bind into the pending conditional: {rendered}"
6114                );
6115            }
6116        }
6117    }
6118
6119    /// A `for` loop lowers to one fold per touched field, and each fold must
6120    /// read the other fields as they were BEFORE the loop, as the sequential
6121    /// kernel does within an iteration. Writing each fold back into the env
6122    /// while lowering handed later folds an earlier field's post-loop value:
6123    /// the causal-tail batch then looked up already-removed cursors and left
6124    /// orphaned queued rows, which the generated outbox invariant caught. So
6125    /// no fold of a loop may take another fold of the same loop as an
6126    /// argument.
6127    #[test]
6128    fn a_for_each_fold_reads_the_other_fields_before_the_loop() {
6129        let model =
6130            render_machine_semantic_model(&meerkat_machine()).expect("render MeerkatMachine model");
6131        let mut checked = 0;
6132        for line in model.lines() {
6133            let Some(eq) = line.find("' = ") else {
6134                continue;
6135            };
6136            let rhs = &line[eq + 4..];
6137            let Some(open) = rhs.find('(') else {
6138                continue;
6139            };
6140            let head = &rhs[..open];
6141            let Some(pos) = head.find("_ForEach") else {
6142                continue;
6143            };
6144            let digits: String = head[pos + "_ForEach".len()..]
6145                .chars()
6146                .take_while(char::is_ascii_digit)
6147                .collect();
6148            let same_loop = format!("{}_ForEach{digits}_", &head[..pos]);
6149            assert!(
6150                !rhs[open..].contains(&same_loop),
6151                "a for-loop fold takes another fold of the same loop as an argument: {line}"
6152            );
6153            checked += 1;
6154        }
6155        assert!(
6156            checked > 0,
6157            "the MeerkatMachine model has for-loop folds to check"
6158        );
6159    }
6160    use meerkat_machine_schema::RustTypeAtom;
6161    use meerkat_machine_schema::catalog::dsl::{
6162        dsl_meerkat_machine as meerkat_machine, dsl_mob_machine as mob_machine,
6163    };
6164    use meerkat_machine_schema::catalog::meerkat_mob_seam_composition;
6165    use meerkat_machine_schema::identity::{
6166        EffectVariantId, MachineId, MachineInstanceId, TransitionId,
6167    };
6168
6169    fn string_domain_values(assignment: &str) -> BTreeSet<String> {
6170        assignment
6171            .trim_start_matches('{')
6172            .trim_end_matches('}')
6173            .split(", ")
6174            .filter(|value| !value.is_empty())
6175            .map(|value| value.trim_matches('"').to_owned())
6176            .collect()
6177    }
6178
6179    fn cfg_string_domain_values(cfg: &str, domain: &str) -> BTreeSet<String> {
6180        let prefix = format!("  {domain} = ");
6181        cfg.lines()
6182            .find_map(|line| line.strip_prefix(&prefix))
6183            .map(string_domain_values)
6184            .unwrap_or_default()
6185    }
6186
6187    fn default_string_domain_values(sample_cardinality: usize) -> BTreeSet<String> {
6188        string_domain_values(&render_default_domain_assignment(
6189            &TypeRef::String,
6190            sample_cardinality,
6191            &BTreeMap::new(),
6192            &BTreeMap::new(),
6193            false,
6194        ))
6195    }
6196
6197    fn assert_session_id_string_overlap(cfg: &str, profile: &str) {
6198        let session_ids = cfg_string_domain_values(cfg, "SessionIdValues");
6199        let strings = cfg_string_domain_values(cfg, "StringValues");
6200        assert!(
6201            !session_ids.is_empty() && !strings.is_empty(),
6202            "{profile} must sample both bridged domains"
6203        );
6204        assert!(
6205            !session_ids.is_disjoint(&strings),
6206            "{profile} must make the SessionId/string equality branch satisfiable"
6207        );
6208        assert!(
6209            strings
6210                .iter()
6211                .any(|candidate| !session_ids.contains(candidate)),
6212            "{profile} must retain a non-matching string candidate for the rejection branch"
6213        );
6214    }
6215
6216    #[test]
6217    fn conjunctive_bool_specialization_is_literal_only_and_conservative() {
6218        let expr = Expr::And(vec![
6219            Expr::Binding("required_true".to_owned()),
6220            Expr::Not(Box::new(Expr::Binding("required_false".to_owned()))),
6221            Expr::Eq(
6222                Box::new(Expr::Binding("equal_true".to_owned())),
6223                Box::new(Expr::Bool(true)),
6224            ),
6225            Expr::Neq(
6226                Box::new(Expr::Bool(true)),
6227                Box::new(Expr::Binding("not_equal_true".to_owned())),
6228            ),
6229            Expr::Or(vec![
6230                Expr::Binding("under_disjunction".to_owned()),
6231                Expr::Binding("alternative".to_owned()),
6232            ]),
6233            Expr::Binding("conflicting".to_owned()),
6234            Expr::Not(Box::new(Expr::Binding("conflicting".to_owned()))),
6235        ]);
6236        let mut requirements = BTreeMap::new();
6237
6238        collect_conjunctive_bool_requirements(&expr, &mut requirements);
6239
6240        assert_eq!(requirements.get("required_true"), Some(&Some(true)));
6241        assert_eq!(requirements.get("required_false"), Some(&Some(false)));
6242        assert_eq!(requirements.get("equal_true"), Some(&Some(true)));
6243        assert_eq!(requirements.get("not_equal_true"), Some(&Some(false)));
6244        assert!(!requirements.contains_key("under_disjunction"));
6245        assert!(!requirements.contains_key("alternative"));
6246        assert_eq!(requirements.get("conflicting"), Some(&None));
6247    }
6248
6249    #[test]
6250    #[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
6251    fn composition_semantic_model_fails_closed_on_undeclared_route_source_machine() {
6252        let mut schema = meerkat_mob_seam_composition();
6253        let route = schema
6254            .routes
6255            .first_mut()
6256            .expect("seam composition has at least one route");
6257        // Repoint the route source at an instance id that is not declared in
6258        // the composition. The CASE builder used to map this to an
6259        // `"unknown_machine"` sentinel; generation must now fail closed.
6260        route.from_machine =
6261            MachineInstanceId::parse("undeclared_source_instance").expect("valid slug");
6262
6263        let result = render_composition_semantic_model(&schema);
6264        assert!(
6265            matches!(
6266                result,
6267                Err(CompositionTlaError::UnknownRouteSourceMachine { .. })
6268            ),
6269            "expected UnknownRouteSourceMachine, got {result:?}"
6270        );
6271    }
6272
6273    #[test]
6274    #[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
6275    fn composition_semantic_model_fails_closed_on_undeclared_route_effect() {
6276        let mut schema = meerkat_mob_seam_composition();
6277        let route = schema
6278            .routes
6279            .first_mut()
6280            .expect("seam composition has at least one route");
6281        // Keep the (declared) source machine but reference an effect variant
6282        // that the source machine does not declare.
6283        route.effect_variant =
6284            EffectVariantId::parse("UndeclaredEffectVariant").expect("valid slug");
6285
6286        let result = render_composition_semantic_model(&schema);
6287        assert!(
6288            matches!(result, Err(CompositionTlaError::UnknownRouteEffect { .. })),
6289            "expected UnknownRouteEffect, got {result:?}"
6290        );
6291    }
6292
6293    #[test]
6294    #[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
6295    fn composition_semantic_model_fails_closed_on_undeclared_witness_transition() {
6296        let mut schema = meerkat_mob_seam_composition();
6297        schema
6298            .witnesses
6299            .first_mut()
6300            .expect("seam composition has at least one witness")
6301            .expected_transitions
6302            .first_mut()
6303            .expect("seam witness has at least one expected transition")
6304            .transition = TransitionId::parse("UndeclaredWitnessTransition").expect("valid slug");
6305
6306        let result = render_composition_semantic_model(&schema);
6307        assert!(
6308            matches!(
6309                result,
6310                Err(CompositionTlaError::UnknownWitnessTransition { .. })
6311            ),
6312            "expected UnknownWitnessTransition, got {result:?}"
6313        );
6314    }
6315
6316    #[test]
6317    #[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
6318    fn composition_semantic_model_renders_for_valid_schema() {
6319        // Sanity: the fail-closed gate does not reject a currently-valid
6320        // composition. (Byte-identity of the output is enforced separately by
6321        // `make machine-check-drift`.)
6322        let schema = meerkat_mob_seam_composition();
6323        let result = render_composition_semantic_model(&schema);
6324        assert!(
6325            result.is_ok(),
6326            "valid composition should render: {result:?}"
6327        );
6328    }
6329
6330    #[test]
6331    #[should_panic(
6332        expected = "composition named-type `AgentRuntimeId` binding must agree across machine schemas"
6333    )]
6334    fn composition_named_binding_merge_rejects_divergent_domain_shapes() {
6335        let mut meerkat = meerkat_machine();
6336        meerkat.machine = MachineId::parse("CompositionMergeLeft").expect("test machine id");
6337        let mut mob = mob_machine();
6338        mob.machine = MachineId::parse("CompositionMergeRight").expect("test machine id");
6339        let binding = mob
6340            .named_types
6341            .iter_mut()
6342            .find(|binding| binding.name.as_str() == "AgentRuntimeId")
6343            .expect("MobMachine AgentRuntimeId binding");
6344        binding.rust = RustTypeAtom::U64;
6345
6346        let _ = collect_composition_named_bindings([&meerkat, &mob]);
6347    }
6348
6349    #[test]
6350    fn composition_named_binding_merge_allows_machine_local_type_path_twins() {
6351        let meerkat = meerkat_machine();
6352        let mob = mob_machine();
6353
6354        let bindings = collect_composition_named_bindings([&meerkat, &mob]);
6355
6356        assert!(
6357            matches!(
6358                bindings.get("PeerAddress"),
6359                Some(RustTypeAtom::TypePath(path))
6360                    if path == "crate::catalog::dsl::meerkat_machine::PeerAddress"
6361            ),
6362            "path-only TypePath twins should not block composition-domain binding merge"
6363        );
6364    }
6365
6366    #[test]
6367    fn mob_generation_native_helper_declares_and_assigns_u64_boundary() {
6368        let schema = mob_machine();
6369        assert!(machine_uses_u64_max(&schema));
6370
6371        let model = render_machine_semantic_model(&schema).expect("render MobMachine model");
6372        let constants_line = model
6373            .lines()
6374            .find(|line| line.starts_with("CONSTANTS "))
6375            .expect("MobMachine model constants");
6376        assert!(constants_line.contains(TLA_RUST_U64_MAX_CONSTANT));
6377
6378        for deep in [false, true] {
6379            let cfg = render_machine_ci_cfg(&schema, deep).expect("valid machine CFG");
6380            assert!(
6381                cfg.contains(&format!(
6382                    "  {TLA_RUST_U64_MAX_CONSTANT} = {TLC_SAFE_RUST_U64_MAX_VALUE}"
6383                )),
6384                "{} config must assign the boundary",
6385                if deep { "deep" } else { "ci" }
6386            );
6387        }
6388    }
6389
6390    #[test]
6391    fn meerkat_deep_cfg_samples_the_native_session_id_string_bridge() {
6392        let schema = meerkat_machine();
6393        assert!(machine_uses_session_id_string_bridge(&schema));
6394
6395        let deep_cfg = render_machine_ci_cfg(&schema, true).expect("valid deep CFG");
6396        assert_session_id_string_overlap(&deep_cfg, "MeerkatMachine Deep config");
6397        assert_eq!(
6398            cfg_string_domain_values(&deep_cfg, "StringValues").len(),
6399            default_string_domain_values(default_sample_cardinality(true)).len(),
6400            "bridge reachability must substitute a Deep string sample, not add one"
6401        );
6402
6403        let ci_cfg = render_machine_ci_cfg(&schema, false).expect("valid CI CFG");
6404        assert!(
6405            cfg_string_domain_values(&ci_cfg, "SessionIdValues").is_empty()
6406                && cfg_string_domain_values(&ci_cfg, "StringValues").is_empty(),
6407            "the step-limit-one CI profile must remain uninflated"
6408        );
6409    }
6410
6411    #[test]
6412    fn mob_deep_cfg_does_not_inflate_unrelated_string_domains() {
6413        let schema = mob_machine();
6414        assert!(!machine_uses_session_id_string_bridge(&schema));
6415
6416        let deep_cfg = render_machine_ci_cfg(&schema, true).expect("valid deep CFG");
6417        let session_ids = cfg_string_domain_values(&deep_cfg, "SessionIdValues");
6418        let strings = cfg_string_domain_values(&deep_cfg, "StringValues");
6419        assert!(
6420            session_ids.is_disjoint(&strings),
6421            "a machine without the native bridge must retain independent domains"
6422        );
6423    }
6424
6425    #[test]
6426    fn mob_identity_classifier_uses_a_typed_tlc_lifecycle_representative() {
6427        let schema = mob_machine();
6428        assert_eq!(
6429            schema
6430                .tlc_representative_inputs
6431                .iter()
6432                .map(|input| input.as_str())
6433                .collect::<Vec<_>>(),
6434            vec!["ClassifyIdentityReconciliation"],
6435            "the schema must explicitly own the TLC-only classifier abstraction"
6436        );
6437
6438        let model = render_machine_semantic_model(&schema).expect("render MobMachine model");
6439        assert!(
6440            model.contains(
6441                "TlcRepresentativeDomain(values) == IF values = {} THEN {} ELSE {CHOOSE value \\in values : TRUE}"
6442            ),
6443            "the representative domain must remain typed and nonempty-aware"
6444        );
6445        assert!(
6446            model.contains(
6447                "\\E intent \\in TlcRepresentativeDomain(IdentityAuthorityConditionValues) : \\E lease \\in TlcRepresentativeDomain(IdentityLeaseConditionValues)"
6448            ),
6449            "MobMachine lifecycle Next must sample one typed identity-classifier tuple"
6450        );
6451        assert!(
6452            !model.contains(
6453                "\\E intent \\in IdentityAuthorityConditionValues : \\E lease \\in IdentityLeaseConditionValues : \\E external_binding_required \\in BOOLEAN"
6454            ),
6455            "MobMachine lifecycle Next must not reintroduce the exhaustive classifier cartesian product"
6456        );
6457
6458        let composition = render_composition_semantic_model(&meerkat_mob_seam_composition())
6459            .expect("render Meerkat/Mob composition");
6460        assert!(
6461            composition.contains(
6462                "\\E arg_intent \\in TlcRepresentativeDomain(IdentityAuthorityConditionValues) : \\E arg_lease \\in TlcRepresentativeDomain(IdentityLeaseConditionValues)"
6463            ),
6464            "composition lifecycle exploration must honor the same schema-owned abstraction"
6465        );
6466    }
6467
6468    #[test]
6469    fn meerkat_mob_composition_deep_cfg_samples_the_included_native_bridge() {
6470        let schema = meerkat_mob_seam_composition();
6471        let deep_cfg = render_composition_ci_cfg(&schema, true);
6472
6473        assert_session_id_string_overlap(&deep_cfg, "Meerkat/Mob composition Deep config");
6474        let string_cardinality = schema
6475            .deep_domain_overrides
6476            .get("StringValues")
6477            .copied()
6478            .unwrap_or(schema.deep_domain_cardinality);
6479        assert_eq!(
6480            cfg_string_domain_values(&deep_cfg, "StringValues").len(),
6481            default_string_domain_values(string_cardinality).len(),
6482            "composition bridge reachability must substitute a string sample, not add one"
6483        );
6484
6485        let ci_cfg = render_composition_ci_cfg(&schema, false);
6486        assert!(
6487            cfg_string_domain_values(&ci_cfg, "SessionIdValues")
6488                .is_disjoint(&cfg_string_domain_values(&ci_cfg, "StringValues")),
6489            "the composition CI profile must remain unchanged"
6490        );
6491    }
6492
6493    #[test]
6494    fn runtime_delivery_recipient_insert_has_identical_local_map_semantics_in_tla() {
6495        let schema = meerkat_machine_schema::catalog::dsl::dsl_runtime_delivery_machine();
6496        let model = render_machine_semantic_model(&schema).expect("render recipient model");
6497        let definition = "runtime_delivery_recipient_outcomes_after_set(current, recipient, outcome) ==\n    MapSet(current, recipient, outcome)\n";
6498        assert!(model.contains(definition));
6499        assert!(
6500            model
6501                .matches("runtime_delivery_recipient_outcomes_after_set(")
6502                .count()
6503                > 1,
6504            "the generated settlement must call the formally defined insert"
6505        );
6506        let composition = render_composition_semantic_model(
6507            &meerkat_machine_schema::catalog::job_runtime_delivery_composition(),
6508        )
6509        .expect("render embedded recipient model");
6510        assert!(
6511            composition.contains(&format!("runtime_delivery__{definition}")),
6512            "embedded delivery machines require their scoped helper definition too"
6513        );
6514    }
6515
6516    #[test]
6517    fn session_document_instruction_natives_have_the_rust_semantics_in_tla() {
6518        // The DSL authority, the kernel oracle and the Core mirror give these
6519        // natives one meaning, pinned here as the generated TLA renders it:
6520        // a slot map with one slot set (insert or replace), the body bytes of
6521        // a slot set's Active slots (a slot the bytes map does not name
6522        // counts nothing), and the entries of a slot map whose slot is
6523        // Active.
6524        let schema = meerkat_machine_schema::catalog::dsl::dsl_session_document_machine();
6525        let model = render_machine_semantic_model(&schema).expect("render model");
6526        let slot_after_set = r"session_document_instruction_slot_after_set(current, slot, value) ==
6527    MapSet(current, slot, value)
6528";
6529        let active_bytes = r#"session_document_instruction_active_bytes(slot_effect, slot_bytes) ==
6530    LET RECURSIVE SessionDocumentInstructionActiveBytesOver(_)
6531        SessionDocumentInstructionActiveBytesOver(instruction_slots) ==
6532            IF instruction_slots = {} THEN 0
6533            ELSE LET instruction_slot == CHOOSE candidate_slot \in instruction_slots : TRUE
6534                 IN (IF slot_effect[instruction_slot] = "Active" /\ instruction_slot \in DOMAIN slot_bytes
6535                     THEN slot_bytes[instruction_slot] ELSE 0)
6536                    + SessionDocumentInstructionActiveBytesOver(instruction_slots \ {instruction_slot})
6537    IN SessionDocumentInstructionActiveBytesOver(DOMAIN slot_effect)
6538"#;
6539        let active_slots = r#"session_document_instruction_active_slots(slot_effect, slot_values) ==
6540    [instruction_slot \in {candidate_slot \in DOMAIN slot_values :
6541            candidate_slot \in DOMAIN slot_effect /\ slot_effect[candidate_slot] = "Active"}
6542        |-> slot_values[instruction_slot]]
6543"#;
6544        let retired_after = r"session_document_activation_retired_after(activation_rows, activation_retired) ==
6545    [activation_key \in DOMAIN activation_rows |->
6546        LET retired_count == IF activation_key \in DOMAIN activation_retired THEN activation_retired[activation_key] ELSE 0
6547            superseded_count == IF activation_rows[activation_key] > 0 THEN activation_rows[activation_key] - 1 ELSE 0
6548        IN IF retired_count >= superseded_count THEN retired_count ELSE superseded_count]
6549";
6550        for (native, definition) in [
6551            (
6552                "session_document_instruction_slot_after_set",
6553                slot_after_set,
6554            ),
6555            ("session_document_instruction_active_bytes", active_bytes),
6556            ("session_document_instruction_active_slots", active_slots),
6557            ("session_document_activation_retired_after", retired_after),
6558        ] {
6559            assert!(
6560                model.contains(definition),
6561                "the generated model must define {native} with its Rust semantics"
6562            );
6563            assert!(
6564                model.matches(&format!("{native}(")).count() > 1,
6565                "the generated arms must call the formally defined {native}"
6566            );
6567        }
6568    }
6569
6570    #[test]
6571    fn meerkat_session_id_native_helper_matches_typed_option_contract() {
6572        let model =
6573            render_machine_semantic_model(&meerkat_machine()).expect("render MeerkatMachine model");
6574        let expected = r"meerkat_machine_session_id_matches_string(current, candidate) ==
6575    current # None /\ current.value = candidate
6576";
6577
6578        assert!(
6579            model.contains(expected),
6580            "MeerkatMachine TLA session identity operator must preserve the Rust typed-option/string comparison contract"
6581        );
6582    }
6583
6584    #[test]
6585    fn mob_placed_native_helpers_are_defined_in_the_tla_model() {
6586        let model = render_machine_semantic_model(&mob_machine()).expect("render MobMachine model");
6587
6588        for operator in [
6589            "mob_machine_finalized_placed_kickoff_recovery_well_formed(",
6590            "mob_machine_placed_completion_obligation_well_formed(",
6591            "mob_machine_placed_completion_custody_admits(",
6592            "mob_machine_adaptive_lifecycle_drained(",
6593            "mob_machine_adaptive_run_custody_drained(",
6594            "mob_machine_placed_kickoff_obligation_well_formed(",
6595            "mob_machine_placed_kickoff_correlation_available(",
6596            "mob_machine_placed_kickoff_custody_absent_for_identity(",
6597            "mob_machine_placed_kickoff_custody_absent_for_host(",
6598            "mob_machine_remote_turn_input_id_available_to_kickoff(",
6599            "mob_machine_placed_carrier_binding_active(",
6600            "mob_machine_placed_carrier_binding_confirmed_revoked(",
6601            "mob_machine_host_binding_generation_tombstone(",
6602        ] {
6603            assert!(
6604                model
6605                    .lines()
6606                    .any(|line| line.starts_with(operator) && line.ends_with(" ==")),
6607                "MobMachine TLA model must define native operator {operator}"
6608            );
6609        }
6610    }
6611
6612    #[test]
6613    fn mob_placed_kickoff_correlation_tla_helper_covers_every_shared_input_namespace() {
6614        let model = render_machine_semantic_model(&mob_machine()).expect("render MobMachine model");
6615        let expected = r"mob_machine_placed_kickoff_correlation_available(pending_kickoffs, resolved_kickoffs, retained_kickoffs, pending_turns, committed_turns, resolved_turns, pending_completions, resolved_completions, candidate) ==
6616    /\ \A row \in pending_kickoffs \cup resolved_kickoffs : /\ row.agent_identity # candidate.agent_identity /\ \lnot (/\ row.host_id = candidate.host_id /\ row.generation = candidate.generation /\ row.fence_token = candidate.fence_token /\ row.input_id = candidate.input_id)
6617    /\ \A identity \in DOMAIN retained_kickoffs : retained_kickoffs[identity].agent_identity # candidate.agent_identity
6618    /\ \A row \in pending_turns \cup committed_turns \cup resolved_turns : \lnot (/\ row.agent_identity = candidate.agent_identity /\ row.host_id = candidate.host_id /\ row.generation = candidate.generation /\ row.fence_token = candidate.fence_token /\ row.input_id = candidate.input_id)
6619    /\ \A row \in pending_completions \cup resolved_completions : \lnot (/\ row.agent_identity = candidate.agent_identity /\ row.host_id = candidate.host_id /\ row.generation = candidate.generation /\ row.fence_token = candidate.fence_token /\ row.input_id = candidate.input_id)
6620";
6621
6622        assert!(
6623            model.contains(expected),
6624            "MobMachine TLA kickoff-correlation helper must reject collisions across kickoff, remote-turn, and placed-completion custody"
6625        );
6626    }
6627
6628    #[test]
6629    fn mob_placed_kickoff_recovery_tla_helper_does_not_shadow_machine_phase() {
6630        let model = render_machine_semantic_model(&mob_machine()).expect("render MobMachine model");
6631        assert!(
6632            model.contains(
6633                r#"Cardinality({ kickoff_phase \in {"Started", "CallbackPending", "Failed", "Cancelled"} :"#
6634            ),
6635            "kickoff recovery helper must bind a helper-local identifier"
6636        );
6637        assert!(
6638            !model.contains(
6639                r#"Cardinality({ phase \in {"Started", "CallbackPending", "Failed", "Cancelled"} :"#
6640            ),
6641            "TLA forbids the helper-local binder from shadowing the machine's phase variable"
6642        );
6643    }
6644
6645    #[test]
6646    fn mob_adaptive_run_custody_native_helper_matches_rust_contract() {
6647        let model = render_machine_semantic_model(&mob_machine()).expect("render MobMachine model");
6648        let expected = r#"mob_machine_adaptive_run_custody_drained(adaptive_run_id, active_layer, active_members, layer_run, layer_phases, layer_dispositions) ==
6649    /\ adaptive_run_id \notin DOMAIN active_layer
6650    /\ (IF adaptive_run_id \in DOMAIN active_members THEN active_members[adaptive_run_id] ELSE 0) = 0
6651    /\ \A layer_id \in DOMAIN layer_run :
6652           \/ layer_run[layer_id] # adaptive_run_id
6653           \/ /\ layer_id \in DOMAIN layer_dispositions
6654              /\ layer_id \in DOMAIN layer_phases
6655              /\ layer_phases[layer_id] \in {"Completed", "SetupFailed", "RunFailed", "ResultInvalid", "Canceled"}
6656"#;
6657
6658        assert!(
6659            model.contains(expected),
6660            "MobMachine TLA adaptive-run custody operator must preserve the Rust absence, zero-active-member, and terminal-layer contract"
6661        );
6662    }
6663
6664    /// Every conjunct of the option-order ASSUME table states what Rust's
6665    /// `Option` order computes, so a TLC run that accepts the ASSUMEs proves
6666    /// `OptionLt` / `OptionLe` right. The table covers both operators over
6667    /// None/None, None/Some, Some/None and Some/Some below, equal and above.
6668    #[test]
6669    #[allow(clippy::panic)]
6670    fn the_option_order_assume_table_is_rusts_option_order() {
6671        use std::cmp::Ordering;
6672
6673        fn operand(text: &str) -> Option<u64> {
6674            if text == "None" {
6675                return None;
6676            }
6677            let value = text
6678                .strip_prefix("Some(")
6679                .and_then(|rest| rest.strip_suffix(')'))
6680                .unwrap_or_else(|| panic!("unexpected operand {text}"));
6681            Some(
6682                value
6683                    .parse()
6684                    .unwrap_or_else(|_| panic!("unexpected operand {text}")),
6685            )
6686        }
6687
6688        // TLC evaluates every disjunct of an action-level `\/`, so a `\/` in
6689        // either definition would read a `None` record's `value` inside a
6690        // guard; the ASSUMEs alone cannot see that.
6691        for line in TLA_OPTION_ORDER_DEFINITIONS
6692            .lines()
6693            .filter(|line| line.starts_with("OptionL"))
6694        {
6695            assert!(!line.contains("\\/"), "{line} branches with a disjunction");
6696        }
6697
6698        let mut covered = BTreeSet::new();
6699        for line in TLA_OPTION_ORDER_DEFINITIONS.lines() {
6700            let Some(table) = line.strip_prefix("ASSUME ") else {
6701                continue;
6702            };
6703            for conjunct in table.split(" /\\ ") {
6704                let (expected, call) = match conjunct.strip_prefix('~') {
6705                    Some(call) => (false, call),
6706                    None => (true, conjunct),
6707                };
6708                let (operator, operands) = call.split_once('(').expect("an operator call");
6709                let (left, right) = operands
6710                    .strip_suffix(')')
6711                    .and_then(|operands| operands.split_once(", "))
6712                    .expect("two operands");
6713                let (left, right) = (operand(left), operand(right));
6714                let rust = match operator {
6715                    "OptionLt" => left < right,
6716                    "OptionLe" => left <= right,
6717                    other => panic!("unexpected operator {other}"),
6718                };
6719                assert_eq!(
6720                    expected, rust,
6721                    "{conjunct} disagrees with Rust's Option order"
6722                );
6723                covered.insert((operator, left.is_some(), right.is_some(), left.cmp(&right)));
6724            }
6725        }
6726        for operator in ["OptionLt", "OptionLe"] {
6727            for case in [
6728                (false, false, Ordering::Equal),
6729                (false, true, Ordering::Less),
6730                (true, false, Ordering::Greater),
6731                (true, true, Ordering::Less),
6732                (true, true, Ordering::Equal),
6733                (true, true, Ordering::Greater),
6734            ] {
6735                assert!(
6736                    covered.contains(&(operator, case.0, case.1, case.2)),
6737                    "the ASSUME table misses {operator} over {case:?}"
6738                );
6739            }
6740        }
6741    }
6742
6743    /// An ordering comparison with an option operand renders through
6744    /// `OptionLt` / `OptionLe` (`>` and `>=` with the operands swapped) for
6745    /// every way an operand is an option, on either side; a plain ordering
6746    /// keeps its TLA+ operator and leaves the module without the definitions.
6747    #[test]
6748    fn an_ordering_with_an_option_operand_renders_in_rusts_option_order() {
6749        let mut schema = mob_machine();
6750        schema.helpers.push(HelperSchema {
6751            name: "maybe_epoch".into(),
6752            params: Vec::new(),
6753            returns: TypeRef::Option(Box::new(TypeRef::U64)),
6754            body: Expr::None,
6755        });
6756        let field = |name: &str| {
6757            Box::new(Expr::Field(
6758                meerkat_machine_schema::identity::FieldId::parse(name).expect("field id"),
6759            ))
6760        };
6761        let binding = |name: &str| Box::new(Expr::Binding(name.to_owned()));
6762        let binding_types = BTreeMap::from([
6763            ("agent_identity".to_owned(), TypeRef::String),
6764            ("maybe".to_owned(), TypeRef::Option(Box::new(TypeRef::U64))),
6765            ("n".to_owned(), TypeRef::U64),
6766            ("run_id".to_owned(), TypeRef::String),
6767        ]);
6768        let options = [
6769            ("a None literal", Expr::None),
6770            ("a Some literal", Expr::Some(Box::new(Expr::U64(3)))),
6771            ("an option binding", Expr::Binding("maybe".to_owned())),
6772            ("an option field", *field("supervisor_authority_epoch")),
6773            (
6774                "the get_copied lowering",
6775                Expr::IfElse {
6776                    condition: Box::new(Expr::MapContainsKey {
6777                        map: field("member_last_observed_at_ms"),
6778                        key: binding("agent_identity"),
6779                    }),
6780                    then_expr: Box::new(Expr::Some(Box::new(Expr::MapGet {
6781                        map: field("member_last_observed_at_ms"),
6782                        key: binding("agent_identity"),
6783                    }))),
6784                    else_expr: Box::new(Expr::None),
6785                },
6786            ),
6787            (
6788                "a read of a map with option values",
6789                Expr::MapGet {
6790                    map: field("run_last_granted_frame"),
6791                    key: binding("run_id"),
6792                },
6793            ),
6794            (
6795                "a helper returning an option",
6796                Expr::Call {
6797                    helper: "maybe_epoch".to_owned(),
6798                    args: Vec::new(),
6799                },
6800            ),
6801        ];
6802        let other = Expr::Some(binding("n"));
6803        for (shape, option) in &options {
6804            let compiler = MachineTlaCompiler::new(&schema);
6805            let render = |expr: &Expr| {
6806                compiler.render_expr_with_types(
6807                    expr,
6808                    &BTreeMap::new(),
6809                    &BTreeMap::new(),
6810                    &binding_types,
6811                )
6812            };
6813            let (a, b) = (render(option), render(&other));
6814            let pair = || (Box::new(option.clone()), Box::new(other.clone()));
6815            let swapped = || (Box::new(other.clone()), Box::new(option.clone()));
6816            for (expr, expected) in [
6817                (Expr::Lt(pair().0, pair().1), format!("OptionLt({a}, {b})")),
6818                (Expr::Lte(pair().0, pair().1), format!("OptionLe({a}, {b})")),
6819                (Expr::Gt(pair().0, pair().1), format!("OptionLt({b}, {a})")),
6820                (Expr::Gte(pair().0, pair().1), format!("OptionLe({b}, {a})")),
6821                (
6822                    Expr::Lt(swapped().0, swapped().1),
6823                    format!("OptionLt({b}, {a})"),
6824                ),
6825                (
6826                    Expr::Gte(swapped().0, swapped().1),
6827                    format!("OptionLe({a}, {b})"),
6828                ),
6829            ] {
6830                assert_eq!(render(&expr), expected, "{shape}: {expr:?}");
6831            }
6832            assert!(compiler.option_order_used.get(), "{shape} marks the module");
6833        }
6834
6835        let compiler = MachineTlaCompiler::new(&schema);
6836        let render = |expr: Expr| {
6837            compiler.render_expr_with_types(
6838                &expr,
6839                &BTreeMap::new(),
6840                &BTreeMap::new(),
6841                &binding_types,
6842            )
6843        };
6844        let one = || Box::new(Expr::U64(1));
6845        assert_eq!(render(Expr::Lt(binding("n"), one())), "(n < 1)");
6846        assert_eq!(render(Expr::Lte(binding("n"), one())), "(n <= 1)");
6847        assert_eq!(render(Expr::Gt(binding("n"), one())), "(n > 1)");
6848        assert_eq!(render(Expr::Gte(binding("n"), one())), "(n >= 1)");
6849        assert!(
6850            !compiler.option_order_used.get(),
6851            "a plain ordering needs no option-order definitions"
6852        );
6853    }
6854
6855    /// A machine or composition module defines `OptionLt` / `OptionLe` if
6856    /// and only if it calls them, so the definitions land only beside an
6857    /// option ordering.
6858    #[test]
6859    fn a_module_defines_the_option_order_operators_iff_it_calls_them() {
6860        let calls_operators = |module: &str, model: &str| {
6861            let defined = model.matches(TLA_OPTION_ORDER_DEFINITIONS).count();
6862            assert!(
6863                defined <= 1,
6864                "{module} defines the operators {defined} times"
6865            );
6866            let body = model.replacen(TLA_OPTION_ORDER_DEFINITIONS, "", 1);
6867            let called = body.contains("OptionLt(") || body.contains("OptionLe(");
6868            assert_eq!(
6869                defined == 1,
6870                called,
6871                "{module}: defined {defined} time(s), called: {called}"
6872            );
6873            called
6874        };
6875        let mut callers = Vec::new();
6876        for machine in canonical_machine_schemas() {
6877            let model = render_machine_semantic_model(&machine).expect("render machine model");
6878            if calls_operators(machine.machine.as_str(), &model) {
6879                callers.push(machine.machine.as_str().to_owned());
6880            }
6881        }
6882        for composition in meerkat_machine_schema::canonical_composition_schemas() {
6883            // meerkat_mob_seam takes about 45 s to render. Its MobMachine part
6884            // goes through the same per-instance compilers as
6885            // adaptive_mob_bundle's two MobMachine instances below, and
6886            // machine-check-drift holds its regenerated model.
6887            if composition.name.as_str() == "meerkat_mob_seam" {
6888                continue;
6889            }
6890            let model =
6891                render_composition_semantic_model(&composition).expect("render composition model");
6892            if calls_operators(composition.name.as_str(), &model) {
6893                callers.push(composition.name.as_str().to_owned());
6894            }
6895        }
6896        for caller in ["MobMachine", "adaptive_mob_bundle"] {
6897            assert!(
6898                callers.iter().any(|candidate| candidate == caller),
6899                "{caller} orders options (MobMachine's member progress guards): {callers:?}"
6900            );
6901        }
6902    }
6903
6904    /// The option-ordering contract: every ordering comparison in a
6905    /// canonical machine whose operand is option-shaped renders through
6906    /// `OptionLt` / `OptionLe`, never as a plain comparison TLC cannot
6907    /// evaluate. The walk decides "option-shaped" from the schema's declared
6908    /// types (state fields, trigger bindings, helper parameters and returns,
6909    /// map value types, `Some` / `None` literals), independently of the
6910    /// renderer's own inference, so a new guard cannot bring the class back
6911    /// through a shape the renderer misses.
6912    #[test]
6913    fn every_canonical_option_ordering_renders_in_rusts_option_order() {
6914        struct Walk<'a> {
6915            schema: &'a MachineSchema,
6916            compiler: MachineTlaCompiler<'a>,
6917            checked: usize,
6918            plain: Vec<String>,
6919        }
6920
6921        impl Walk<'_> {
6922            fn declared<'t>(
6923                &'t self,
6924                expr: &Expr,
6925                bindings: &'t BTreeMap<String, TypeRef>,
6926            ) -> Option<&'t TypeRef> {
6927                match expr {
6928                    Expr::Field(field) => self
6929                        .schema
6930                        .state
6931                        .fields
6932                        .iter()
6933                        .find(|candidate| candidate.name == *field)
6934                        .map(|candidate| &candidate.ty),
6935                    Expr::Binding(name) => bindings.get(name),
6936                    Expr::Call { helper, .. } => self
6937                        .schema
6938                        .helpers
6939                        .iter()
6940                        .chain(self.schema.derived.iter())
6941                        .find(|candidate| candidate.name == *helper)
6942                        .map(|candidate| &candidate.returns),
6943                    Expr::MapGet { map, .. } | Expr::MapValue { map, .. } => {
6944                        match self.declared(map, bindings)? {
6945                            TypeRef::Map(_, value) => Some(value.as_ref()),
6946                            _ => None,
6947                        }
6948                    }
6949                    _ => None,
6950                }
6951            }
6952
6953            fn option_shaped(&self, expr: &Expr, bindings: &BTreeMap<String, TypeRef>) -> bool {
6954                match expr {
6955                    Expr::Some(_) | Expr::None => true,
6956                    Expr::IfElse {
6957                        then_expr,
6958                        else_expr,
6959                        ..
6960                    } => {
6961                        self.option_shaped(then_expr, bindings)
6962                            || self.option_shaped(else_expr, bindings)
6963                    }
6964                    other => matches!(self.declared(other, bindings), Some(TypeRef::Option(_))),
6965                }
6966            }
6967
6968            fn walk(&mut self, site: &str, expr: &Expr, bindings: &BTreeMap<String, TypeRef>) {
6969                match expr {
6970                    Expr::Lt(left, right)
6971                    | Expr::Lte(left, right)
6972                    | Expr::Gt(left, right)
6973                    | Expr::Gte(left, right) => {
6974                        if self.option_shaped(left, bindings) || self.option_shaped(right, bindings)
6975                        {
6976                            self.checked += 1;
6977                            let rendered = self.compiler.render_expr_with_types(
6978                                expr,
6979                                &BTreeMap::new(),
6980                                &BTreeMap::new(),
6981                                bindings,
6982                            );
6983                            if !rendered.starts_with("OptionLt(")
6984                                && !rendered.starts_with("OptionLe(")
6985                            {
6986                                self.plain
6987                                    .push(format!("{} {site}: {rendered}", self.schema.machine));
6988                            }
6989                        }
6990                        self.walk(site, left, bindings);
6991                        self.walk(site, right, bindings);
6992                    }
6993                    Expr::Bool(_)
6994                    | Expr::U64(_)
6995                    | Expr::U64Max
6996                    | Expr::String(_)
6997                    | Expr::NamedVariant { .. }
6998                    | Expr::EmptySet
6999                    | Expr::EmptyMap
7000                    | Expr::CurrentPhase
7001                    | Expr::Phase(_)
7002                    | Expr::Field(_)
7003                    | Expr::Binding(_)
7004                    | Expr::Variant(_)
7005                    | Expr::None => {}
7006                    Expr::FieldAccess { base, .. } => self.walk(site, base, bindings),
7007                    Expr::EnumVariantIs { value, .. }
7008                    | Expr::EnumStringSetPayload { value, .. } => self.walk(site, value, bindings),
7009                    Expr::SeqLiteral(items) | Expr::And(items) | Expr::Or(items) => {
7010                        for item in items {
7011                            self.walk(site, item, bindings);
7012                        }
7013                    }
7014                    Expr::IfElse {
7015                        condition,
7016                        then_expr,
7017                        else_expr,
7018                    } => {
7019                        self.walk(site, condition, bindings);
7020                        self.walk(site, then_expr, bindings);
7021                        self.walk(site, else_expr, bindings);
7022                    }
7023                    Expr::Not(inner)
7024                    | Expr::SeqElements(inner)
7025                    | Expr::Len(inner)
7026                    | Expr::Head(inner)
7027                    | Expr::MapKeys(inner)
7028                    | Expr::Some(inner) => self.walk(site, inner, bindings),
7029                    Expr::Eq(left, right)
7030                    | Expr::Neq(left, right)
7031                    | Expr::Add(left, right)
7032                    | Expr::Sub(left, right) => {
7033                        self.walk(site, left, bindings);
7034                        self.walk(site, right, bindings);
7035                    }
7036                    Expr::Contains { collection, value } | Expr::Count { collection, value } => {
7037                        self.walk(site, collection, bindings);
7038                        self.walk(site, value, bindings);
7039                    }
7040                    Expr::MapContainsKey { map, key }
7041                    | Expr::MapGet { map, key }
7042                    | Expr::MapValue { map, key } => {
7043                        self.walk(site, map, bindings);
7044                        self.walk(site, key, bindings);
7045                    }
7046                    Expr::SeqStartsWith { seq, prefix } => {
7047                        self.walk(site, seq, bindings);
7048                        self.walk(site, prefix, bindings);
7049                    }
7050                    Expr::MapLiteral(entries) => {
7051                        for (key, value) in entries {
7052                            self.walk(site, key, bindings);
7053                            self.walk(site, value, bindings);
7054                        }
7055                    }
7056                    Expr::Call { args, .. } => {
7057                        for arg in args {
7058                            self.walk(site, arg, bindings);
7059                        }
7060                    }
7061                    Expr::Quantified { over, body, .. } => {
7062                        self.walk(site, over, bindings);
7063                        self.walk(site, body, bindings);
7064                    }
7065                }
7066            }
7067
7068            fn walk_updates(
7069                &mut self,
7070                site: &str,
7071                updates: &[Update],
7072                bindings: &BTreeMap<String, TypeRef>,
7073            ) {
7074                for update in updates {
7075                    match update {
7076                        Update::Assign { expr, .. } => self.walk(site, expr, bindings),
7077                        Update::Increment { .. }
7078                        | Update::Decrement { .. }
7079                        | Update::SeqPopFront { .. } => {}
7080                        Update::MapInsert { key, value, .. } => {
7081                            self.walk(site, key, bindings);
7082                            self.walk(site, value, bindings);
7083                        }
7084                        Update::MapIncrement { key, .. }
7085                        | Update::MapDecrement { key, .. }
7086                        | Update::MapRemove { key, .. } => self.walk(site, key, bindings),
7087                        Update::SetInsert { value, .. }
7088                        | Update::SetRemove { value, .. }
7089                        | Update::SeqAppend { value, .. }
7090                        | Update::SeqRemoveValue { value, .. } => self.walk(site, value, bindings),
7091                        Update::SeqPrepend { values, .. } | Update::SeqRemoveAll { values, .. } => {
7092                            self.walk(site, values, bindings)
7093                        }
7094                        Update::Conditional {
7095                            condition,
7096                            then_updates,
7097                            else_updates,
7098                        } => {
7099                            self.walk(site, condition, bindings);
7100                            self.walk_updates(site, then_updates, bindings);
7101                            self.walk_updates(site, else_updates, bindings);
7102                        }
7103                        Update::ForEach { over, updates, .. } => {
7104                            self.walk(site, over, bindings);
7105                            self.walk_updates(site, updates, bindings);
7106                        }
7107                    }
7108                }
7109            }
7110        }
7111
7112        let mut checked = 0;
7113        let mut plain = Vec::new();
7114        for schema in canonical_machine_schemas() {
7115            let mut walk = Walk {
7116                schema: &schema,
7117                compiler: MachineTlaCompiler::new(&schema),
7118                checked: 0,
7119                plain: Vec::new(),
7120            };
7121            let none = BTreeMap::new();
7122            for transition in &schema.transitions {
7123                let bindings = walk.compiler.binding_type_map(transition);
7124                let site = transition.name.as_str();
7125                for guard in &transition.guards {
7126                    walk.walk(site, &guard.expr, &bindings);
7127                }
7128                walk.walk_updates(site, &transition.updates, &bindings);
7129                for emit in &transition.emit {
7130                    for expr in emit.fields.values() {
7131                        walk.walk(site, expr, &bindings);
7132                    }
7133                }
7134            }
7135            for invariant in &schema.invariants {
7136                walk.walk(&invariant.name, &invariant.expr, &none);
7137            }
7138            for helper in schema.helpers.iter().chain(schema.derived.iter()) {
7139                let params = helper
7140                    .params
7141                    .iter()
7142                    .map(|param| (param.name.as_str().to_owned(), param.ty.clone()))
7143                    .collect::<BTreeMap<_, _>>();
7144                walk.walk(&helper.name, &helper.body, &params);
7145            }
7146            checked += walk.checked;
7147            plain.extend(walk.plain);
7148        }
7149        assert!(
7150            plain.is_empty(),
7151            "option orderings rendered as plain comparisons (TLC cannot order option records):\n{}",
7152            plain.join("\n")
7153        );
7154        // MobMachine's seven member-progress guards order options: the walk
7155        // must find them, or the contract passes vacuously.
7156        assert!(checked >= 7, "the walk found {checked} option orderings");
7157    }
7158}
7159
7160fn render_sequence_domain_definition(inner: &TypeRef) -> String {
7161    let inner_domain = render_type_domain_expr(inner);
7162    format!(
7163        "{{<<>>}} \\cup {{<<x>> : x \\in {inner_domain}}} \\cup {{<<x, y>> : x \\in {inner_domain}, y \\in {inner_domain}}}"
7164    )
7165}
7166
7167fn render_option_domain_definition(inner: &TypeRef) -> String {
7168    let inner_domain = render_type_domain_expr(inner);
7169    format!("{{None}} \\cup {{Some(x) : x \\in {inner_domain}}}")
7170}
7171
7172fn render_map_domain_definition(key: &TypeRef, value: &TypeRef) -> String {
7173    let key_domain = render_type_domain_expr(key);
7174    let value_domain = render_type_domain_expr(value);
7175    let empty_map = "[x \\in {} |-> None]";
7176    format!(
7177        "{{{empty_map}}} \\cup {{ [x \\in {{k}} |-> v] : k \\in {key_domain}, v \\in {value_domain} }}"
7178    )
7179}
7180
7181fn ordered_composite_domain_definitions(
7182    constants: &BTreeMap<String, TypeRef>,
7183) -> Vec<(&String, &TypeRef)> {
7184    let mut domains = constants
7185        .iter()
7186        .filter(|(_, ty)| {
7187            matches!(
7188                ty,
7189                TypeRef::Seq(_) | TypeRef::Option(_) | TypeRef::Map(_, _)
7190            )
7191        })
7192        .collect::<Vec<_>>();
7193    domains.sort_by_key(|(name, ty)| (domain_dependency_depth(ty), (*name).clone()));
7194    domains
7195}
7196
7197fn domain_dependency_depth(ty: &TypeRef) -> usize {
7198    match ty {
7199        TypeRef::Option(inner) | TypeRef::Seq(inner) | TypeRef::Set(inner) => {
7200            1 + domain_dependency_depth(inner)
7201        }
7202        TypeRef::Map(key, value) => {
7203            1 + domain_dependency_depth(key).max(domain_dependency_depth(value))
7204        }
7205        TypeRef::Bool
7206        | TypeRef::U32
7207        | TypeRef::U64
7208        | TypeRef::String
7209        | TypeRef::Named(_)
7210        | TypeRef::Enum(_) => 0,
7211    }
7212}
7213
7214/// The rendered payload of one owner feedback input.
7215struct FeedbackPayload {
7216    payload_expr: String,
7217    quantifiers: Vec<String>,
7218    /// `(obligation field, bound member variable)` per `ObligationMember`.
7219    members: Vec<(String, String)>,
7220}
7221
7222/// Whether `NoOpenObligationsOnTerminal_<protocol>` applies: the producer has
7223/// terminal phases and the protocol is `AckRequired`, so only owner feedback
7224/// closes its obligations. Under `AckOrAbort` and `TerminalClosure` the
7225/// terminal phase is itself the closure, and a `PublicationOnly` protocol has
7226/// no feedback (the publication closes it), so for those the invariant would be
7227/// unsatisfiable once the producer reaches a terminal phase.
7228fn terminal_closure_required(
7229    protocol: &meerkat_machine_schema::EffectHandoffProtocol,
7230    producer: &MachineSchema,
7231) -> bool {
7232    !producer.state.terminal_phases.is_empty()
7233        && matches!(
7234            protocol.closure_policy,
7235            meerkat_machine_schema::ClosurePolicy::AckRequired
7236        )
7237}
7238
7239fn render_type_domain_expr(ty: &TypeRef) -> String {
7240    match ty {
7241        TypeRef::Bool => "BOOLEAN".into(),
7242        // dogma #172 (codegen half): U32 and U64 are distinct bounded domains,
7243        // not one collapsed `NatValues`. The domains-map machinery auto-declares
7244        // the `U32Values` CONSTANT and emits its .cfg sample assignment, so a
7245        // u32 field references its own domain (matching the kernel's u32 width
7246        // check) rather than aliasing the unbounded u64 domain.
7247        TypeRef::U32 => "U32Values".into(),
7248        TypeRef::U64 => "NatValues".into(),
7249        TypeRef::String => "StringValues".into(),
7250        TypeRef::Named(_)
7251        | TypeRef::Enum(_)
7252        | TypeRef::Set(_)
7253        | TypeRef::Seq(_)
7254        | TypeRef::Option(_)
7255        | TypeRef::Map(_, _) => domain_constant_name(ty),
7256    }
7257}
7258
7259fn domain_constant_name(ty: &TypeRef) -> String {
7260    match ty {
7261        TypeRef::Named(name) => format!("{}Values", tla_ident(name)),
7262        TypeRef::Enum(name) => format!("{}Values", tla_ident(name)),
7263        TypeRef::Seq(inner) => format!("SeqOf{}Values", tla_ident(type_ref_name(inner))),
7264        TypeRef::Set(inner) => format!("SetOf{}Values", tla_ident(type_ref_name(inner))),
7265        TypeRef::String => "StringValues".into(),
7266        TypeRef::Bool => "BooleanValues".into(),
7267        TypeRef::U32 => "U32Values".into(),
7268        TypeRef::U64 => "NatValues".into(),
7269        TypeRef::Option(inner) => format!("Option{}Values", tla_ident(type_ref_name(inner))),
7270        TypeRef::Map(key, value) => {
7271            format!(
7272                "Map{}{}Values",
7273                tla_ident(type_ref_name(key)),
7274                tla_ident(type_ref_name(value))
7275            )
7276        }
7277    }
7278}
7279
7280fn type_ref_name(ty: &TypeRef) -> String {
7281    match ty {
7282        TypeRef::Bool => "Bool".into(),
7283        TypeRef::U32 => "U32".into(),
7284        TypeRef::U64 => "U64".into(),
7285        TypeRef::String => "String".into(),
7286        TypeRef::Named(name) => name.as_str().to_owned(),
7287        TypeRef::Enum(name) => name.as_str().to_owned(),
7288        TypeRef::Option(inner) => format!("Option{}", type_ref_name(inner)),
7289        TypeRef::Set(inner) => format!("Set{}", type_ref_name(inner)),
7290        TypeRef::Seq(inner) => format!("Seq{}", type_ref_name(inner)),
7291        TypeRef::Map(key, value) => format!("Map{}{}", type_ref_name(key), type_ref_name(value)),
7292    }
7293}
7294
7295struct CompositionTlaCompiler<'a> {
7296    schema: &'a CompositionSchema,
7297    machine_by_instance: BTreeMap<&'a str, &'a MachineSchema>,
7298    named_bindings: BTreeMap<String, meerkat_machine_schema::RustTypeAtom>,
7299    fallback_machine: &'a MachineSchema,
7300    unchanged_frames: RefCell<UnchangedFrameInterner>,
7301    /// Shared with every machine compiler that renders into this module (see
7302    /// `MachineTlaCompiler::option_order_used`).
7303    option_order_used: Rc<Cell<bool>>,
7304}
7305
7306const COMPOSITION_UNCHANGED_CHUNK_SIZE: usize = 64;
7307const COMPOSITION_UNCHANGED_SPLIT_THRESHOLD: usize = 96;
7308
7309/// Prefix for the generated named UNCHANGED frame operators.
7310///
7311/// Deliberately upper-camel: the machine-poster TLA reader treats a
7312/// `^[a-z_][A-Za-z0-9_]* == ...` line before `THEOREM` as a machine invariant,
7313/// and a line ending in bare `==` as the head of a multi-line definition. An
7314/// upper-case name on a single line is invisible to both.
7315const UNCHANGED_FRAME_PREFIX: &str = "UnchangedFrame_";
7316
7317/// Stable 64-bit FNV-1a.
7318///
7319/// Frame operator names are derived from frame content so that adding or
7320/// removing a transition perturbs exactly the frames it touches instead of
7321/// renumbering every later one. That only holds if the hash itself is stable:
7322/// `std::collections::hash_map::DefaultHasher` is explicitly documented as not
7323/// stable across Rust releases, so a toolchain bump would rename every frame
7324/// and turn `machine-check-drift` red with no source change. FNV-1a is pinned
7325/// here for that reason.
7326fn fnv1a64(bytes: &[u8]) -> u64 {
7327    const OFFSET_BASIS: u64 = 0xcbf2_9ce4_8422_2325;
7328    const PRIME: u64 = 0x0000_0100_0000_01b3;
7329    let mut hash = OFFSET_BASIS;
7330    for byte in bytes {
7331        hash ^= u64::from(*byte);
7332        hash = hash.wrapping_mul(PRIME);
7333    }
7334    hash
7335}
7336
7337/// Renders one UNCHANGED frame as a single TLA line.
7338///
7339/// `chunking` carries the composition-only `(split_threshold, chunk_size)`
7340/// policy: TLC's semantic pass can overflow on very large tuple frames, so a
7341/// composition frame past the threshold is expressed as a conjunction of
7342/// smaller tuples. `/\` is an ordinary infix operator, so the conjunction is
7343/// the same formula as the previously emitted bulleted list. Machines pass
7344/// `None` and keep their single-tuple frame verbatim.
7345fn unchanged_frame_body(vars: &[String], chunking: Option<(usize, usize)>) -> String {
7346    if let Some((split_threshold, chunk_size)) = chunking
7347        && vars.len() > split_threshold
7348    {
7349        return vars
7350            .chunks(chunk_size)
7351            .map(|chunk| format!("UNCHANGED << {} >>", chunk.join(", ")))
7352            .collect::<Vec<_>>()
7353            .join(" /\\ ");
7354    }
7355    format!("UNCHANGED << {} >>", vars.join(", "))
7356}
7357
7358/// Interns the distinct UNCHANGED frames of one generated TLA module.
7359///
7360/// The renderer used to expand a full frame tuple inline at every action. On
7361/// the largest composition that was 32,850 expansions of 650 distinct frames,
7362/// which is where ~85% of the emitted bytes went. Each distinct frame is now
7363/// emitted once as a named operator and referenced by name.
7364#[derive(Default)]
7365struct UnchangedFrameInterner {
7366    /// Frame operator name -> single-line frame body. Names are derived from
7367    /// the body, so a name already bound to a *different* body is a hash
7368    /// collision, never a rename.
7369    frames: BTreeMap<String, String>,
7370    /// First observed collision, if any. Recorded rather than resolved: a
7371    /// counter suffix would be order-dependent across schema edits and, worse,
7372    /// would silently hand one action a different frame condition than it had.
7373    /// The owning `render` turns this into a typed error and emits nothing.
7374    collision: Option<UnchangedFrameCollision>,
7375}
7376
7377/// Two distinct frames that derive the same operator name.
7378#[derive(Debug, Clone, PartialEq, Eq)]
7379pub struct UnchangedFrameCollision {
7380    pub name: String,
7381    pub first: String,
7382    pub second: String,
7383}
7384
7385impl std::fmt::Display for UnchangedFrameCollision {
7386    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
7387        write!(
7388            f,
7389            "frame operator `{}` derives from two different frames:\n  {}\n  {}",
7390            self.name, self.first, self.second
7391        )
7392    }
7393}
7394
7395impl UnchangedFrameInterner {
7396    /// Returns the operator name for `body`, registering the definition on
7397    /// first sight.
7398    fn intern(&mut self, body: String) -> String {
7399        let name = format!("{UNCHANGED_FRAME_PREFIX}{:016x}", fnv1a64(body.as_bytes()));
7400        match self.frames.get(&name) {
7401            Some(existing) if *existing == body => {}
7402            Some(existing) => {
7403                if self.collision.is_none() {
7404                    self.collision = Some(UnchangedFrameCollision {
7405                        name: name.clone(),
7406                        first: existing.clone(),
7407                        second: body,
7408                    });
7409                }
7410            }
7411            None => {
7412                self.frames.insert(name.clone(), body);
7413            }
7414        }
7415        name
7416    }
7417
7418    fn collision(&self) -> Option<&UnchangedFrameCollision> {
7419        self.collision.as_ref()
7420    }
7421
7422    /// Renders the definition block, sorted by operator name.
7423    ///
7424    /// Sorted rather than first-use order so that a later schema edit inserts
7425    /// or drops a single definition line instead of shifting every definition
7426    /// after it. Returns `String::new()` when the module has no frames.
7427    fn definitions_block(&self) -> String {
7428        if self.frames.is_empty() {
7429            return String::new();
7430        }
7431        let mut out = String::new();
7432        pushln!(
7433            &mut out,
7434            "\\* Named UNCHANGED frames. One definition per distinct frame; every action"
7435        );
7436        pushln!(
7437            &mut out,
7438            "\\* that leaves those variables unchanged references the definition by name."
7439        );
7440        for (name, body) in &self.frames {
7441            pushln!(&mut out, "{name} == {body}");
7442        }
7443        pushln!(&mut out);
7444        out
7445    }
7446}
7447
7448impl<'a> CompositionTlaCompiler<'a> {
7449    fn new(
7450        schema: &'a CompositionSchema,
7451        machine_catalog: &'a [MachineSchema],
7452    ) -> Result<Self, String> {
7453        let machine_catalog_by_name = machine_catalog
7454            .iter()
7455            .map(|machine| (machine.machine.as_str(), machine))
7456            .collect::<BTreeMap<_, _>>();
7457
7458        let mut machine_by_instance = BTreeMap::new();
7459        for instance in &schema.machines {
7460            let machine = machine_catalog_by_name
7461                .get(instance.machine_name.as_str())
7462                .copied()
7463                .ok_or_else(|| {
7464                    format!(
7465                        "unknown machine schema `{}` for composition `{}`",
7466                        instance.machine_name, schema.name
7467                    )
7468                })?;
7469            machine_by_instance.insert(instance.instance_id.as_str(), machine);
7470        }
7471        let named_bindings =
7472            collect_composition_named_bindings(machine_by_instance.values().copied());
7473
7474        Ok(Self {
7475            schema,
7476            machine_by_instance,
7477            named_bindings,
7478            fallback_machine: machine_catalog.first().ok_or_else(|| {
7479                format!(
7480                    "no machine catalog available for composition `{}`",
7481                    schema.name
7482                )
7483            })?,
7484            unchanged_frames: RefCell::new(UnchangedFrameInterner::default()),
7485            option_order_used: Rc::default(),
7486        })
7487    }
7488
7489    /// The machine compiler for one instance's part of this module. Every
7490    /// compiler that renders into the module shares its option-order flag, so
7491    /// an `OptionLt` / `OptionLe` call never reaches the module without the
7492    /// definitions.
7493    fn instance_compiler(
7494        &self,
7495        instance_id: &str,
7496        helper_prefix: String,
7497    ) -> MachineTlaCompiler<'_> {
7498        MachineTlaCompiler::new_with_helper_prefix(self.machine(instance_id), helper_prefix)
7499            .with_phase_symbol(self.phase_var(instance_id))
7500            .with_field_env_override(self.machine_field_env(instance_id))
7501            .with_option_order_flag(Rc::clone(&self.option_order_used))
7502    }
7503
7504    fn render_unchanged_vars(&self, out: &mut String, prefix: &str, vars: &[String]) {
7505        if vars.is_empty() {
7506            return;
7507        }
7508        // The frame is interned on its variable list alone and referenced at
7509        // the caller's own `prefix`, so the conjunct keeps its original column.
7510        // Indentation is semantically load-bearing in TLA bulleted lists.
7511        let body = unchanged_frame_body(
7512            vars,
7513            Some((
7514                COMPOSITION_UNCHANGED_SPLIT_THRESHOLD,
7515                COMPOSITION_UNCHANGED_CHUNK_SIZE,
7516            )),
7517        );
7518        let name = self.unchanged_frames.borrow_mut().intern(body);
7519        writeln!(out, "{prefix}{name}").expect("write to string");
7520    }
7521
7522    fn render(&self) -> std::result::Result<String, CompositionTlaError> {
7523        // Fail-closed gate: every route component must resolve against the
7524        // composition schema before any CASE expression is emitted. This makes
7525        // the defensive `OTHER -> "unknown_*"` branches in the generated TLA
7526        // provably unreachable rather than silent catch-alls.
7527        self.validate_routes()?;
7528
7529        let mut out = String::new();
7530        let constants = self.collect_binding_domains();
7531        let named_samples =
7532            collect_composition_named_type_samples(self.schema, &self.machine_by_instance);
7533        let machine_vars = self.machine_vars();
7534        let obligation_vars = self.obligation_vars();
7535        let mut machine_invariant_names = Vec::new();
7536
7537        pushln!(&mut out, "---- MODULE model ----");
7538        pushln!(&mut out, "EXTENDS TLC, Naturals, Sequences, FiniteSets");
7539        pushln!(&mut out);
7540        writeln!(
7541            &mut out,
7542            "\\* Generated composition model for {}.",
7543            self.schema.name
7544        )
7545        .expect("write to string");
7546        pushln!(&mut out);
7547
7548        let mut model_constants = constants
7549            .iter()
7550            .filter(|(_, ty)| {
7551                !matches!(
7552                    ty,
7553                    TypeRef::Seq(_) | TypeRef::Option(_) | TypeRef::Map(_, _)
7554                )
7555            })
7556            .map(|(name, _)| name)
7557            .cloned()
7558            .collect::<Vec<_>>();
7559        if composition_uses_u64_max(self.schema, &self.machine_by_instance) {
7560            model_constants.push(TLA_RUST_U64_MAX_CONSTANT.to_owned());
7561        }
7562        if !model_constants.is_empty() {
7563            if model_constants
7564                .iter()
7565                .any(|constant| constant == TLA_RUST_U64_MAX_CONSTANT)
7566            {
7567                pushln!(
7568                    &mut out,
7569                    "\\* RustU64Max is the TLA boundary for Expr::U64Max; production generated Rust renders u64::MAX."
7570                );
7571            }
7572            writeln!(&mut out, "CONSTANTS {}", model_constants.join(", "))
7573                .expect("write to string");
7574            pushln!(&mut out);
7575        }
7576
7577        writeln!(&mut out, "None == [tag |-> \"none\", value |-> \"none\"]")
7578            .expect("write to string");
7579        writeln!(&mut out, "Some(v) == [tag |-> \"some\", value |-> v]");
7580        pushln!(&mut out);
7581        let option_order_anchor = out.len();
7582
7583        push_cfg_assignment_operator_definitions(
7584            &mut out,
7585            &constants,
7586            &self.named_bindings,
7587            &CfgAssignmentOperatorProfile {
7588                suffix: "Ci".to_owned(),
7589                explicit_values: None,
7590                sample_cardinality: default_sample_cardinality(false),
7591                domain_overrides: None,
7592                named_samples: &named_samples,
7593                include_string_samples: false,
7594            },
7595        );
7596        push_cfg_assignment_operator_definitions(
7597            &mut out,
7598            &constants,
7599            &self.named_bindings,
7600            &CfgAssignmentOperatorProfile {
7601                suffix: "Deep".to_owned(),
7602                explicit_values: None,
7603                sample_cardinality: self.schema.deep_domain_cardinality,
7604                domain_overrides: Some(&self.schema.deep_domain_overrides),
7605                named_samples: &named_samples,
7606                include_string_samples: false,
7607            },
7608        );
7609        for witness in &self.schema.witnesses {
7610            let witness_samples = collect_composition_witness_named_type_samples(
7611                self.schema,
7612                witness,
7613                &self.machine_by_instance,
7614            );
7615            push_cfg_assignment_operator_definitions(
7616                &mut out,
7617                &constants,
7618                &self.named_bindings,
7619                &CfgAssignmentOperatorProfile {
7620                    suffix: witness_cfg_operator_suffix(witness),
7621                    explicit_values: None,
7622                    sample_cardinality: self
7623                        .schema
7624                        .witness_domain_cardinality
7625                        .max(max_named_sample_cardinality(&witness_samples)),
7626                    domain_overrides: None,
7627                    named_samples: &witness_samples,
7628                    include_string_samples: true,
7629                },
7630            );
7631        }
7632        for (name, ty) in ordered_composite_domain_definitions(&constants) {
7633            let definition = match ty {
7634                TypeRef::Seq(inner) => render_sequence_domain_definition(inner),
7635                TypeRef::Option(inner) => render_option_domain_definition(inner),
7636                TypeRef::Map(key, value) => render_map_domain_definition(key, value),
7637                _ => continue,
7638            };
7639            writeln!(&mut out, "{} == {}", name, definition).expect("write to string");
7640        }
7641        if constants.values().any(|ty| {
7642            matches!(
7643                ty,
7644                TypeRef::Seq(_) | TypeRef::Option(_) | TypeRef::Map(_, _)
7645            )
7646        }) {
7647            pushln!(&mut out);
7648        }
7649        writeln!(
7650            &mut out,
7651            "MapLookup(map, key) == IF key \\in DOMAIN map THEN map[key] ELSE None"
7652        )
7653        .expect("write to string");
7654        writeln!(
7655            &mut out,
7656            "MapSet(map, key, value) == [x \\in DOMAIN map \\cup {{key}} |-> IF x = key THEN value ELSE map[x]]"
7657        )
7658        .expect("write to string");
7659        writeln!(
7660            &mut out,
7661            "MapIncrement(map, key, amount) == [x \\in DOMAIN map \\cup {{key}} |-> IF x = key THEN (IF key \\in DOMAIN map THEN map[key] ELSE 0) + amount ELSE map[x]]"
7662        )
7663        .expect("write to string");
7664        writeln!(
7665            &mut out,
7666            "MapDecrement(map, key, amount) == [x \\in DOMAIN map \\cup {{key}} |-> IF x = key THEN (IF key \\in DOMAIN map THEN map[key] ELSE 0) - amount ELSE map[x]]"
7667        )
7668        .expect("write to string");
7669        writeln!(
7670            &mut out,
7671            "MapRemove(map, key) == [x \\in DOMAIN map \\ {{key}} |-> map[x]]"
7672        )
7673        .expect("write to string");
7674        writeln!(
7675            &mut out,
7676            "StartsWith(seq, prefix) == /\\ Len(prefix) <= Len(seq) /\\ SubSeq(seq, 1, Len(prefix)) = prefix"
7677        )
7678        .expect("write to string");
7679        writeln!(
7680            &mut out,
7681            "SeqElements(seq) == {{seq[i] : i \\in 1..Len(seq)}}"
7682        )
7683        .expect("write to string");
7684        writeln!(
7685            &mut out,
7686            "Count(seq, value) == Cardinality({{i \\in DOMAIN seq : seq[i] = value}})"
7687        )
7688        .expect("write to string");
7689        if self.schema.machines.iter().any(|instance| {
7690            !self
7691                .machine(instance.instance_id.as_str())
7692                .tlc_representative_inputs
7693                .is_empty()
7694        }) {
7695            writeln!(
7696                &mut out,
7697                "{TLC_REPRESENTATIVE_DOMAIN_HELPER}(values) == IF values = {{}} THEN {{}} ELSE {{CHOOSE value \\in values : TRUE}}"
7698            )
7699            .expect("write to string");
7700        }
7701        writeln!(
7702            &mut out,
7703            "RECURSIVE SeqRemove(_, _)\nSeqRemove(seq, value) == IF Len(seq) = 0 THEN <<>> ELSE IF Head(seq) = value THEN Tail(seq) ELSE <<Head(seq)>> \\o SeqRemove(Tail(seq), value)"
7704        )
7705        .expect("write to string");
7706        writeln!(
7707            &mut out,
7708            "RECURSIVE SeqRemoveAll(_, _)\nSeqRemoveAll(seq, values) == IF Len(values) = 0 THEN seq ELSE SeqRemoveAll(SeqRemove(seq, Head(values)), Tail(values))"
7709        )
7710        .expect("write to string");
7711        writeln!(
7712            &mut out,
7713            "AppendIfMissing(seq, value) == IF value \\in SeqElements(seq) THEN seq ELSE Append(seq, value)"
7714        )
7715        .expect("write to string");
7716        self.render_static_sets(&mut out)?;
7717
7718        let all_vars = {
7719            let mut v = machine_vars;
7720            v.extend(obligation_vars.clone());
7721            v.push("model_step_count".into());
7722            v.push("pending_inputs".into());
7723            v.push("observed_inputs".into());
7724            v.push("pending_routes".into());
7725            v.push("delivered_routes".into());
7726            v.push("emitted_effects".into());
7727            v.push("observed_transitions".into());
7728            v.push("witness_current_script_input".into());
7729            v.push("witness_remaining_script_inputs".into());
7730            v
7731        };
7732        writeln!(&mut out, "VARIABLES {}", all_vars.join(", ")).expect("write to string");
7733        writeln!(&mut out, "vars == << {} >>", all_vars.join(", ")).expect("write to string");
7734        pushln!(&mut out);
7735
7736        // Named UNCHANGED frames are spliced back in here once the whole module
7737        // body is rendered: the frames are discovered while rendering actions,
7738        // but TLA requires an operator to be defined before it is referenced.
7739        // This is the first point where every frame variable is in scope.
7740        let unchanged_frame_anchor = out.len();
7741
7742        writeln!(
7743            &mut out,
7744            "RoutePackets == SeqElements(pending_routes) \\cup delivered_routes"
7745        )
7746        .expect("write to string");
7747        writeln!(
7748            &mut out,
7749            "PendingActors == {{ActorOfMachine(packet.machine) : packet \\in SeqElements(pending_inputs)}}"
7750        )
7751        .expect("write to string");
7752        writeln!(
7753            &mut out,
7754            "HigherPriorityReady(actor) == \\E priority \\in ActorPriorities : /\\ priority[2] = actor /\\ priority[1] \\in PendingActors"
7755        )
7756        .expect("write to string");
7757        pushln!(&mut out);
7758
7759        pushln!(&mut out, "BaseInit ==");
7760        for instance in &self.schema.machines {
7761            let machine = self.machine(instance.instance_id.as_str());
7762            writeln!(
7763                &mut out,
7764                "    /\\ {} = {}",
7765                self.phase_var(instance.instance_id.as_str()),
7766                tla_string(&machine.state.init.phase)
7767            )
7768            .expect("write to string");
7769            for field in &machine.state.fields {
7770                let init_expr = machine
7771                    .state
7772                    .init
7773                    .fields
7774                    .iter()
7775                    .find(|item| item.field == field.name)
7776                    .map(|item| {
7777                        let compiler = self.instance_compiler(
7778                            instance.instance_id.as_str(),
7779                            format!("{}__", tla_ident(&instance.instance_id)),
7780                        );
7781                        compiler.render_expr(&item.expr, &BTreeMap::new(), &BTreeMap::new())
7782                    })
7783                    .unwrap_or_else(|| default_state_init_expr(&field.ty));
7784                writeln!(
7785                    &mut out,
7786                    "    /\\ {} = {}",
7787                    self.field_var(instance.instance_id.as_str(), field.name.as_str()),
7788                    init_expr
7789                )
7790                .expect("write to string");
7791            }
7792        }
7793        for var in &obligation_vars {
7794            pushln!(&mut out, "    /\\ {} = {{}}", var);
7795        }
7796        pushln!(&mut out, "    /\\ model_step_count = 0");
7797        pushln!(&mut out, "    /\\ pending_routes = <<>>");
7798        pushln!(&mut out, "    /\\ delivered_routes = {{}}");
7799        pushln!(&mut out, "    /\\ emitted_effects = {{}}");
7800        pushln!(&mut out, "    /\\ observed_transitions = {{}}");
7801        pushln!(&mut out);
7802
7803        pushln!(&mut out, "Init ==");
7804        pushln!(&mut out, "    /\\ BaseInit");
7805        pushln!(&mut out, "    /\\ pending_inputs = <<>>");
7806        pushln!(&mut out, "    /\\ observed_inputs = {{}}");
7807        pushln!(&mut out, "    /\\ witness_current_script_input = None");
7808        pushln!(&mut out, "    /\\ witness_remaining_script_inputs = <<>>");
7809        pushln!(&mut out);
7810
7811        for witness in &self.schema.witnesses {
7812            writeln!(
7813                &mut out,
7814                "{} ==",
7815                composition_witness_init_name(&witness.name)
7816            )
7817            .expect("write to string");
7818            writeln!(&mut out, "    /\\ BaseInit");
7819            writeln!(
7820                &mut out,
7821                "    /\\ pending_inputs = {}",
7822                self.witness_initial_pending_inputs_expr(witness)
7823            )
7824            .expect("write to string");
7825            writeln!(
7826                &mut out,
7827                "    /\\ observed_inputs = {}",
7828                self.witness_initial_observed_inputs_expr(witness)
7829            )
7830            .expect("write to string");
7831            writeln!(
7832                &mut out,
7833                "    /\\ witness_current_script_input = {}",
7834                self.witness_current_script_input_expr(witness)
7835            )
7836            .expect("write to string");
7837            writeln!(
7838                &mut out,
7839                "    /\\ witness_remaining_script_inputs = {}",
7840                self.witness_remaining_script_inputs_expr(witness)
7841            )
7842            .expect("write to string");
7843            pushln!(&mut out);
7844        }
7845
7846        for instance in &self.schema.machines {
7847            let machine = self.machine(instance.instance_id.as_str());
7848            let helper_prefix = format!("{}__", tla_ident(&instance.instance_id));
7849            let mut compiler = self.instance_compiler(instance.instance_id.as_str(), helper_prefix);
7850            for derived in helper_dependency_order(machine)? {
7851                compiler.render_helper(&mut out, derived);
7852                pushln!(&mut out);
7853            }
7854            if machine.machine.as_str() == "MobMachine" {
7855                compiler.render_mob_machine_native_helpers(&mut out);
7856                pushln!(&mut out);
7857            }
7858            if machine.machine.as_str() == "MeerkatMachine" {
7859                compiler.render_meerkat_machine_native_helpers(&mut out);
7860                pushln!(&mut out);
7861            }
7862            if machine.machine.as_str() == "RuntimeDeliveryMachine" {
7863                compiler.render_runtime_delivery_native_helpers(&mut out);
7864                pushln!(&mut out);
7865            }
7866            if machine.machine.as_str() == "SessionDocumentMachine" {
7867                compiler.render_session_document_native_helpers(&mut out);
7868                pushln!(&mut out);
7869            }
7870
7871            let mut rendered_actions = Vec::new();
7872            for transition in &machine.transitions {
7873                let mut action = String::new();
7874                self.render_machine_transition_action(
7875                    &mut compiler,
7876                    instance.instance_id.as_str(),
7877                    transition,
7878                    &mut action,
7879                )?;
7880                rendered_actions.push(action);
7881            }
7882
7883            for helper in &compiler.helper_defs {
7884                pushln!(&mut out, "{helper}");
7885                pushln!(&mut out);
7886            }
7887
7888            for action in &rendered_actions {
7889                pushln!(&mut out, "{action}");
7890                pushln!(&mut out);
7891            }
7892
7893            let invariant_field_env = self.machine_field_env(instance.instance_id.as_str());
7894            let invariant_binding_env = BTreeMap::new();
7895            let invariant_types = BTreeMap::new();
7896            for invariant in &machine.invariants {
7897                let invariant_name =
7898                    self.machine_invariant_name(instance.instance_id.as_str(), &invariant.name);
7899                machine_invariant_names.push(invariant_name.clone());
7900                writeln!(
7901                    &mut out,
7902                    "{} == {}",
7903                    invariant_name,
7904                    compiler.render_expr_with_types(
7905                        &invariant.expr,
7906                        &invariant_field_env,
7907                        &invariant_binding_env,
7908                        &invariant_types
7909                    )
7910                )
7911                .expect("write to string");
7912            }
7913            if !machine.invariants.is_empty() {
7914                pushln!(&mut out);
7915            }
7916        }
7917
7918        self.render_entry_packet_admissibility_helpers(&mut out)?;
7919        self.render_entry_input_actions(&mut out);
7920        self.render_deliver_queued_route_action(&mut out);
7921        self.render_reject_pending_entry_input_action(&mut out);
7922        self.render_quiescent_stutter(&mut out);
7923        self.render_witness_inject_actions(&mut out);
7924        self.render_witness_completion_operators(&mut out);
7925        self.render_witness_action_constraint_operators(&mut out);
7926        self.render_witness_satisfied_stutter_actions(&mut out);
7927        // TLA+ does not permit action references before their definitions.
7928        // Owner-feedback actions participate in CoreNext and witness Next, so
7929        // render them before either dispatcher is declared.
7930        self.render_owner_actor_processes(&mut out)?;
7931
7932        let core_next_branches = self.core_next_branches();
7933
7934        pushln!(&mut out, "CoreNext ==");
7935        for branch in &core_next_branches {
7936            pushln!(&mut out, "    \\/ {branch}");
7937        }
7938        pushln!(&mut out);
7939
7940        let inject_branches = self
7941            .schema
7942            .entry_inputs
7943            .iter()
7944            .map(|entry_input| self.render_entry_input_call(entry_input))
7945            .collect::<Vec<_>>();
7946
7947        pushln!(&mut out, "InjectNext ==");
7948        if inject_branches.is_empty() {
7949            pushln!(&mut out, "    FALSE");
7950        } else {
7951            for branch in &inject_branches {
7952                pushln!(&mut out, "    \\/ {branch}");
7953            }
7954        }
7955        pushln!(&mut out);
7956
7957        pushln!(&mut out, "Next ==");
7958        pushln!(&mut out, "    \\/ CoreNext");
7959        if !inject_branches.is_empty() {
7960            pushln!(&mut out, "    \\/ InjectNext");
7961        }
7962        pushln!(&mut out);
7963
7964        for witness in &self.schema.witnesses {
7965            let witness_branches = self.witness_next_branches(witness)?;
7966            writeln!(
7967                &mut out,
7968                "{} ==",
7969                composition_witness_next_name(&witness.name)
7970            )
7971            .expect("write to string");
7972            for branch in &witness_branches {
7973                pushln!(&mut out, "    \\/ {branch}");
7974            }
7975            writeln!(
7976                &mut out,
7977                "    \\/ {}",
7978                self.render_witness_inject_next_call(witness)
7979            )
7980            .expect("write to string");
7981            pushln!(&mut out);
7982        }
7983        pushln!(&mut out);
7984
7985        for invariant in &self.schema.invariants {
7986            writeln!(
7987                &mut out,
7988                "{} == {}",
7989                invariant.name,
7990                render_composition_invariant_formula(self.schema, &invariant.kind)
7991            )
7992            .expect("write to string");
7993        }
7994        if !self.schema.invariants.is_empty() {
7995            pushln!(&mut out);
7996        }
7997
7998        self.render_obligation_invariants(&mut out, &mut machine_invariant_names)?;
7999
8000        self.render_coverage_instrumentation(&mut out);
8001
8002        writeln!(
8003            &mut out,
8004            "CiStateConstraint == {}",
8005            render_composition_state_constraint(
8006                self.schema,
8007                self.schema
8008                    .ci_limits
8009                    .as_ref()
8010                    .unwrap_or(&CompositionStateLimits::ci_defaults()),
8011                self
8012            )
8013        )
8014        .expect("write to string");
8015        writeln!(
8016            &mut out,
8017            "DeepStateConstraint == {}",
8018            render_composition_state_constraint(
8019                self.schema,
8020                &composition_deep_state_limits(self.schema),
8021                self
8022            )
8023        )
8024        .expect("write to string");
8025        for witness in &self.schema.witnesses {
8026            writeln!(
8027                &mut out,
8028                "{} == {}",
8029                composition_witness_state_constraint_name(&witness.name),
8030                render_composition_state_constraint(
8031                    self.schema,
8032                    &effective_composition_state_limits(&witness.state_limits, Some(witness)),
8033                    self
8034                )
8035            )
8036            .expect("write to string");
8037        }
8038        pushln!(&mut out);
8039
8040        pushln!(&mut out, "Spec ==");
8041        pushln!(&mut out, "    /\\ Init");
8042        pushln!(&mut out, "    /\\ [][Next]_vars");
8043        pushln!(&mut out);
8044
8045        for witness in &self.schema.witnesses {
8046            let fairness_clauses = self.witness_fairness_clauses(witness)?;
8047            let fairness_chunk_names = fairness_clauses
8048                .chunks(24)
8049                .enumerate()
8050                .map(|(index, chunk)| {
8051                    let chunk_name = composition_witness_fairness_name(&witness.name, index);
8052                    writeln!(&mut out, "{chunk_name} ==").expect("write to string");
8053                    for clause in chunk {
8054                        writeln!(&mut out, "    /\\ WF_vars({clause})").expect("write to string");
8055                    }
8056                    pushln!(&mut out);
8057                    chunk_name
8058                })
8059                .collect::<Vec<_>>();
8060
8061            writeln!(
8062                &mut out,
8063                "{} ==",
8064                composition_witness_spec_name(&witness.name),
8065            )
8066            .expect("write to string");
8067            writeln!(
8068                &mut out,
8069                "    /\\ {}",
8070                composition_witness_init_name(&witness.name),
8071            )
8072            .expect("write to string");
8073            writeln!(
8074                &mut out,
8075                "    /\\ [] [{}]_vars",
8076                composition_witness_next_name(&witness.name)
8077            )
8078            .expect("write to string");
8079            for chunk_name in fairness_chunk_names {
8080                writeln!(&mut out, "    /\\ {chunk_name}").expect("write to string");
8081            }
8082            pushln!(&mut out);
8083        }
8084        for witness in &self.schema.witnesses {
8085            for route in &witness.expected_routes {
8086                let formula = composition_route_observed_operator_name(route);
8087                writeln!(
8088                    &mut out,
8089                    "{} == {}",
8090                    composition_witness_route_property_name(&witness.name, route),
8091                    self.render_witness_obligation_formula(witness, formula)
8092                )
8093                .expect("write to string");
8094            }
8095            for rule in &witness.expected_scheduler_rules {
8096                let formula = composition_scheduler_triggered_operator_name(rule);
8097                writeln!(
8098                    &mut out,
8099                    "{} == {}",
8100                    composition_witness_scheduler_property_name(&witness.name, rule),
8101                    self.render_witness_obligation_formula(witness, formula)
8102                )
8103                .expect("write to string");
8104            }
8105            for (idx, state) in witness.expected_states.iter().enumerate() {
8106                let formula = self.render_witness_state_formula(state);
8107                writeln!(
8108                    &mut out,
8109                    "{} == {}",
8110                    composition_witness_state_property_name(&witness.name, idx),
8111                    self.render_witness_obligation_formula(witness, formula)
8112                )
8113                .expect("write to string");
8114            }
8115            for transition in &witness.expected_transitions {
8116                let formula = self.render_witness_transition_formula(transition);
8117                writeln!(
8118                    &mut out,
8119                    "{} == {}",
8120                    composition_witness_transition_property_name(
8121                        &witness.name,
8122                        &transition.machine,
8123                        &transition.transition,
8124                    ),
8125                    self.render_witness_obligation_formula(witness, formula)
8126                )
8127                .expect("write to string");
8128            }
8129            for (idx, ordering) in witness.expected_transition_order.iter().enumerate() {
8130                let formula = self.render_witness_transition_order_formula(ordering);
8131                writeln!(
8132                    &mut out,
8133                    "{} == {}",
8134                    composition_witness_transition_order_property_name(&witness.name, idx),
8135                    self.render_witness_obligation_formula(witness, formula)
8136                )
8137                .expect("write to string");
8138            }
8139        }
8140        if !self.schema.witnesses.is_empty() {
8141            pushln!(&mut out);
8142        }
8143        for invariant in &self.schema.invariants {
8144            pushln!(&mut out, "THEOREM Spec => []{}", invariant.name);
8145        }
8146        for invariant_name in &machine_invariant_names {
8147            pushln!(&mut out, "THEOREM Spec => []{}", invariant_name);
8148        }
8149        pushln!(&mut out);
8150        writeln!(
8151            &mut out,
8152            "============================================================================="
8153        )
8154        .expect("write to string");
8155
8156        // Fail closed on a frame-name collision: the rendered body already
8157        // references one name for two different frames, so returning it would
8158        // silently give an action the wrong frame condition.
8159        let frames = self.unchanged_frames.borrow();
8160        if let Some(collision) = frames.collision() {
8161            return Err(CompositionTlaError::UnchangedFrameCollision {
8162                composition: self.schema.name.as_str().to_owned(),
8163                collision: collision.clone(),
8164            });
8165        }
8166        out.insert_str(unchanged_frame_anchor, &frames.definitions_block());
8167        // Before the frame anchor, so inserting it last leaves that one valid.
8168        if self.option_order_used.get() {
8169            out.insert_str(option_order_anchor, TLA_OPTION_ORDER_DEFINITIONS);
8170        }
8171
8172        Ok(out)
8173    }
8174
8175    fn collect_binding_domains(&self) -> BTreeMap<String, TypeRef> {
8176        collect_composition_binding_domains(self.schema, &self.machine_by_instance)
8177    }
8178
8179    fn machine(&self, instance_id: impl AsRef<str>) -> &MachineSchema {
8180        self.machine_by_instance
8181            .get(instance_id.as_ref())
8182            .copied()
8183            .unwrap_or(self.fallback_machine)
8184    }
8185
8186    fn actor(&self, instance_id: impl AsRef<str>) -> &str {
8187        let instance_id = instance_id.as_ref();
8188        self.schema
8189            .machines
8190            .iter()
8191            .find(|machine| machine.instance_id.as_str() == instance_id)
8192            .map(|machine| machine.actor.as_str())
8193            .unwrap_or("")
8194    }
8195
8196    fn phase_var(&self, instance_id: impl AsRef<str>) -> String {
8197        format!("{}_phase", tla_ident(instance_id))
8198    }
8199
8200    fn field_var(&self, instance_id: impl AsRef<str>, field: impl AsRef<str>) -> String {
8201        format!("{}_{}", tla_ident(instance_id), tla_ident(field))
8202    }
8203
8204    fn machine_invariant_name(
8205        &self,
8206        instance_id: impl AsRef<str>,
8207        invariant: impl AsRef<str>,
8208    ) -> String {
8209        format!("{}_{}", tla_ident(instance_id), tla_ident(invariant))
8210    }
8211
8212    fn machine_transition_name(
8213        &self,
8214        instance_id: impl AsRef<str>,
8215        transition: &TransitionSchema,
8216    ) -> String {
8217        format!("{}_{}", tla_ident(instance_id), tla_ident(&transition.name))
8218    }
8219
8220    fn machine_transition_call(&self, instance_id: &str, transition: &TransitionSchema) -> String {
8221        if transition.on.bindings().is_empty() {
8222            self.machine_transition_name(instance_id, transition)
8223        } else {
8224            let binding_types = transition_trigger_variant(self.machine(instance_id), transition)
8225                .map(|variant| {
8226                    variant
8227                        .fields
8228                        .iter()
8229                        .filter(|field| {
8230                            transition
8231                                .on
8232                                .bindings()
8233                                .iter()
8234                                .any(|binding| binding == &field.name)
8235                        })
8236                        .map(|field| (field.name.as_str().to_owned(), field.ty.clone()))
8237                        .collect::<BTreeMap<_, _>>()
8238                })
8239                .unwrap_or_default();
8240            let forced_bool_literals = transition_forced_bool_literals(transition, &binding_types);
8241            let mut prefix = String::new();
8242            for binding in transition.on.bindings() {
8243                if forced_bool_literals.contains_key(binding.as_str()) {
8244                    continue;
8245                }
8246                let local = format!("arg_{}", tla_ident(binding.as_str()));
8247                let Some(ty) = binding_types.get(binding.as_str()) else {
8248                    return self.machine_transition_name(instance_id, transition);
8249                };
8250                let domain = self.binding_domain_for_binding(
8251                    instance_id,
8252                    trigger_input_variant(transition),
8253                    binding.as_str(),
8254                    ty,
8255                );
8256                let domain = if transition_uses_tlc_representative_payload(
8257                    self.machine(instance_id),
8258                    transition,
8259                ) {
8260                    tlc_representative_domain(domain)
8261                } else {
8262                    domain
8263                };
8264                push_fmt(&mut prefix, format_args!("\\E {local} \\in {domain} : "));
8265            }
8266            let args = transition
8267                .on
8268                .bindings()
8269                .iter()
8270                .map(|binding| {
8271                    forced_bool_literals
8272                        .get(binding.as_str())
8273                        .map(|value| tla_bool_literal(*value).to_owned())
8274                        .unwrap_or_else(|| format!("arg_{}", tla_ident(binding.as_str())))
8275                })
8276                .collect::<Vec<_>>()
8277                .join(", ");
8278            format!(
8279                "{prefix}{}({args})",
8280                self.machine_transition_name(instance_id, transition)
8281            )
8282        }
8283    }
8284
8285    fn binding_domain_for_type(&self, ty: &TypeRef) -> String {
8286        match ty {
8287            TypeRef::Bool => "BOOLEAN".into(),
8288            TypeRef::U32 | TypeRef::U64 => "0..2".into(),
8289            TypeRef::String => "StringValues".into(),
8290            TypeRef::Named(_)
8291            | TypeRef::Enum(_)
8292            | TypeRef::Seq(_)
8293            | TypeRef::Set(_)
8294            | TypeRef::Option(_)
8295            | TypeRef::Map(_, _) => domain_constant_name(ty),
8296        }
8297    }
8298
8299    /// Payload domain for one bound field of `input` on `instance_id`: the
8300    /// machine's declared input field domain if it has one, otherwise the
8301    /// type's default domain.
8302    fn binding_domain_for_binding(
8303        &self,
8304        instance_id: &str,
8305        input: Option<&str>,
8306        binding: &str,
8307        ty: &TypeRef,
8308    ) -> String {
8309        let declared =
8310            input.and_then(|input| self.machine(instance_id).input_field_domain(input, binding));
8311        match declared {
8312            Some(meerkat_machine_schema::InputFieldDomainKind::StateField(state_field)) => {
8313                format!("{{{}}}", self.field_var(instance_id, state_field.as_str()))
8314            }
8315            Some(meerkat_machine_schema::InputFieldDomainKind::AdditionalValues(values)) => {
8316                additional_values_domain(&self.binding_domain_for_type(ty), values)
8317            }
8318            // A composition has no machine CI profile: it explores the
8319            // field's Deep samples, the declared values and `0..2`.
8320            Some(meerkat_machine_schema::InputFieldDomainKind::CiValues(values)) => {
8321                render_u64_set(&broad_input_samples(values))
8322            }
8323            // ... and the whole type domain of a `CiSamples` field.
8324            Some(meerkat_machine_schema::InputFieldDomainKind::CiSamples(_)) | None => {
8325                self.binding_domain_for_type(ty)
8326            }
8327        }
8328    }
8329
8330    fn machine_vars(&self) -> Vec<String> {
8331        let mut vars = Vec::new();
8332        for instance in &self.schema.machines {
8333            vars.push(self.phase_var(instance.instance_id.as_str()));
8334            let machine = self.machine(instance.instance_id.as_str());
8335            for field in &machine.state.fields {
8336                vars.push(self.field_var(instance.instance_id.as_str(), field.name.as_str()));
8337            }
8338        }
8339        vars
8340    }
8341
8342    fn machine_field_env(&self, instance_id: &str) -> BTreeMap<String, String> {
8343        let machine = self.machine(instance_id);
8344        machine
8345            .state
8346            .fields
8347            .iter()
8348            .map(|field| {
8349                (
8350                    field.name.as_str().to_owned(),
8351                    self.field_var(instance_id, field.name.as_str()),
8352                )
8353            })
8354            .collect()
8355    }
8356
8357    fn obligation_symbol_suffix(
8358        &self,
8359        protocol: &meerkat_machine_schema::EffectHandoffProtocol,
8360    ) -> String {
8361        format!(
8362            "{}_{}",
8363            tla_ident(&protocol.producer_instance),
8364            tla_ident(&protocol.name)
8365        )
8366    }
8367
8368    fn obligation_var(&self, protocol: &meerkat_machine_schema::EffectHandoffProtocol) -> String {
8369        format!("obligation_{}", self.obligation_symbol_suffix(protocol))
8370    }
8371
8372    /// Returns TLA+ variable names for obligation tracking — one per
8373    /// concrete producer/protocol pair.
8374    fn obligation_vars(&self) -> Vec<String> {
8375        self.schema
8376            .handoff_protocols
8377            .iter()
8378            .map(|protocol| self.obligation_var(protocol))
8379            .collect()
8380    }
8381
8382    fn feedback_variant(
8383        &self,
8384        feedback: &FeedbackInputRef,
8385    ) -> std::result::Result<&VariantSchema, String> {
8386        self.machine(&feedback.machine_instance)
8387            .inputs
8388            .variant_named(&feedback.input_variant)
8389            .map_err(|_| {
8390                format!(
8391                    "feedback variant `{}` not found for machine `{}`",
8392                    feedback.input_variant, feedback.machine_instance
8393                )
8394            })
8395    }
8396
8397    /// The feedback input's payload record, the quantifiers over the values it
8398    /// leaves open, and the obligation members it names. An `ObligationMember`
8399    /// value ranges over that set field of the obligation token, so the owner
8400    /// can only name a member the obligation actually carries.
8401    fn feedback_payload_expr(
8402        &self,
8403        feedback: &FeedbackInputRef,
8404        token_var: &str,
8405    ) -> std::result::Result<FeedbackPayload, String> {
8406        let variant = self.feedback_variant(feedback)?;
8407        let mut owner_context_quantifiers = Vec::new();
8408        let mut payload_fields = Vec::new();
8409        let mut members = Vec::new();
8410
8411        for field in &variant.fields {
8412            let binding = feedback
8413                .field_bindings
8414                .iter()
8415                .find(|binding| binding.input_field == field.name)
8416                .ok_or_else(|| format!("feedback binding for field `{}` not found", field.name))?;
8417            let expr = match &binding.source {
8418                FeedbackFieldSource::ObligationField(source_field) => {
8419                    format!("{token_var}.{}", tla_ident(source_field))
8420                }
8421                FeedbackFieldSource::ObligationMember(source_field) => {
8422                    let var_name = format!("member_{}", tla_ident(source_field));
8423                    owner_context_quantifiers.push(format!(
8424                        "{var_name} \\in {token_var}.{}",
8425                        tla_ident(source_field)
8426                    ));
8427                    members.push((tla_ident(source_field), var_name.clone()));
8428                    var_name
8429                }
8430                FeedbackFieldSource::OwnerContext(name) => {
8431                    let var_name = format!("owner_ctx_{}", tla_ident(name));
8432                    let domain = render_type_domain_expr(&field.ty);
8433                    owner_context_quantifiers.push(format!("{var_name} \\in {domain}"));
8434                    var_name
8435                }
8436            };
8437            payload_fields.push(format!("{} |-> {}", tla_ident(&field.name), expr));
8438        }
8439
8440        let payload_expr = if payload_fields.is_empty() {
8441            "[tag |-> \"unit\"]".to_string()
8442        } else {
8443            format!("[{}]", payload_fields.join(", "))
8444        };
8445
8446        Ok(FeedbackPayload {
8447            payload_expr,
8448            quantifiers: owner_context_quantifiers,
8449            members,
8450        })
8451    }
8452
8453    /// Obligation fields some feedback input of `protocol` names members of.
8454    /// The obligation token stays open while any of them is non-empty.
8455    fn protocol_member_fields(
8456        protocol: &meerkat_machine_schema::EffectHandoffProtocol,
8457    ) -> BTreeSet<String> {
8458        protocol
8459            .allowed_feedback_inputs
8460            .iter()
8461            .flat_map(|feedback| feedback.field_bindings.iter())
8462            .filter_map(|binding| match &binding.source {
8463                FeedbackFieldSource::ObligationMember(field) => Some(tla_ident(field)),
8464                _ => None,
8465            })
8466            .collect()
8467    }
8468
8469    /// Renders obligation closure invariants into the TLA+ output.
8470    ///
8471    /// For each handoff protocol, generates:
8472    /// - `NoOpenObligationsOnTerminal_<protocol>`: when the producer machine is
8473    ///   in a terminal phase, the obligation set must be empty.
8474    /// - `NoFeedbackWithoutObligation_<protocol>`: a feedback input can only be
8475    ///   observed if there's a corresponding outstanding obligation.
8476    fn render_obligation_invariants(
8477        &self,
8478        out: &mut String,
8479        invariant_names: &mut Vec<String>,
8480    ) -> std::result::Result<(), String> {
8481        for protocol in &self.schema.handoff_protocols {
8482            let suffix = self.obligation_symbol_suffix(protocol);
8483            let var = self.obligation_var(protocol);
8484            let phase_var = self.phase_var(&protocol.producer_instance);
8485
8486            // Find terminal phases for the producer machine.
8487            let machine = self.machine(&protocol.producer_instance);
8488            let terminal_phases: Vec<&str> = machine
8489                .state
8490                .terminal_phases
8491                .iter()
8492                .map(meerkat_machine_schema::identity::PhaseId::as_str)
8493                .collect();
8494
8495            // NoOpenObligationsOnTerminal: terminal phase => obligation set is
8496            // empty. Only an AckRequired protocol needs owner feedback to close
8497            // its obligations; under AckOrAbort and TerminalClosure the terminal
8498            // phase is itself the closure, and a PublicationOnly protocol has no
8499            // feedback (the publication closes it), so for those the invariant
8500            // would be unsatisfiable once the producer reaches a terminal phase.
8501            if terminal_closure_required(protocol, machine) {
8502                let inv_name = format!("NoOpenObligationsOnTerminal_{}", suffix);
8503                let terminal_disjuncts: Vec<String> = terminal_phases
8504                    .iter()
8505                    .map(|phase| format!("{} = {}", phase_var, tla_string(phase)))
8506                    .collect();
8507                writeln!(
8508                    out,
8509                    "{} == ({}) => {} = {{}}",
8510                    inv_name,
8511                    terminal_disjuncts.join(" \\/ "),
8512                    var
8513                )
8514                .expect("write to string");
8515                invariant_names.push(inv_name);
8516            }
8517        }
8518
8519        let owner_feedback_sources = self
8520            .schema
8521            .handoff_protocols
8522            .iter()
8523            .flat_map(|protocol| {
8524                protocol.allowed_feedback_inputs.iter().map(move |feedback| {
8525                    format!(
8526                        "(/\\ input_packet.machine = {} /\\ input_packet.variant = {} /\\ input_packet.source_machine = {} /\\ input_packet.source_effect = {} /\\ \\E effect_packet \\in emitted_effects : /\\ effect_packet.machine = {} /\\ effect_packet.variant = {} /\\ effect_packet.effect_id = input_packet.effect_id)",
8527                        tla_string(&feedback.machine_instance),
8528                        tla_string(&feedback.input_variant),
8529                        tla_string(&protocol.producer_instance),
8530                        tla_string(&protocol.effect_variant),
8531                        tla_string(&protocol.producer_instance),
8532                        tla_string(&protocol.effect_variant),
8533                    )
8534                })
8535            })
8536            .collect::<Vec<_>>();
8537        if !owner_feedback_sources.is_empty() {
8538            pushln!(out, "OwnerFeedbackHasProtocolProvenance ==");
8539            pushln!(out, "    \\A input_packet \\in observed_inputs :");
8540            pushln!(out, "        input_packet.source_kind /= \"owner\"");
8541            writeln!(
8542                out,
8543                "        \\/ ({})",
8544                owner_feedback_sources.join(" \\/ ")
8545            )
8546            .expect("write to string");
8547            invariant_names.push("OwnerFeedbackHasProtocolProvenance".to_string());
8548        }
8549
8550        if !self.schema.handoff_protocols.is_empty() {
8551            pushln!(out);
8552        }
8553        Ok(())
8554    }
8555
8556    /// Renders owner-actor process definitions: nondeterministic actions that
8557    /// model the owner choosing to submit protocol-allowed feedback when an
8558    /// obligation is outstanding.
8559    ///
8560    /// Each allowed feedback input generates an
8561    /// `OwnerFeedback_<protocol>_<input>` action that:
8562    /// - Is enabled when the obligation set is non-empty
8563    /// - Nondeterministically picks one of the allowed feedback inputs
8564    /// - Removes one obligation token from the set
8565    /// - Injects the feedback as a pending input
8566    ///
8567    /// If any protocols have `liveness_annotation`, fairness comments are added.
8568    fn render_owner_actor_processes(&self, out: &mut String) -> std::result::Result<(), String> {
8569        for protocol in &self.schema.handoff_protocols {
8570            let var = self.obligation_var(protocol);
8571
8572            if protocol.allowed_feedback_inputs.is_empty() {
8573                continue;
8574            }
8575
8576            if let Some(liveness) = &protocol.liveness_annotation {
8577                writeln!(out, "\\* Liveness: {liveness}").expect("write to string");
8578            }
8579
8580            for feedback in &protocol.allowed_feedback_inputs {
8581                let action_name = self.owner_feedback_action_name(protocol, feedback);
8582                let FeedbackPayload {
8583                    payload_expr,
8584                    quantifiers: owner_context_quantifiers,
8585                    members,
8586                } = self.feedback_payload_expr(feedback, "token")?;
8587                let input_expr = format!(
8588                    "[machine |-> {}, variant |-> {}, source_kind |-> \"owner\", source_machine |-> {}, source_effect |-> {}, source_route |-> \"none\", effect_id |-> token.effect_id, payload |-> {}]",
8589                    tla_string(&feedback.machine_instance),
8590                    tla_string(&feedback.input_variant),
8591                    tla_string(&protocol.producer_instance),
8592                    tla_string(&protocol.effect_variant),
8593                    payload_expr,
8594                );
8595
8596                writeln!(out, "{action_name} ==").expect("write to string");
8597                writeln!(out, "    /\\ {} /= {{}}", var).expect("write to string");
8598                writeln!(out, "    /\\ \\E token \\in {} :", var).expect("write to string");
8599                let quantifier_prefix = if owner_context_quantifiers.is_empty() {
8600                    String::new()
8601                } else {
8602                    format!("\\E {} : ", owner_context_quantifiers.join(", "))
8603                };
8604                // Feedback naming obligation members discharges only those
8605                // members; the token closes once every member-bearing field of
8606                // the protocol is empty. Other feedback closes the token.
8607                let obligation_update = if members.is_empty() {
8608                    format!("{var}' = {var} \\ {{token}}")
8609                } else {
8610                    let residual = format!(
8611                        "[token EXCEPT {}]",
8612                        members
8613                            .iter()
8614                            .map(|(field, member)| format!("!.{field} = @ \\ {{{member}}}"))
8615                            .collect::<Vec<_>>()
8616                            .join(", ")
8617                    );
8618                    let drained = Self::protocol_member_fields(protocol)
8619                        .iter()
8620                        .map(|field| format!("{residual}.{field} = {{}}"))
8621                        .collect::<Vec<_>>()
8622                        .join(" /\\ ");
8623                    // Parenthesised: an unbracketed ELSE would swallow the
8624                    // conjuncts that follow it in the action.
8625                    format!(
8626                        "{var}' = (IF {drained} THEN {var} \\ {{token}} ELSE ({var} \\ {{token}}) \\cup {{{residual}}})"
8627                    )
8628                };
8629                writeln!(
8630                    out,
8631                    "        /\\ {quantifier_prefix}(/\\ pending_inputs' = Append(pending_inputs, {input_expr}) /\\ observed_inputs' = observed_inputs \\cup {{{input_expr}}} /\\ {obligation_update} /\\ model_step_count' = model_step_count + 1)"
8632                )
8633                .expect("write to string");
8634
8635                let unchanged_vars: Vec<String> = self
8636                    .machine_vars()
8637                    .into_iter()
8638                    .chain(self.obligation_vars().into_iter().filter(|v| *v != var))
8639                    .chain(
8640                        [
8641                            "pending_routes",
8642                            "delivered_routes",
8643                            "emitted_effects",
8644                            "observed_transitions",
8645                            "witness_current_script_input",
8646                            "witness_remaining_script_inputs",
8647                        ]
8648                        .iter()
8649                        .map(std::string::ToString::to_string),
8650                    )
8651                    .collect();
8652                self.render_unchanged_vars(out, "    /\\ ", &unchanged_vars);
8653                pushln!(out);
8654            }
8655        }
8656        Ok(())
8657    }
8658
8659    fn render_coverage_instrumentation(&self, out: &mut String) {
8660        let route_ops = self
8661            .schema
8662            .routes
8663            .iter()
8664            .map(|route| composition_route_coverage_operator_name(&route.name))
8665            .collect::<Vec<_>>();
8666        let scheduler_ops = self
8667            .schema
8668            .scheduler_rules
8669            .iter()
8670            .map(composition_scheduler_coverage_operator_name)
8671            .collect::<Vec<_>>();
8672
8673        for route in &self.schema.routes {
8674            writeln!(
8675                out,
8676                "{} == \\E packet \\in delivered_routes : packet.route = {}",
8677                composition_route_observed_operator_name(&route.name),
8678                tla_string(&route.name)
8679            )
8680            .expect("write to string");
8681            writeln!(
8682                out,
8683                "{} == ({} \\/ ~{})",
8684                composition_route_coverage_operator_name(&route.name),
8685                composition_route_observed_operator_name(&route.name),
8686                composition_route_observed_operator_name(&route.name)
8687            )
8688            .expect("write to string");
8689        }
8690        for rule in &self.schema.scheduler_rules {
8691            writeln!(
8692                out,
8693                "{} == {}",
8694                composition_scheduler_triggered_operator_name(rule),
8695                render_scheduler_trigger_formula(rule)
8696            )
8697            .expect("write to string");
8698            writeln!(
8699                out,
8700                "{} == ({} \\/ ~{})",
8701                composition_scheduler_coverage_operator_name(rule),
8702                composition_scheduler_triggered_operator_name(rule),
8703                composition_scheduler_triggered_operator_name(rule)
8704            )
8705            .expect("write to string");
8706        }
8707
8708        let mut instrumentation_terms = Vec::new();
8709        instrumentation_terms.extend(route_ops.into_iter());
8710        instrumentation_terms.extend(scheduler_ops.into_iter());
8711
8712        let instrumentation = if instrumentation_terms.is_empty() {
8713            "TRUE".to_string()
8714        } else {
8715            instrumentation_terms.join(" /\\ ")
8716        };
8717
8718        pushln!(out, "CoverageInstrumentation == {instrumentation}");
8719        pushln!(out);
8720    }
8721
8722    /// Fail-closed resolution check for every route in the composition.
8723    ///
8724    /// Confirms that each route's `from_machine` and `to.machine` is a declared
8725    /// machine instance, that `effect_variant` is a declared effect on the
8726    /// source machine, and that `to.input_variant` is a declared input/signal
8727    /// (per `to.kind`) on the target machine. The composition CASE builders
8728    /// (`ActorOfMachine`, `RouteSource`, `RouteEffect`, `RouteTargetMachine`,
8729    /// `RouteTargetInput`) used to map an unresolved component to a sentinel
8730    /// (`"unknown_*"`) default; with this gate run first, those sentinels are
8731    /// unreachable-by-construction for valid input, and malformed input fails
8732    /// closed instead of silently emitting a broken model.
8733    fn validate_routes(&self) -> std::result::Result<(), CompositionTlaError> {
8734        let composition = self.schema.name.as_str();
8735        for route in &self.schema.routes {
8736            let route_name = route.name.as_str();
8737
8738            // Source machine instance must be declared.
8739            let source = self
8740                .machine_by_instance
8741                .get(route.from_machine.as_str())
8742                .copied()
8743                .ok_or_else(|| CompositionTlaError::UnknownRouteSourceMachine {
8744                    composition: composition.to_owned(),
8745                    route: route_name.to_owned(),
8746                    machine: route.from_machine.as_str().to_owned(),
8747                })?;
8748
8749            // Effect variant must be declared on the source machine.
8750            if source
8751                .effects
8752                .variant_named(route.effect_variant.as_str())
8753                .is_err()
8754            {
8755                return Err(CompositionTlaError::UnknownRouteEffect {
8756                    composition: composition.to_owned(),
8757                    route: route_name.to_owned(),
8758                    machine: route.from_machine.as_str().to_owned(),
8759                    effect: route.effect_variant.as_str().to_owned(),
8760                });
8761            }
8762
8763            // Target machine instance must be declared.
8764            let target = self
8765                .machine_by_instance
8766                .get(route.to.machine.as_str())
8767                .copied()
8768                .ok_or_else(|| CompositionTlaError::UnknownRouteTargetMachine {
8769                    composition: composition.to_owned(),
8770                    route: route_name.to_owned(),
8771                    machine: route.to.machine.as_str().to_owned(),
8772                })?;
8773
8774            // Target input/signal variant must be declared on the target
8775            // machine, dispatching on the route's structural kind.
8776            match route.to.kind {
8777                RouteTargetKind::Input => {
8778                    if target
8779                        .inputs
8780                        .variant_named(route.to.input_variant.as_str())
8781                        .is_err()
8782                    {
8783                        return Err(CompositionTlaError::UnknownRouteTargetInput {
8784                            composition: composition.to_owned(),
8785                            route: route_name.to_owned(),
8786                            machine: route.to.machine.as_str().to_owned(),
8787                            input: route.to.input_variant.as_str().to_owned(),
8788                        });
8789                    }
8790                }
8791                RouteTargetKind::Signal => {
8792                    if target
8793                        .signals
8794                        .variant_named(route.to.input_variant.as_str())
8795                        .is_err()
8796                    {
8797                        return Err(CompositionTlaError::UnknownRouteTargetSignal {
8798                            composition: composition.to_owned(),
8799                            route: route_name.to_owned(),
8800                            machine: route.to.machine.as_str().to_owned(),
8801                            signal: route.to.input_variant.as_str().to_owned(),
8802                        });
8803                    }
8804                }
8805            }
8806        }
8807        Ok(())
8808    }
8809
8810    fn render_static_sets(&self, out: &mut String) -> std::result::Result<(), CompositionTlaError> {
8811        pushln!(out, "Machines == {{");
8812        for (idx, machine) in self.schema.machines.iter().enumerate() {
8813            let suffix = if idx + 1 == self.schema.machines.len() {
8814                ""
8815            } else {
8816                ","
8817            };
8818            writeln!(
8819                out,
8820                "    <<{}, {}, {}>>{}",
8821                tla_string(&machine.instance_id),
8822                tla_string(&machine.machine_name),
8823                tla_string(&machine.actor),
8824                suffix
8825            )
8826            .expect("write to string");
8827        }
8828        pushln!(out, "}}");
8829        pushln!(out);
8830
8831        pushln!(out, "RouteNames == {{");
8832        for (idx, route) in self.schema.routes.iter().enumerate() {
8833            let suffix = if idx + 1 == self.schema.routes.len() {
8834                ""
8835            } else {
8836                ","
8837            };
8838            pushln!(out, "    {}{}", tla_string(&route.name), suffix);
8839        }
8840        pushln!(out, "}}");
8841        pushln!(out);
8842
8843        pushln!(out, "Actors == {{");
8844        for (idx, machine) in self.schema.machines.iter().enumerate() {
8845            let suffix = if idx + 1 == self.schema.machines.len() {
8846                ""
8847            } else {
8848                ","
8849            };
8850            pushln!(out, "    {}{}", tla_string(&machine.actor), suffix);
8851        }
8852        pushln!(out, "}}");
8853        pushln!(out);
8854
8855        pushln!(out, "ActorPriorities == {{");
8856        for (idx, priority) in self.schema.actor_priorities.iter().enumerate() {
8857            let suffix = if idx + 1 == self.schema.actor_priorities.len() {
8858                ""
8859            } else {
8860                ","
8861            };
8862            writeln!(
8863                out,
8864                "    <<{}, {}>>{}",
8865                tla_string(&priority.higher),
8866                tla_string(&priority.lower),
8867                suffix
8868            )
8869            .expect("write to string");
8870        }
8871        pushln!(out, "}}");
8872        pushln!(out);
8873
8874        pushln!(out, "SchedulerRules == {{");
8875        for (idx, rule) in self.schema.scheduler_rules.iter().enumerate() {
8876            let suffix = if idx + 1 == self.schema.scheduler_rules.len() {
8877                ""
8878            } else {
8879                ","
8880            };
8881            pushln!(out, "    {}{}", render_scheduler_rule_tuple(rule), suffix);
8882        }
8883        writeln!(out, "}}");
8884        pushln!(out);
8885
8886        let composition_name = self.schema.name.as_str();
8887        render_composition_case_fn(
8888            out,
8889            composition_name,
8890            "ActorOfMachine",
8891            "machine_id",
8892            self.schema
8893                .machines
8894                .iter()
8895                .map(|machine| (machine.instance_id.as_str(), tla_string(&machine.actor)))
8896                .collect(),
8897            CaseDefault::FailClosed {
8898                component: "actor",
8899                require_mapping: true,
8900            },
8901        )?;
8902        render_composition_case_fn(
8903            out,
8904            composition_name,
8905            "RouteSource",
8906            "route_name",
8907            self.schema
8908                .routes
8909                .iter()
8910                .map(|route| (route.name.as_str(), tla_string(&route.from_machine)))
8911                .collect(),
8912            CaseDefault::FailClosed {
8913                component: "route_source_machine",
8914                require_mapping: false,
8915            },
8916        )?;
8917        render_composition_case_fn(
8918            out,
8919            composition_name,
8920            "RouteEffect",
8921            "route_name",
8922            self.schema
8923                .routes
8924                .iter()
8925                .map(|route| (route.name.as_str(), tla_string(&route.effect_variant)))
8926                .collect(),
8927            CaseDefault::FailClosed {
8928                component: "route_effect",
8929                require_mapping: false,
8930            },
8931        )?;
8932        render_composition_case_fn(
8933            out,
8934            composition_name,
8935            "RouteTargetMachine",
8936            "route_name",
8937            self.schema
8938                .routes
8939                .iter()
8940                .map(|route| (route.name.as_str(), tla_string(&route.to.machine)))
8941                .collect(),
8942            CaseDefault::FailClosed {
8943                component: "route_target_machine",
8944                require_mapping: false,
8945            },
8946        )?;
8947        render_composition_case_fn(
8948            out,
8949            composition_name,
8950            "RouteTargetInput",
8951            "route_name",
8952            self.schema
8953                .routes
8954                .iter()
8955                .map(|route| (route.name.as_str(), tla_string(&route.to.input_variant)))
8956                .collect(),
8957            CaseDefault::FailClosed {
8958                component: "route_target_input",
8959                require_mapping: false,
8960            },
8961        )?;
8962        render_composition_case_fn(
8963            out,
8964            composition_name,
8965            "RouteTargetKind",
8966            "route_name",
8967            self.schema
8968                .routes
8969                .iter()
8970                .map(|route| {
8971                    (
8972                        route.name.as_str(),
8973                        tla_string(match route.to.kind {
8974                            RouteTargetKind::Input => "Input",
8975                            RouteTargetKind::Signal => "Signal",
8976                        }),
8977                    )
8978                })
8979                .collect(),
8980            CaseDefault::ClosedEnum(tla_string("Unknown")),
8981        )?;
8982        render_composition_case_fn(
8983            out,
8984            composition_name,
8985            "RouteDeliveryKind",
8986            "route_name",
8987            self.schema
8988                .routes
8989                .iter()
8990                .map(|route| {
8991                    (
8992                        route.name.as_str(),
8993                        tla_string(match route.delivery {
8994                            RouteDelivery::Immediate => "Immediate",
8995                            RouteDelivery::Enqueue => "Enqueue",
8996                        }),
8997                    )
8998                })
8999                .collect(),
9000            CaseDefault::ClosedEnum(tla_string("Unknown")),
9001        )?;
9002        writeln!(
9003            out,
9004            "RouteTargetActor(route_name) == ActorOfMachine(RouteTargetMachine(route_name))"
9005        );
9006        pushln!(out);
9007        Ok(())
9008    }
9009
9010    fn render_entry_input_actions(&self, out: &mut String) {
9011        for entry_input in &self.schema.entry_inputs {
9012            let machine = self.machine(entry_input.machine.as_str());
9013            let Ok(variant) = machine.inputs.variant_named(&entry_input.input_variant) else {
9014                continue;
9015            };
9016            let action_name = self.entry_input_action_name(entry_input);
9017            let params = variant
9018                .fields
9019                .iter()
9020                .map(|field| format!("arg_{}", tla_ident(&field.name)))
9021                .collect::<Vec<_>>();
9022            let packet_expr = self.input_packet_expr(
9023                entry_input.machine.as_str(),
9024                &entry_input.input_variant,
9025                &variant
9026                    .fields
9027                    .iter()
9028                    .map(|field| {
9029                        (
9030                            field.name.as_str().to_owned(),
9031                            format!("arg_{}", tla_ident(&field.name)),
9032                        )
9033                    })
9034                    .collect::<BTreeMap<String, _>>(),
9035                "entry",
9036                &entry_input.name,
9037                "external_entry",
9038                &entry_input.input_variant,
9039                "0",
9040            );
9041
9042            if params.is_empty() {
9043                pushln!(out, "{} ==", action_name);
9044            } else {
9045                pushln!(out, "{}({}) ==", action_name, params.join(", "));
9046            }
9047            writeln!(
9048                out,
9049                "    /\\ ~({} \\in SeqElements(pending_inputs))",
9050                packet_expr
9051            )
9052            .expect("write to string");
9053            writeln!(out, "    /\\ EntryPacketAdmissible({packet_expr})").expect("write to string");
9054            writeln!(
9055                out,
9056                "    /\\ pending_inputs' = Append(pending_inputs, {})",
9057                packet_expr
9058            )
9059            .expect("write to string");
9060            writeln!(
9061                out,
9062                "    /\\ observed_inputs' = observed_inputs \\cup {{{}}}",
9063                packet_expr
9064            )
9065            .expect("write to string");
9066            writeln!(out, "    /\\ model_step_count' = model_step_count + 1")
9067                .expect("write to string");
9068            {
9069                let mut unchanged = self.machine_vars();
9070                unchanged.extend(self.obligation_vars());
9071                unchanged.extend([
9072                    "pending_routes".into(),
9073                    "delivered_routes".into(),
9074                    "emitted_effects".into(),
9075                    "observed_transitions".into(),
9076                    "witness_current_script_input".into(),
9077                    "witness_remaining_script_inputs".into(),
9078                ]);
9079                self.render_unchanged_vars(out, "    /\\ ", &unchanged);
9080            }
9081            pushln!(out);
9082        }
9083    }
9084
9085    fn render_entry_input_call(&self, entry_input: &EntryInput) -> String {
9086        let machine = self.machine(entry_input.machine.as_str());
9087        let Ok(variant) = machine.inputs.variant_named(&entry_input.input_variant) else {
9088            return self.entry_input_action_name(entry_input);
9089        };
9090        let action_name = self.entry_input_action_name(entry_input);
9091        if variant.fields.is_empty() {
9092            action_name
9093        } else {
9094            let prefix = variant
9095                .fields
9096                .iter()
9097                .map(|field| {
9098                    let local = format!("arg_{}", tla_ident(&field.name));
9099                    let domain = self.binding_domain_for_type(&field.ty);
9100                    format!("\\E {local} \\in {domain} : ")
9101                })
9102                .collect::<String>();
9103            let args = variant
9104                .fields
9105                .iter()
9106                .map(|field| format!("arg_{}", tla_ident(&field.name)))
9107                .collect::<Vec<_>>()
9108                .join(", ");
9109            format!("{prefix}{action_name}({args})")
9110        }
9111    }
9112
9113    fn render_deliver_queued_route_action(&self, out: &mut String) {
9114        writeln!(out, "DeliverQueuedRoute ==");
9115        pushln!(out, "    /\\ Len(pending_routes) > 0");
9116        pushln!(out, "    /\\ LET route == Head(pending_routes) IN");
9117        pushln!(out, "       /\\ pending_routes' = Tail(pending_routes)");
9118        writeln!(
9119            out,
9120            "       /\\ delivered_routes' = delivered_routes \\cup {{route}}"
9121        )
9122        .expect("write to string");
9123        writeln!(out, "       /\\ model_step_count' = model_step_count + 1")
9124            .expect("write to string");
9125        writeln!(
9126            out,
9127            "       /\\ pending_inputs' = AppendIfMissing(pending_inputs, [machine |-> route.target_machine, variant |-> route.target_input, payload |-> route.payload, source_kind |-> \"route\", source_route |-> route.route, source_machine |-> route.source_machine, source_effect |-> route.effect, effect_id |-> route.effect_id])"
9128        )
9129        .expect("write to string");
9130        writeln!(
9131            out,
9132            "       /\\ observed_inputs' = observed_inputs \\cup {{[machine |-> route.target_machine, variant |-> route.target_input, payload |-> route.payload, source_kind |-> \"route\", source_route |-> route.route, source_machine |-> route.source_machine, source_effect |-> route.effect, effect_id |-> route.effect_id]}}"
9133        )
9134        .expect("write to string");
9135        {
9136            let mut unchanged = self.machine_vars();
9137            unchanged.extend(self.obligation_vars());
9138            unchanged.extend([
9139                "emitted_effects".into(),
9140                "observed_transitions".into(),
9141                "witness_current_script_input".into(),
9142                "witness_remaining_script_inputs".into(),
9143            ]);
9144            self.render_unchanged_vars(out, "       /\\ ", &unchanged);
9145        }
9146        pushln!(out);
9147    }
9148
9149    fn entry_packet_admissibility_name(&self, instance_id: &str) -> String {
9150        format!("EntryPacketAdmissible_{}", tla_ident(instance_id))
9151    }
9152
9153    fn render_entry_packet_admissibility_helpers(
9154        &self,
9155        out: &mut String,
9156    ) -> std::result::Result<(), CompositionTlaError> {
9157        if self.schema.entry_inputs.is_empty()
9158            && !self
9159                .schema
9160                .witnesses
9161                .iter()
9162                .any(|witness| !witness.preload_inputs.is_empty())
9163        {
9164            return Ok(());
9165        }
9166
9167        for instance in &self.schema.machines {
9168            let machine = self.machine(instance.instance_id.as_str());
9169            let helper_prefix = format!("{}__entry_packet__", tla_ident(&instance.instance_id));
9170            let mut compiler = self.instance_compiler(instance.instance_id.as_str(), helper_prefix);
9171
9172            for derived in helper_dependency_order(machine)? {
9173                compiler.render_helper(out, derived);
9174                pushln!(out);
9175            }
9176            if machine.machine.as_str() == "MobMachine" {
9177                compiler.render_mob_machine_native_helpers(out);
9178                pushln!(out);
9179            }
9180            if machine.machine.as_str() == "MeerkatMachine" {
9181                compiler.render_meerkat_machine_native_helpers(out);
9182                pushln!(out);
9183            }
9184            if machine.machine.as_str() == "RuntimeDeliveryMachine" {
9185                compiler.render_runtime_delivery_native_helpers(out);
9186                pushln!(out);
9187            }
9188            if machine.machine.as_str() == "SessionDocumentMachine" {
9189                compiler.render_session_document_native_helpers(out);
9190                pushln!(out);
9191            }
9192
9193            let branches = machine
9194                .transitions
9195                .iter()
9196                .map(|transition| {
9197                    self.render_machine_packet_admissibility_branch(
9198                        &mut compiler,
9199                        instance.instance_id.as_str(),
9200                        transition,
9201                    )
9202                })
9203                .collect::<Vec<_>>();
9204
9205            for helper in &compiler.helper_defs {
9206                pushln!(out, "{helper}");
9207                pushln!(out);
9208            }
9209
9210            writeln!(
9211                out,
9212                "{}(packet) ==",
9213                self.entry_packet_admissibility_name(instance.instance_id.as_str())
9214            )
9215            .expect("write to string");
9216            if branches.is_empty() {
9217                pushln!(out, "    FALSE");
9218            } else {
9219                for branch in &branches {
9220                    pushln!(out, "    \\/ {branch}");
9221                }
9222            }
9223            pushln!(out);
9224        }
9225
9226        writeln!(out, "EntryPacketAdmissible(packet) ==").expect("write to string");
9227        pushln!(out, "    CASE");
9228        for (idx, instance) in self.schema.machines.iter().enumerate() {
9229            let prefix = if idx == 0 { "      " } else { "      [] " };
9230            writeln!(
9231                out,
9232                "{}packet.machine = {} -> {}(packet)",
9233                prefix,
9234                tla_string(&instance.instance_id),
9235                self.entry_packet_admissibility_name(instance.instance_id.as_str())
9236            )
9237            .expect("write to string");
9238        }
9239        pushln!(out, "      [] OTHER -> FALSE");
9240        pushln!(out);
9241        Ok(())
9242    }
9243
9244    fn render_machine_packet_admissibility_branch(
9245        &self,
9246        compiler: &mut MachineTlaCompiler<'_>,
9247        instance_id: &str,
9248        transition: &TransitionSchema,
9249    ) -> String {
9250        let phase_var = self.phase_var(instance_id);
9251        let from_guard = if transition.from.len() == 1 {
9252            format!("{phase_var} = {}", tla_string(&transition.from[0]))
9253        } else {
9254            transition
9255                .from
9256                .iter()
9257                .map(|phase| format!("{phase_var} = {}", tla_string(phase)))
9258                .collect::<Vec<_>>()
9259                .join(" \\/ ")
9260        };
9261
9262        let binding_types = compiler.binding_type_map(transition);
9263        let binding_env = transition
9264            .on
9265            .bindings()
9266            .iter()
9267            .map(|binding| {
9268                (
9269                    binding.as_str().to_owned(),
9270                    format!("packet.payload.{}", tla_ident(binding)),
9271                )
9272            })
9273            .collect::<BTreeMap<_, _>>();
9274        let field_env = self.machine_field_env(instance_id);
9275
9276        let mut clauses = vec![
9277            format!(
9278                "packet.variant = {}",
9279                tla_string(transition.on.variant_str())
9280            ),
9281            from_guard,
9282        ];
9283        clauses.extend(
9284            transition.guards.iter().map(|guard| {
9285                compiler.render_guard(guard, &field_env, &binding_env, &binding_types)
9286            }),
9287        );
9288
9289        format!(
9290            "/\\ {}",
9291            clauses
9292                .into_iter()
9293                .map(|clause| format!("({clause})"))
9294                .collect::<Vec<_>>()
9295                .join(" /\\ ")
9296        )
9297    }
9298
9299    fn render_reject_pending_entry_input_action(&self, out: &mut String) {
9300        if self.schema.entry_inputs.is_empty() {
9301            return;
9302        }
9303
9304        writeln!(out, "RejectPendingEntryInput ==").expect("write to string");
9305        pushln!(out, "    /\\ \\E packet \\in SeqElements(pending_inputs) :");
9306        pushln!(out, "       /\\ packet.source_kind = \"entry\"");
9307        pushln!(out, "       /\\ ~EntryPacketAdmissible(packet)");
9308        pushln!(
9309            out,
9310            "       /\\ pending_inputs' = SeqRemove(pending_inputs, packet)"
9311        );
9312        pushln!(out, "       /\\ observed_inputs' = observed_inputs");
9313        pushln!(out, "       /\\ pending_routes' = pending_routes");
9314        pushln!(out, "       /\\ delivered_routes' = delivered_routes");
9315        pushln!(out, "       /\\ emitted_effects' = emitted_effects");
9316        pushln!(
9317            out,
9318            "       /\\ observed_transitions' = observed_transitions"
9319        );
9320        writeln!(out, "       /\\ model_step_count' = model_step_count + 1")
9321            .expect("write to string");
9322        let mut unchanged = self.machine_vars();
9323        unchanged.extend(self.obligation_vars());
9324        unchanged.extend([
9325            "witness_current_script_input".into(),
9326            "witness_remaining_script_inputs".into(),
9327        ]);
9328        self.render_unchanged_vars(out, "       /\\ ", &unchanged);
9329        pushln!(out);
9330    }
9331
9332    fn render_quiescent_stutter(&self, out: &mut String) {
9333        writeln!(out, "QuiescentStutter ==");
9334        pushln!(out, "    /\\ Len(pending_routes) = 0");
9335        pushln!(out, "    /\\ Len(pending_inputs) = 0");
9336        pushln!(out, "    /\\ UNCHANGED vars");
9337        pushln!(out);
9338    }
9339
9340    fn render_witness_inject_next_call(&self, witness: &CompositionWitness) -> String {
9341        format!("WitnessInjectNext_{}", tla_ident(&witness.name))
9342    }
9343
9344    fn render_witness_satisfied_stutter_call(&self, witness: &CompositionWitness) -> String {
9345        format!("WitnessSatisfiedStutter_{}", tla_ident(&witness.name))
9346    }
9347
9348    fn core_next_branches(&self) -> Vec<String> {
9349        let mut branches = Vec::new();
9350        if !self.schema.routes.is_empty() {
9351            branches.push("DeliverQueuedRoute".into());
9352        }
9353        if !self.schema.entry_inputs.is_empty() {
9354            branches.push("RejectPendingEntryInput".into());
9355        }
9356        for instance in &self.schema.machines {
9357            let machine = self.machine(instance.instance_id.as_str());
9358            for transition in &machine.transitions {
9359                branches
9360                    .push(self.machine_transition_call(instance.instance_id.as_str(), transition));
9361            }
9362        }
9363        branches.extend(self.owner_feedback_branches());
9364        branches.push("QuiescentStutter".into());
9365        branches
9366    }
9367
9368    fn owner_feedback_branches(&self) -> Vec<String> {
9369        self.schema
9370            .handoff_protocols
9371            .iter()
9372            .flat_map(|protocol| {
9373                protocol
9374                    .allowed_feedback_inputs
9375                    .iter()
9376                    .map(move |feedback| self.owner_feedback_action_name(protocol, feedback))
9377            })
9378            .collect()
9379    }
9380
9381    fn owner_feedback_action_name(
9382        &self,
9383        protocol: &meerkat_machine_schema::EffectHandoffProtocol,
9384        feedback: &FeedbackInputRef,
9385    ) -> String {
9386        format!(
9387            "OwnerFeedback_{}_{}",
9388            self.obligation_symbol_suffix(protocol),
9389            tla_ident(&feedback.input_variant)
9390        )
9391    }
9392
9393    fn witness_owner_feedback_branches(&self, witness: &CompositionWitness) -> Vec<String> {
9394        let expected_inputs = witness
9395            .expected_transitions
9396            .iter()
9397            .filter_map(|expected| {
9398                let machine = self.machine_by_instance.get(expected.machine.as_str())?;
9399                let transition = machine
9400                    .transitions
9401                    .iter()
9402                    .find(|transition| transition.name == expected.transition)?;
9403                match &transition.on {
9404                    TriggerMatch::Input { variant, .. } => {
9405                        Some((expected.machine.clone(), variant.clone()))
9406                    }
9407                    TriggerMatch::Signal { .. } => None,
9408                }
9409            })
9410            .collect::<BTreeSet<_>>();
9411
9412        let ordered_predecessor_effects = witness
9413            .expected_transition_order
9414            .iter()
9415            .filter_map(|order| {
9416                let predecessor_machine = self
9417                    .machine_by_instance
9418                    .get(order.earlier.machine.as_str())?;
9419                let predecessor = predecessor_machine
9420                    .transitions
9421                    .iter()
9422                    .find(|transition| transition.name == order.earlier.transition)?;
9423                Some((
9424                    (order.later.machine.clone(), order.later.transition.clone()),
9425                    predecessor
9426                        .emit
9427                        .iter()
9428                        .map(|effect| (order.earlier.machine.clone(), effect.variant.clone()))
9429                        .collect::<BTreeSet<_>>(),
9430                ))
9431            })
9432            .fold(
9433                BTreeMap::<_, BTreeSet<_>>::new(),
9434                |mut effects, (transition, predecessor_effects)| {
9435                    effects
9436                        .entry(transition)
9437                        .or_default()
9438                        .extend(predecessor_effects);
9439                    effects
9440                },
9441            );
9442
9443        self.schema
9444            .handoff_protocols
9445            .iter()
9446            .flat_map(|protocol| {
9447                protocol
9448                    .allowed_feedback_inputs
9449                    .iter()
9450                    .filter_map(|feedback| {
9451                        let input = (
9452                            feedback.machine_instance.clone(),
9453                            feedback.input_variant.clone(),
9454                        );
9455                        if !expected_inputs.contains(&input) {
9456                            return None;
9457                        }
9458                        let receiver_machine = self
9459                            .machine_by_instance
9460                            .get(feedback.machine_instance.as_str())?;
9461                        let receiver = receiver_machine.transitions.iter().find(|transition| {
9462                            matches!(
9463                                &transition.on,
9464                                TriggerMatch::Input { variant, .. }
9465                                    if variant == &feedback.input_variant
9466                            )
9467                        })?;
9468                        let receiver_key =
9469                            (feedback.machine_instance.clone(), receiver.name.clone());
9470                        if let Some(predecessor_effects) =
9471                            ordered_predecessor_effects.get(&receiver_key)
9472                        {
9473                            let producer = (
9474                                protocol.producer_instance.clone(),
9475                                protocol.effect_variant.clone(),
9476                            );
9477                            if !predecessor_effects.contains(&producer) {
9478                                return None;
9479                            }
9480                        }
9481                        Some(self.owner_feedback_action_name(protocol, feedback))
9482                    })
9483            })
9484            .collect::<BTreeSet<_>>()
9485            .into_iter()
9486            .collect()
9487    }
9488
9489    fn witness_next_branches(
9490        &self,
9491        witness: &CompositionWitness,
9492    ) -> Result<Vec<String>, CompositionTlaError> {
9493        if !Self::witness_has_explicit_progress(witness) {
9494            let mut branches = vec!["CoreNext".into()];
9495            branches.push(self.render_witness_satisfied_stutter_call(witness));
9496            return Ok(branches);
9497        }
9498        let mut branches = self.witness_progress_branches(witness)?;
9499        branches.push(self.render_witness_satisfied_stutter_call(witness));
9500        Ok(branches)
9501    }
9502
9503    fn witness_progress_branches(
9504        &self,
9505        witness: &CompositionWitness,
9506    ) -> Result<Vec<String>, CompositionTlaError> {
9507        let mut branches = Vec::new();
9508        if !witness.expected_routes.is_empty() {
9509            branches.push("DeliverQueuedRoute".into());
9510        }
9511        for expected in &witness.expected_transitions {
9512            branches.push(self.witness_transition_call(witness, expected)?);
9513        }
9514        branches.extend(self.witness_owner_feedback_branches(witness));
9515        Ok(branches)
9516    }
9517
9518    fn witness_transition_call(
9519        &self,
9520        witness: &CompositionWitness,
9521        expected: &meerkat_machine_schema::CompositionWitnessTransition,
9522    ) -> Result<String, CompositionTlaError> {
9523        let machine = self
9524            .machine_by_instance
9525            .get(expected.machine.as_str())
9526            .ok_or_else(|| CompositionTlaError::UnknownWitnessMachine {
9527                composition: self.schema.name.to_string(),
9528                witness: witness.name.to_string(),
9529                machine: expected.machine.to_string(),
9530            })?;
9531        let transition = machine
9532            .transitions
9533            .iter()
9534            .find(|transition| transition.name == expected.transition)
9535            .ok_or_else(|| CompositionTlaError::UnknownWitnessTransition {
9536                composition: self.schema.name.to_string(),
9537                witness: witness.name.to_string(),
9538                machine: expected.machine.to_string(),
9539                transition: expected.transition.to_string(),
9540            })?;
9541        if transition.on.bindings().is_empty() {
9542            return Ok(self.machine_transition_name(expected.machine.as_str(), transition));
9543        }
9544        // A scripted witness supplies exact typed packets. Sampling the ordinary
9545        // exploration domains again can make those packets impossible to consume
9546        // (for example, revisions 3 and 4 outside the bounded 0..2 sample).
9547        // Reuse the same guarded action with the queued payload, without changing
9548        // ordinary exploration bounds or bypassing action admission checks.
9549        let args = transition
9550            .on
9551            .bindings()
9552            .iter()
9553            .map(|binding| format!("witness_packet.payload.{}", tla_ident(binding)))
9554            .collect::<Vec<_>>()
9555            .join(", ");
9556        Ok(format!(
9557            "\\E witness_packet \\in SeqElements(pending_inputs) : /\\ witness_packet.machine = {} /\\ witness_packet.variant = {} /\\ {}({args})",
9558            tla_string(expected.machine.as_str()),
9559            tla_string(transition.on.variant_str()),
9560            self.machine_transition_name(expected.machine.as_str(), transition),
9561        ))
9562    }
9563
9564    fn witness_fairness_clauses(
9565        &self,
9566        witness: &CompositionWitness,
9567    ) -> Result<Vec<String>, CompositionTlaError> {
9568        if Self::witness_has_explicit_progress(witness) {
9569            return Ok(Vec::new());
9570        }
9571
9572        let mut clauses = self.core_fairness_clauses();
9573        if witness.preload_inputs.len() > 1 {
9574            clauses.push(self.render_witness_inject_next_call(witness));
9575        }
9576        Ok(clauses)
9577    }
9578
9579    fn core_fairness_clauses(&self) -> Vec<String> {
9580        let mut clauses = Vec::new();
9581        if !self.schema.routes.is_empty() {
9582            clauses.push("DeliverQueuedRoute".into());
9583        }
9584        if !self.schema.entry_inputs.is_empty() {
9585            clauses.push("RejectPendingEntryInput".into());
9586        }
9587        clauses.extend(self.schema.machines.iter().flat_map(|instance| {
9588            let machine = self.machine(instance.instance_id.as_str());
9589            machine
9590                .transitions
9591                .iter()
9592                .map(|transition| {
9593                    self.machine_transition_call(instance.instance_id.as_str(), transition)
9594                })
9595                .collect::<Vec<_>>()
9596        }));
9597        clauses
9598    }
9599
9600    fn witness_has_explicit_progress(witness: &CompositionWitness) -> bool {
9601        !witness.preload_inputs.is_empty() || !witness.expected_transitions.is_empty()
9602    }
9603
9604    fn entry_input_action_name(&self, entry_input: &EntryInput) -> String {
9605        format!("Inject_{}", tla_ident(&entry_input.name))
9606    }
9607
9608    fn input_packet_expr(
9609        &self,
9610        machine_id: impl AsRef<str>,
9611        input_variant: impl AsRef<str>,
9612        payload_fields: &BTreeMap<String, String>,
9613        source_kind: impl AsRef<str>,
9614        source_route: impl AsRef<str>,
9615        source_machine: impl AsRef<str>,
9616        source_effect: impl AsRef<str>,
9617        effect_id: impl AsRef<str>,
9618    ) -> String {
9619        format!(
9620            "[machine |-> {}, variant |-> {}, payload |-> {}, source_kind |-> {}, source_route |-> {}, source_machine |-> {}, source_effect |-> {}, effect_id |-> {}]",
9621            tla_string(machine_id),
9622            tla_string(input_variant),
9623            self.payload_record_expr(payload_fields),
9624            tla_string(source_kind),
9625            tla_string(source_route),
9626            tla_string(source_machine),
9627            tla_string(source_effect),
9628            effect_id.as_ref()
9629        )
9630    }
9631
9632    fn input_packet_expr_from_payload_expr(
9633        &self,
9634        machine_id: impl AsRef<str>,
9635        input_variant: impl AsRef<str>,
9636        payload_expr: &str,
9637        source_kind: impl AsRef<str>,
9638        source_route: impl AsRef<str>,
9639        source_machine: impl AsRef<str>,
9640        source_effect: impl AsRef<str>,
9641        effect_id: impl AsRef<str>,
9642    ) -> String {
9643        format!(
9644            "[machine |-> {}, variant |-> {}, payload |-> {}, source_kind |-> {}, source_route |-> {}, source_machine |-> {}, source_effect |-> {}, effect_id |-> {}]",
9645            tla_string(machine_id),
9646            tla_string(input_variant),
9647            payload_expr,
9648            tla_string(source_kind),
9649            tla_string(source_route),
9650            tla_string(source_machine),
9651            tla_string(source_effect),
9652            effect_id.as_ref()
9653        )
9654    }
9655
9656    fn payload_record_expr(&self, payload_fields: &BTreeMap<String, String>) -> String {
9657        if payload_fields.is_empty() {
9658            "[tag |-> \"unit\"]".into()
9659        } else {
9660            format!(
9661                "[{}]",
9662                payload_fields
9663                    .iter()
9664                    .map(|(field, expr)| format!("{field} |-> {expr}"))
9665                    .collect::<Vec<_>>()
9666                    .join(", ")
9667            )
9668        }
9669    }
9670
9671    fn witness_packet_exprs(&self, witness: &CompositionWitness) -> Vec<String> {
9672        witness
9673            .preload_inputs
9674            .iter()
9675            .enumerate()
9676            .map(|(idx, packet)| {
9677                let payload_fields = packet
9678                    .fields
9679                    .iter()
9680                    .map(|field| {
9681                        (
9682                            field.field.as_str().to_owned(),
9683                            self.render_literal_expr(&field.expr),
9684                        )
9685                    })
9686                    .collect::<BTreeMap<String, _>>();
9687                self.input_packet_expr(
9688                    packet.machine.as_str(),
9689                    packet.input_variant.as_str(),
9690                    &payload_fields,
9691                    "entry",
9692                    format!("witness:{}:{}", witness.name, idx + 1),
9693                    "external_entry",
9694                    &packet.input_variant,
9695                    "0",
9696                )
9697            })
9698            .collect()
9699    }
9700
9701    fn witness_initial_batch_size(&self, witness: &CompositionWitness) -> usize {
9702        if witness.expected_scheduler_rules.is_empty() {
9703            1
9704        } else {
9705            witness.preload_inputs.len().min(2).max(1)
9706        }
9707    }
9708
9709    fn witness_initial_observed_inputs_expr(&self, witness: &CompositionWitness) -> String {
9710        let packets = self.witness_packet_exprs(witness);
9711        let batch_size = self.witness_initial_batch_size(witness);
9712        if packets.is_empty() {
9713            "{}".into()
9714        } else {
9715            format!(
9716                "{{{}}}",
9717                packets
9718                    .into_iter()
9719                    .take(batch_size)
9720                    .collect::<Vec<_>>()
9721                    .join(", ")
9722            )
9723        }
9724    }
9725
9726    fn witness_initial_pending_inputs_expr(&self, witness: &CompositionWitness) -> String {
9727        let packets = self.witness_packet_exprs(witness);
9728        let batch_size = self.witness_initial_batch_size(witness);
9729        if packets.is_empty() {
9730            "<<>>".into()
9731        } else {
9732            format!(
9733                "<<{}>>",
9734                packets
9735                    .into_iter()
9736                    .take(batch_size)
9737                    .collect::<Vec<_>>()
9738                    .join(", ")
9739            )
9740        }
9741    }
9742
9743    fn witness_current_script_input_expr(&self, witness: &CompositionWitness) -> String {
9744        let packets = self.witness_packet_exprs(witness);
9745        let batch_size = self.witness_initial_batch_size(witness);
9746        packets
9747            .into_iter()
9748            .take(batch_size)
9749            .last()
9750            .unwrap_or_else(|| "None".into())
9751    }
9752
9753    fn witness_remaining_script_inputs_expr(&self, witness: &CompositionWitness) -> String {
9754        let packets = self.witness_packet_exprs(witness);
9755        let batch_size = self.witness_initial_batch_size(witness);
9756        if packets.len() <= batch_size {
9757            return "<<>>".into();
9758        }
9759
9760        format!(
9761            "<<{}>>",
9762            packets
9763                .into_iter()
9764                .skip(batch_size)
9765                .collect::<Vec<_>>()
9766                .join(", ")
9767        )
9768    }
9769
9770    fn render_witness_inject_actions(&self, out: &mut String) {
9771        for witness in &self.schema.witnesses {
9772            let action_name = self.render_witness_inject_next_call(witness);
9773            pushln!(out, "{action_name} ==");
9774            if witness.preload_inputs.len() <= 1 {
9775                pushln!(out, "    FALSE");
9776                pushln!(out);
9777                continue;
9778            }
9779
9780            pushln!(
9781                out,
9782                "    LET next_script_input == IF Len(witness_remaining_script_inputs) > 0 THEN Head(witness_remaining_script_inputs) ELSE witness_current_script_input"
9783            );
9784            pushln!(
9785                out,
9786                "        next_remaining_script_inputs == IF Len(witness_remaining_script_inputs) > 0 THEN Tail(witness_remaining_script_inputs) ELSE <<>>"
9787            );
9788            pushln!(out, "    IN");
9789            pushln!(out, "    /\\ witness_current_script_input # None");
9790            writeln!(
9791                out,
9792                "    /\\ ~(witness_current_script_input \\in SeqElements(pending_inputs))"
9793            )
9794            .expect("write to string");
9795            pushln!(out, "    /\\ EntryPacketAdmissible(next_script_input)");
9796            pushln!(out, "    /\\ Len(pending_inputs) = 0");
9797            pushln!(out, "    /\\ Len(pending_routes) = 0");
9798            pushln!(out, "    /\\ Len(witness_remaining_script_inputs) > 0");
9799            writeln!(
9800                out,
9801                "    /\\ pending_inputs' = Append(pending_inputs, next_script_input)"
9802            )
9803            .expect("write to string");
9804            writeln!(
9805                out,
9806                "    /\\ observed_inputs' = observed_inputs \\cup {{next_script_input}}"
9807            )
9808            .expect("write to string");
9809            writeln!(
9810                out,
9811                "    /\\ witness_current_script_input' = next_script_input"
9812            )
9813            .expect("write to string");
9814            writeln!(
9815                out,
9816                "    /\\ witness_remaining_script_inputs' = next_remaining_script_inputs"
9817            )
9818            .expect("write to string");
9819            writeln!(out, "    /\\ model_step_count' = model_step_count + 1")
9820                .expect("write to string");
9821            {
9822                let mut unchanged = self.machine_vars();
9823                unchanged.extend(self.obligation_vars());
9824                unchanged.extend([
9825                    "pending_routes".into(),
9826                    "delivered_routes".into(),
9827                    "emitted_effects".into(),
9828                    "observed_transitions".into(),
9829                ]);
9830                self.render_unchanged_vars(out, "    /\\ ", &unchanged);
9831            }
9832            pushln!(out);
9833        }
9834    }
9835
9836    fn render_witness_satisfied_stutter_actions(&self, out: &mut String) {
9837        for witness in &self.schema.witnesses {
9838            let action_name = self.render_witness_satisfied_stutter_call(witness);
9839            pushln!(out, "{action_name} ==");
9840            let mut conditions = self.witness_satisfaction_conditions(witness);
9841            if Self::witness_has_explicit_progress(witness) {
9842                conditions.insert(0, composition_witness_completion_name(&witness.name));
9843            }
9844            if conditions.is_empty() {
9845                pushln!(out, "    /\\ FALSE");
9846            } else {
9847                for condition in conditions {
9848                    pushln!(out, "    /\\ {condition}");
9849                }
9850                pushln!(out, "    /\\ UNCHANGED vars");
9851            }
9852            pushln!(out);
9853        }
9854    }
9855
9856    fn render_witness_completion_operators(&self, out: &mut String) {
9857        for witness in &self.schema.witnesses {
9858            if !Self::witness_has_explicit_progress(witness) {
9859                continue;
9860            }
9861            writeln!(
9862                out,
9863                "{} ==",
9864                composition_witness_completion_name(&witness.name)
9865            )
9866            .expect("write to string");
9867            pushln!(out, "    /\\ Len(witness_remaining_script_inputs) = 0");
9868            pushln!(
9869                out,
9870                "    /\\ ~(witness_current_script_input \\in SeqElements(pending_inputs))"
9871            );
9872            pushln!(out, "    /\\ Len(pending_routes) = 0");
9873            for condition in self.witness_satisfaction_conditions(witness) {
9874                pushln!(out, "    /\\ {condition}");
9875            }
9876            pushln!(out);
9877        }
9878    }
9879
9880    fn render_witness_action_constraint_operators(&self, out: &mut String) {
9881        for witness in &self.schema.witnesses {
9882            if !Self::witness_has_explicit_progress(witness) {
9883                continue;
9884            }
9885            writeln!(
9886                out,
9887                "{} ==",
9888                composition_witness_action_constraint_name(&witness.name)
9889            )
9890            .expect("write to string");
9891            writeln!(
9892                out,
9893                "    \\/ {}",
9894                composition_witness_completion_name(&witness.name)
9895            )
9896            .expect("write to string");
9897            pushln!(out, "    \\/ model_step_count' # model_step_count");
9898            pushln!(out);
9899        }
9900    }
9901
9902    fn witness_satisfaction_conditions(&self, witness: &CompositionWitness) -> Vec<String> {
9903        let mut conditions = Vec::new();
9904        conditions.extend(witness.expected_routes.iter().map(|route| {
9905            format!(
9906                "\\E packet \\in delivered_routes : packet.route = {}",
9907                tla_string(route)
9908            )
9909        }));
9910        conditions.extend(
9911            witness
9912                .expected_scheduler_rules
9913                .iter()
9914                .map(render_scheduler_trigger_formula),
9915        );
9916        conditions.extend(
9917            witness
9918                .expected_states
9919                .iter()
9920                .map(|state| format!("({})", self.render_witness_state_formula(state))),
9921        );
9922        conditions.extend(
9923            witness.expected_transitions.iter().map(|transition| {
9924                format!("({})", self.render_witness_transition_formula(transition))
9925            }),
9926        );
9927        conditions.extend(
9928            witness
9929                .expected_transition_order
9930                .iter()
9931                .map(|order| format!("({})", self.render_witness_transition_order_formula(order))),
9932        );
9933        conditions
9934    }
9935
9936    fn render_witness_obligation_formula(
9937        &self,
9938        witness: &CompositionWitness,
9939        formula: String,
9940    ) -> String {
9941        if Self::witness_has_explicit_progress(witness) {
9942            format!(
9943                "{} => ({formula})",
9944                composition_witness_completion_name(&witness.name)
9945            )
9946        } else {
9947            format!("<> ({formula})")
9948        }
9949    }
9950
9951    fn render_literal_expr(&self, expr: &Expr) -> String {
9952        match expr {
9953            Expr::Bool(value) => {
9954                if *value {
9955                    "TRUE".into()
9956                } else {
9957                    "FALSE".into()
9958                }
9959            }
9960            Expr::U64(value) => value.to_string(),
9961            Expr::U64Max => TLA_RUST_U64_MAX_CONSTANT.to_owned(),
9962            Expr::String(value) => tla_string(value),
9963            Expr::NamedVariant { enum_name, variant } => render_named_variant_value(
9964                enum_name.as_str(),
9965                variant.as_str(),
9966                &self.named_bindings,
9967            ),
9968            Expr::None => "None".into(),
9969            Expr::Some(inner) => format!("Some({})", self.render_literal_expr(inner)),
9970            Expr::SeqLiteral(items) => {
9971                let rendered = items
9972                    .iter()
9973                    .map(|item| self.render_literal_expr(item))
9974                    .collect::<Vec<_>>()
9975                    .join(", ");
9976                format!("<<{rendered}>>")
9977            }
9978            Expr::EmptySet => "{}".into(),
9979            Expr::EmptyMap => "<< >>".into(),
9980            // A populated map literal (witness inputs, manifests) as a TLC
9981            // function; never the `None` fallback below.
9982            Expr::MapLiteral(entries) => {
9983                let rendered = entries
9984                    .iter()
9985                    .map(|(key, value)| {
9986                        format!(
9987                            "{} :> {}",
9988                            self.render_literal_expr(key),
9989                            self.render_literal_expr(value)
9990                        )
9991                    })
9992                    .collect::<Vec<_>>()
9993                    .join(" @@ ");
9994                format!("({rendered})")
9995            }
9996            _ => "None".into(),
9997        }
9998    }
9999
10000    fn render_witness_state_formula(
10001        &self,
10002        state: &meerkat_machine_schema::CompositionWitnessState,
10003    ) -> String {
10004        let mut clauses = Vec::new();
10005        if let Some(phase) = &state.phase {
10006            clauses.push(format!(
10007                "{} = {}",
10008                self.phase_var(&state.machine),
10009                tla_string(phase)
10010            ));
10011        }
10012        for field in &state.fields {
10013            clauses.push(format!(
10014                "{} = {}",
10015                self.field_var(&state.machine, &field.field),
10016                self.render_literal_expr(&field.expr)
10017            ));
10018        }
10019        if clauses.is_empty() {
10020            "TRUE".into()
10021        } else {
10022            clauses.join(" /\\ ")
10023        }
10024    }
10025
10026    fn render_witness_transition_formula(
10027        &self,
10028        transition: &meerkat_machine_schema::CompositionWitnessTransition,
10029    ) -> String {
10030        format!(
10031            "\\E packet \\in observed_transitions : /\\ packet.machine = {} /\\ packet.transition = {}",
10032            tla_string(&transition.machine),
10033            tla_string(&transition.transition)
10034        )
10035    }
10036
10037    fn render_witness_transition_order_formula(
10038        &self,
10039        ordering: &meerkat_machine_schema::CompositionWitnessTransitionOrder,
10040    ) -> String {
10041        format!(
10042            "\\E earlier \\in observed_transitions, later \\in observed_transitions : /\\ earlier.machine = {} /\\ earlier.transition = {} /\\ later.machine = {} /\\ later.transition = {} /\\ earlier.step < later.step",
10043            tla_string(&ordering.earlier.machine),
10044            tla_string(&ordering.earlier.transition),
10045            tla_string(&ordering.later.machine),
10046            tla_string(&ordering.later.transition),
10047        )
10048    }
10049
10050    fn route_packet_expr(
10051        &self,
10052        route_name: impl AsRef<str>,
10053        from_machine: impl AsRef<str>,
10054        effect_variant: impl AsRef<str>,
10055        to_machine: impl AsRef<str>,
10056        to_input_variant: impl AsRef<str>,
10057        payload_expr: &str,
10058        effect_id_expr: &str,
10059        source_transition: impl AsRef<str>,
10060    ) -> String {
10061        let to_machine = to_machine.as_ref();
10062        format!(
10063            "[route |-> {}, source_machine |-> {}, effect |-> {}, target_machine |-> {}, target_input |-> {}, payload |-> {}, actor |-> {}, effect_id |-> {}, source_transition |-> {}]",
10064            tla_string(route_name),
10065            tla_string(from_machine),
10066            tla_string(effect_variant),
10067            tla_string(to_machine),
10068            tla_string(to_input_variant),
10069            payload_expr,
10070            tla_string(self.actor(to_machine)),
10071            effect_id_expr,
10072            tla_string(source_transition)
10073        )
10074    }
10075
10076    fn render_machine_transition_action(
10077        &self,
10078        compiler: &mut MachineTlaCompiler<'_>,
10079        instance_id: &str,
10080        transition: &TransitionSchema,
10081        out: &mut String,
10082    ) -> std::result::Result<(), CompositionTlaError> {
10083        let machine = self.machine(instance_id);
10084        let action_name = self.machine_transition_name(instance_id, transition);
10085        let binding_types = compiler.binding_type_map(transition);
10086        let binding_env = transition
10087            .on
10088            .bindings()
10089            .iter()
10090            .map(|binding| {
10091                (
10092                    binding.as_str().to_owned(),
10093                    format!("packet.payload.{}", tla_ident(binding)),
10094                )
10095            })
10096            .collect::<BTreeMap<String, _>>();
10097        let params = transition
10098            .on
10099            .bindings()
10100            .iter()
10101            .map(|binding| format!("arg_{}", tla_ident(binding)))
10102            .collect::<Vec<_>>();
10103
10104        if params.is_empty() {
10105            writeln!(out, "{} ==", action_name);
10106        } else {
10107            pushln!(out, "{}({}) ==", action_name, params.join(", "));
10108        }
10109
10110        let phase_var = self.phase_var(instance_id);
10111        let from_guard = if transition.from.len() == 1 {
10112            format!("{} = {}", phase_var, tla_string(&transition.from[0]))
10113        } else {
10114            transition
10115                .from
10116                .iter()
10117                .map(|phase| format!("{} = {}", phase_var, tla_string(phase)))
10118                .collect::<Vec<_>>()
10119                .join(" \\/ ")
10120        };
10121
10122        pushln!(out, "    /\\ \\E packet \\in SeqElements(pending_inputs) :");
10123        writeln!(
10124            out,
10125            "       /\\ packet.machine = {}",
10126            tla_string(instance_id)
10127        )
10128        .expect("write to string");
10129        writeln!(
10130            out,
10131            "       /\\ packet.variant = {}",
10132            tla_string(transition.on.variant_str())
10133        )
10134        .expect("write to string");
10135        for binding in transition.on.bindings() {
10136            let arg_name = format!("arg_{}", tla_ident(binding));
10137            writeln!(
10138                out,
10139                "       /\\ packet.payload.{} = {}",
10140                tla_ident(binding),
10141                arg_name
10142            )
10143            .expect("write to string");
10144        }
10145        writeln!(
10146            out,
10147            "       /\\ ~HigherPriorityReady({})",
10148            tla_string(self.actor(instance_id))
10149        )
10150        .expect("write to string");
10151        writeln!(out, "       /\\ {}", from_guard);
10152
10153        let field_env = self.machine_field_env(instance_id);
10154        for guard in &transition.guards {
10155            writeln!(
10156                out,
10157                "       /\\ {}",
10158                compiler.render_guard(guard, &field_env, &binding_env, &binding_types)
10159            )
10160            .expect("write to string");
10161        }
10162
10163        let next_env = compiler.compile_updates(
10164            &action_name,
10165            &field_env,
10166            &binding_env,
10167            &binding_types,
10168            &transition.updates,
10169        );
10170        let effect_id_expr = "(model_step_count + 1)".to_string();
10171        let current_phase_symbol = compiler.phase_symbol.clone();
10172        compiler.phase_symbol = Some(tla_string(&transition.to));
10173        let effect_packets = transition
10174            .emit
10175            .iter()
10176            .map(|effect| {
10177                let payload_fields = effect
10178                    .fields
10179                    .iter()
10180                    .map(|(field, expr)| {
10181                        (
10182                            field.as_str().to_owned(),
10183                            compiler.render_expr_with_types(
10184                                expr,
10185                                &next_env,
10186                                &binding_env,
10187                                &binding_types,
10188                            ),
10189                        )
10190                    })
10191                    .collect::<BTreeMap<String, _>>();
10192                (
10193                    effect.variant.as_str().to_owned(),
10194                    format!(
10195                        "[machine |-> {}, variant |-> {}, payload |-> {}, effect_id |-> {}, source_transition |-> {}]",
10196                        tla_string(instance_id),
10197                        tla_string(&effect.variant),
10198                        self.payload_record_expr(&payload_fields),
10199                        effect_id_expr,
10200                        tla_string(&transition.name)
10201                    ),
10202                    payload_fields,
10203                )
10204            })
10205            .collect::<Vec<_>>();
10206        compiler.phase_symbol = current_phase_symbol;
10207
10208        let mut queued_route_packets = Vec::new();
10209        let mut immediate_route_packets = Vec::new();
10210        let mut owner_route_quantifiers = Vec::new();
10211        for (effect_variant, _effect_packet, payload_fields) in &effect_packets {
10212            for route in self.schema.routes.iter().filter(|route| {
10213                route.from_machine.as_str() == instance_id
10214                    && route.effect_variant.as_str() == effect_variant.as_str()
10215            }) {
10216                let (target_payload, route_owner_quantifiers) = self.target_payload_for_route(
10217                    machine,
10218                    effect_variant,
10219                    payload_fields,
10220                    route,
10221                    compiler,
10222                    &next_env,
10223                    &binding_env,
10224                    &binding_types,
10225                );
10226                for quantifier in route_owner_quantifiers {
10227                    if !owner_route_quantifiers.contains(&quantifier) {
10228                        owner_route_quantifiers.push(quantifier);
10229                    }
10230                }
10231                let route_packet = self.route_packet_expr(
10232                    &route.name,
10233                    instance_id,
10234                    effect_variant,
10235                    &route.to.machine,
10236                    &route.to.input_variant,
10237                    &target_payload,
10238                    &effect_id_expr,
10239                    &transition.name,
10240                );
10241                match route.delivery {
10242                    RouteDelivery::Enqueue => {
10243                        queued_route_packets.push((route_packet, target_payload))
10244                    }
10245                    RouteDelivery::Immediate => immediate_route_packets.push((
10246                        route_packet,
10247                        self.input_packet_expr_from_payload_expr(
10248                            &route.to.machine,
10249                            &route.to.input_variant,
10250                            &target_payload,
10251                            "route",
10252                            &route.name,
10253                            instance_id,
10254                            effect_variant,
10255                            &effect_id_expr,
10256                        ),
10257                    )),
10258                }
10259            }
10260        }
10261
10262        writeln!(
10263            out,
10264            "       /\\ {}' = {}",
10265            phase_var,
10266            tla_string(&transition.to)
10267        )
10268        .expect("write to string");
10269        let touched = machine
10270            .state
10271            .fields
10272            .iter()
10273            .filter_map(|field| {
10274                let next = next_env.get(field.name.as_str())?;
10275                if field_env
10276                    .get(field.name.as_str())
10277                    .is_some_and(|current| next != current)
10278                {
10279                    Some((field.name.as_str(), next.as_str()))
10280                } else {
10281                    None
10282                }
10283            })
10284            .collect::<Vec<_>>();
10285        for (field, expr) in &touched {
10286            writeln!(
10287                out,
10288                "       /\\ {}' = {}",
10289                self.field_var(instance_id, field),
10290                expr
10291            )
10292            .expect("write to string");
10293        }
10294
10295        let mut unchanged_machine_vars = Vec::new();
10296        for instance in &self.schema.machines {
10297            if instance.instance_id.as_str() == instance_id {
10298                for field in &machine.state.fields {
10299                    if !touched.iter().any(|(name, _)| *name == field.name.as_str()) {
10300                        unchanged_machine_vars
10301                            .push(self.field_var(instance_id, field.name.as_str()));
10302                    }
10303                }
10304            } else {
10305                unchanged_machine_vars.push(self.phase_var(instance.instance_id.as_str()));
10306                let other_machine = self.machine(instance.instance_id.as_str());
10307                for field in &other_machine.state.fields {
10308                    unchanged_machine_vars
10309                        .push(self.field_var(instance.instance_id.as_str(), field.name.as_str()));
10310                }
10311            }
10312        }
10313
10314        unchanged_machine_vars.push("witness_current_script_input".into());
10315        unchanged_machine_vars.push("witness_remaining_script_inputs".into());
10316
10317        if !unchanged_machine_vars.is_empty() {
10318            self.render_unchanged_vars(out, "       /\\ ", &unchanged_machine_vars);
10319        }
10320
10321        let pending_inputs_next = self.append_if_missing_chain(
10322            format!("SeqRemove(pending_inputs, packet)"),
10323            &immediate_route_packets
10324                .iter()
10325                .map(|(_, input_packet)| input_packet)
10326                .cloned()
10327                .collect::<Vec<_>>(),
10328        );
10329        let pending_routes_next = self.append_if_missing_chain(
10330            "pending_routes".into(),
10331            &queued_route_packets
10332                .iter()
10333                .map(|(route_packet, _)| route_packet)
10334                .cloned()
10335                .collect::<Vec<_>>(),
10336        );
10337        let delivered_routes_next = if immediate_route_packets.is_empty() {
10338            "delivered_routes".into()
10339        } else {
10340            format!(
10341                "delivered_routes \\cup {{ {} }}",
10342                immediate_route_packets
10343                    .iter()
10344                    .map(|(route_packet, _)| route_packet)
10345                    .cloned()
10346                    .collect::<Vec<_>>()
10347                    .join(", ")
10348            )
10349        };
10350        let observed_inputs_next = {
10351            let immediate_inputs = immediate_route_packets
10352                .iter()
10353                .map(|(_, input_packet)| input_packet)
10354                .cloned()
10355                .collect::<Vec<_>>();
10356            self.union_set_items("observed_inputs".into(), &immediate_inputs)
10357        };
10358        let emitted_effects_next = if effect_packets.is_empty() {
10359            "emitted_effects".into()
10360        } else {
10361            format!(
10362                "emitted_effects \\cup {{ {} }}",
10363                effect_packets
10364                    .iter()
10365                    .map(|(_, effect_packet, _)| effect_packet)
10366                    .cloned()
10367                    .collect::<Vec<_>>()
10368                    .join(", ")
10369            )
10370        };
10371        let observed_transitions_next = format!(
10372            "observed_transitions \\cup {{{}}}",
10373            self.transition_packet_expr(instance_id, transition)
10374        );
10375
10376        // Compute obligation set updates: when a transition emits an effect
10377        // that matches a handoff_protocol, add a record to the obligation set
10378        // with the protocol's declared obligation fields from the effect payload.
10379        let mut obligation_updates: BTreeMap<String, String> = BTreeMap::new();
10380        for (effect_variant, _effect_packet, payload_fields) in &effect_packets {
10381            for protocol in &self.schema.handoff_protocols {
10382                if protocol.producer_instance.as_str() == instance_id
10383                    && protocol.effect_variant.as_str() == effect_variant.as_str()
10384                {
10385                    let var = self.obligation_var(protocol);
10386                    let mut record_fields: Vec<String> =
10387                        Vec::with_capacity(protocol.obligation_fields.len() + 1);
10388                    record_fields.push("effect_id |-> (model_step_count + 1)".to_string());
10389                    for field in &protocol.obligation_fields {
10390                        let tla_field = tla_ident(field);
10391                        // Fail closed: an obligation field that is absent from
10392                        // the matching effect's payload used to be papered over
10393                        // with an `"unknown_<field>"` sentinel literal.
10394                        let value =
10395                            payload_fields.get(field.as_str()).cloned().ok_or_else(|| {
10396                                CompositionTlaError::UnknownObligationField {
10397                                    composition: self.schema.name.as_str().to_owned(),
10398                                    protocol: protocol.name.as_str().to_owned(),
10399                                    effect: effect_variant.clone(),
10400                                    field: field.as_str().to_owned(),
10401                                }
10402                            })?;
10403                        record_fields.push(format!("{} |-> {}", tla_field, value));
10404                    }
10405                    let record = if record_fields.is_empty() {
10406                        "\"token\"".to_string()
10407                    } else {
10408                        format!("[{}]", record_fields.join(", "))
10409                    };
10410                    obligation_updates.insert(var.clone(), format!("{} \\cup {{{}}}", var, record));
10411                }
10412            }
10413        }
10414
10415        let route_update_prefix = if owner_route_quantifiers.is_empty() {
10416            "       /\\"
10417        } else {
10418            writeln!(
10419                out,
10420                "       /\\ \\E {} :",
10421                owner_route_quantifiers.join(", ")
10422            )
10423            .expect("write to string");
10424            "           /\\"
10425        };
10426        writeln!(
10427            out,
10428            "{route_update_prefix} pending_inputs' = {pending_inputs_next}"
10429        )
10430        .expect("write to string");
10431        writeln!(
10432            out,
10433            "{route_update_prefix} observed_inputs' = {observed_inputs_next}"
10434        )
10435        .expect("write to string");
10436        writeln!(
10437            out,
10438            "{route_update_prefix} pending_routes' = {pending_routes_next}"
10439        )
10440        .expect("write to string");
10441        writeln!(
10442            out,
10443            "{route_update_prefix} delivered_routes' = {delivered_routes_next}"
10444        )
10445        .expect("write to string");
10446        writeln!(
10447            out,
10448            "{route_update_prefix} emitted_effects' = {emitted_effects_next}"
10449        )
10450        .expect("write to string");
10451        writeln!(
10452            out,
10453            "{route_update_prefix} observed_transitions' = {observed_transitions_next}"
10454        )
10455        .expect("write to string");
10456        // Write obligation variable updates — touched protocols get \cup, untouched get UNCHANGED
10457        let all_obligation_vars = self.obligation_vars();
10458        let mut unchanged_obligation_vars = Vec::new();
10459        for ovar in &all_obligation_vars {
10460            if let Some(next_expr) = obligation_updates.get(ovar) {
10461                writeln!(out, "{route_update_prefix} {}' = {}", ovar, next_expr)
10462                    .expect("write to string");
10463            } else {
10464                unchanged_obligation_vars.push(ovar.clone());
10465            }
10466        }
10467        if !unchanged_obligation_vars.is_empty() {
10468            let unchanged_prefix = format!("{route_update_prefix} ");
10469            self.render_unchanged_vars(out, &unchanged_prefix, &unchanged_obligation_vars);
10470        }
10471        writeln!(
10472            out,
10473            "{route_update_prefix} model_step_count' = model_step_count + 1"
10474        )
10475        .expect("write to string");
10476        Ok(())
10477    }
10478
10479    fn target_payload_for_route(
10480        &self,
10481        source_machine: &MachineSchema,
10482        effect_variant: &str,
10483        effect_payload_fields: &BTreeMap<String, String>,
10484        route: &Route,
10485        compiler: &MachineTlaCompiler<'_>,
10486        next_env: &BTreeMap<String, String>,
10487        binding_env: &BTreeMap<String, String>,
10488        binding_types: &BTreeMap<String, TypeRef>,
10489    ) -> (String, Vec<String>) {
10490        let target_machine = self.machine(route.to.machine.as_str());
10491        let Some(target_variant) = route_target_variant(target_machine, &route.to) else {
10492            return (String::new(), Vec::new());
10493        };
10494        let Ok(source_effect_variant) = source_machine.effects.variant_named(effect_variant) else {
10495            return (String::new(), Vec::new());
10496        };
10497        let mut owner_context_quantifiers = Vec::new();
10498        let bindings = route
10499            .bindings
10500            .iter()
10501            .map(|binding| {
10502                let expr = match &binding.source {
10503                    RouteBindingSource::Field {
10504                        from_field,
10505                        allow_named_alias: _,
10506                    } => effect_payload_fields
10507                        .get(from_field.as_str())
10508                        .cloned()
10509                        .or_else(|| {
10510                            source_effect_variant
10511                                .fields
10512                                .iter()
10513                                .find(|field| field.name == *from_field)
10514                                .map(|_| format!("packet.payload.{}", tla_ident(from_field)))
10515                        })
10516                        .unwrap_or_else(|| "None".to_string()),
10517                    RouteBindingSource::Literal(expr) => {
10518                        compiler.render_expr_with_types(expr, next_env, binding_env, binding_types)
10519                    }
10520                    RouteBindingSource::OwnerProvided => {
10521                        if let Some(target_field) = target_variant
10522                            .fields
10523                            .iter()
10524                            .find(|field| field.name == binding.to_field)
10525                        {
10526                            let var_name = format!(
10527                                "route_owner_ctx_{}_{}",
10528                                tla_ident(&route.name),
10529                                tla_ident(&binding.to_field)
10530                            );
10531                            let domain = self.binding_domain_for_binding(
10532                                route.to.machine.as_str(),
10533                                Some(target_variant.name.as_str()),
10534                                binding.to_field.as_str(),
10535                                &target_field.ty,
10536                            );
10537                            owner_context_quantifiers.push(format!("{var_name} \\in {domain}"));
10538                            var_name
10539                        } else {
10540                            "\"owner_val\"".to_string()
10541                        }
10542                    }
10543                };
10544                (binding.to_field.as_str().to_owned(), expr)
10545            })
10546            .collect::<BTreeMap<String, _>>();
10547        let payload_fields = target_variant
10548            .fields
10549            .iter()
10550            .map(|field| {
10551                let expr = bindings
10552                    .get(field.name.as_str())
10553                    .cloned()
10554                    .unwrap_or_else(|| default_state_init_expr(&field.ty));
10555                (field.name.as_str().to_owned(), expr)
10556            })
10557            .collect::<BTreeMap<String, _>>();
10558        (
10559            self.payload_record_expr(&payload_fields),
10560            owner_context_quantifiers,
10561        )
10562    }
10563
10564    fn append_if_missing_chain(&self, base: String, items: &[String]) -> String {
10565        items.iter().fold(base, |expr, item| {
10566            format!("AppendIfMissing({expr}, {item})")
10567        })
10568    }
10569
10570    fn union_set_items(&self, base: String, items: &[String]) -> String {
10571        if items.is_empty() {
10572            base
10573        } else {
10574            format!("{base} \\cup {{{}}}", items.join(", "))
10575        }
10576    }
10577
10578    fn transition_packet_expr(&self, instance_id: &str, transition: &TransitionSchema) -> String {
10579        format!(
10580            "[machine |-> {}, transition |-> {}, actor |-> {}, step |-> (model_step_count + 1), from_phase |-> {}, to_phase |-> {}]",
10581            tla_string(instance_id),
10582            tla_string(&transition.name),
10583            tla_string(self.actor(instance_id)),
10584            self.phase_var(instance_id),
10585            tla_string(&transition.to)
10586        )
10587    }
10588}
10589
10590#[derive(Clone, Copy)]
10591enum OrderingOperator {
10592    Lt,
10593    Lte,
10594    Gt,
10595    Gte,
10596}
10597
10598struct MachineTlaCompiler<'a> {
10599    schema: &'a MachineSchema,
10600    named_bindings: BTreeMap<String, meerkat_machine_schema::RustTypeAtom>,
10601    helper_defs: Vec<String>,
10602    helper_counter: usize,
10603    helper_prefix: Option<String>,
10604    phase_symbol: Option<String>,
10605    field_env_override: Option<BTreeMap<String, String>>,
10606    unchanged_frames: UnchangedFrameInterner,
10607    /// Set when an ordering comparison renders through `OptionLt` /
10608    /// `OptionLe`; the module then defines them. Shared by every compiler
10609    /// that renders into the same module.
10610    option_order_used: Rc<Cell<bool>>,
10611}
10612
10613impl<'a> MachineTlaCompiler<'a> {
10614    fn new(schema: &'a MachineSchema) -> Self {
10615        Self {
10616            schema,
10617            named_bindings: collect_machine_named_bindings(schema),
10618            helper_defs: Vec::new(),
10619            helper_counter: 0,
10620            helper_prefix: None,
10621            phase_symbol: None,
10622            field_env_override: None,
10623            unchanged_frames: UnchangedFrameInterner::default(),
10624            option_order_used: Rc::default(),
10625        }
10626    }
10627
10628    fn new_with_helper_prefix(schema: &'a MachineSchema, helper_prefix: impl Into<String>) -> Self {
10629        Self {
10630            schema,
10631            named_bindings: collect_machine_named_bindings(schema),
10632            helper_defs: Vec::new(),
10633            helper_counter: 0,
10634            helper_prefix: Some(helper_prefix.into()),
10635            phase_symbol: None,
10636            field_env_override: None,
10637            unchanged_frames: UnchangedFrameInterner::default(),
10638            option_order_used: Rc::default(),
10639        }
10640    }
10641
10642    fn with_option_order_flag(mut self, option_order_used: Rc<Cell<bool>>) -> Self {
10643        self.option_order_used = option_order_used;
10644        self
10645    }
10646
10647    fn with_phase_symbol(mut self, phase_symbol: impl Into<String>) -> Self {
10648        self.phase_symbol = Some(phase_symbol.into());
10649        self
10650    }
10651
10652    fn with_field_env_override(mut self, field_env_override: BTreeMap<String, String>) -> Self {
10653        self.field_env_override = Some(field_env_override);
10654        self
10655    }
10656
10657    fn render(&mut self) -> std::result::Result<String, CompositionTlaError> {
10658        let mut out = String::new();
10659        let constants = collect_binding_domains(self.schema);
10660        let named_samples = collect_machine_named_type_samples(self.schema);
10661        let named_bindings = collect_machine_named_bindings(self.schema);
10662
10663        pushln!(&mut out, "---- MODULE model ----");
10664        pushln!(&mut out, "EXTENDS TLC, Naturals, Sequences, FiniteSets");
10665        pushln!(&mut out);
10666        writeln!(
10667            &mut out,
10668            "\\* Generated semantic machine model for {}.",
10669            self.schema.machine
10670        )
10671        .expect("write to string");
10672        pushln!(&mut out);
10673
10674        let mut model_constants = constants
10675            .iter()
10676            .filter(|(_, ty)| {
10677                !matches!(
10678                    ty,
10679                    TypeRef::Seq(_) | TypeRef::Option(_) | TypeRef::Map(_, _)
10680                )
10681            })
10682            .map(|(name, _)| name)
10683            .cloned()
10684            .collect::<Vec<_>>();
10685        model_constants.extend(
10686            machine_input_sample_constants(self.schema)
10687                .into_iter()
10688                .map(|(constant, _)| constant),
10689        );
10690        model_constants.extend(
10691            machine_input_typed_sample_constants(self.schema)
10692                .into_iter()
10693                .map(|(constant, _, _)| constant),
10694        );
10695        if machine_uses_u64_max(self.schema) {
10696            model_constants.push(TLA_RUST_U64_MAX_CONSTANT.to_owned());
10697        }
10698        if !model_constants.is_empty() {
10699            let constant_list = model_constants.join(", ");
10700            if model_constants
10701                .iter()
10702                .any(|constant| constant == TLA_RUST_U64_MAX_CONSTANT)
10703            {
10704                pushln!(
10705                    &mut out,
10706                    "\\* RustU64Max is the TLA boundary for Expr::U64Max; production generated Rust renders u64::MAX."
10707                );
10708            }
10709            writeln!(&mut out, "CONSTANTS {constant_list}");
10710            pushln!(&mut out);
10711        }
10712
10713        pushln!(&mut out, "None == [tag |-> \"none\", value |-> \"none\"]");
10714        writeln!(&mut out, "Some(v) == [tag |-> \"some\", value |-> v]");
10715        pushln!(&mut out);
10716        let option_order_anchor = out.len();
10717
10718        push_cfg_assignment_operator_definitions(
10719            &mut out,
10720            &constants,
10721            &named_bindings,
10722            &CfgAssignmentOperatorProfile {
10723                suffix: "Ci".to_owned(),
10724                explicit_values: self.schema.tlc_model.as_ref().map(|model| &model.ci),
10725                sample_cardinality: machine_cfg_sample_cardinality(self.schema, false),
10726                domain_overrides: None,
10727                named_samples: &named_samples,
10728                include_string_samples: false,
10729            },
10730        );
10731        push_cfg_assignment_operator_definitions(
10732            &mut out,
10733            &constants,
10734            &named_bindings,
10735            &CfgAssignmentOperatorProfile {
10736                suffix: "Deep".to_owned(),
10737                explicit_values: self.schema.tlc_model.as_ref().map(|model| &model.deep),
10738                sample_cardinality: machine_cfg_sample_cardinality(self.schema, true),
10739                domain_overrides: Some(&self.schema.deep_domain_overrides),
10740                named_samples: &with_guard_binding_string_samples(&named_samples, self.schema),
10741                include_string_samples: !machine_uses_session_id_string_bridge(self.schema),
10742            },
10743        );
10744
10745        for (name, ty) in ordered_composite_domain_definitions(&constants) {
10746            let definition = match ty {
10747                TypeRef::Seq(inner) => render_sequence_domain_definition(inner),
10748                TypeRef::Option(inner) => render_option_domain_definition(inner),
10749                TypeRef::Map(key, value) => render_map_domain_definition(key, value),
10750                _ => continue,
10751            };
10752            writeln!(&mut out, "{} == {}", name, definition).expect("write to string");
10753        }
10754        if constants.values().any(|ty| {
10755            matches!(
10756                ty,
10757                TypeRef::Seq(_) | TypeRef::Option(_) | TypeRef::Map(_, _)
10758            )
10759        }) {
10760            pushln!(&mut out);
10761        }
10762        // What each profile's config assigns a `CiSamples` input field's
10763        // constant: the CI profile the declared values, the Deep profile the
10764        // field type's whole domain (defined above).
10765        let typed_samples = machine_input_typed_sample_constants(self.schema);
10766        for (constant, samples, ty) in &typed_samples {
10767            writeln!(
10768                &mut out,
10769                "{} == {}",
10770                cfg_assignment_operator_name(constant, "Ci"),
10771                render_explicit_values(samples)
10772            )
10773            .expect("write to string");
10774            writeln!(
10775                &mut out,
10776                "{} == {}",
10777                cfg_assignment_operator_name(constant, "Deep"),
10778                self.binding_domain_for_type(ty)
10779            )
10780            .expect("write to string");
10781        }
10782        if !typed_samples.is_empty() {
10783            pushln!(&mut out);
10784        }
10785        writeln!(
10786            &mut out,
10787            "MapLookup(map, key) == IF key \\in DOMAIN map THEN map[key] ELSE None"
10788        )
10789        .expect("write to string");
10790        writeln!(
10791            &mut out,
10792            "MapSet(map, key, value) == [x \\in DOMAIN map \\cup {{key}} |-> IF x = key THEN value ELSE map[x]]"
10793        )
10794        .expect("write to string");
10795        writeln!(
10796            &mut out,
10797            "MapIncrement(map, key, amount) == [x \\in DOMAIN map \\cup {{key}} |-> IF x = key THEN (IF key \\in DOMAIN map THEN map[key] ELSE 0) + amount ELSE map[x]]"
10798        )
10799        .expect("write to string");
10800        writeln!(
10801            &mut out,
10802            "MapDecrement(map, key, amount) == [x \\in DOMAIN map \\cup {{key}} |-> IF x = key THEN (IF key \\in DOMAIN map THEN map[key] ELSE 0) - amount ELSE map[x]]"
10803        )
10804        .expect("write to string");
10805        writeln!(
10806            &mut out,
10807            "MapRemove(map, key) == [x \\in DOMAIN map \\ {{key}} |-> map[x]]"
10808        )
10809        .expect("write to string");
10810        writeln!(
10811            &mut out,
10812            "StartsWith(seq, prefix) == /\\ Len(prefix) <= Len(seq) /\\ SubSeq(seq, 1, Len(prefix)) = prefix"
10813        )
10814        .expect("write to string");
10815        writeln!(
10816            &mut out,
10817            "SeqElements(seq) == {{seq[i] : i \\in 1..Len(seq)}}"
10818        )
10819        .expect("write to string");
10820        writeln!(
10821            &mut out,
10822            "Count(seq, value) == Cardinality({{i \\in DOMAIN seq : seq[i] = value}})"
10823        )
10824        .expect("write to string");
10825        if !self.schema.tlc_representative_inputs.is_empty() {
10826            writeln!(
10827                &mut out,
10828                "{TLC_REPRESENTATIVE_DOMAIN_HELPER}(values) == IF values = {{}} THEN {{}} ELSE {{CHOOSE value \\in values : TRUE}}"
10829            )
10830            .expect("write to string");
10831        }
10832        writeln!(
10833            &mut out,
10834            "RECURSIVE SeqRemove(_, _)\nSeqRemove(seq, value) == IF Len(seq) = 0 THEN <<>> ELSE IF Head(seq) = value THEN SeqRemove(Tail(seq), value) ELSE <<Head(seq)>> \\o SeqRemove(Tail(seq), value)"
10835        )
10836        .expect("write to string");
10837        writeln!(
10838            &mut out,
10839            "RECURSIVE SeqRemoveAll(_, _)\nSeqRemoveAll(seq, values) == IF Len(values) = 0 THEN seq ELSE SeqRemoveAll(SeqRemove(seq, Head(values)), Tail(values))"
10840        )
10841        .expect("write to string");
10842        pushln!(&mut out);
10843
10844        let variable_list = std::iter::once("phase".to_string())
10845            .chain(std::iter::once("model_step_count".to_string()))
10846            .chain(
10847                self.schema
10848                    .state
10849                    .fields
10850                    .iter()
10851                    .map(|field| field.name.as_str().to_owned()),
10852            )
10853            .collect::<Vec<_>>()
10854            .join(", ");
10855        pushln!(&mut out, "VARIABLES {variable_list}");
10856        pushln!(&mut out);
10857        let vars = std::iter::once("phase".to_string())
10858            .chain(std::iter::once("model_step_count".to_string()))
10859            .chain(
10860                self.schema
10861                    .state
10862                    .fields
10863                    .iter()
10864                    .map(|field| field.name.as_str().to_owned()),
10865            )
10866            .collect::<Vec<_>>();
10867        pushln!(&mut out, "vars == << {} >>", vars.join(", "));
10868        pushln!(&mut out);
10869
10870        for helper in helper_dependency_order(self.schema)? {
10871            self.render_helper(&mut out, helper);
10872        }
10873        if self.schema.machine.as_str() == "MobMachine" {
10874            self.render_mob_machine_native_helpers(&mut out);
10875        }
10876        if self.schema.machine.as_str() == "MeerkatMachine" {
10877            self.render_meerkat_machine_native_helpers(&mut out);
10878        }
10879        if self.schema.machine.as_str() == "RuntimeDeliveryMachine" {
10880            self.render_runtime_delivery_native_helpers(&mut out);
10881        }
10882        if self.schema.machine.as_str() == "SessionDocumentMachine" {
10883            self.render_session_document_native_helpers(&mut out);
10884        }
10885        if !self.schema.helpers.is_empty() || !self.schema.derived.is_empty() {
10886            pushln!(&mut out);
10887        }
10888
10889        pushln!(&mut out, "Init ==");
10890        writeln!(
10891            &mut out,
10892            "    /\\ phase = {}",
10893            tla_string(&self.schema.state.init.phase)
10894        )
10895        .expect("write to string");
10896        pushln!(&mut out, "    /\\ model_step_count = 0");
10897        for field in &self.schema.state.fields {
10898            let init_expr = self
10899                .schema
10900                .state
10901                .init
10902                .fields
10903                .iter()
10904                .find(|item| item.field == field.name)
10905                .map(|item| self.render_expr(&item.expr, &BTreeMap::new(), &BTreeMap::new()))
10906                .unwrap_or_else(|| default_state_init_expr(&field.ty));
10907            pushln!(&mut out, "    /\\ {} = {}", field.name, init_expr);
10908        }
10909        pushln!(&mut out);
10910
10911        let mut rendered_transitions = Vec::new();
10912        for transition in &self.schema.transitions {
10913            let mut rendered = String::new();
10914            self.render_transition(&mut rendered, transition);
10915            rendered_transitions.push(rendered);
10916        }
10917
10918        if !self.schema.state.terminal_phases.is_empty() {
10919            let terminal_guard = if self.schema.state.terminal_phases.len() == 1 {
10920                format!(
10921                    "phase = {}",
10922                    tla_string(&self.schema.state.terminal_phases[0])
10923                )
10924            } else {
10925                self.schema
10926                    .state
10927                    .terminal_phases
10928                    .iter()
10929                    .map(|phase| format!("phase = {}", tla_string(phase)))
10930                    .collect::<Vec<_>>()
10931                    .join(" \\/ ")
10932            };
10933            pushln!(&mut out, "TerminalStutter ==");
10934            pushln!(&mut out, "    /\\ {}", terminal_guard);
10935            pushln!(&mut out, "    /\\ UNCHANGED vars");
10936            pushln!(&mut out);
10937        }
10938
10939        // Fail closed on a frame-name collision: the rendered transitions
10940        // already reference one name for two different frames, so returning the
10941        // module would silently give an action the wrong frame condition.
10942        if let Some(collision) = self.unchanged_frames.collision() {
10943            return Err(CompositionTlaError::MachineUnchangedFrameCollision {
10944                machine: self.schema.machine.as_str().to_owned(),
10945                collision: collision.clone(),
10946            });
10947        }
10948        // Every frame variable is in scope from the VARIABLES declaration
10949        // above, and every reference is in the transition bodies below.
10950        out.push_str(&self.unchanged_frames.definitions_block());
10951
10952        if !self.helper_defs.is_empty() {
10953            for helper in &self.helper_defs {
10954                pushln!(&mut out, "{helper}");
10955                pushln!(&mut out);
10956            }
10957        }
10958
10959        for transition in &rendered_transitions {
10960            pushln!(&mut out, "{transition}");
10961            pushln!(&mut out);
10962        }
10963
10964        pushln!(&mut out, "Next ==");
10965        for transition in &self.schema.transitions {
10966            let call = if transition.on.bindings().is_empty() {
10967                transition.name.as_str().to_owned()
10968            } else {
10969                let binding_types = self.binding_type_map(transition);
10970                let forced_bool_literals =
10971                    transition_forced_bool_literals(transition, &binding_types);
10972                let binding_env = transition
10973                    .on
10974                    .bindings()
10975                    .iter()
10976                    .map(|binding| {
10977                        (
10978                            binding.as_str().to_owned(),
10979                            self.local_binding_name(binding.as_str()),
10980                        )
10981                    })
10982                    .collect::<BTreeMap<_, _>>();
10983                let mut prefix = String::new();
10984                for binding in transition.on.bindings() {
10985                    if forced_bool_literals.contains_key(binding.as_str()) {
10986                        continue;
10987                    }
10988                    let Some(ty) = binding_types.get(binding.as_str()) else {
10989                        return Ok(String::new());
10990                    };
10991                    let domain = self.binding_domain_for_binding(
10992                        trigger_input_variant(transition),
10993                        binding.as_str(),
10994                        ty,
10995                    );
10996                    let domain =
10997                        if transition_uses_tlc_representative_payload(self.schema, transition) {
10998                            tlc_representative_domain(domain)
10999                        } else {
11000                            domain
11001                        };
11002                    let local = binding_env
11003                        .get(binding.as_str())
11004                        .cloned()
11005                        .unwrap_or_else(|| binding.as_str().to_owned());
11006                    prefix.push_str(&format!("\\E {local} \\in {domain} : "));
11007                }
11008                let args = transition
11009                    .on
11010                    .bindings()
11011                    .iter()
11012                    .map(|binding| {
11013                        forced_bool_literals
11014                            .get(binding.as_str())
11015                            .map(|value| tla_bool_literal(*value).to_owned())
11016                            .unwrap_or_else(|| {
11017                                binding_env
11018                                    .get(binding.as_str())
11019                                    .cloned()
11020                                    .unwrap_or_else(|| binding.as_str().to_owned())
11021                            })
11022                    })
11023                    .collect::<Vec<_>>()
11024                    .join(", ");
11025                // Hoist the source-phase guard ahead of the parameter
11026                // quantifiers. The guard is the first conjunct of the action
11027                // body too, so the disjunct is unchanged in meaning, but TLC
11028                // no longer splits it into one action per parameter tuple
11029                // that it must enumerate in every state: states outside the
11030                // source phase reject the whole disjunct at once.
11031                let from_guard = transition
11032                    .from
11033                    .iter()
11034                    .map(|phase| format!("phase = {}", tla_string(phase)))
11035                    .collect::<Vec<_>>()
11036                    .join(" \\/ ");
11037                if prefix.is_empty() || from_guard.is_empty() {
11038                    format!("{prefix}{}({})", transition.name, args)
11039                } else {
11040                    format!("({from_guard}) /\\ {prefix}{}({})", transition.name, args)
11041                }
11042            };
11043            pushln!(&mut out, "    \\/ {}", call);
11044        }
11045        if !self.schema.state.terminal_phases.is_empty() {
11046            pushln!(&mut out, "    \\/ TerminalStutter");
11047        }
11048        pushln!(&mut out);
11049
11050        for invariant in &self.schema.invariants {
11051            writeln!(
11052                &mut out,
11053                "{} == {}",
11054                invariant.name,
11055                self.render_expr(&invariant.expr, &BTreeMap::new(), &BTreeMap::new())
11056            )
11057            .expect("write to string");
11058        }
11059        pushln!(&mut out);
11060
11061        writeln!(
11062            &mut out,
11063            "CiStateConstraint == {}",
11064            render_machine_state_constraint(self.schema, false)
11065        )
11066        .expect("write to string");
11067        writeln!(
11068            &mut out,
11069            "DeepStateConstraint == {}",
11070            render_machine_state_constraint(self.schema, true)
11071        )
11072        .expect("write to string");
11073        pushln!(&mut out);
11074
11075        pushln!(&mut out, "Spec == Init /\\ [][Next]_vars");
11076        pushln!(&mut out);
11077        for invariant in &self.schema.invariants {
11078            pushln!(&mut out, "THEOREM Spec => []{}", invariant.name);
11079        }
11080        pushln!(&mut out);
11081        writeln!(
11082            &mut out,
11083            "============================================================================="
11084        )
11085        .expect("write to string");
11086
11087        if self.option_order_used.get() {
11088            out.insert_str(option_order_anchor, TLA_OPTION_ORDER_DEFINITIONS);
11089        }
11090        Ok(out)
11091    }
11092
11093    fn render_helper(&self, out: &mut String, helper: &HelperSchema) {
11094        let params = helper
11095            .params
11096            .iter()
11097            .map(|field| self.local_binding_name(field.name.as_str()))
11098            .collect::<Vec<_>>()
11099            .join(", ");
11100        let binding_env = helper
11101            .params
11102            .iter()
11103            .map(|field| {
11104                (
11105                    field.name.as_str().to_owned(),
11106                    self.local_binding_name(field.name.as_str()),
11107                )
11108            })
11109            .collect::<BTreeMap<String, _>>();
11110        let field_env = self.field_env_override.clone().unwrap_or_else(|| {
11111            self.schema
11112                .state
11113                .fields
11114                .iter()
11115                .map(|field| {
11116                    (
11117                        field.name.as_str().to_owned(),
11118                        field.name.as_str().to_owned(),
11119                    )
11120                })
11121                .collect::<BTreeMap<String, _>>()
11122        });
11123        let binding_types = helper
11124            .params
11125            .iter()
11126            .map(|field| (field.name.as_str().to_owned(), field.ty.clone()))
11127            .collect::<BTreeMap<String, _>>();
11128        if helper.params.is_empty() {
11129            writeln!(
11130                out,
11131                "{} == {}",
11132                self.scoped_helper_name(&helper.name),
11133                self.render_expr_with_types(&helper.body, &field_env, &binding_env, &binding_types)
11134            )
11135            .expect("write to string");
11136        } else {
11137            writeln!(
11138                out,
11139                "{}({}) == {}",
11140                self.scoped_helper_name(&helper.name),
11141                params,
11142                self.render_expr_with_types(&helper.body, &field_env, &binding_env, &binding_types)
11143            )
11144            .expect("write to string");
11145        }
11146    }
11147
11148    fn render_runtime_delivery_native_helpers(&self, out: &mut String) {
11149        writeln!(
11150            out,
11151            "{}(current, recipient, outcome) ==",
11152            self.scoped_helper_name("runtime_delivery_recipient_outcomes_after_set")
11153        )
11154        .expect("write to string");
11155        pushln!(out, "    MapSet(current, recipient, outcome)");
11156    }
11157
11158    fn render_session_document_native_helpers(&self, out: &mut String) {
11159        writeln!(
11160            out,
11161            "{}(current, slot, value) ==",
11162            self.scoped_helper_name("session_document_instruction_slot_after_set")
11163        )
11164        .expect("write to string");
11165        pushln!(out, "    MapSet(current, slot, value)");
11166        // The body bytes of the Active slots; a slot the bytes map does not
11167        // name counts nothing (the Rust authorities agree).
11168        writeln!(
11169            out,
11170            "{}(slot_effect, slot_bytes) ==",
11171            self.scoped_helper_name("session_document_instruction_active_bytes")
11172        )
11173        .expect("write to string");
11174        pushln!(
11175            out,
11176            "    LET RECURSIVE SessionDocumentInstructionActiveBytesOver(_)"
11177        );
11178        pushln!(
11179            out,
11180            "        SessionDocumentInstructionActiveBytesOver(instruction_slots) =="
11181        );
11182        pushln!(out, "            IF instruction_slots = {{}} THEN 0");
11183        pushln!(
11184            out,
11185            "            ELSE LET instruction_slot == CHOOSE candidate_slot \\in instruction_slots : TRUE"
11186        );
11187        pushln!(
11188            out,
11189            "                 IN (IF slot_effect[instruction_slot] = \"Active\" /\\ instruction_slot \\in DOMAIN slot_bytes"
11190        );
11191        pushln!(
11192            out,
11193            "                     THEN slot_bytes[instruction_slot] ELSE 0)"
11194        );
11195        pushln!(
11196            out,
11197            "                    + SessionDocumentInstructionActiveBytesOver(instruction_slots \\ {{instruction_slot}})"
11198        );
11199        pushln!(
11200            out,
11201            "    IN SessionDocumentInstructionActiveBytesOver(DOMAIN slot_effect)"
11202        );
11203        // The entries of a slot map whose slot is Active: what an
11204        // application puts in effect (the Rust authorities agree).
11205        writeln!(
11206            out,
11207            "{}(slot_effect, slot_values) ==",
11208            self.scoped_helper_name("session_document_instruction_active_slots")
11209        )
11210        .expect("write to string");
11211        pushln!(
11212            out,
11213            "    [instruction_slot \\in {{candidate_slot \\in DOMAIN slot_values :"
11214        );
11215        pushln!(
11216            out,
11217            "            candidate_slot \\in DOMAIN slot_effect /\\ slot_effect[candidate_slot] = \"Active\"}}"
11218        );
11219        pushln!(out, "        |-> slot_values[instruction_slot]]");
11220        // Per activation key, the rows a retirement leaves retired: every
11221        // row but the newest, or the recovered count when that is more; a
11222        // key the retired map does not name counts none (the Rust
11223        // authorities agree).
11224        writeln!(
11225            out,
11226            "{}(activation_rows, activation_retired) ==",
11227            self.scoped_helper_name("session_document_activation_retired_after")
11228        )
11229        .expect("write to string");
11230        pushln!(out, "    [activation_key \\in DOMAIN activation_rows |->");
11231        pushln!(
11232            out,
11233            "        LET retired_count == IF activation_key \\in DOMAIN activation_retired THEN activation_retired[activation_key] ELSE 0"
11234        );
11235        pushln!(
11236            out,
11237            "            superseded_count == IF activation_rows[activation_key] > 0 THEN activation_rows[activation_key] - 1 ELSE 0"
11238        );
11239        pushln!(
11240            out,
11241            "        IN IF retired_count >= superseded_count THEN retired_count ELSE superseded_count]"
11242        );
11243    }
11244
11245    fn render_meerkat_machine_native_helpers(&self, out: &mut String) {
11246        let prefix = |name: &str| self.scoped_helper_name(name);
11247        writeln!(
11248            out,
11249            "{}(current, candidate) ==",
11250            prefix("meerkat_machine_session_id_matches_string")
11251        )
11252        .expect("write to string");
11253        pushln!(out, "    current # None /\\ current.value = candidate");
11254        writeln!(
11255            out,
11256            "{}(endpoints, endpoint_count) ==",
11257            prefix("meerkat_peer_endpoint_set_cardinality_matches")
11258        )
11259        .expect("write to string");
11260        pushln!(out, "    Cardinality(endpoints) = endpoint_count");
11261        writeln!(
11262            out,
11263            "{}(endpoints, peer_id) ==",
11264            prefix("meerkat_peer_endpoint_set_contains_peer_id")
11265        )
11266        .expect("write to string");
11267        pushln!(
11268            out,
11269            "    \\E endpoint \\in endpoints: endpoint.peer_id = peer_id"
11270        );
11271        writeln!(
11272            out,
11273            "{}(endpoint, peer_id) ==",
11274            prefix("meerkat_peer_endpoint_option_peer_id_matches")
11275        )
11276        .expect("write to string");
11277        pushln!(
11278            out,
11279            "    endpoint # None /\\ endpoint.value.peer_id = peer_id"
11280        );
11281        writeln!(
11282            out,
11283            "{}(endpoint, peer_id) ==",
11284            prefix("meerkat_peer_endpoint_peer_id_matches")
11285        )
11286        .expect("write to string");
11287        pushln!(out, "    endpoint.peer_id = peer_id");
11288        writeln!(
11289            out,
11290            "{}(endpoints) ==",
11291            prefix("meerkat_peer_endpoint_set_peer_ids_unique")
11292        )
11293        .expect("write to string");
11294        pushln!(
11295            out,
11296            "    Cardinality(endpoints) = Cardinality({{ endpoint.peer_id : endpoint \\in endpoints }})"
11297        );
11298        writeln!(
11299            out,
11300            "{}(rows, operation_by_authority, operation_id) ==",
11301            prefix("meerkat_machine_live_bridge_authority_rows_without_operation")
11302        )
11303        .expect("write to string");
11304        pushln!(
11305            out,
11306            "    [authority_id \\in {{ candidate \\in DOMAIN rows : IF candidate \\in DOMAIN operation_by_authority THEN operation_by_authority[candidate] # operation_id ELSE TRUE }} |-> rows[authority_id]]"
11307        );
11308        writeln!(
11309            out,
11310            "{}(authorities, operation_by_authority, operation_id) ==",
11311            prefix("meerkat_machine_live_bridge_authorities_without_operation")
11312        )
11313        .expect("write to string");
11314        pushln!(
11315            out,
11316            "    {{ authority_id \\in authorities : IF authority_id \\in DOMAIN operation_by_authority THEN operation_by_authority[authority_id] # operation_id ELSE TRUE }}"
11317        );
11318        // The inputs still bound to one run: its batch and its durable joins,
11319        // staged or, in a resumed run, applied by a committed round. The
11320        // parameters are prefixed: TLA+ forbids a parameter named like a
11321        // state variable (`input_phases`).
11322        writeln!(
11323            out,
11324            "{}(arg_run_associations, arg_input_phases, arg_run_id) ==",
11325            prefix("meerkat_machine_run_contributor_count")
11326        )
11327        .expect("write to string");
11328        pushln!(
11329            out,
11330            "    Cardinality({{ arg_input_id \\in DOMAIN arg_run_associations : IF arg_run_associations[arg_input_id] = arg_run_id /\\ arg_input_id \\in DOMAIN arg_input_phases THEN arg_input_phases[arg_input_id] \\in {{\"Staged\", \"Applied\", \"AppliedPendingConsumption\"}} ELSE FALSE }})"
11331        );
11332        // The most contributors one run's commit names. A defined operator,
11333        // not a literal in the guard, so a bounded audit can substitute a
11334        // small bound (`meerkat_machine_run_contributor_limit <- ...`) and
11335        // explore the refused join.
11336        writeln!(
11337            out,
11338            "{} == {}",
11339            prefix("meerkat_machine_run_contributor_limit"),
11340            meerkat_machine_schema::catalog::dsl::meerkat_machine::command_capabilities::RUNTIME_LOOP_BATCH_MAX_INPUTS
11341        )
11342        .expect("write to string");
11343    }
11344
11345    fn render_mob_machine_native_helpers(&self, out: &mut String) {
11346        let prefix = |name: &str| self.scoped_helper_name(name);
11347        let local = |name: &str| self.local_binding_name(name);
11348        // Row #181: compute the next monotone respawn generation for an
11349        // identity. Missing identity starts at generation zero. A retained
11350        // u64::MAX generation has no successor and must never wrap to zero.
11351        writeln!(
11352            out,
11353            "{}(arg_identity_runtime_generations, arg_agent_identity) ==",
11354            prefix("mob_machine_next_respawn_generation")
11355        )
11356        .expect("write to string");
11357        pushln!(
11358            out,
11359            "    IF arg_agent_identity \\notin DOMAIN arg_identity_runtime_generations"
11360        );
11361        pushln!(out, "    THEN Some(0)");
11362        pushln!(
11363            out,
11364            "    ELSE IF arg_identity_runtime_generations[arg_agent_identity] = {TLA_RUST_U64_MAX_CONSTANT}"
11365        );
11366        pushln!(out, "         THEN None");
11367        pushln!(
11368            out,
11369            "         ELSE Some(arg_identity_runtime_generations[arg_agent_identity] + 1)"
11370        );
11371        // The generation a new incarnation mints: one past the larger of the
11372        // retained generation and the recovered high-water, zero for an
11373        // identity in neither map, and no successor past the Rust u64
11374        // ceiling. Recovery replay keeps the operator above, which reads the
11375        // retained map only.
11376        writeln!(
11377            out,
11378            "{}(arg_identity_runtime_generations, arg_identity_generation_highwater, arg_agent_identity) ==",
11379            prefix("mob_machine_next_minted_generation")
11380        )
11381        .expect("write to string");
11382        pushln!(
11383            out,
11384            "    LET retained == IF arg_agent_identity \\in DOMAIN arg_identity_runtime_generations"
11385        );
11386        pushln!(
11387            out,
11388            "                    THEN arg_identity_runtime_generations[arg_agent_identity] ELSE 0"
11389        );
11390        pushln!(
11391            out,
11392            "        highwater == IF arg_agent_identity \\in DOMAIN arg_identity_generation_highwater"
11393        );
11394        pushln!(
11395            out,
11396            "                     THEN arg_identity_generation_highwater[arg_agent_identity] ELSE 0"
11397        );
11398        pushln!(
11399            out,
11400            "        base == IF retained >= highwater THEN retained ELSE highwater"
11401        );
11402        pushln!(
11403            out,
11404            "    IN IF arg_agent_identity \\notin DOMAIN arg_identity_runtime_generations /\\ arg_agent_identity \\notin DOMAIN arg_identity_generation_highwater"
11405        );
11406        pushln!(out, "       THEN Some(0)");
11407        pushln!(
11408            out,
11409            "       ELSE IF base = {TLA_RUST_U64_MAX_CONSTANT} THEN None ELSE Some(base + 1)"
11410        );
11411        // Supervisor epochs use the same non-wrapping u64 successor relation
11412        // in both plain and Option-valued recovered tuples. These operators
11413        // deliberately mention the Rust u64 ceiling so TLC cannot admit
11414        // MAX -> 0 as a successor through unbounded integer arithmetic.
11415        writeln!(
11416            out,
11417            "{}(arg_current, arg_next) ==",
11418            prefix("mob_machine_u64_is_exact_successor")
11419        )
11420        .expect("write to string");
11421        pushln!(out, "    /\\ arg_current # {TLA_RUST_U64_MAX_CONSTANT}");
11422        pushln!(out, "    /\\ arg_next = arg_current + 1");
11423        writeln!(
11424            out,
11425            "{}(arg_current, arg_next) ==",
11426            prefix("mob_machine_optional_u64_is_exact_successor")
11427        )
11428        .expect("write to string");
11429        pushln!(out, "    /\\ arg_current # {TLA_RUST_U64_MAX_CONSTANT}");
11430        pushln!(out, "    /\\ arg_next = Some(arg_current + 1)");
11431        // Remote-turn custody admission is a native MobMachine reducer because
11432        // it enforces aggregate cardinality and correlation-key uniqueness
11433        // across all three custody sets. Keep this operator structurally
11434        // equivalent to the Rust helper in the canonical MobMachine catalog.
11435        writeln!(
11436            out,
11437            "{}(pending, committed, resolved, candidate) ==",
11438            prefix("mob_machine_remote_turn_custody_admits")
11439        )
11440        .expect("write to string");
11441        pushln!(
11442            out,
11443            "    LET same_member_host_count == Cardinality({{ row \\in pending : /\\ row.agent_identity = candidate.agent_identity /\\ row.host_id = candidate.host_id }})"
11444        );
11445        pushln!(
11446            out,
11447            "            + Cardinality({{ row \\in committed : /\\ row.agent_identity = candidate.agent_identity /\\ row.host_id = candidate.host_id }})"
11448        );
11449        pushln!(
11450            out,
11451            "            + Cardinality({{ row \\in resolved : /\\ row.agent_identity = candidate.agent_identity /\\ row.host_id = candidate.host_id }})"
11452        );
11453        pushln!(
11454            out,
11455            "    IN /\\ Cardinality(pending) + Cardinality(committed) + Cardinality(resolved) < 4096"
11456        );
11457        pushln!(out, "       /\\ candidate.dispatch_sequence > 0");
11458        pushln!(out, "       /\\ candidate.input_id # \"\"");
11459        pushln!(out, "       /\\ candidate.run_id # \"\"");
11460        pushln!(out, "       /\\ candidate.step_id # \"\"");
11461        pushln!(out, "       /\\ candidate.host_id # \"\"");
11462        pushln!(out, "       /\\ candidate.member_session_id # \"\"");
11463        for rows in ["pending", "committed", "resolved"] {
11464            pushln!(
11465                out,
11466                "       /\\ \\A row \\in {rows} : /\\ row.dispatch_sequence # candidate.dispatch_sequence /\\ \\lnot (/\\ row.agent_identity = candidate.agent_identity /\\ row.host_id = candidate.host_id /\\ row.generation = candidate.generation /\\ row.fence_token = candidate.fence_token /\\ row.input_id = candidate.input_id)"
11467            );
11468        }
11469        pushln!(out, "       /\\ same_member_host_count < 256");
11470        // Placed completion/kickoff helpers. TLC treats canonical UUID lexical
11471        // shape as an abstract non-empty string property; Rust performs the
11472        // stricter parse-and-roundtrip check at the executable boundary.
11473        writeln!(
11474            out,
11475            "{}(candidate) ==",
11476            prefix("mob_machine_placed_completion_obligation_well_formed")
11477        )
11478        .expect("write to string");
11479        pushln!(out, "    /\\ candidate.agent_identity # \"\"");
11480        pushln!(out, "    /\\ candidate.host_id # \"\"");
11481        pushln!(out, "    /\\ candidate.host_binding_generation > 0");
11482        pushln!(out, "    /\\ candidate.member_session_id # \"\"");
11483        pushln!(out, "    /\\ candidate.dispatch_sequence > 0");
11484        pushln!(out, "    /\\ candidate.input_id # \"\"");
11485        writeln!(
11486            out,
11487            "{}(pending, resolved, candidate) ==",
11488            prefix("mob_machine_placed_completion_custody_admits")
11489        )
11490        .expect("write to string");
11491        pushln!(out, "    LET rows == pending \\cup resolved");
11492        pushln!(
11493            out,
11494            "        same_member_host == Cardinality({{ row \\in rows : /\\ row.agent_identity = candidate.agent_identity /\\ row.host_id = candidate.host_id }})"
11495        );
11496        pushln!(out, "    IN /\\ Cardinality(rows) < 4096");
11497        pushln!(
11498            out,
11499            "       /\\ \\A row \\in rows : /\\ row.dispatch_sequence # candidate.dispatch_sequence /\\ \\lnot (/\\ row.agent_identity = candidate.agent_identity /\\ row.host_id = candidate.host_id /\\ row.generation = candidate.generation /\\ row.fence_token = candidate.fence_token /\\ row.input_id = candidate.input_id)"
11500        );
11501        pushln!(out, "       /\\ same_member_host < 256");
11502        writeln!(
11503            out,
11504            "{}(active_run, active_layer, active_members, layer_phases, layer_dispositions) ==",
11505            prefix("mob_machine_adaptive_lifecycle_drained")
11506        )
11507        .expect("write to string");
11508        pushln!(out, "    /\\ active_run = None");
11509        pushln!(out, "    /\\ DOMAIN active_layer = {{}}");
11510        pushln!(
11511            out,
11512            "    /\\ \\A run_id \\in DOMAIN active_members : active_members[run_id] = 0"
11513        );
11514        pushln!(out, "    /\\ \\A layer_id \\in DOMAIN layer_phases :");
11515        pushln!(
11516            out,
11517            "           \\/ layer_phases[layer_id] = \"Validating\""
11518        );
11519        pushln!(
11520            out,
11521            "           \\/ /\\ layer_id \\in DOMAIN layer_dispositions"
11522        );
11523        pushln!(
11524            out,
11525            "              /\\ layer_phases[layer_id] \\in {{\"Completed\", \"SetupFailed\", \"RunFailed\", \"ResultInvalid\", \"Canceled\"}}"
11526        );
11527        writeln!(
11528            out,
11529            "{}(adaptive_run_id, active_layer, active_members, layer_run, layer_phases, layer_dispositions) ==",
11530            prefix("mob_machine_adaptive_run_custody_drained")
11531        )
11532        .expect("write to string");
11533        pushln!(out, "    /\\ adaptive_run_id \\notin DOMAIN active_layer");
11534        pushln!(
11535            out,
11536            "    /\\ (IF adaptive_run_id \\in DOMAIN active_members THEN active_members[adaptive_run_id] ELSE 0) = 0"
11537        );
11538        pushln!(out, "    /\\ \\A layer_id \\in DOMAIN layer_run :");
11539        pushln!(out, "           \\/ layer_run[layer_id] # adaptive_run_id");
11540        pushln!(
11541            out,
11542            "           \\/ /\\ layer_id \\in DOMAIN layer_dispositions"
11543        );
11544        pushln!(out, "              /\\ layer_id \\in DOMAIN layer_phases");
11545        pushln!(
11546            out,
11547            "              /\\ layer_phases[layer_id] \\in {{\"Completed\", \"SetupFailed\", \"RunFailed\", \"ResultInvalid\", \"Canceled\"}}"
11548        );
11549        writeln!(
11550            out,
11551            "{}(started, callback_pending, failed, cancelled, kickoff_errors, identity, outcome_kind, outcome_error, closure_kind) ==",
11552            prefix("mob_machine_finalized_placed_kickoff_recovery_well_formed")
11553        )
11554        .expect("write to string");
11555        pushln!(
11556            out,
11557            "    /\\ Cardinality({{ kickoff_phase \\in {{\"Started\", \"CallbackPending\", \"Failed\", \"Cancelled\"}} :"
11558        );
11559        pushln!(
11560            out,
11561            "           CASE kickoff_phase = \"Started\" -> identity \\in started"
11562        );
11563        pushln!(
11564            out,
11565            "             [] kickoff_phase = \"CallbackPending\" -> identity \\in callback_pending"
11566        );
11567        pushln!(
11568            out,
11569            "             [] kickoff_phase = \"Failed\" -> identity \\in failed"
11570        );
11571        pushln!(
11572            out,
11573            "             [] OTHER -> identity \\in cancelled }}) = 1"
11574        );
11575        pushln!(
11576            out,
11577            "    /\\ CASE outcome_kind = \"Failed\" -> outcome_error # None"
11578        );
11579        pushln!(
11580            out,
11581            "          [] outcome_kind = \"RejectedNoEffect\" -> /\\ outcome_error # None /\\ outcome_error.value # \"\""
11582        );
11583        pushln!(out, "          [] OTHER -> outcome_error = None");
11584        pushln!(
11585            out,
11586            "    /\\ CASE closure_kind = \"Acknowledged\" -> /\\ outcome_kind # \"RejectedNoEffect\" /\\ outcome_kind # \"Disposed\""
11587        );
11588        pushln!(
11589            out,
11590            "          [] closure_kind = \"RejectedNoEffect\" -> outcome_kind = \"RejectedNoEffect\""
11591        );
11592        pushln!(
11593            out,
11594            "          [] OTHER -> outcome_kind # \"RejectedNoEffect\""
11595        );
11596        pushln!(
11597            out,
11598            "    /\\ CASE identity \\in cancelled -> identity \\notin DOMAIN kickoff_errors"
11599        );
11600        pushln!(
11601            out,
11602            "          [] identity \\in started -> /\\ outcome_kind = \"Started\" /\\ identity \\notin DOMAIN kickoff_errors"
11603        );
11604        pushln!(
11605            out,
11606            "          [] identity \\in callback_pending -> /\\ outcome_kind = \"CallbackPending\" /\\ identity \\notin DOMAIN kickoff_errors"
11607        );
11608        pushln!(
11609            out,
11610            "          [] OTHER -> /\\ outcome_kind \\in {{\"Failed\", \"RejectedNoEffect\"}} /\\ identity \\in DOMAIN kickoff_errors /\\ outcome_error = Some(kickoff_errors[identity])"
11611        );
11612        writeln!(
11613            out,
11614            "{}(candidate) ==",
11615            prefix("mob_machine_placed_kickoff_obligation_well_formed")
11616        )
11617        .expect("write to string");
11618        pushln!(out, "    /\\ candidate.agent_identity # \"\"");
11619        pushln!(out, "    /\\ candidate.host_id # \"\"");
11620        pushln!(out, "    /\\ candidate.host_binding_generation > 0");
11621        pushln!(out, "    /\\ candidate.member_session_id # \"\"");
11622        pushln!(out, "    /\\ candidate.input_id # \"\"");
11623        pushln!(out, "    /\\ candidate.objective_id # \"\"");
11624        writeln!(
11625            out,
11626            "{}(pending_kickoffs, resolved_kickoffs, retained_kickoffs, pending_turns, committed_turns, resolved_turns, pending_completions, resolved_completions, candidate) ==",
11627            prefix("mob_machine_placed_kickoff_correlation_available")
11628        )
11629        .expect("write to string");
11630        pushln!(
11631            out,
11632            "    /\\ \\A row \\in pending_kickoffs \\cup resolved_kickoffs : /\\ row.agent_identity # candidate.agent_identity /\\ \\lnot (/\\ row.host_id = candidate.host_id /\\ row.generation = candidate.generation /\\ row.fence_token = candidate.fence_token /\\ row.input_id = candidate.input_id)"
11633        );
11634        pushln!(
11635            out,
11636            "    /\\ \\A identity \\in DOMAIN retained_kickoffs : retained_kickoffs[identity].agent_identity # candidate.agent_identity"
11637        );
11638        pushln!(
11639            out,
11640            "    /\\ \\A row \\in pending_turns \\cup committed_turns \\cup resolved_turns : \\lnot (/\\ row.agent_identity = candidate.agent_identity /\\ row.host_id = candidate.host_id /\\ row.generation = candidate.generation /\\ row.fence_token = candidate.fence_token /\\ row.input_id = candidate.input_id)"
11641        );
11642        pushln!(
11643            out,
11644            "    /\\ \\A row \\in pending_completions \\cup resolved_completions : \\lnot (/\\ row.agent_identity = candidate.agent_identity /\\ row.host_id = candidate.host_id /\\ row.generation = candidate.generation /\\ row.fence_token = candidate.fence_token /\\ row.input_id = candidate.input_id)"
11645        );
11646        writeln!(
11647            out,
11648            "{}(pending, resolved, agent_identity) ==",
11649            prefix("mob_machine_placed_kickoff_custody_absent_for_identity")
11650        )
11651        .expect("write to string");
11652        pushln!(
11653            out,
11654            "    \\A row \\in pending \\cup resolved : row.agent_identity # agent_identity"
11655        );
11656        writeln!(
11657            out,
11658            "{}(pending, resolved, host_id) ==",
11659            prefix("mob_machine_placed_kickoff_custody_absent_for_host")
11660        )
11661        .expect("write to string");
11662        pushln!(
11663            out,
11664            "    \\A row \\in pending \\cup resolved : row.host_id # host_id"
11665        );
11666        writeln!(
11667            out,
11668            "{}(pending, resolved, retained, candidate) ==",
11669            prefix("mob_machine_remote_turn_input_id_available_to_kickoff")
11670        )
11671        .expect("write to string");
11672        pushln!(
11673            out,
11674            "    /\\ \\A row \\in pending \\cup resolved : \\lnot (/\\ row.agent_identity = candidate.agent_identity /\\ row.host_id = candidate.host_id /\\ row.generation = candidate.generation /\\ row.fence_token = candidate.fence_token /\\ row.input_id = candidate.input_id)"
11675        );
11676        pushln!(
11677            out,
11678            "    /\\ \\A identity \\in DOMAIN retained : \\lnot (/\\ retained[identity].agent_identity = candidate.agent_identity /\\ retained[identity].host_id = candidate.host_id /\\ retained[identity].generation = candidate.generation /\\ retained[identity].fence_token = candidate.fence_token /\\ retained[identity].input_id = candidate.input_id)"
11679        );
11680        // Retirement atomically prunes every local wiring edge incident to
11681        // the retiring identity. This mirrors the catalog-native Rust helper
11682        // and keeps cold replay from resurrecting topology to an absent member.
11683        writeln!(
11684            out,
11685            "{}(arg_wiring_edges, arg_agent_identity) ==",
11686            prefix("mob_machine_wiring_edges_without_identity")
11687        )
11688        .expect("write to string");
11689        pushln!(
11690            out,
11691            "    {{ edge \\in arg_wiring_edges : /\\ edge.a # arg_agent_identity /\\ edge.b # arg_agent_identity }}"
11692        );
11693        // An edge's other end, and the owned edges a removal leaves (every
11694        // owned edge of the removed identity ends, whichever end owns it):
11695        // the catalog-native Rust helpers' mirrors.
11696        writeln!(
11697            out,
11698            "{}(arg_edge, arg_agent_identity) ==",
11699            prefix("mob_machine_wiring_edge_other")
11700        )
11701        .expect("write to string");
11702        pushln!(
11703            out,
11704            "    IF arg_edge.a = arg_agent_identity THEN arg_edge.b ELSE arg_edge.a"
11705        );
11706        writeln!(
11707            out,
11708            "{}(arg_identity_edge_owners, arg_agent_identity) ==",
11709            prefix("mob_machine_owned_edges_without_identity")
11710        )
11711        .expect("write to string");
11712        pushln!(
11713            out,
11714            "    [edge \\in {{ e \\in DOMAIN arg_identity_edge_owners : /\\ e.a # arg_agent_identity /\\ e.b # arg_agent_identity }} |-> arg_identity_edge_owners[edge]]"
11715        );
11716        writeln!(
11717            out,
11718            "{}(arg_external_peer_edges, arg_agent_identity) ==",
11719            prefix("mob_machine_external_peer_edges_without_identity")
11720        )
11721        .expect("write to string");
11722        pushln!(
11723            out,
11724            "    {{ edge \\in arg_external_peer_edges : edge.local # arg_agent_identity }}"
11725        );
11726        writeln!(
11727            out,
11728            "{}(arg_external_peer_edges_by_key, arg_agent_identity) ==",
11729            prefix("mob_machine_external_peer_edges_by_key_without_identity")
11730        )
11731        .expect("write to string");
11732        pushln!(
11733            out,
11734            "    [key \\in {{ key \\in DOMAIN arg_external_peer_edges_by_key : key.local # arg_agent_identity }} |-> arg_external_peer_edges_by_key[key]]"
11735        );
11736        // The next sessions of the pending FreshSession rotations, which a
11737        // destroy's admission abandons. A SameSession rotation names its
11738        // member's own session, which the destroy's retirement of that member
11739        // disposes of. Mirror of the catalog-native Rust helper.
11740        writeln!(
11741            out,
11742            "{}(arg_member_rotation_session_ids, arg_member_rotation_targets) ==",
11743            prefix("mob_machine_fresh_rotation_sessions")
11744        )
11745        .expect("write to string");
11746        pushln!(
11747            out,
11748            "    [id \\in {{ id \\in DOMAIN arg_member_rotation_session_ids : ~(id \\in DOMAIN arg_member_rotation_targets /\\ arg_member_rotation_targets[id] = \"SameSession\") }} |-> arg_member_rotation_session_ids[id]]"
11749        );
11750        // Row #351: reconcile-membership spawn/retire set helpers. The DSL
11751        // ReconcileMembership effect emits calls to these, but they had no TLA+
11752        // operator definitions, so TLC reported "Unknown operator" for
11753        // MobMachine (and any composition embedding it). Mirror of the Rust
11754        // helpers in `catalog::dsl::mob_machine`: spawn = desired identities not
11755        // yet bound to a runtime; retire = currently-bound identities that are
11756        // no longer desired, gated on `retire_stale` (empty set otherwise).
11757        // `identity_to_runtime` is the bound-identity function (DOMAIN = the
11758        // currently-bound identities); `desired` is the target identity set.
11759        // Both range over workers only: an identity entry (DOMAIN of
11760        // `identity_entry_origins`) is never spawned or retired by them, and
11761        // neither is a reserved name (`identity_entry_tombstones`, never
11762        // seated, is never spawned; `identity_entry_unreadable` is neither
11763        // spawned nor retired).
11764        writeln!(
11765            out,
11766            "{}(arg_identity_to_runtime, arg_identity_entry_origins, arg_identity_entry_tombstones, arg_identity_entry_unreadable, arg_desired) ==",
11767            prefix("mob_machine_members_to_spawn")
11768        )
11769        .expect("write to string");
11770        pushln!(
11771            out,
11772            "    {{ member \\in arg_desired : member \\notin DOMAIN arg_identity_to_runtime /\\ member \\notin DOMAIN arg_identity_entry_origins /\\ member \\notin arg_identity_entry_tombstones /\\ member \\notin arg_identity_entry_unreadable }}"
11773        );
11774        writeln!(
11775            out,
11776            "{}(arg_identity_to_runtime, arg_identity_entry_origins, arg_identity_entry_unreadable, arg_desired, arg_retire_stale) ==",
11777            prefix("mob_machine_members_to_retire")
11778        )
11779        .expect("write to string");
11780        pushln!(out, "    IF arg_retire_stale");
11781        pushln!(
11782            out,
11783            "    THEN {{ member \\in DOMAIN arg_identity_to_runtime : member \\notin arg_desired /\\ member \\notin DOMAIN arg_identity_entry_origins /\\ member \\notin arg_identity_entry_unreadable }}"
11784        );
11785        pushln!(out, "    ELSE {{}}");
11786        // Placed-carrier cleanup is identity-exclusive and carries the exact
11787        // durable operation tuple. Both operators are native Rust helpers in
11788        // the catalog, so every standalone/composition TLA namespace must
11789        // define their semantic twins explicitly.
11790        writeln!(
11791            out,
11792            "{}(arg_obligations, arg_agent_identity) ==",
11793            prefix("mob_machine_placed_cleanup_absent_for_identity")
11794        )
11795        .expect("write to string");
11796        pushln!(
11797            out,
11798            "    \\A obligation \\in arg_obligations : obligation.agent_identity # arg_agent_identity"
11799        );
11800        writeln!(
11801            out,
11802            "{}(arg_agent_identity, arg_spawn_id, arg_generation, arg_fence_token, arg_provision_operation_id, arg_operation_owner_session_id, arg_expected_phase) ==",
11803            prefix("mob_machine_placed_cleanup_obligation")
11804        )
11805        .expect("write to string");
11806        pushln!(
11807            out,
11808            "    [agent_identity |-> arg_agent_identity, spawn_id |-> arg_spawn_id, generation |-> arg_generation, fence_token |-> arg_fence_token, provision_operation_id |-> arg_provision_operation_id, operation_owner_session_id |-> arg_operation_owner_session_id, expected_phase |-> arg_expected_phase]"
11809        );
11810        // A placed carrier is live only at the exact currently bound host
11811        // generation. Keep every partial-map read behind a TLA IF so sampled
11812        // malformed/partial states evaluate to FALSE instead of indexing an
11813        // absent function key.
11814        writeln!(
11815            out,
11816            "{}(arg_member_placement, arg_current_binding_generations, arg_host_bind_phase, arg_host_binding_generations, arg_agent_identity) ==",
11817            prefix("mob_machine_placed_carrier_binding_active")
11818        )
11819        .expect("write to string");
11820        pushln!(
11821            out,
11822            "    IF arg_agent_identity \\notin DOMAIN arg_member_placement"
11823        );
11824        pushln!(out, "    THEN FALSE");
11825        pushln!(
11826            out,
11827            "    ELSE LET host == arg_member_placement[arg_agent_identity]"
11828        );
11829        pushln!(
11830            out,
11831            "         IN IF host \\notin DOMAIN arg_host_bind_phase"
11832        );
11833        pushln!(out, "            THEN FALSE");
11834        pushln!(
11835            out,
11836            "            ELSE IF arg_host_bind_phase[host] # \"Bound\""
11837        );
11838        pushln!(out, "                 THEN FALSE");
11839        pushln!(
11840            out,
11841            "                 ELSE IF arg_agent_identity \\notin DOMAIN arg_current_binding_generations"
11842        );
11843        pushln!(out, "                      THEN FALSE");
11844        pushln!(
11845            out,
11846            "                      ELSE LET generation == arg_current_binding_generations[arg_agent_identity]"
11847        );
11848        pushln!(out, "                           IN /\\ generation > 0");
11849        pushln!(
11850            out,
11851            "                              /\\ host \\in DOMAIN arg_host_binding_generations"
11852        );
11853        pushln!(
11854            out,
11855            "                              /\\ arg_host_binding_generations[host] = generation"
11856        );
11857        writeln!(
11858            out,
11859            "{}(arg_host_id, arg_binding_generation) ==",
11860            prefix("mob_machine_host_binding_generation_tombstone")
11861        )
11862        .expect("write to string");
11863        pushln!(
11864            out,
11865            "    [host_id |-> arg_host_id, binding_generation |-> arg_binding_generation]"
11866        );
11867        // Cleanup after a revoke is authorized only when the exact retained
11868        // carrier generation has a durable revocation tombstone and that host
11869        // is no longer Bound.
11870        writeln!(
11871            out,
11872            "{}(arg_member_placement, arg_current_binding_generations, arg_host_bind_phase, arg_confirmed_revocations, arg_agent_identity) ==",
11873            prefix("mob_machine_placed_carrier_binding_confirmed_revoked")
11874        )
11875        .expect("write to string");
11876        pushln!(
11877            out,
11878            "    IF arg_agent_identity \\notin DOMAIN arg_member_placement"
11879        );
11880        pushln!(out, "    THEN FALSE");
11881        pushln!(
11882            out,
11883            "    ELSE LET host == arg_member_placement[arg_agent_identity]"
11884        );
11885        pushln!(
11886            out,
11887            "         IN IF arg_agent_identity \\notin DOMAIN arg_current_binding_generations"
11888        );
11889        pushln!(out, "            THEN FALSE");
11890        pushln!(
11891            out,
11892            "            ELSE LET generation == arg_current_binding_generations[arg_agent_identity]"
11893        );
11894        pushln!(out, "                 IN /\\ generation > 0");
11895        pushln!(
11896            out,
11897            "                    /\\ (IF host \\in DOMAIN arg_host_bind_phase THEN arg_host_bind_phase[host] # \"Bound\" ELSE TRUE)"
11898        );
11899        pushln!(
11900            out,
11901            "                    /\\ [host_id |-> host, binding_generation |-> generation] \\in arg_confirmed_revocations"
11902        );
11903        // Mob-coordination temporal predicates (work-intent / resource-claim
11904        // expiry). The DSL emits calls to these guards but they had no TLA+
11905        // definitions, so TLC reported "Unknown operator" for MobMachine (and
11906        // for any composition embedding it). The expires-at argument is the
11907        // stored `Option<u64>` (`Some(ms)`/`None`) and `now_ms` is a raw value;
11908        // `e # None /\ e.value <= now_ms` short-circuits when there is no expiry.
11909        // Resource-claim status arrives as the raw status string.
11910        writeln!(
11911            out,
11912            "{}(expires_at_ms, now_ms) ==",
11913            prefix("mob_coordination_expired_at")
11914        )
11915        .expect("write to string");
11916        pushln!(out, "    /\\ expires_at_ms # None");
11917        pushln!(out, "    /\\ expires_at_ms.value <= now_ms");
11918        writeln!(
11919            out,
11920            "{}(expires_at_ms, now_ms) == ~{}(expires_at_ms, now_ms)",
11921            prefix("mob_coordination_work_intent_unexpired"),
11922            prefix("mob_coordination_expired_at")
11923        )
11924        .expect("write to string");
11925        writeln!(
11926            out,
11927            "{}(expires_at_ms, now_ms) == ~{}(expires_at_ms, now_ms)",
11928            prefix("mob_coordination_resource_claim_unexpired"),
11929            prefix("mob_coordination_expired_at")
11930        )
11931        .expect("write to string");
11932        writeln!(
11933            out,
11934            "{}(status, expires_at_ms, now_ms) ==",
11935            prefix("mob_coordination_resource_claim_active_at")
11936        )
11937        .expect("write to string");
11938        pushln!(out, "    /\\ status = \"Active\"");
11939        writeln!(
11940            out,
11941            "    /\\ ~{}(expires_at_ms, now_ms)",
11942            prefix("mob_coordination_expired_at")
11943        )
11944        .expect("write to string");
11945        writeln!(
11946            out,
11947            "{}(status, expires_at_ms, now_ms) == ~{}(status, expires_at_ms, now_ms)",
11948            prefix("mob_coordination_resource_claim_inactive_at"),
11949            prefix("mob_coordination_resource_claim_active_at")
11950        )
11951        .expect("write to string");
11952        writeln!(
11953            out,
11954            "{}(edges_by_key, edge) ==",
11955            prefix("mob_machine_external_peer_edge_has_matching_key")
11956        )
11957        .expect("write to string");
11958        pushln!(
11959            out,
11960            "    LET key == [local |-> edge.local, name |-> edge.endpoint.name]"
11961        );
11962        pushln!(out, "    IN /\\ key \\in DOMAIN edges_by_key");
11963        pushln!(out, "       /\\ edges_by_key[key] = edge");
11964        writeln!(
11965            out,
11966            "{}(edge) == edge.local",
11967            prefix("mob_machine_external_peer_edge_local")
11968        )
11969        .expect("write to string");
11970        writeln!(
11971            out,
11972            "{}(edge) == edge.endpoint.peer_id",
11973            prefix("mob_machine_external_peer_edge_peer_id")
11974        )
11975        .expect("write to string");
11976        writeln!(
11977            out,
11978            "{}(key, edge) ==",
11979            prefix("mob_machine_external_peer_key_matches_edge")
11980        )
11981        .expect("write to string");
11982        pushln!(out, "    /\\ key.local = edge.local");
11983        pushln!(out, "    /\\ key.name = edge.endpoint.name");
11984        writeln!(
11985            out,
11986            "{}(key, agent_identity) == key.local = agent_identity",
11987            prefix("mob_machine_external_peer_key_matches_local")
11988        )
11989        .expect("write to string");
11990        writeln!(
11991            out,
11992            "{}(edges, agent_identity) ==",
11993            prefix("mob_machine_external_peer_identity_absent")
11994        )
11995        .expect("write to string");
11996        pushln!(
11997            out,
11998            "    \\A edge \\in edges : edge.endpoint.name /= agent_identity"
11999        );
12000        writeln!(
12001            out,
12002            "{}({}, agent_identity) ==",
12003            prefix("mob_machine_identity_has_session_binding"),
12004            local("member_session_bindings")
12005        )
12006        .expect("write to string");
12007        pushln!(
12008            out,
12009            "    /\\ agent_identity \\in DOMAIN {}",
12010            local("member_session_bindings")
12011        );
12012        pushln!(
12013            out,
12014            "    /\\ {}[agent_identity] /= \"\"",
12015            local("member_session_bindings")
12016        );
12017        writeln!(
12018            out,
12019            "{}({}, {}, {}, expected_runtime_ids) ==",
12020            prefix("mob_machine_session_bound_live_runtime_ids_match"),
12021            local("identity_to_runtime"),
12022            local("member_session_bindings"),
12023            local("live_runtime_ids")
12024        )
12025        .expect("write to string");
12026        pushln!(
12027            out,
12028            "    LET eligible_ids == {{ candidate \\in DOMAIN {} : {}[candidate] /= \"\" /\\ candidate \\in DOMAIN {} /\\ {}[candidate] \\in {} }}",
12029            local("member_session_bindings"),
12030            local("member_session_bindings"),
12031            local("identity_to_runtime"),
12032            local("identity_to_runtime"),
12033            local("live_runtime_ids")
12034        );
12035        pushln!(
12036            out,
12037            "    IN expected_runtime_ids = {{ {}[id] : id \\in eligible_ids }}",
12038            local("identity_to_runtime")
12039        );
12040        writeln!(
12041            out,
12042            "{}(endpoint) == endpoint.peer_id",
12043            prefix("mob_machine_member_peer_endpoint_peer_id")
12044        )
12045        .expect("write to string");
12046        writeln!(
12047            out,
12048            "{}(host_id, peer_id) == host_id = peer_id",
12049            prefix("mob_machine_host_id_matches_peer_id")
12050        )
12051        .expect("write to string");
12052        writeln!(
12053            out,
12054            "{}(current_endpoints, prior_endpoints, agent_identity, candidate_endpoint) ==",
12055            prefix("mob_machine_member_peer_id_available_for_identity")
12056        )
12057        .expect("write to string");
12058        pushln!(
12059            out,
12060            "    /\\ \\A other_identity \\in DOMAIN current_endpoints : other_identity = agent_identity \\/ current_endpoints[other_identity].peer_id /= candidate_endpoint.peer_id"
12061        );
12062        pushln!(
12063            out,
12064            "    /\\ \\A other_identity \\in DOMAIN prior_endpoints : other_identity = agent_identity \\/ \\A endpoint \\in prior_endpoints[other_identity] : endpoint.peer_id /= candidate_endpoint.peer_id"
12065        );
12066        writeln!(
12067            out,
12068            "{}(edges, agent_identity) ==",
12069            prefix("mob_machine_member_has_no_external_peer_edges")
12070        )
12071        .expect("write to string");
12072        pushln!(
12073            out,
12074            "    \\A edge \\in edges : edge.local /= agent_identity"
12075        );
12076        writeln!(
12077            out,
12078            "{}(all_prior_endpoints, agent_identity, current_endpoint, next_endpoint) ==",
12079            prefix("mob_machine_member_prior_peer_endpoints_after_migration")
12080        )
12081        .expect("write to string");
12082        pushln!(
12083            out,
12084            "    LET prior == IF agent_identity \\in DOMAIN all_prior_endpoints THEN all_prior_endpoints[agent_identity] ELSE {{}}"
12085        );
12086        pushln!(
12087            out,
12088            "        retained == {{ endpoint \\in (prior \\cup {{current_endpoint}}) : endpoint.peer_id /= next_endpoint.peer_id }}"
12089        );
12090        pushln!(out, "    IN IF retained = {{}}");
12091        pushln!(
12092            out,
12093            "       THEN [id \\in (DOMAIN all_prior_endpoints \\ {{agent_identity}}) |-> all_prior_endpoints[id]]"
12094        );
12095        pushln!(
12096            out,
12097            "       ELSE [id \\in (DOMAIN all_prior_endpoints \\cup {{agent_identity}}) |-> IF id = agent_identity THEN retained ELSE all_prior_endpoints[id]]"
12098        );
12099        writeln!(
12100            out,
12101            "{}(endpoint_identity, migrated_identity, retained_peer_endpoint, current_peer_ids) ==",
12102            prefix("mob_machine_member_endpoint_migration_cleanup_peer_id")
12103        )
12104        .expect("write to string");
12105        pushln!(
12106            out,
12107            "    IF endpoint_identity = migrated_identity THEN retained_peer_endpoint.peer_id ELSE current_peer_ids[endpoint_identity]"
12108        );
12109        writeln!(
12110            out,
12111            "{}(edge) == edge.a",
12112            prefix("mob_machine_wiring_edge_a")
12113        )
12114        .expect("write to string");
12115        writeln!(
12116            out,
12117            "{}(edge) == edge.b",
12118            prefix("mob_machine_wiring_edge_b")
12119        )
12120        .expect("write to string");
12121        writeln!(
12122            out,
12123            "{}(edge, agent_identity) == edge.a = agent_identity \\/ edge.b = agent_identity",
12124            prefix("mob_machine_wiring_edge_contains_identity")
12125        )
12126        .expect("write to string");
12127        writeln!(
12128            out,
12129            "{}({}, {}, agent_identity) ==",
12130            prefix("mob_machine_member_peer_overlay_complete"),
12131            local("wiring_edges"),
12132            local("member_peer_endpoints")
12133        )
12134        .expect("write to string");
12135        pushln!(
12136            out,
12137            "    \\A edge \\in {}: IF edge.a = agent_identity THEN edge.b \\in DOMAIN {} ELSE IF edge.b = agent_identity THEN edge.a \\in DOMAIN {} ELSE TRUE",
12138            local("wiring_edges"),
12139            local("member_peer_endpoints"),
12140            local("member_peer_endpoints")
12141        );
12142        writeln!(
12143            out,
12144            "{}({}, {}, {}, agent_identity) ==",
12145            prefix("mob_machine_member_peer_overlay"),
12146            local("wiring_edges"),
12147            local("member_peer_endpoints"),
12148            local("external_peer_edges")
12149        )
12150        .expect("write to string");
12151        pushln!(
12152            out,
12153            "    LET outgoing_edges == {{ edge \\in {} : edge.a = agent_identity /\\ edge.b \\in DOMAIN {} }}",
12154            local("wiring_edges"),
12155            local("member_peer_endpoints")
12156        );
12157        pushln!(
12158            out,
12159            "        incoming_edges == {{ edge \\in {} : edge.b = agent_identity /\\ edge.a \\in DOMAIN {} }}",
12160            local("wiring_edges"),
12161            local("member_peer_endpoints")
12162        );
12163        pushln!(
12164            out,
12165            "        local_external_edges == {{ edge \\in {} : edge.local = agent_identity }}",
12166            local("external_peer_edges")
12167        );
12168        pushln!(
12169            out,
12170            "    IN {{ {}[edge.b] : edge \\in outgoing_edges }}",
12171            local("member_peer_endpoints")
12172        );
12173        pushln!(
12174            out,
12175            "       \\cup {{ {}[edge.a] : edge \\in incoming_edges }}",
12176            local("member_peer_endpoints")
12177        );
12178        pushln!(
12179            out,
12180            "       \\cup {{ [name |-> edge.endpoint.name, peer_id |-> edge.endpoint.peer_id, address |-> edge.endpoint.address, signing_key |-> edge.endpoint.signing_key, transport |-> \"Tcp\"] : edge \\in local_external_edges }}"
12181        );
12182        writeln!(
12183            out,
12184            "{}({}, a_identity, b_identity) == \\E edge \\in {}: (edge.a = a_identity /\\ edge.b = b_identity) \\/ (edge.a = b_identity /\\ edge.b = a_identity)",
12185            prefix("mob_machine_wiring_contains_pair"),
12186            local("wiring_edges"),
12187            local("wiring_edges")
12188        )
12189        .expect("write to string");
12190        writeln!(
12191            out,
12192            "{}({}, {}, agent_identity, excluded_identity) ==",
12193            prefix("mob_machine_member_peer_overlay_without_identity_complete"),
12194            local("wiring_edges"),
12195            local("member_peer_endpoints")
12196        )
12197        .expect("write to string");
12198        pushln!(
12199            out,
12200            "    \\A edge \\in {}: IF edge.a = agent_identity /\\ edge.b # excluded_identity THEN edge.b \\in DOMAIN {} ELSE IF edge.b = agent_identity /\\ edge.a # excluded_identity THEN edge.a \\in DOMAIN {} ELSE TRUE",
12201            local("wiring_edges"),
12202            local("member_peer_endpoints"),
12203            local("member_peer_endpoints")
12204        );
12205        writeln!(
12206            out,
12207            "{}({}, {}, {}, agent_identity, excluded_identity) ==",
12208            prefix("mob_machine_member_peer_overlay_without_identity"),
12209            local("wiring_edges"),
12210            local("member_peer_endpoints"),
12211            local("external_peer_edges")
12212        )
12213        .expect("write to string");
12214        pushln!(
12215            out,
12216            "    LET outgoing_edges == {{ edge \\in {} : edge.a = agent_identity /\\ edge.b # excluded_identity /\\ edge.b \\in DOMAIN {} }}",
12217            local("wiring_edges"),
12218            local("member_peer_endpoints")
12219        );
12220        pushln!(
12221            out,
12222            "        incoming_edges == {{ edge \\in {} : edge.b = agent_identity /\\ edge.a # excluded_identity /\\ edge.a \\in DOMAIN {} }}",
12223            local("wiring_edges"),
12224            local("member_peer_endpoints")
12225        );
12226        pushln!(
12227            out,
12228            "        local_external_edges == {{ edge \\in {} : edge.local = agent_identity }}",
12229            local("external_peer_edges")
12230        );
12231        pushln!(
12232            out,
12233            "    IN {{ {}[edge.b] : edge \\in outgoing_edges }}",
12234            local("member_peer_endpoints")
12235        );
12236        pushln!(
12237            out,
12238            "       \\cup {{ {}[edge.a] : edge \\in incoming_edges }}",
12239            local("member_peer_endpoints")
12240        );
12241        pushln!(
12242            out,
12243            "       \\cup {{ [name |-> edge.endpoint.name, peer_id |-> edge.endpoint.peer_id, address |-> edge.endpoint.address, signing_key |-> edge.endpoint.signing_key, transport |-> \"Tcp\"] : edge \\in local_external_edges }}"
12244        );
12245        writeln!(
12246            out,
12247            "{}({}, {}, {}, agent_identity, excluded_identity) ==",
12248            prefix("mob_machine_member_peer_overlay_without_identity_peer_ids_unique"),
12249            local("wiring_edges"),
12250            local("member_peer_endpoints"),
12251            local("external_peer_edges")
12252        )
12253        .expect("write to string");
12254        writeln!(
12255            out,
12256            "    LET overlay == {}({}, {}, {}, agent_identity, excluded_identity) IN Cardinality(overlay) = Cardinality({{endpoint.peer_id : endpoint \\in overlay}})",
12257            prefix("mob_machine_member_peer_overlay_without_identity"),
12258            local("wiring_edges"),
12259            local("member_peer_endpoints"),
12260            local("external_peer_edges")
12261        )
12262        .expect("write to string");
12263        writeln!(
12264            out,
12265            "{}({}, {}, {}, agent_identity) ==",
12266            prefix("mob_machine_member_peer_overlay_peer_ids_unique"),
12267            local("wiring_edges"),
12268            local("member_peer_endpoints"),
12269            local("external_peer_edges")
12270        )
12271        .expect("write to string");
12272        writeln!(
12273            out,
12274            "    LET overlay == {}({}, {}, {}, agent_identity) IN Cardinality(overlay) = Cardinality({{endpoint.peer_id : endpoint \\in overlay}})",
12275            prefix("mob_machine_member_peer_overlay"),
12276            local("wiring_edges"),
12277            local("member_peer_endpoints"),
12278            local("external_peer_edges")
12279        )
12280        .expect("write to string");
12281        writeln!(
12282            out,
12283            "{}(edge, a_identity, b_identity) ==",
12284            prefix("mob_machine_wiring_edge_matches_members")
12285        )
12286        .expect("write to string");
12287        pushln!(out, "    /\\ edge.a = a_identity");
12288        pushln!(out, "    /\\ edge.b = b_identity");
12289        writeln!(
12290            out,
12291            "{}(all_statuses, run_id, step_id, status) ==",
12292            prefix("mob_machine_run_step_status_after_set")
12293        )
12294        .expect("write to string");
12295        pushln!(
12296            out,
12297            "    LET current == IF run_id \\in DOMAIN all_statuses THEN all_statuses[run_id] ELSE [x \\in {{}} |-> None]"
12298        );
12299        pushln!(
12300            out,
12301            "    IN MapSet(all_statuses, run_id, MapSet(current, step_id, Some(status)))"
12302        );
12303        writeln!(
12304            out,
12305            "{}(all_statuses, run_id) ==",
12306            prefix("mob_machine_run_step_status_after_cancel_unfinished")
12307        )
12308        .expect("write to string");
12309        pushln!(
12310            out,
12311            "    LET current == IF run_id \\in DOMAIN all_statuses THEN all_statuses[run_id] ELSE [x \\in {{}} |-> None]"
12312        );
12313        pushln!(
12314            out,
12315            "        folded == [step_id \\in DOMAIN current |-> IF current[step_id] = None \\/ current[step_id] = Some(\"Dispatched\") THEN Some(\"Canceled\") ELSE current[step_id]]"
12316        );
12317        pushln!(out, "    IN MapSet(all_statuses, run_id, folded)");
12318        writeln!(
12319            out,
12320            "{}(all_values, run_id, step_id, value) ==",
12321            prefix("mob_machine_run_step_bool_after_set")
12322        )
12323        .expect("write to string");
12324        pushln!(
12325            out,
12326            "    LET current == IF run_id \\in DOMAIN all_values THEN all_values[run_id] ELSE [x \\in {{}} |-> FALSE]"
12327        );
12328        pushln!(
12329            out,
12330            "    IN MapSet(all_values, run_id, MapSet(current, step_id, value))"
12331        );
12332        writeln!(
12333            out,
12334            "{}(all_results, run_id, step_id, result) ==",
12335            prefix("mob_machine_run_step_condition_result_after_set")
12336        )
12337        .expect("write to string");
12338        pushln!(
12339            out,
12340            "    LET current == IF run_id \\in DOMAIN all_results THEN all_results[run_id] ELSE [x \\in {{}} |-> None]"
12341        );
12342        pushln!(
12343            out,
12344            "    IN MapSet(all_results, run_id, MapSet(current, step_id, Some(result)))"
12345        );
12346        writeln!(
12347            out,
12348            "{}(all_counts, run_id, step_id, value) ==",
12349            prefix("mob_machine_run_step_u64_after_set")
12350        )
12351        .expect("write to string");
12352        pushln!(
12353            out,
12354            "    LET current == IF run_id \\in DOMAIN all_counts THEN all_counts[run_id] ELSE [x \\in {{}} |-> 0]"
12355        );
12356        pushln!(
12357            out,
12358            "    IN MapSet(all_counts, run_id, MapSet(current, step_id, value))"
12359        );
12360        writeln!(
12361            out,
12362            "{}(all_counts, run_id, step_id, delta) ==",
12363            prefix("mob_machine_run_step_u64_after_increment")
12364        )
12365        .expect("write to string");
12366        pushln!(
12367            out,
12368            "    LET current == IF run_id \\in DOMAIN all_counts THEN all_counts[run_id] ELSE [x \\in {{}} |-> 0]"
12369        );
12370        pushln!(
12371            out,
12372            "        current_value == IF step_id \\in DOMAIN current THEN current[step_id] ELSE 0"
12373        );
12374        pushln!(
12375            out,
12376            "    IN MapSet(all_counts, run_id, MapSet(current, step_id, current_value + delta))"
12377        );
12378        writeln!(
12379            out,
12380            "{}(all_counts, run_id, retry_key, delta) ==",
12381            prefix("mob_machine_run_retry_count_after_increment")
12382        )
12383        .expect("write to string");
12384        pushln!(
12385            out,
12386            "    LET current == IF run_id \\in DOMAIN all_counts THEN all_counts[run_id] ELSE [x \\in {{}} |-> 0]"
12387        );
12388        pushln!(
12389            out,
12390            "        current_value == IF retry_key \\in DOMAIN current THEN current[retry_key] ELSE 0"
12391        );
12392        pushln!(
12393            out,
12394            "    IN MapSet(all_counts, run_id, MapSet(current, retry_key, current_value + delta))"
12395        );
12396        writeln!(
12397            out,
12398            "{}(all_values, frame_id, node_id, value) ==",
12399            prefix("mob_machine_frame_node_bool_after_set")
12400        )
12401        .expect("write to string");
12402        pushln!(
12403            out,
12404            "    LET current == IF frame_id \\in DOMAIN all_values THEN all_values[frame_id] ELSE [x \\in {{}} |-> FALSE]"
12405        );
12406        pushln!(
12407            out,
12408            "    IN MapSet(all_values, frame_id, MapSet(current, node_id, value))"
12409        );
12410        writeln!(
12411            out,
12412            "{}(status) == status \\in {{\"Completed\", \"Failed\", \"Skipped\", \"Canceled\"}}",
12413            prefix("mob_machine_node_terminal")
12414        )
12415        .expect("write to string");
12416        writeln!(
12417            out,
12418            "{}(status) ==",
12419            prefix("mob_machine_step_status_from_frame_node_status")
12420        )
12421        .expect("write to string");
12422        pushln!(out, "    IF status = \"Completed\" THEN \"Completed\"");
12423        pushln!(out, "    ELSE IF status = \"Skipped\" THEN \"Skipped\"");
12424        pushln!(out, "    ELSE IF status = \"Failed\" THEN \"Failed\"");
12425        pushln!(out, "    ELSE IF status = \"Canceled\" THEN \"Canceled\"");
12426        pushln!(out, "    ELSE \"Dispatched\"");
12427        writeln!(
12428            out,
12429            "{}(all_statuses, frame_branches, ordered_nodes_by_frame, frame_id, node_id) ==",
12430            prefix("mob_machine_frame_node_status_after_admit")
12431        )
12432        .expect("write to string");
12433        pushln!(
12434            out,
12435            "    LET current == IF frame_id \\in DOMAIN all_statuses THEN all_statuses[frame_id] ELSE [x \\in {{}} |-> None]"
12436        );
12437        pushln!(
12438            out,
12439            "        branches == IF frame_id \\in DOMAIN frame_branches THEN frame_branches[frame_id] ELSE [x \\in {{}} |-> None]"
12440        );
12441        pushln!(
12442            out,
12443            "        admitted_branch == IF node_id \\in DOMAIN branches THEN branches[node_id] ELSE None"
12444        );
12445        pushln!(
12446            out,
12447            "        after_branch_reservation == [candidate \\in DOMAIN current |->"
12448        );
12449        pushln!(out, "            IF admitted_branch # None");
12450        pushln!(out, "                /\\ candidate # node_id");
12451        pushln!(out, "                /\\ candidate \\in DOMAIN branches");
12452        pushln!(
12453            out,
12454            "                /\\ branches[candidate] = admitted_branch"
12455        );
12456        pushln!(out, "                /\\ current[candidate] = \"Ready\"");
12457        pushln!(out, "            THEN \"Pending\" ELSE current[candidate]]");
12458        pushln!(
12459            out,
12460            "        after_admit == MapSet(after_branch_reservation, node_id, \"Running\")"
12461        );
12462        pushln!(out, "    IN MapSet(all_statuses, frame_id, after_admit)");
12463        writeln!(
12464            out,
12465            "{}(all_ready_queues, all_statuses, ordered_nodes_by_frame, frame_id) ==",
12466            prefix("mob_machine_frame_ready_queue_after_terminal")
12467        )
12468        .expect("write to string");
12469        pushln!(
12470            out,
12471            "    LET statuses == IF frame_id \\in DOMAIN all_statuses THEN all_statuses[frame_id] ELSE [x \\in {{}} |-> None]"
12472        );
12473        pushln!(
12474            out,
12475            "        ordered == IF frame_id \\in DOMAIN ordered_nodes_by_frame THEN ordered_nodes_by_frame[frame_id] ELSE <<>>"
12476        );
12477        pushln!(
12478            out,
12479            "    IN MapSet(all_ready_queues, frame_id, SelectSeq(ordered, LAMBDA candidate: candidate \\in DOMAIN statuses /\\ statuses[candidate] = \"Ready\"))"
12480        );
12481        writeln!(
12482            out,
12483            "{}(all_ready_queues, all_statuses, ordered_nodes_by_frame, frame_id) ==",
12484            prefix("mob_machine_frame_ready_queue_after_admit")
12485        )
12486        .expect("write to string");
12487        writeln!(
12488            out,
12489            "    {}(all_ready_queues, all_statuses, ordered_nodes_by_frame, frame_id)",
12490            prefix("mob_machine_frame_ready_queue_after_terminal")
12491        )
12492        .expect("write to string");
12493        writeln!(
12494            out,
12495            "{}(current, branches, node_id, terminal_status) ==",
12496            prefix("mob_machine_frame_node_status_after_terminal_branch")
12497        )
12498        .expect("write to string");
12499        pushln!(
12500            out,
12501            "    LET after_terminal == MapSet(current, node_id, terminal_status)"
12502        );
12503        pushln!(out, "    IN [candidate \\in DOMAIN after_terminal |->");
12504        pushln!(
12505            out,
12506            "        IF terminal_status = \"Completed\" /\\ candidate # node_id"
12507        );
12508        pushln!(
12509            out,
12510            "            /\\ candidate \\in DOMAIN branches /\\ node_id \\in DOMAIN branches"
12511        );
12512        pushln!(out, "            /\\ branches[node_id] # None");
12513        pushln!(
12514            out,
12515            "            /\\ branches[candidate] = branches[node_id]"
12516        );
12517        writeln!(
12518            out,
12519            "            /\\ ~{}(after_terminal[candidate])",
12520            prefix("mob_machine_node_terminal")
12521        )
12522        .expect("write to string");
12523        pushln!(
12524            out,
12525            "            /\\ after_terminal[candidate] # \"Running\""
12526        );
12527        pushln!(
12528            out,
12529            "        THEN \"Skipped\" ELSE after_terminal[candidate]]"
12530        );
12531        writeln!(
12532            out,
12533            "{}(after_branch, dependencies, dependency_modes) ==",
12534            prefix("mob_machine_frame_node_status_after_terminal_dependencies")
12535        )
12536        .expect("write to string");
12537        pushln!(out, "    [candidate \\in DOMAIN after_branch |->");
12538        pushln!(
12539            out,
12540            "        IF after_branch[candidate] # \"Pending\" THEN after_branch[candidate]"
12541        );
12542        pushln!(
12543            out,
12544            "        ELSE LET deps == IF candidate \\in DOMAIN dependencies THEN dependencies[candidate] ELSE <<>>"
12545        );
12546        pushln!(
12547            out,
12548            "                 mode == IF candidate \\in DOMAIN dependency_modes THEN dependency_modes[candidate] ELSE \"All\""
12549        );
12550        pushln!(out, "                 failed == Len(deps) # 0");
12551        pushln!(
12552            out,
12553            "                     /\\ ((mode = \"All\" /\\ \\E dep_index \\in DOMAIN deps: LET dep == deps[dep_index] IN dep \\in DOMAIN after_branch /\\ after_branch[dep] \\in {{\"Failed\", \"Skipped\", \"Canceled\"}})"
12554        );
12555        pushln!(
12556            out,
12557            "                         \\/ (mode = \"Any\" /\\ \\A dep_index \\in DOMAIN deps: LET dep == deps[dep_index] IN dep \\in DOMAIN after_branch /\\ after_branch[dep] \\in {{\"Failed\", \"Skipped\", \"Canceled\"}}))"
12558        );
12559        pushln!(out, "                 satisfied == Len(deps) = 0");
12560        pushln!(
12561            out,
12562            "                     \\/ (mode = \"All\" /\\ \\A dep_index \\in DOMAIN deps: LET dep == deps[dep_index] IN dep \\in DOMAIN after_branch /\\ after_branch[dep] = \"Completed\")"
12563        );
12564        pushln!(
12565            out,
12566            "                     \\/ (mode = \"Any\" /\\ \\E dep_index \\in DOMAIN deps: LET dep == deps[dep_index] IN dep \\in DOMAIN after_branch /\\ after_branch[dep] = \"Completed\")"
12567        );
12568        pushln!(
12569            out,
12570            "             IN IF failed THEN \"Skipped\" ELSE IF satisfied THEN \"Ready\" ELSE after_branch[candidate]]"
12571        );
12572        writeln!(
12573            out,
12574            "{}(all_statuses, frame_branches, ordered_nodes_by_frame, dependencies_by_frame, dependency_modes_by_frame, frame_id, node_id, terminal_status) ==",
12575            prefix("mob_machine_frame_node_status_after_terminal")
12576        )
12577        .expect("write to string");
12578        pushln!(
12579            out,
12580            "    LET current == IF frame_id \\in DOMAIN all_statuses THEN all_statuses[frame_id] ELSE [x \\in {{}} |-> None]"
12581        );
12582        pushln!(
12583            out,
12584            "        branches == IF frame_id \\in DOMAIN frame_branches THEN frame_branches[frame_id] ELSE [x \\in {{}} |-> None]"
12585        );
12586        pushln!(
12587            out,
12588            "        dependencies == IF frame_id \\in DOMAIN dependencies_by_frame THEN dependencies_by_frame[frame_id] ELSE [x \\in {{}} |-> <<>>]"
12589        );
12590        pushln!(
12591            out,
12592            "        dependency_modes == IF frame_id \\in DOMAIN dependency_modes_by_frame THEN dependency_modes_by_frame[frame_id] ELSE [x \\in {{}} |-> \"All\"]"
12593        );
12594        writeln!(
12595            out,
12596            "        after_branch == {}(current, branches, node_id, terminal_status)",
12597            prefix("mob_machine_frame_node_status_after_terminal_branch")
12598        )
12599        .expect("write to string");
12600        writeln!(
12601            out,
12602            "        after_dependencies == {}(after_branch, dependencies, dependency_modes)",
12603            prefix("mob_machine_frame_node_status_after_terminal_dependencies")
12604        )
12605        .expect("write to string");
12606        pushln!(
12607            out,
12608            "    IN MapSet(all_statuses, frame_id, after_dependencies)"
12609        );
12610        // Operator instructions: the machine's records reuse the session
12611        // document's slot-set natives (one slot set, and the body bytes of
12612        // the Active slots).
12613        self.render_session_document_native_helpers(out);
12614    }
12615
12616    fn render_transition(&mut self, out: &mut String, transition: &TransitionSchema) {
12617        let binding_types = self.binding_type_map(transition);
12618        let binding_env = transition
12619            .on
12620            .bindings()
12621            .iter()
12622            .map(|binding| {
12623                (
12624                    binding.as_str().to_owned(),
12625                    self.local_binding_name(binding.as_str()),
12626                )
12627            })
12628            .collect::<BTreeMap<String, _>>();
12629        let params = transition
12630            .on
12631            .bindings()
12632            .iter()
12633            .map(|binding| {
12634                binding_env
12635                    .get(binding.as_str())
12636                    .cloned()
12637                    .unwrap_or_else(|| binding.as_str().to_owned())
12638            })
12639            .collect::<Vec<_>>()
12640            .join(", ");
12641        if params.is_empty() {
12642            writeln!(out, "{} ==", transition.name);
12643        } else {
12644            pushln!(out, "{}({}) ==", transition.name, params);
12645        }
12646
12647        let from_guard = if transition.from.len() == 1 {
12648            format!("phase = {}", tla_string(&transition.from[0]))
12649        } else {
12650            transition
12651                .from
12652                .iter()
12653                .map(|phase| format!("phase = {}", tla_string(phase)))
12654                .collect::<Vec<_>>()
12655                .join(" \\/ ")
12656        };
12657        pushln!(out, "    /\\ {}", from_guard);
12658
12659        let mut env = self
12660            .schema
12661            .state
12662            .fields
12663            .iter()
12664            .map(|field| {
12665                (
12666                    field.name.as_str().to_owned(),
12667                    field.name.as_str().to_owned(),
12668                )
12669            })
12670            .collect::<BTreeMap<String, _>>();
12671
12672        for guard in &transition.guards {
12673            writeln!(
12674                out,
12675                "    /\\ {}",
12676                self.render_guard(guard, &env, &binding_env, &binding_types)
12677            )
12678            .expect("write to string");
12679        }
12680
12681        env = self.compile_updates(
12682            transition.name.as_str(),
12683            &env,
12684            &binding_env,
12685            &binding_types,
12686            &transition.updates,
12687        );
12688
12689        pushln!(out, "    /\\ phase' = {}", tla_string(&transition.to));
12690        pushln!(out, "    /\\ model_step_count' = model_step_count + 1");
12691        let touched = self
12692            .schema
12693            .state
12694            .fields
12695            .iter()
12696            .filter_map(|field| {
12697                let next = env.get(field.name.as_str())?;
12698                if next != field.name.as_str() {
12699                    Some((field.name.as_str(), next.as_str()))
12700                } else {
12701                    None
12702                }
12703            })
12704            .collect::<Vec<_>>();
12705
12706        for (field, expr) in &touched {
12707            pushln!(out, "    /\\ {}' = {}", field, expr);
12708        }
12709
12710        let unchanged = self
12711            .schema
12712            .state
12713            .fields
12714            .iter()
12715            .filter(|field| !touched.iter().any(|(name, _)| *name == field.name.as_str()))
12716            .map(|field| field.name.as_str().to_owned())
12717            .collect::<Vec<_>>();
12718        if !unchanged.is_empty() {
12719            // Machine frames are never chunked: the split policy is a
12720            // composition-scale TLC mitigation, and applying it here would
12721            // change the emitted formula for wide machines.
12722            let name = self
12723                .unchanged_frames
12724                .intern(unchanged_frame_body(&unchanged, None));
12725            pushln!(out, "    /\\ {name}");
12726        }
12727    }
12728
12729    fn render_guard(
12730        &self,
12731        guard: &Guard,
12732        env: &BTreeMap<String, String>,
12733        binding_env: &BTreeMap<String, String>,
12734        binding_types: &BTreeMap<String, TypeRef>,
12735    ) -> String {
12736        self.render_expr_with_types(&guard.expr, env, binding_env, binding_types)
12737    }
12738
12739    fn binding_type_map(&self, transition: &TransitionSchema) -> BTreeMap<String, TypeRef> {
12740        let mut map = BTreeMap::new();
12741        if let Some(variant) = transition_trigger_variant(self.schema, transition) {
12742            for binding in transition.on.bindings() {
12743                if let Some(field) = variant.fields.iter().find(|field| field.name == *binding) {
12744                    map.insert(binding.as_str().to_owned(), field.ty.clone());
12745                }
12746            }
12747        }
12748        map
12749    }
12750
12751    fn local_binding_name(&self, name: impl AsRef<str>) -> String {
12752        let name = name.as_ref();
12753        let candidate = tla_ident(name);
12754        if candidate == "phase"
12755            || self
12756                .schema
12757                .state
12758                .fields
12759                .iter()
12760                .any(|field| field.name.as_str() == name)
12761        {
12762            format!("arg_{candidate}")
12763        } else {
12764            candidate
12765        }
12766    }
12767
12768    fn binding_domain_for_type(&self, ty: &TypeRef) -> String {
12769        match ty {
12770            TypeRef::Bool => "BOOLEAN".into(),
12771            TypeRef::U32 | TypeRef::U64 => "0..2".into(),
12772            TypeRef::String => "StringValues".into(),
12773            TypeRef::Named(_)
12774            | TypeRef::Enum(_)
12775            | TypeRef::Seq(_)
12776            | TypeRef::Set(_)
12777            | TypeRef::Option(_)
12778            | TypeRef::Map(_, _) => domain_constant_name(ty),
12779        }
12780    }
12781
12782    /// Payload domain for one bound field of `input`: the declared input
12783    /// field domain if the schema has one, otherwise the type's default.
12784    fn binding_domain_for_binding(
12785        &self,
12786        input: Option<&str>,
12787        binding: &str,
12788        ty: &TypeRef,
12789    ) -> String {
12790        let declared = input.and_then(|input| {
12791            self.schema
12792                .input_field_domain(input, binding)
12793                .map(|domain| (input, domain))
12794        });
12795        match declared {
12796            Some((_, meerkat_machine_schema::InputFieldDomainKind::StateField(state_field))) => {
12797                format!("{{{}}}", state_field.as_str())
12798            }
12799            Some((_, meerkat_machine_schema::InputFieldDomainKind::AdditionalValues(values))) => {
12800                additional_values_domain(&self.binding_domain_for_type(ty), values)
12801            }
12802            // A model constant that each profile's config assigns: the CI
12803            // profile the declared values, the Deep profile those and `0..2`
12804            // for `CiValues`, the field type's whole domain for `CiSamples`.
12805            Some((
12806                input,
12807                meerkat_machine_schema::InputFieldDomainKind::CiValues(_)
12808                | meerkat_machine_schema::InputFieldDomainKind::CiSamples(_),
12809            )) => input_samples_constant_name(input, binding),
12810            None => self.binding_domain_for_type(ty),
12811        }
12812    }
12813
12814    fn compile_updates(
12815        &mut self,
12816        transition_name: &str,
12817        env: &BTreeMap<String, String>,
12818        binding_env: &BTreeMap<String, String>,
12819        binding_types: &BTreeMap<String, TypeRef>,
12820        updates: &[Update],
12821    ) -> BTreeMap<String, String> {
12822        let mut current = env.clone();
12823        for update in updates {
12824            self.apply_update(
12825                transition_name,
12826                &mut current,
12827                binding_env,
12828                binding_types,
12829                update,
12830            );
12831        }
12832        current
12833    }
12834
12835    fn apply_update(
12836        &mut self,
12837        transition_name: &str,
12838        env: &mut BTreeMap<String, String>,
12839        binding_env: &BTreeMap<String, String>,
12840        binding_types: &BTreeMap<String, TypeRef>,
12841        update: &Update,
12842    ) {
12843        match update {
12844            Update::Assign { field, expr } => {
12845                let value = self.render_expr_with_types(expr, env, binding_env, binding_types);
12846                env.insert(field.as_str().to_owned(), value);
12847            }
12848            Update::Increment { field, amount } => {
12849                let current = env
12850                    .get(field.as_str())
12851                    .cloned()
12852                    .unwrap_or_else(|| field.as_str().to_owned());
12853                env.insert(field.as_str().to_owned(), format!("({current}) + {amount}"));
12854            }
12855            Update::Decrement { field, amount } => {
12856                let current = env
12857                    .get(field.as_str())
12858                    .cloned()
12859                    .unwrap_or_else(|| field.as_str().to_owned());
12860                env.insert(field.as_str().to_owned(), format!("({current}) - {amount}"));
12861            }
12862            Update::MapInsert { field, key, value } => {
12863                let current = env
12864                    .get(field.as_str())
12865                    .cloned()
12866                    .unwrap_or_else(|| field.as_str().to_owned());
12867                let key_expr = self.render_expr_with_types(key, env, binding_env, binding_types);
12868                let value_expr =
12869                    self.render_expr_with_types(value, env, binding_env, binding_types);
12870                env.insert(
12871                    field.as_str().to_owned(),
12872                    format!("MapSet({current}, {key_expr}, {value_expr})"),
12873                );
12874            }
12875            Update::MapRemove { field, key } => {
12876                let current = env
12877                    .get(field.as_str())
12878                    .cloned()
12879                    .unwrap_or_else(|| field.as_str().to_owned());
12880                let key_expr = self.render_expr_with_types(key, env, binding_env, binding_types);
12881                env.insert(
12882                    field.as_str().to_owned(),
12883                    format!("MapRemove({current}, {key_expr})"),
12884                );
12885            }
12886            Update::MapIncrement { field, key, amount } => {
12887                let current = env
12888                    .get(field.as_str())
12889                    .cloned()
12890                    .unwrap_or_else(|| field.as_str().to_owned());
12891                let key_expr = self.render_expr_with_types(key, env, binding_env, binding_types);
12892                env.insert(
12893                    field.as_str().to_owned(),
12894                    format!("MapIncrement({current}, {key_expr}, {amount})"),
12895                );
12896            }
12897            Update::MapDecrement { field, key, amount } => {
12898                let current = env
12899                    .get(field.as_str())
12900                    .cloned()
12901                    .unwrap_or_else(|| field.as_str().to_owned());
12902                let key_expr = self.render_expr_with_types(key, env, binding_env, binding_types);
12903                env.insert(
12904                    field.as_str().to_owned(),
12905                    format!("MapDecrement({current}, {key_expr}, {amount})"),
12906                );
12907            }
12908            Update::SetInsert { field, value } => {
12909                // The field's pending value may be an unparenthesized
12910                // conditional (`IF c THEN a ELSE b`); spliced bare as the left
12911                // operand, the ELSE branch would capture the set operator.
12912                let current = env
12913                    .get(field.as_str())
12914                    .map(|value| tla_delimited(value))
12915                    .unwrap_or_else(|| field.as_str().to_owned());
12916                let value_expr =
12917                    self.render_expr_with_types(value, env, binding_env, binding_types);
12918                env.insert(
12919                    field.as_str().to_owned(),
12920                    format!("({current} \\cup {{{value_expr}}})"),
12921                );
12922            }
12923            Update::SetRemove { field, value } => {
12924                // The field's pending value may be an unparenthesized
12925                // conditional (`IF c THEN a ELSE b`); spliced bare as the left
12926                // operand, the ELSE branch would capture the set operator.
12927                let current = env
12928                    .get(field.as_str())
12929                    .map(|value| tla_delimited(value))
12930                    .unwrap_or_else(|| field.as_str().to_owned());
12931                let value_expr =
12932                    self.render_expr_with_types(value, env, binding_env, binding_types);
12933                env.insert(
12934                    field.as_str().to_owned(),
12935                    format!("({current} \\ {{{value_expr}}})"),
12936                );
12937            }
12938            Update::SeqAppend { field, value } => {
12939                let current = env
12940                    .get(field.as_str())
12941                    .cloned()
12942                    .unwrap_or_else(|| field.as_str().to_owned());
12943                let value_expr =
12944                    self.render_expr_with_types(value, env, binding_env, binding_types);
12945                env.insert(
12946                    field.as_str().to_owned(),
12947                    format!("Append({current}, {value_expr})"),
12948                );
12949            }
12950            Update::SeqPrepend { field, values } => {
12951                let current = env
12952                    .get(field.as_str())
12953                    .cloned()
12954                    .unwrap_or_else(|| field.as_str().to_owned());
12955                let value_expr =
12956                    self.render_expr_with_types(values, env, binding_env, binding_types);
12957                env.insert(
12958                    field.as_str().to_owned(),
12959                    format!("({value_expr} \\o {current})"),
12960                );
12961            }
12962            Update::SeqPopFront { field } => {
12963                let current = env
12964                    .get(field.as_str())
12965                    .cloned()
12966                    .unwrap_or_else(|| field.as_str().to_owned());
12967                env.insert(field.as_str().to_owned(), format!("Tail({current})"));
12968            }
12969            Update::SeqRemoveValue { field, value } => {
12970                let current = env
12971                    .get(field.as_str())
12972                    .cloned()
12973                    .unwrap_or_else(|| field.as_str().to_owned());
12974                let value_expr =
12975                    self.render_expr_with_types(value, env, binding_env, binding_types);
12976                env.insert(
12977                    field.as_str().to_owned(),
12978                    format!("SeqRemove({current}, {value_expr})"),
12979                );
12980            }
12981            Update::SeqRemoveAll { field, values } => {
12982                let current = env
12983                    .get(field.as_str())
12984                    .cloned()
12985                    .unwrap_or_else(|| field.as_str().to_owned());
12986                let value_expr =
12987                    self.render_expr_with_types(values, env, binding_env, binding_types);
12988                env.insert(
12989                    field.as_str().to_owned(),
12990                    format!("SeqRemoveAll({current}, {value_expr})"),
12991                );
12992            }
12993            Update::Conditional {
12994                condition,
12995                then_updates,
12996                else_updates,
12997            } => {
12998                let base = env.clone();
12999                let mut then_env = base.clone();
13000                for update in then_updates {
13001                    self.apply_update(
13002                        transition_name,
13003                        &mut then_env,
13004                        binding_env,
13005                        binding_types,
13006                        update,
13007                    );
13008                }
13009                let mut else_env = base.clone();
13010                for update in else_updates {
13011                    self.apply_update(
13012                        transition_name,
13013                        &mut else_env,
13014                        binding_env,
13015                        binding_types,
13016                        update,
13017                    );
13018                }
13019                let condition_expr =
13020                    self.render_expr_with_types(condition, &base, binding_env, binding_types);
13021                let touched = union_touched_fields(&base, &then_env, &else_env);
13022                for field in touched {
13023                    let then_expr = then_env
13024                        .get(&field)
13025                        .cloned()
13026                        .unwrap_or_else(|| field.clone());
13027                    let else_expr = else_env
13028                        .get(&field)
13029                        .cloned()
13030                        .unwrap_or_else(|| field.clone());
13031                    env.insert(
13032                        field.clone(),
13033                        format!("IF {condition_expr} THEN {then_expr} ELSE {else_expr}"),
13034                    );
13035                }
13036            }
13037            Update::ForEach {
13038                binding,
13039                over,
13040                updates,
13041            } => {
13042                let helper_index = self.helper_counter;
13043                self.helper_counter += 1;
13044                let over_expr = self.render_expr_with_types(over, env, binding_env, binding_types);
13045                let touched = collect_update_fields(updates);
13046                // Every touched field's fold reads the other fields as they
13047                // were BEFORE the loop: the loop below writes each fold back
13048                // into `env` as it goes, so reading `env` there would hand a
13049                // later field the earlier field's post-loop value (all of its
13050                // iterations already applied), not the value an iteration
13051                // reads in the sequential kernel.
13052                let base_env = env.clone();
13053                let referenced_bindings = collect_update_bindings(updates)
13054                    .into_iter()
13055                    .filter(|item| item != binding)
13056                    .collect::<BTreeSet<_>>();
13057                let referenced_fields = collect_update_fields_exprs(updates)
13058                    .into_iter()
13059                    .filter(|field| {
13060                        touched.contains(field) || base_env.get(field.as_str()) != Some(field)
13061                    })
13062                    .collect::<BTreeSet<_>>();
13063
13064                for field in touched {
13065                    let current = base_env
13066                        .get(&field)
13067                        .cloned()
13068                        .unwrap_or_else(|| field.clone());
13069                    let helper_name = format!(
13070                        "{}_ForEach{}_{}",
13071                        tla_ident(transition_name),
13072                        helper_index,
13073                        tla_ident(&field)
13074                    );
13075                    let collection_kind = infer_collection_kind(over, self.schema, binding_types);
13076
13077                    let mut param_defs = Vec::new();
13078                    let mut call_args = vec![current.clone(), over_expr.clone()];
13079                    let mut helper_binding_env = binding_env.clone();
13080                    helper_binding_env.insert(binding.clone(), binding.clone());
13081                    let mut helper_field_env = self
13082                        .schema
13083                        .state
13084                        .fields
13085                        .iter()
13086                        .map(|item| (item.name.as_str().to_owned(), item.name.as_str().to_owned()))
13087                        .collect::<BTreeMap<String, _>>();
13088                    helper_field_env.insert(field.clone(), "acc".into());
13089
13090                    for outer_binding in &referenced_bindings {
13091                        let param = format!("outer_{}", tla_ident(outer_binding));
13092                        param_defs.push(param.clone());
13093                        call_args.push(
13094                            binding_env
13095                                .get(outer_binding)
13096                                .cloned()
13097                                .unwrap_or_else(|| outer_binding.clone()),
13098                        );
13099                        helper_binding_env.insert(outer_binding.clone(), param);
13100                    }
13101
13102                    for ref_field in &referenced_fields {
13103                        if *ref_field == field {
13104                            continue;
13105                        }
13106                        let current_expr = base_env
13107                            .get(ref_field)
13108                            .cloned()
13109                            .unwrap_or_else(|| ref_field.clone());
13110                        if current_expr != *ref_field {
13111                            let param = format!("captured_{}", tla_ident(ref_field));
13112                            param_defs.push(param.clone());
13113                            call_args.push(current_expr);
13114                            helper_field_env.insert(ref_field.clone(), param);
13115                        }
13116                    }
13117
13118                    let body_expr = self.compile_for_each_field_body(
13119                        &field,
13120                        &helper_field_env,
13121                        &helper_binding_env,
13122                        binding_types,
13123                        updates,
13124                    );
13125
13126                    let helper_def = match collection_kind {
13127                        CollectionKind::Sequence => render_sequence_foreach_helper(
13128                            &helper_name,
13129                            binding,
13130                            &param_defs,
13131                            &body_expr,
13132                        ),
13133                        CollectionKind::Set => render_set_foreach_helper(
13134                            &helper_name,
13135                            binding,
13136                            &param_defs,
13137                            &body_expr,
13138                        ),
13139                    };
13140                    self.helper_defs.push(helper_def);
13141                    env.insert(
13142                        field.clone(),
13143                        format!("{}({})", helper_name, call_args.join(", ")),
13144                    );
13145                }
13146            }
13147        }
13148    }
13149
13150    fn compile_for_each_field_body(
13151        &mut self,
13152        target_field: &str,
13153        env: &BTreeMap<String, String>,
13154        binding_env: &BTreeMap<String, String>,
13155        binding_types: &BTreeMap<String, TypeRef>,
13156        updates: &[Update],
13157    ) -> String {
13158        let mut current = env.clone();
13159        for update in updates {
13160            self.apply_update_for_target(
13161                target_field,
13162                &mut current,
13163                binding_env,
13164                binding_types,
13165                update,
13166            );
13167        }
13168        current
13169            .get(target_field)
13170            .cloned()
13171            .unwrap_or_else(|| target_field.to_owned())
13172    }
13173
13174    fn apply_update_for_target(
13175        &mut self,
13176        target_field: &str,
13177        env: &mut BTreeMap<String, String>,
13178        binding_env: &BTreeMap<String, String>,
13179        binding_types: &BTreeMap<String, TypeRef>,
13180        update: &Update,
13181    ) {
13182        match update {
13183            Update::Conditional {
13184                condition,
13185                then_updates,
13186                else_updates,
13187            } => {
13188                let base = env.clone();
13189                let mut then_env = base.clone();
13190                for update in then_updates {
13191                    self.apply_update_for_target(
13192                        target_field,
13193                        &mut then_env,
13194                        binding_env,
13195                        binding_types,
13196                        update,
13197                    );
13198                }
13199                let mut else_env = base.clone();
13200                for update in else_updates {
13201                    self.apply_update_for_target(
13202                        target_field,
13203                        &mut else_env,
13204                        binding_env,
13205                        binding_types,
13206                        update,
13207                    );
13208                }
13209                let base_expr = base
13210                    .get(target_field)
13211                    .cloned()
13212                    .unwrap_or_else(|| target_field.to_owned());
13213                let then_expr = then_env
13214                    .get(target_field)
13215                    .cloned()
13216                    .unwrap_or_else(|| base_expr.clone());
13217                let else_expr = else_env
13218                    .get(target_field)
13219                    .cloned()
13220                    .unwrap_or_else(|| base_expr.clone());
13221                if then_expr != base_expr || else_expr != base_expr {
13222                    let condition_expr =
13223                        self.render_expr_with_types(condition, &base, binding_env, binding_types);
13224                    env.insert(
13225                        target_field.to_owned(),
13226                        format!("IF {condition_expr} THEN {then_expr} ELSE {else_expr}"),
13227                    );
13228                }
13229            }
13230            Update::ForEach {
13231                binding,
13232                over,
13233                updates,
13234            } => {
13235                let helper_index = self.helper_counter;
13236                self.helper_counter += 1;
13237                let over_expr = self.render_expr_with_types(over, env, binding_env, binding_types);
13238                let helper_name = format!(
13239                    "{}_NestedForEach{}_{}",
13240                    tla_ident(target_field),
13241                    helper_index,
13242                    tla_ident(binding)
13243                );
13244                let collection_kind = infer_collection_kind(over, self.schema, binding_types);
13245                let mut nested_binding_env = binding_env.clone();
13246                nested_binding_env.insert(binding.clone(), binding.clone());
13247                let mut nested_env = env.clone();
13248                nested_env.insert(target_field.to_owned(), "acc".into());
13249                let body_expr = self.compile_for_each_field_body(
13250                    target_field,
13251                    &nested_env,
13252                    &nested_binding_env,
13253                    binding_types,
13254                    updates,
13255                );
13256                let helper_def = match collection_kind {
13257                    CollectionKind::Sequence => {
13258                        render_sequence_foreach_helper(&helper_name, binding, &[], &body_expr)
13259                    }
13260                    CollectionKind::Set => {
13261                        render_set_foreach_helper(&helper_name, binding, &[], &body_expr)
13262                    }
13263                };
13264                self.helper_defs.push(helper_def);
13265                let current = env
13266                    .get(target_field)
13267                    .cloned()
13268                    .unwrap_or_else(|| target_field.to_owned());
13269                env.insert(
13270                    target_field.to_owned(),
13271                    format!("{}({}, {})", helper_name, current, over_expr),
13272                );
13273            }
13274            _ => {
13275                let before = env
13276                    .get(target_field)
13277                    .cloned()
13278                    .unwrap_or_else(|| target_field.to_owned());
13279                self.apply_update(
13280                    &format!("Target{}", target_field),
13281                    env,
13282                    binding_env,
13283                    binding_types,
13284                    update,
13285                );
13286                let after = env
13287                    .get(target_field)
13288                    .cloned()
13289                    .unwrap_or_else(|| target_field.to_owned());
13290                if after == before {
13291                    env.insert(target_field.to_owned(), before);
13292                }
13293            }
13294        }
13295    }
13296
13297    fn render_expr(
13298        &self,
13299        expr: &Expr,
13300        env: &BTreeMap<String, String>,
13301        binding_env: &BTreeMap<String, String>,
13302    ) -> String {
13303        self.render_expr_with_types(expr, env, binding_env, &BTreeMap::new())
13304    }
13305
13306    fn scoped_helper_name(&self, helper: &str) -> String {
13307        match &self.helper_prefix {
13308            Some(prefix) => format!("{prefix}{}", tla_ident(helper)),
13309            None => helper.to_owned(),
13310        }
13311    }
13312
13313    fn render_expr_with_types(
13314        &self,
13315        expr: &Expr,
13316        env: &BTreeMap<String, String>,
13317        binding_env: &BTreeMap<String, String>,
13318        binding_types: &BTreeMap<String, TypeRef>,
13319    ) -> String {
13320        match expr {
13321            Expr::Bool(value) => {
13322                if *value {
13323                    "TRUE".into()
13324                } else {
13325                    "FALSE".into()
13326                }
13327            }
13328            Expr::U64(value) => value.to_string(),
13329            Expr::U64Max => TLA_RUST_U64_MAX_CONSTANT.to_owned(),
13330            Expr::String(value) => tla_string(value),
13331            Expr::NamedVariant { enum_name, variant } => render_named_variant_value(
13332                enum_name.as_str(),
13333                variant.as_str(),
13334                &self.named_bindings,
13335            ),
13336            Expr::FieldAccess { base, field } => format!(
13337                "{}.{}",
13338                self.render_expr_with_types(base, env, binding_env, binding_types),
13339                tla_ident(field.as_str())
13340            ),
13341            Expr::EnumVariantIs { value, variant, .. } => format!(
13342                "({}.tag = {})",
13343                self.render_expr_with_types(value, env, binding_env, binding_types),
13344                tla_string(variant.as_str())
13345            ),
13346            Expr::EnumStringSetPayload {
13347                value,
13348                variant,
13349                field,
13350                ..
13351            } => {
13352                let rendered = self.render_expr_with_types(value, env, binding_env, binding_types);
13353                let tag = tla_string(variant.as_str());
13354                let field = tla_ident(field.as_str());
13355                format!("(IF {rendered}.tag = {tag} THEN {rendered}.{field} ELSE {{}})")
13356            }
13357            Expr::EmptySet => "{}".into(),
13358            Expr::EmptyMap => "[x \\in {} |-> None]".into(),
13359            Expr::SeqLiteral(items) => format!(
13360                "<<{}>>",
13361                items
13362                    .iter()
13363                    .map(|item| self.render_expr_with_types(item, env, binding_env, binding_types))
13364                    .collect::<Vec<_>>()
13365                    .join(", ")
13366            ),
13367            Expr::CurrentPhase => self.phase_symbol.clone().unwrap_or_else(|| "phase".into()),
13368            Expr::Phase(value) => tla_string(value),
13369            // A field already assigned earlier in the same update block reads
13370            // its pending value, which may be an unparenthesized compound
13371            // (a conditional update renders `IF c THEN a ELSE b`). Spliced bare
13372            // into a larger expression, TLA+ precedence would capture the
13373            // surrounding operator: `IF c THEN a ELSE b = x` parses as
13374            // `IF c THEN a ELSE (b = x)`. Delimit every substituted value.
13375            Expr::Field(name) => match env.get(name.as_str()) {
13376                Some(value) if value != name.as_str() => tla_delimited(value),
13377                Some(value) => value.clone(),
13378                None => name.as_str().to_owned(),
13379            },
13380            Expr::Binding(name) => binding_env
13381                .get(name)
13382                .cloned()
13383                .unwrap_or_else(|| name.clone()),
13384            Expr::Variant(name) => tla_string(name),
13385            Expr::None => "None".into(),
13386            Expr::IfElse {
13387                condition,
13388                then_expr,
13389                else_expr,
13390            } => format!(
13391                "(IF {} THEN {} ELSE {})",
13392                self.render_expr_with_types(condition, env, binding_env, binding_types),
13393                self.render_expr_with_types(then_expr, env, binding_env, binding_types),
13394                self.render_expr_with_types(else_expr, env, binding_env, binding_types)
13395            ),
13396            Expr::Not(inner) => format!(
13397                "~({})",
13398                self.render_expr_with_types(inner, env, binding_env, binding_types)
13399            ),
13400            Expr::And(items) => join_exprs(
13401                &items
13402                    .iter()
13403                    .map(|item| self.render_expr_with_types(item, env, binding_env, binding_types))
13404                    .collect::<Vec<_>>(),
13405                " /\\ ",
13406            ),
13407            Expr::Or(items) => render_or_short_circuit(
13408                &items
13409                    .iter()
13410                    .map(|item| self.render_expr_with_types(item, env, binding_env, binding_types))
13411                    .collect::<Vec<_>>(),
13412            ),
13413            Expr::Eq(left, right) => format!(
13414                "({} = {})",
13415                self.render_expr_with_types(left, env, binding_env, binding_types),
13416                self.render_expr_with_types(right, env, binding_env, binding_types)
13417            ),
13418            Expr::Neq(left, right) => format!(
13419                "({} # {})",
13420                self.render_expr_with_types(left, env, binding_env, binding_types),
13421                self.render_expr_with_types(right, env, binding_env, binding_types)
13422            ),
13423            Expr::Add(left, right) => format!(
13424                "({} + {})",
13425                self.render_expr_with_types(left, env, binding_env, binding_types),
13426                self.render_expr_with_types(right, env, binding_env, binding_types)
13427            ),
13428            Expr::Sub(left, right) => format!(
13429                "({} - {})",
13430                self.render_expr_with_types(left, env, binding_env, binding_types),
13431                self.render_expr_with_types(right, env, binding_env, binding_types)
13432            ),
13433            Expr::Gt(left, right) => self.render_ordering(
13434                OrderingOperator::Gt,
13435                left,
13436                right,
13437                env,
13438                binding_env,
13439                binding_types,
13440            ),
13441            Expr::Gte(left, right) => self.render_ordering(
13442                OrderingOperator::Gte,
13443                left,
13444                right,
13445                env,
13446                binding_env,
13447                binding_types,
13448            ),
13449            Expr::Lt(left, right) => self.render_ordering(
13450                OrderingOperator::Lt,
13451                left,
13452                right,
13453                env,
13454                binding_env,
13455                binding_types,
13456            ),
13457            Expr::Lte(left, right) => self.render_ordering(
13458                OrderingOperator::Lte,
13459                left,
13460                right,
13461                env,
13462                binding_env,
13463                binding_types,
13464            ),
13465            Expr::Contains { collection, value } => format!(
13466                "({} \\in {})",
13467                self.render_expr_with_types(value, env, binding_env, binding_types),
13468                self.render_collection_domain(collection, env, binding_env, binding_types)
13469            ),
13470            Expr::MapContainsKey { map, key } => format!(
13471                "({} \\in DOMAIN {})",
13472                self.render_expr_with_types(key, env, binding_env, binding_types),
13473                self.render_expr_with_types(map, env, binding_env, binding_types)
13474            ),
13475            Expr::SeqStartsWith { seq, prefix } => format!(
13476                "StartsWith({}, {})",
13477                self.render_expr_with_types(seq, env, binding_env, binding_types),
13478                self.render_expr_with_types(prefix, env, binding_env, binding_types)
13479            ),
13480            Expr::SeqElements(inner) => format!(
13481                "SeqElements({})",
13482                self.render_expr_with_types(inner, env, binding_env, binding_types)
13483            ),
13484            Expr::Len(inner) => {
13485                // The kernel counts the entries of a sequence, set or map
13486                // alike; TLA+ `Len` is defined only on sequences.
13487                let rendered = self.render_expr_with_types(inner, env, binding_env, binding_types);
13488                match self.infer_expr_type_for_render(inner, binding_types) {
13489                    Some(TypeRef::Map(_, _)) => format!("Cardinality(DOMAIN {rendered})"),
13490                    Some(ty) if self.type_renders_as_set(&ty) => {
13491                        format!("Cardinality({rendered})")
13492                    }
13493                    _ => format!("Len({rendered})"),
13494                }
13495            }
13496            Expr::Count { collection, value } => format!(
13497                "Count({}, {})",
13498                self.render_expr_with_types(collection, env, binding_env, binding_types),
13499                self.render_expr_with_types(value, env, binding_env, binding_types)
13500            ),
13501            Expr::Head(inner) => format!(
13502                "Head({})",
13503                self.render_expr_with_types(inner, env, binding_env, binding_types)
13504            ),
13505            Expr::MapKeys(inner) => format!(
13506                "DOMAIN {}",
13507                self.render_expr_with_types(inner, env, binding_env, binding_types)
13508            ),
13509            Expr::MapGet { map, key } => format!(
13510                "{}",
13511                if self.is_scalar_value_projection(map, key, binding_types) {
13512                    self.render_expr_with_types(map, env, binding_env, binding_types)
13513                } else {
13514                    format!(
13515                        "(IF {} \\in DOMAIN {} THEN {}[{}] ELSE {})",
13516                        self.render_expr_with_types(key, env, binding_env, binding_types),
13517                        self.render_expr_with_types(map, env, binding_env, binding_types),
13518                        self.render_expr_with_types(map, env, binding_env, binding_types),
13519                        self.render_expr_with_types(key, env, binding_env, binding_types),
13520                        self.map_absent_value_expr(map, binding_types)
13521                    )
13522                }
13523            ),
13524            // A populated map literal as a TLC function: `k1 :> v1 @@ k2 :> v2`
13525            // (the TLC module every generated model extends).
13526            Expr::MapLiteral(entries) => format!(
13527                "({})",
13528                entries
13529                    .iter()
13530                    .map(|(key, value)| format!(
13531                        "{} :> {}",
13532                        self.render_expr_with_types(key, env, binding_env, binding_types),
13533                        self.render_expr_with_types(value, env, binding_env, binding_types)
13534                    ))
13535                    .collect::<Vec<_>>()
13536                    .join(" @@ ")
13537            ),
13538            // Strict read: plain function application, so TLC reports an
13539            // error if a reachable state reads a key outside DOMAIN (#1811).
13540            Expr::MapValue { map, key } => format!(
13541                "({})[{}]",
13542                self.render_expr_with_types(map, env, binding_env, binding_types),
13543                self.render_expr_with_types(key, env, binding_env, binding_types)
13544            ),
13545            Expr::Some(inner) => format!(
13546                "Some({})",
13547                self.render_expr_with_types(inner, env, binding_env, binding_types)
13548            ),
13549            Expr::Call { helper, args } => format!(
13550                "{}",
13551                if args.is_empty() {
13552                    self.scoped_helper_name(helper)
13553                } else {
13554                    format!(
13555                        "{}({})",
13556                        self.scoped_helper_name(helper),
13557                        args.iter()
13558                            .map(|arg| self.render_expr_with_types(
13559                                arg,
13560                                env,
13561                                binding_env,
13562                                binding_types
13563                            ))
13564                            .collect::<Vec<_>>()
13565                            .join(", ")
13566                    )
13567                }
13568            ),
13569            Expr::Quantified {
13570                quantifier,
13571                binding,
13572                over,
13573                body,
13574            } => {
13575                let keyword = match quantifier {
13576                    Quantifier::Any => "\\E",
13577                    Quantifier::All => "\\A",
13578                };
13579                let mut nested_bindings = binding_env.clone();
13580                nested_bindings.insert(binding.clone(), binding.clone());
13581                let mut nested_binding_types = binding_types.clone();
13582                if let Some(item_ty) = self.collection_item_type(over, binding_types) {
13583                    nested_binding_types.insert(binding.clone(), item_ty);
13584                }
13585                format!(
13586                    "({} {} \\in {} : {})",
13587                    keyword,
13588                    binding,
13589                    self.render_collection_domain(over, env, binding_env, binding_types),
13590                    self.render_expr_with_types(body, env, &nested_bindings, &nested_binding_types)
13591                )
13592            }
13593        }
13594    }
13595
13596    /// `left op right` for an ordering comparison. With an `Option` operand
13597    /// it takes Rust's order through `OptionLt` / `OptionLe` (see
13598    /// [`TLA_OPTION_ORDER_DEFINITIONS`]); otherwise the TLA+ operator.
13599    fn render_ordering(
13600        &self,
13601        operator: OrderingOperator,
13602        left: &Expr,
13603        right: &Expr,
13604        env: &BTreeMap<String, String>,
13605        binding_env: &BTreeMap<String, String>,
13606        binding_types: &BTreeMap<String, TypeRef>,
13607    ) -> String {
13608        let left_tla = self.render_expr_with_types(left, env, binding_env, binding_types);
13609        let right_tla = self.render_expr_with_types(right, env, binding_env, binding_types);
13610        if !self.is_option_operand(left, binding_types)
13611            && !self.is_option_operand(right, binding_types)
13612        {
13613            let symbol = match operator {
13614                OrderingOperator::Lt => "<",
13615                OrderingOperator::Lte => "<=",
13616                OrderingOperator::Gt => ">",
13617                OrderingOperator::Gte => ">=",
13618            };
13619            return format!("({left_tla} {symbol} {right_tla})");
13620        }
13621        self.option_order_used.set(true);
13622        match operator {
13623            OrderingOperator::Lt => format!("OptionLt({left_tla}, {right_tla})"),
13624            OrderingOperator::Lte => format!("OptionLe({left_tla}, {right_tla})"),
13625            OrderingOperator::Gt => format!("OptionLt({right_tla}, {left_tla})"),
13626            OrderingOperator::Gte => format!("OptionLe({right_tla}, {left_tla})"),
13627        }
13628    }
13629
13630    /// Whether `expr` is an `Option` value: a `None` / `Some` literal, or an
13631    /// operand whose type is `Option<_>` (a field, a trigger binding or helper
13632    /// parameter, a helper call, a map read, the `get_copied` / `get_cloned`
13633    /// lowering).
13634    fn is_option_operand(&self, expr: &Expr, binding_types: &BTreeMap<String, TypeRef>) -> bool {
13635        matches!(expr, Expr::None | Expr::Some(_))
13636            || matches!(
13637                self.infer_expr_type_for_render(expr, binding_types),
13638                Some(TypeRef::Option(_))
13639            )
13640    }
13641
13642    fn infer_expr_type_for_render(
13643        &self,
13644        expr: &Expr,
13645        binding_types: &BTreeMap<String, TypeRef>,
13646    ) -> Option<TypeRef> {
13647        // A projection into a structural record (`restrictions.lifetime.unresolved`)
13648        // takes the declared type of the record field, so `.len()` on a
13649        // field-presence set reached through one renders as `Cardinality`.
13650        if let Expr::FieldAccess { base, field } = expr {
13651            let TypeRef::Named(record) = self.infer_expr_type_for_render(base, binding_types)?
13652            else {
13653                return None;
13654            };
13655            let meerkat_machine_schema::RustTypeAtom::TypePathStruct { fields, .. } =
13656                self.named_bindings.get(record.as_str())?
13657            else {
13658                return None;
13659            };
13660            return match &fields
13661                .iter()
13662                .find(|candidate| candidate.name == *field)?
13663                .atom
13664            {
13665                meerkat_machine_schema::TypePathStructFieldAtom::String => Some(TypeRef::String),
13666                meerkat_machine_schema::TypePathStructFieldAtom::Named(name) => {
13667                    Some(TypeRef::Named(name.clone()))
13668                }
13669                meerkat_machine_schema::TypePathStructFieldAtom::OptionalNamed(name) => {
13670                    Some(TypeRef::Option(Box::new(TypeRef::Named(name.clone()))))
13671                }
13672            };
13673        }
13674        let field_types = self
13675            .schema
13676            .state
13677            .fields
13678            .iter()
13679            .map(|field| (field.name.as_str().to_owned(), field.ty.clone()))
13680            .collect::<BTreeMap<String, _>>();
13681        let helper_returns = self
13682            .schema
13683            .helpers
13684            .iter()
13685            .chain(self.schema.derived.iter())
13686            .map(|helper| (helper.name.clone(), helper.returns.clone()))
13687            .collect::<BTreeMap<String, _>>();
13688        infer_expr_type(expr, &field_types, &helper_returns, binding_types)
13689    }
13690
13691    fn type_renders_as_set(&self, ty: &TypeRef) -> bool {
13692        match ty {
13693            TypeRef::Set(_) => true,
13694            TypeRef::Named(name) => matches!(
13695                self.named_bindings.get(name.as_str()),
13696                Some(meerkat_machine_schema::RustTypeAtom::TypePathFieldPresenceSet { .. })
13697            ),
13698            TypeRef::Enum(name) => matches!(
13699                self.named_bindings.get(name.as_str()),
13700                Some(meerkat_machine_schema::RustTypeAtom::TypePathFieldPresenceSet { .. })
13701            ),
13702            _ => false,
13703        }
13704    }
13705
13706    fn render_collection_domain(
13707        &self,
13708        over: &Expr,
13709        env: &BTreeMap<String, String>,
13710        binding_env: &BTreeMap<String, String>,
13711        binding_types: &BTreeMap<String, TypeRef>,
13712    ) -> String {
13713        let rendered = self.render_expr_with_types(over, env, binding_env, binding_types);
13714        match self.collection_item_type(over, binding_types) {
13715            Some(_) if self.is_sequence_expr(over, binding_types) => {
13716                format!("SeqElements({rendered})")
13717            }
13718            _ => rendered,
13719        }
13720    }
13721
13722    fn collection_item_type(
13723        &self,
13724        expr: &Expr,
13725        binding_types: &BTreeMap<String, TypeRef>,
13726    ) -> Option<TypeRef> {
13727        match expr {
13728            Expr::Field(name) => self
13729                .schema
13730                .state
13731                .fields
13732                .iter()
13733                .find(|field| field.name == *name)
13734                .and_then(|field| match &field.ty {
13735                    TypeRef::Seq(inner) | TypeRef::Set(inner) => Some((**inner).clone()),
13736                    _ => None,
13737                }),
13738            Expr::Binding(name) => binding_types.get(name).and_then(|ty| match ty {
13739                TypeRef::Seq(inner) | TypeRef::Set(inner) => Some((**inner).clone()),
13740                _ => None,
13741            }),
13742            Expr::EnumStringSetPayload { .. } => Some(TypeRef::String),
13743            Expr::SeqLiteral(items) => {
13744                if let Some(first) = items.first() {
13745                    self.scalar_expr_type(first, binding_types)
13746                } else {
13747                    Some(TypeRef::String)
13748                }
13749            }
13750            Expr::MapKeys(_) | Expr::EmptySet => Some(TypeRef::String),
13751            _ => None,
13752        }
13753    }
13754
13755    fn scalar_expr_type(
13756        &self,
13757        expr: &Expr,
13758        binding_types: &BTreeMap<String, TypeRef>,
13759    ) -> Option<TypeRef> {
13760        match expr {
13761            Expr::Bool(_) => Some(TypeRef::Bool),
13762            Expr::U64(_) | Expr::U64Max => Some(TypeRef::U64),
13763            Expr::String(_) | Expr::Phase(_) | Expr::Variant(_) => Some(TypeRef::String),
13764            Expr::NamedVariant { enum_name, .. } => Some(TypeRef::Enum(enum_name.clone())),
13765            Expr::FieldAccess { .. } => None,
13766            Expr::EnumVariantIs { .. } => Some(TypeRef::Bool),
13767            Expr::EnumStringSetPayload { .. } => Some(TypeRef::Set(Box::new(TypeRef::String))),
13768            Expr::MapGet { map, .. } | Expr::MapValue { map, .. } => {
13769                self.map_value_type(map, binding_types)
13770            }
13771            Expr::Field(name) => self
13772                .schema
13773                .state
13774                .fields
13775                .iter()
13776                .find(|field| field.name == *name)
13777                .map(|field| &field.ty)
13778                .cloned(),
13779            Expr::Binding(name) => binding_types.get(name).cloned(),
13780            _ => None,
13781        }
13782    }
13783
13784    fn is_scalar_value_projection(
13785        &self,
13786        map: &Expr,
13787        key: &Expr,
13788        binding_types: &BTreeMap<String, TypeRef>,
13789    ) -> bool {
13790        matches!(key, Expr::String(value) if value == "value")
13791            && matches!(
13792                self.scalar_expr_type(map, binding_types),
13793                Some(
13794                    TypeRef::Bool
13795                        | TypeRef::U32
13796                        | TypeRef::U64
13797                        | TypeRef::String
13798                        | TypeRef::Enum(_)
13799                        | TypeRef::Named(_)
13800                )
13801            )
13802    }
13803
13804    fn map_value_type(
13805        &self,
13806        expr: &Expr,
13807        binding_types: &BTreeMap<String, TypeRef>,
13808    ) -> Option<TypeRef> {
13809        match expr {
13810            Expr::Field(name) => self
13811                .schema
13812                .state
13813                .fields
13814                .iter()
13815                .find(|field| field.name == *name)
13816                .and_then(|field| match &field.ty {
13817                    TypeRef::Map(_, value) => Some((**value).clone()),
13818                    _ => None,
13819                }),
13820            Expr::Binding(name) => binding_types.get(name).and_then(|ty| match ty {
13821                TypeRef::Map(_, value) => Some((**value).clone()),
13822                _ => None,
13823            }),
13824            _ => None,
13825        }
13826    }
13827
13828    fn map_absent_value_expr(
13829        &self,
13830        expr: &Expr,
13831        binding_types: &BTreeMap<String, TypeRef>,
13832    ) -> String {
13833        self.map_value_type(expr, binding_types)
13834            .map(|ty| default_absent_map_value_expr(&ty))
13835            .unwrap_or_else(|| "None".into())
13836    }
13837
13838    fn is_sequence_expr(&self, expr: &Expr, binding_types: &BTreeMap<String, TypeRef>) -> bool {
13839        match expr {
13840            Expr::Field(name) => self
13841                .schema
13842                .state
13843                .fields
13844                .iter()
13845                .find(|field| field.name == *name)
13846                .is_some_and(|field| matches!(field.ty, TypeRef::Seq(_))),
13847            Expr::Binding(name) => binding_types
13848                .get(name)
13849                .is_some_and(|ty| matches!(ty, TypeRef::Seq(_))),
13850            Expr::SeqLiteral(_) => true,
13851            _ => false,
13852        }
13853    }
13854}
13855
13856#[derive(Copy, Clone)]
13857enum CollectionKind {
13858    Sequence,
13859    Set,
13860}
13861
13862fn infer_collection_kind(
13863    expr: &Expr,
13864    schema: &MachineSchema,
13865    binding_types: &BTreeMap<String, TypeRef>,
13866) -> CollectionKind {
13867    match expr {
13868        Expr::Field(name) => schema
13869            .state
13870            .fields
13871            .iter()
13872            .find(|field| field.name == *name)
13873            .map(|field| match field.ty {
13874                TypeRef::Set(_) => CollectionKind::Set,
13875                _ => CollectionKind::Sequence,
13876            })
13877            .unwrap_or(CollectionKind::Sequence),
13878        Expr::Binding(name) => binding_types
13879            .get(name)
13880            .map(|ty| match ty {
13881                TypeRef::Set(_) => CollectionKind::Set,
13882                _ => CollectionKind::Sequence,
13883            })
13884            .unwrap_or(CollectionKind::Sequence),
13885        Expr::MapKeys(_) | Expr::EmptySet | Expr::EnumStringSetPayload { .. } => {
13886            CollectionKind::Set
13887        }
13888        _ => CollectionKind::Sequence,
13889    }
13890}
13891
13892fn render_sequence_foreach_helper(
13893    name: &str,
13894    binding: &str,
13895    extra_params: &[String],
13896    body_expr: &str,
13897) -> String {
13898    let mut params = vec!["acc".to_owned(), "items".to_owned()];
13899    params.extend(extra_params.iter().cloned());
13900    let params_str = params.join(", ");
13901    let recurse_args = std::iter::once("next_acc".to_owned())
13902        .chain(std::iter::once("Tail(items)".to_owned()))
13903        .chain(extra_params.iter().cloned())
13904        .collect::<Vec<_>>()
13905        .join(", ");
13906    let recursive_args = std::iter::repeat_n("_", params.len())
13907        .collect::<Vec<_>>()
13908        .join(", ");
13909
13910    format!(
13911        "RECURSIVE {name}({recursive_args})\n{name}({params_str}) == IF Len(items) = 0 THEN acc ELSE LET {binding} == Head(items) IN LET next_acc == {body_expr} IN {name}({recurse_args})"
13912    )
13913}
13914
13915fn render_set_foreach_helper(
13916    name: &str,
13917    binding: &str,
13918    extra_params: &[String],
13919    body_expr: &str,
13920) -> String {
13921    let mut params = vec!["acc".to_owned(), "remaining".to_owned()];
13922    params.extend(extra_params.iter().cloned());
13923    let params_str = params.join(", ");
13924    let recurse_args = std::iter::once("next_acc".to_owned())
13925        .chain(std::iter::once("remaining \\ {item}".to_owned()))
13926        .chain(extra_params.iter().cloned())
13927        .collect::<Vec<_>>()
13928        .join(", ");
13929    let recursive_args = std::iter::repeat_n("_", params.len())
13930        .collect::<Vec<_>>()
13931        .join(", ");
13932
13933    format!(
13934        "RECURSIVE {name}({recursive_args})\n{name}({params_str}) == IF remaining = {{}} THEN acc ELSE LET item == CHOOSE x \\in remaining : TRUE IN LET {binding} == item IN LET next_acc == {body_expr} IN {name}({recurse_args})"
13935    )
13936}
13937
13938fn collect_update_fields(updates: &[Update]) -> BTreeSet<String> {
13939    let mut fields = BTreeSet::new();
13940    for update in updates {
13941        match update {
13942            Update::Assign { field, .. }
13943            | Update::Increment { field, .. }
13944            | Update::Decrement { field, .. }
13945            | Update::MapInsert { field, .. }
13946            | Update::MapIncrement { field, .. }
13947            | Update::MapDecrement { field, .. }
13948            | Update::MapRemove { field, .. }
13949            | Update::SetInsert { field, .. }
13950            | Update::SetRemove { field, .. }
13951            | Update::SeqAppend { field, .. }
13952            | Update::SeqPrepend { field, .. }
13953            | Update::SeqPopFront { field }
13954            | Update::SeqRemoveValue { field, .. }
13955            | Update::SeqRemoveAll { field, .. } => {
13956                fields.insert(field.as_str().to_owned());
13957            }
13958            Update::Conditional {
13959                then_updates,
13960                else_updates,
13961                ..
13962            } => {
13963                fields.extend(collect_update_fields(then_updates));
13964                fields.extend(collect_update_fields(else_updates));
13965            }
13966            Update::ForEach { updates, .. } => {
13967                fields.extend(collect_update_fields(updates));
13968            }
13969        }
13970    }
13971    fields
13972}
13973
13974fn collect_update_bindings(updates: &[Update]) -> BTreeSet<String> {
13975    let mut bindings = BTreeSet::new();
13976    for update in updates {
13977        match update {
13978            Update::Assign { expr, .. } => collect_expr_bindings(expr, &mut bindings),
13979            Update::MapInsert { key, value, .. } => {
13980                collect_expr_bindings(key, &mut bindings);
13981                collect_expr_bindings(value, &mut bindings);
13982            }
13983            Update::MapRemove { key, .. } => {
13984                collect_expr_bindings(key, &mut bindings);
13985            }
13986            Update::MapIncrement { key, .. } | Update::MapDecrement { key, .. } => {
13987                collect_expr_bindings(key, &mut bindings);
13988            }
13989            Update::SetInsert { value, .. }
13990            | Update::SetRemove { value, .. }
13991            | Update::SeqAppend { value, .. }
13992            | Update::SeqRemoveValue { value, .. }
13993            | Update::SeqPrepend { values: value, .. }
13994            | Update::SeqRemoveAll { values: value, .. } => {
13995                collect_expr_bindings(value, &mut bindings);
13996            }
13997            Update::Conditional {
13998                condition,
13999                then_updates,
14000                else_updates,
14001            } => {
14002                collect_expr_bindings(condition, &mut bindings);
14003                bindings.extend(collect_update_bindings(then_updates));
14004                bindings.extend(collect_update_bindings(else_updates));
14005            }
14006            Update::ForEach {
14007                binding,
14008                over,
14009                updates,
14010            } => {
14011                bindings.insert(binding.clone());
14012                collect_expr_bindings(over, &mut bindings);
14013                bindings.extend(collect_update_bindings(updates));
14014            }
14015            Update::Increment { .. } | Update::Decrement { .. } | Update::SeqPopFront { .. } => {}
14016        }
14017    }
14018    bindings
14019}
14020
14021fn collect_update_fields_exprs(updates: &[Update]) -> BTreeSet<String> {
14022    let mut fields = BTreeSet::new();
14023    for update in updates {
14024        match update {
14025            Update::Assign { expr, .. } => collect_expr_fields(expr, &mut fields),
14026            Update::MapInsert { key, value, .. } => {
14027                collect_expr_fields(key, &mut fields);
14028                collect_expr_fields(value, &mut fields);
14029            }
14030            Update::MapRemove { key, .. } => {
14031                collect_expr_fields(key, &mut fields);
14032            }
14033            Update::MapIncrement { key, .. } | Update::MapDecrement { key, .. } => {
14034                collect_expr_fields(key, &mut fields);
14035            }
14036            Update::SetInsert { value, .. }
14037            | Update::SetRemove { value, .. }
14038            | Update::SeqAppend { value, .. }
14039            | Update::SeqRemoveValue { value, .. }
14040            | Update::SeqPrepend { values: value, .. }
14041            | Update::SeqRemoveAll { values: value, .. } => {
14042                collect_expr_fields(value, &mut fields);
14043            }
14044            Update::Conditional {
14045                condition,
14046                then_updates,
14047                else_updates,
14048            } => {
14049                collect_expr_fields(condition, &mut fields);
14050                fields.extend(collect_update_fields_exprs(then_updates));
14051                fields.extend(collect_update_fields_exprs(else_updates));
14052            }
14053            Update::ForEach { over, updates, .. } => {
14054                collect_expr_fields(over, &mut fields);
14055                fields.extend(collect_update_fields_exprs(updates));
14056            }
14057            Update::Increment { .. } | Update::Decrement { .. } | Update::SeqPopFront { .. } => {}
14058        }
14059    }
14060    fields
14061}
14062
14063fn collect_expr_bindings(expr: &Expr, bindings: &mut BTreeSet<String>) {
14064    match expr {
14065        Expr::Binding(name) => {
14066            bindings.insert(name.clone());
14067        }
14068        Expr::SeqLiteral(items) | Expr::And(items) | Expr::Or(items) => {
14069            for item in items {
14070                collect_expr_bindings(item, bindings);
14071            }
14072        }
14073        Expr::IfElse {
14074            condition,
14075            then_expr,
14076            else_expr,
14077        } => {
14078            collect_expr_bindings(condition, bindings);
14079            collect_expr_bindings(then_expr, bindings);
14080            collect_expr_bindings(else_expr, bindings);
14081        }
14082        Expr::Not(inner)
14083        | Expr::SeqElements(inner)
14084        | Expr::Len(inner)
14085        | Expr::Head(inner)
14086        | Expr::MapKeys(inner)
14087        | Expr::Some(inner)
14088        | Expr::FieldAccess { base: inner, .. }
14089        | Expr::EnumVariantIs { value: inner, .. }
14090        | Expr::EnumStringSetPayload { value: inner, .. } => collect_expr_bindings(inner, bindings),
14091        Expr::Eq(left, right)
14092        | Expr::Neq(left, right)
14093        | Expr::Add(left, right)
14094        | Expr::Sub(left, right)
14095        | Expr::Gt(left, right)
14096        | Expr::Gte(left, right)
14097        | Expr::Lt(left, right)
14098        | Expr::Lte(left, right) => {
14099            collect_expr_bindings(left, bindings);
14100            collect_expr_bindings(right, bindings);
14101        }
14102        Expr::Contains { collection, value } => {
14103            collect_expr_bindings(collection, bindings);
14104            collect_expr_bindings(value, bindings);
14105        }
14106        Expr::Count { collection, value } => {
14107            collect_expr_bindings(collection, bindings);
14108            collect_expr_bindings(value, bindings);
14109        }
14110        Expr::MapContainsKey { map, key } => {
14111            collect_expr_bindings(map, bindings);
14112            collect_expr_bindings(key, bindings);
14113        }
14114        Expr::SeqStartsWith { seq, prefix } => {
14115            collect_expr_bindings(seq, bindings);
14116            collect_expr_bindings(prefix, bindings);
14117        }
14118        Expr::MapGet { map, key } | Expr::MapValue { map, key } => {
14119            collect_expr_bindings(map, bindings);
14120            collect_expr_bindings(key, bindings);
14121        }
14122        Expr::MapLiteral(entries) => {
14123            for (key, value) in entries {
14124                collect_expr_bindings(key, bindings);
14125                collect_expr_bindings(value, bindings);
14126            }
14127        }
14128        Expr::Call { args, .. } => {
14129            for arg in args {
14130                collect_expr_bindings(arg, bindings);
14131            }
14132        }
14133        Expr::Quantified {
14134            binding,
14135            over,
14136            body,
14137            ..
14138        } => {
14139            bindings.insert(binding.clone());
14140            collect_expr_bindings(over, bindings);
14141            collect_expr_bindings(body, bindings);
14142        }
14143        Expr::Bool(_)
14144        | Expr::U64(_)
14145        | Expr::U64Max
14146        | Expr::String(_)
14147        | Expr::NamedVariant { .. }
14148        | Expr::EmptySet
14149        | Expr::EmptyMap
14150        | Expr::CurrentPhase
14151        | Expr::Phase(_)
14152        | Expr::Field(_)
14153        | Expr::Variant(_)
14154        | Expr::None => {}
14155    }
14156}
14157
14158fn collect_expr_fields(expr: &Expr, fields: &mut BTreeSet<String>) {
14159    match expr {
14160        Expr::Field(name) => {
14161            fields.insert(name.as_str().to_owned());
14162        }
14163        Expr::SeqLiteral(items) | Expr::And(items) | Expr::Or(items) => {
14164            for item in items {
14165                collect_expr_fields(item, fields);
14166            }
14167        }
14168        Expr::IfElse {
14169            condition,
14170            then_expr,
14171            else_expr,
14172        } => {
14173            collect_expr_fields(condition, fields);
14174            collect_expr_fields(then_expr, fields);
14175            collect_expr_fields(else_expr, fields);
14176        }
14177        Expr::Not(inner)
14178        | Expr::SeqElements(inner)
14179        | Expr::Len(inner)
14180        | Expr::Head(inner)
14181        | Expr::MapKeys(inner)
14182        | Expr::Some(inner)
14183        | Expr::FieldAccess { base: inner, .. }
14184        | Expr::EnumVariantIs { value: inner, .. }
14185        | Expr::EnumStringSetPayload { value: inner, .. } => collect_expr_fields(inner, fields),
14186        Expr::Eq(left, right)
14187        | Expr::Neq(left, right)
14188        | Expr::Add(left, right)
14189        | Expr::Sub(left, right)
14190        | Expr::Gt(left, right)
14191        | Expr::Gte(left, right)
14192        | Expr::Lt(left, right)
14193        | Expr::Lte(left, right) => {
14194            collect_expr_fields(left, fields);
14195            collect_expr_fields(right, fields);
14196        }
14197        Expr::Contains { collection, value } => {
14198            collect_expr_fields(collection, fields);
14199            collect_expr_fields(value, fields);
14200        }
14201        Expr::Count { collection, value } => {
14202            collect_expr_fields(collection, fields);
14203            collect_expr_fields(value, fields);
14204        }
14205        Expr::MapContainsKey { map, key } => {
14206            collect_expr_fields(map, fields);
14207            collect_expr_fields(key, fields);
14208        }
14209        Expr::SeqStartsWith { seq, prefix } => {
14210            collect_expr_fields(seq, fields);
14211            collect_expr_fields(prefix, fields);
14212        }
14213        Expr::MapGet { map, key } | Expr::MapValue { map, key } => {
14214            collect_expr_fields(map, fields);
14215            collect_expr_fields(key, fields);
14216        }
14217        Expr::MapLiteral(entries) => {
14218            for (key, value) in entries {
14219                collect_expr_fields(key, fields);
14220                collect_expr_fields(value, fields);
14221            }
14222        }
14223        Expr::Call { args, .. } => {
14224            for arg in args {
14225                collect_expr_fields(arg, fields);
14226            }
14227        }
14228        Expr::Quantified { over, body, .. } => {
14229            collect_expr_fields(over, fields);
14230            collect_expr_fields(body, fields);
14231        }
14232        Expr::Bool(_)
14233        | Expr::U64(_)
14234        | Expr::U64Max
14235        | Expr::String(_)
14236        | Expr::NamedVariant { .. }
14237        | Expr::EmptySet
14238        | Expr::EmptyMap
14239        | Expr::CurrentPhase
14240        | Expr::Phase(_)
14241        | Expr::Binding(_)
14242        | Expr::Variant(_)
14243        | Expr::None => {}
14244    }
14245}
14246
14247fn union_touched_fields(
14248    base: &BTreeMap<String, String>,
14249    then_env: &BTreeMap<String, String>,
14250    else_env: &BTreeMap<String, String>,
14251) -> BTreeSet<String> {
14252    base.keys()
14253        .filter(|field| {
14254            then_env.get(*field) != base.get(*field) || else_env.get(*field) != base.get(*field)
14255        })
14256        .cloned()
14257        .collect()
14258}
14259
14260fn join_exprs(items: &[String], separator: &str) -> String {
14261    if items.is_empty() {
14262        return "TRUE".into();
14263    }
14264    if items.len() == 1 {
14265        items[0].clone()
14266    } else {
14267        format!("({})", items.join(separator))
14268    }
14269}
14270
14271/// Render a boolean disjunction as a short-circuiting `IF a THEN TRUE ELSE …`
14272/// chain instead of `a \/ b`.
14273///
14274/// TLC expands an action-level `\/` into a tableau and evaluates *every*
14275/// disjunct independently to enumerate successor states. That breaks the
14276/// idiomatic optional guard `opt = None \/ opt.value > now`: the second
14277/// disjunct's `opt.value > now` is evaluated even when `opt = None`
14278/// (`None` still has a `"value"` field equal to the string `"none"`), so TLC
14279/// raises `first argument of > should be an integer, but instead it is "none"`.
14280/// `IF a THEN TRUE ELSE b` is boolean-equivalent to `a \/ b` but is evaluated
14281/// as a single function: the `ELSE` branch is only evaluated when `a` is false,
14282/// matching the short-circuit that `/\` already gives conjunctive guards. State
14283/// space and enabledness are unchanged. Empty/single disjunctions preserve the
14284/// prior `join_exprs` behavior.
14285fn render_or_short_circuit(items: &[String]) -> String {
14286    match items {
14287        [] => "TRUE".into(),
14288        [single] => single.clone(),
14289        [first, rest @ ..] => {
14290            format!(
14291                "(IF {first} THEN TRUE ELSE {})",
14292                render_or_short_circuit(rest)
14293            )
14294        }
14295    }
14296}
14297
14298fn default_state_init_expr(ty: &TypeRef) -> String {
14299    match ty {
14300        TypeRef::Bool => "FALSE".into(),
14301        TypeRef::U32 | TypeRef::U64 => "0".into(),
14302        TypeRef::String => tla_string(""),
14303        TypeRef::Named(name) => tla_string(format!("{}_default", tla_ident(name).to_lowercase())),
14304        TypeRef::Enum(name) => tla_string(format!("{}_default", tla_ident(name).to_lowercase())),
14305        TypeRef::Option(_) => "None".into(),
14306        TypeRef::Set(_) => "{}".into(),
14307        TypeRef::Seq(_) => "<<>>".into(),
14308        TypeRef::Map(_, _) => "[x \\in {} |-> None]".into(),
14309    }
14310}
14311
14312fn default_absent_map_value_expr(ty: &TypeRef) -> String {
14313    match ty {
14314        TypeRef::Bool => "FALSE".into(),
14315        TypeRef::U32 | TypeRef::U64 => "0".into(),
14316        TypeRef::String | TypeRef::Named(_) | TypeRef::Enum(_) => tla_string("None"),
14317        TypeRef::Option(_) => "None".into(),
14318        TypeRef::Set(_) => "{}".into(),
14319        TypeRef::Seq(_) => "<<>>".into(),
14320        TypeRef::Map(_, _) => "[x \\in {} |-> None]".into(),
14321    }
14322}
14323
14324fn render_type_ref(ty: &TypeRef) -> String {
14325    match ty {
14326        TypeRef::Bool => "Bool".into(),
14327        TypeRef::U32 => "u32".into(),
14328        TypeRef::U64 => "u64".into(),
14329        TypeRef::String => "String".into(),
14330        TypeRef::Named(name) => name.as_str().to_owned(),
14331        TypeRef::Enum(name) => name.as_str().to_owned(),
14332        TypeRef::Option(inner) => format!("Option<{}>", render_type_ref(inner)),
14333        TypeRef::Set(inner) => format!("Set<{}>", render_type_ref(inner)),
14334        TypeRef::Seq(inner) => format!("Seq<{}>", render_type_ref(inner)),
14335        TypeRef::Map(key, value) => {
14336            format!("Map<{}, {}>", render_type_ref(key), render_type_ref(value))
14337        }
14338    }
14339}
14340
14341fn render_route_delivery(route: &meerkat_machine_schema::Route) -> &'static str {
14342    match route.delivery {
14343        RouteDelivery::Immediate => "Immediate",
14344        RouteDelivery::Enqueue => "Enqueue",
14345    }
14346}
14347
14348fn render_scheduler_rule(rule: &SchedulerRule) -> String {
14349    match rule {
14350        SchedulerRule::PreemptWhenReady { higher, lower } => {
14351            format!("PreemptWhenReady({higher}, {lower})")
14352        }
14353    }
14354}
14355
14356fn render_scheduler_rule_tuple(rule: &SchedulerRule) -> String {
14357    match rule {
14358        SchedulerRule::PreemptWhenReady { higher, lower } => {
14359            format!(
14360                "<<{}, {}, {}>>",
14361                tla_string("PreemptWhenReady"),
14362                tla_string(higher),
14363                tla_string(lower)
14364            )
14365        }
14366    }
14367}
14368
14369fn render_scheduler_trigger_formula(rule: &SchedulerRule) -> String {
14370    match rule {
14371        SchedulerRule::PreemptWhenReady { higher, lower } => format!(
14372            "/\\ {} \\in PendingActors /\\ {} \\in PendingActors",
14373            tla_string(higher),
14374            tla_string(lower)
14375        ),
14376    }
14377}
14378
14379fn render_composition_invariant_formula(
14380    schema: &CompositionSchema,
14381    kind: &CompositionInvariantKind,
14382) -> String {
14383    match kind {
14384        CompositionInvariantKind::RoutePresent {
14385            from_machine,
14386            effect_variant,
14387            to_machine,
14388            input_variant,
14389        } => format!(
14390            "\\E route_name \\in RouteNames : /\\ RouteSource(route_name) = {} /\\ RouteEffect(route_name) = {} /\\ RouteTargetMachine(route_name) = {} /\\ RouteTargetInput(route_name) = {}",
14391            tla_string(from_machine),
14392            tla_string(effect_variant),
14393            tla_string(to_machine),
14394            tla_string(input_variant)
14395        ),
14396        CompositionInvariantKind::ObservedInputOriginatesFromEffect {
14397            to_machine,
14398            input_variant,
14399            from_machine,
14400            effect_variant,
14401        } => format!(
14402            "\\A input_packet \\in observed_inputs : ((input_packet.machine = {} /\\ input_packet.variant = {}) => (/\\ input_packet.source_kind = \"route\" /\\ input_packet.source_machine = {} /\\ input_packet.source_effect = {} /\\ \\E effect_packet \\in emitted_effects : /\\ effect_packet.machine = {} /\\ effect_packet.variant = {} /\\ effect_packet.effect_id = input_packet.effect_id /\\ \\E route_packet \\in RoutePackets : /\\ route_packet.route = input_packet.source_route /\\ route_packet.source_machine = {} /\\ route_packet.effect = {} /\\ route_packet.target_machine = {} /\\ route_packet.target_input = {} /\\ route_packet.effect_id = input_packet.effect_id /\\ route_packet.payload = input_packet.payload))",
14403            tla_string(to_machine),
14404            tla_string(input_variant),
14405            tla_string(from_machine),
14406            tla_string(effect_variant),
14407            tla_string(from_machine),
14408            tla_string(effect_variant),
14409            tla_string(from_machine),
14410            tla_string(effect_variant),
14411            tla_string(to_machine),
14412            tla_string(input_variant)
14413        ),
14414        CompositionInvariantKind::ObservedRouteInputOriginatesFromEffect {
14415            route_name,
14416            to_machine,
14417            input_variant,
14418            from_machine,
14419            effect_variant,
14420        } => format!(
14421            "\\A input_packet \\in observed_inputs : ((input_packet.machine = {} /\\ input_packet.variant = {} /\\ input_packet.source_route = {}) => (/\\ input_packet.source_kind = \"route\" /\\ input_packet.source_machine = {} /\\ input_packet.source_effect = {} /\\ \\E effect_packet \\in emitted_effects : /\\ effect_packet.machine = {} /\\ effect_packet.variant = {} /\\ effect_packet.effect_id = input_packet.effect_id /\\ \\E route_packet \\in RoutePackets : /\\ route_packet.route = {} /\\ route_packet.source_machine = {} /\\ route_packet.effect = {} /\\ route_packet.target_machine = {} /\\ route_packet.target_input = {} /\\ route_packet.effect_id = input_packet.effect_id /\\ route_packet.payload = input_packet.payload))",
14422            tla_string(to_machine),
14423            tla_string(input_variant),
14424            tla_string(route_name),
14425            tla_string(from_machine),
14426            tla_string(effect_variant),
14427            tla_string(from_machine),
14428            tla_string(effect_variant),
14429            tla_string(route_name),
14430            tla_string(from_machine),
14431            tla_string(effect_variant),
14432            tla_string(to_machine),
14433            tla_string(input_variant)
14434        ),
14435        CompositionInvariantKind::ActorPriorityPresent { higher, lower } => format!(
14436            "<<{}, {}>> \\in ActorPriorities",
14437            tla_string(higher),
14438            tla_string(lower)
14439        ),
14440        CompositionInvariantKind::SchedulerRulePresent { rule } => {
14441            format!("{} \\in SchedulerRules", render_scheduler_rule_tuple(rule))
14442        }
14443        CompositionInvariantKind::OutcomeHandled {
14444            from_machine,
14445            effect_variant,
14446            required_targets,
14447        } => {
14448            let required = required_targets
14449                .iter()
14450                .enumerate()
14451                .map(|(idx, target)| {
14452                    let binding = format!("route_packet_{idx}");
14453                    let input_binding = format!("input_packet_{idx}");
14454                    format!(
14455                        "\\E {binding} \\in RoutePackets : /\\ {binding}.source_machine = {} /\\ {binding}.effect = {} /\\ {binding}.target_machine = {} /\\ {binding}.target_input = {} /\\ {binding}.effect_id = effect_packet.effect_id /\\ IF RouteDeliveryKind({binding}.route) = \"Immediate\" THEN \\E {input_binding} \\in observed_inputs : /\\ {input_binding}.machine = {} /\\ {input_binding}.variant = {} /\\ {input_binding}.source_kind = \"route\" /\\ {input_binding}.source_route = {binding}.route /\\ {input_binding}.source_machine = {} /\\ {input_binding}.source_effect = {} /\\ {input_binding}.effect_id = effect_packet.effect_id /\\ {input_binding}.payload = {binding}.payload ELSE TRUE",
14456                        tla_string(from_machine),
14457                        tla_string(effect_variant),
14458                        tla_string(&target.machine),
14459                        tla_string(&target.input_variant)
14460                        ,
14461                        tla_string(&target.machine),
14462                        tla_string(&target.input_variant),
14463                        tla_string(from_machine),
14464                        tla_string(effect_variant)
14465                    )
14466                })
14467                .collect::<Vec<_>>()
14468                .join(" /\\ ");
14469            let fallback = schema
14470                .routes
14471                .iter()
14472                .filter(|route| {
14473                    route.from_machine == *from_machine && route.effect_variant == *effect_variant
14474                })
14475                .count();
14476            if fallback == 0 {
14477                "FALSE".into()
14478            } else {
14479                format!(
14480                    "\\A effect_packet \\in emitted_effects : ((effect_packet.machine = {} /\\ effect_packet.variant = {}) => ({}))",
14481                    tla_string(from_machine),
14482                    tla_string(effect_variant),
14483                    required
14484                )
14485            }
14486        }
14487        CompositionInvariantKind::HandoffProtocolCovered { .. } => {
14488            // Structural invariant — validated at schema level, always TRUE in TLA+.
14489            "TRUE".into()
14490        }
14491    }
14492}
14493
14494fn render_composition_state_constraint(
14495    schema: &CompositionSchema,
14496    limits: &CompositionStateLimits,
14497    compiler: &CompositionTlaCompiler<'_>,
14498) -> String {
14499    let limits = effective_composition_state_limits(limits, None);
14500    let mut clauses = vec![
14501        format!("model_step_count <= {}", limits.step_limit),
14502        format!("Len(pending_inputs) <= {}", limits.pending_input_limit),
14503        format!(
14504            "Cardinality(observed_inputs) <= {}",
14505            limits.pending_input_limit + limits.delivered_route_limit + 2
14506        ),
14507        format!("Len(pending_routes) <= {}", limits.pending_route_limit),
14508        format!(
14509            "Cardinality(delivered_routes) <= {}",
14510            limits.delivered_route_limit
14511        ),
14512        format!(
14513            "Cardinality(emitted_effects) <= {}",
14514            limits.emitted_effect_limit
14515        ),
14516        format!("Cardinality(observed_transitions) <= {}", limits.step_limit),
14517    ];
14518
14519    for instance in &schema.machines {
14520        let machine = compiler.machine(instance.instance_id.as_str());
14521        for field in &machine.state.fields {
14522            let field_var = compiler.field_var(instance.instance_id.as_str(), field.name.as_str());
14523            match &field.ty {
14524                TypeRef::Seq(_) => {
14525                    clauses.push(format!("Len({field_var}) <= {}", limits.seq_limit))
14526                }
14527                TypeRef::Set(_) => {
14528                    clauses.push(format!("Cardinality({field_var}) <= {}", limits.set_limit))
14529                }
14530                TypeRef::Map(_, _) => clauses.push(format!(
14531                    "Cardinality(DOMAIN {field_var}) <= {}",
14532                    limits.map_limit
14533                )),
14534                _ => {}
14535            }
14536        }
14537    }
14538
14539    format!("/\\ {}", clauses.join(" /\\ "))
14540}
14541
14542fn effective_composition_state_limits(
14543    limits: &CompositionStateLimits,
14544    witness: Option<&CompositionWitness>,
14545) -> CompositionStateLimits {
14546    let mut effective = limits.clone();
14547    if let Some(witness) = witness {
14548        let minimum_step_limit =
14549            (witness.preload_inputs.len() + witness.expected_transitions.len()) as u32;
14550        effective.step_limit = effective.step_limit.max(minimum_step_limit);
14551        effective.delivered_route_limit = effective
14552            .delivered_route_limit
14553            .max(witness.expected_routes.len() as u32);
14554        effective.emitted_effect_limit = effective
14555            .emitted_effect_limit
14556            .max(witness.expected_transitions.len() as u32);
14557        effective.pending_input_limit = effective.pending_input_limit.max(1);
14558    }
14559    effective
14560}
14561
14562fn composition_deep_state_limits(schema: &CompositionSchema) -> CompositionStateLimits {
14563    let mut deep = CompositionStateLimits::deep_defaults();
14564    if let Some(ci) = &schema.ci_limits {
14565        deep.step_limit = deep.step_limit.max(ci.step_limit);
14566        deep.pending_input_limit = deep.pending_input_limit.max(ci.pending_input_limit);
14567        deep.pending_route_limit = deep.pending_route_limit.max(ci.pending_route_limit);
14568        deep.delivered_route_limit = deep.delivered_route_limit.max(ci.delivered_route_limit);
14569        deep.emitted_effect_limit = deep.emitted_effect_limit.max(ci.emitted_effect_limit);
14570        deep.seq_limit = deep.seq_limit.max(ci.seq_limit);
14571        deep.set_limit = deep.set_limit.max(ci.set_limit);
14572        deep.map_limit = deep.map_limit.max(ci.map_limit);
14573    }
14574    deep
14575}
14576
14577fn render_machine_state_constraint(schema: &MachineSchema, deep: bool) -> String {
14578    let step_limit = if deep {
14579        8
14580    } else {
14581        schema.ci_step_limit.unwrap_or(6) as usize
14582    };
14583    let seq_limit = if deep { 2 } else { 1 };
14584    let set_limit = if deep { 2 } else { 1 };
14585    let map_limit = if deep { 2 } else { 1 };
14586    let (step_limit, seq_limit, set_limit, map_limit) =
14587        if !deep && let Some(model) = &schema.tlc_model {
14588            let limits = &model.ci_limits;
14589            (
14590                limits.step_limit as usize,
14591                limits.seq_limit as usize,
14592                limits.set_limit as usize,
14593                limits.map_limit as usize,
14594            )
14595        } else {
14596            (step_limit, seq_limit, set_limit, map_limit)
14597        };
14598    let mut clauses = vec![format!("model_step_count <= {step_limit}")];
14599
14600    for field in &schema.state.fields {
14601        match &field.ty {
14602            TypeRef::Seq(_) => {
14603                clauses.push(format!("Len({}) <= {seq_limit}", tla_ident(&field.name)))
14604            }
14605            TypeRef::Set(_) => clauses.push(format!(
14606                "Cardinality({}) <= {set_limit}",
14607                tla_ident(&field.name)
14608            )),
14609            TypeRef::Map(_, _) => clauses.push(format!(
14610                "Cardinality(DOMAIN {}) <= {map_limit}",
14611                tla_ident(&field.name)
14612            )),
14613            _ => {}
14614        }
14615    }
14616
14617    if clauses.is_empty() {
14618        "TRUE".into()
14619    } else {
14620        format!("/\\ {}", clauses.join(" /\\ "))
14621    }
14622}
14623
14624/// Default arm for a generated composition `CASE` operator.
14625///
14626/// Route-component lookups (`RouteSource`, `RouteEffect`, …) are validated
14627/// up-front by [`CompositionTlaCompiler::validate_routes`], so the historical
14628/// `OTHER -> "unknown_*"` arm is provably unreachable for any real route name.
14629/// Emitting that sentinel was a silent catch-all that could launder an
14630/// undeclared route component into a passing model. Such lookups now use
14631/// [`CaseDefault::FailClosed`]: the `OTHER` arm is dropped entirely so an
14632/// unmatched route name surfaces as a TLC error instead of a fabricated value,
14633/// and the renderer fails closed at codegen time if a route component cannot
14634/// be resolved.
14635///
14636/// Genuinely closed enumerations (`RouteTargetKind`, `RouteDeliveryKind`) keep
14637/// a total literal fallback via [`CaseDefault::ClosedEnum`]; every input maps
14638/// to a finite, exhaustive enum, so the literal is a sound total default rather
14639/// than a sentinel standing in for an undeclared component.
14640enum CaseDefault {
14641    /// Total literal fallback over a closed enumeration domain.
14642    ClosedEnum(String),
14643    /// Fail-closed route-component lookup: no `OTHER` sentinel is emitted.
14644    ///
14645    /// `require_mapping` is `true` for operators whose domain must be
14646    /// non-empty for a well-formed composition (e.g. `ActorOfMachine`, which
14647    /// maps over declared machine instances): an empty mapping is then a hard
14648    /// codegen error. It is `false` for operators keyed on routes, since a
14649    /// protocol-only composition legitimately declares zero routes — the
14650    /// operator is structurally defined but never evaluated.
14651    FailClosed {
14652        component: &'static str,
14653        require_mapping: bool,
14654    },
14655}
14656
14657fn render_composition_case_fn(
14658    out: &mut String,
14659    composition: &str,
14660    fn_name: &str,
14661    param: &str,
14662    mappings: Vec<(&str, String)>,
14663    default: CaseDefault,
14664) -> std::result::Result<(), CompositionTlaError> {
14665    writeln!(out, "{fn_name}({param}) ==");
14666    if mappings.is_empty() {
14667        // No keys to map. For a closed-enum operator the literal fallback is
14668        // the operator body. For a fail-closed route-component operator the
14669        // composition declares no routes, so the operator is structurally
14670        // defined but unreachable; emitting the bare error label as a string
14671        // makes any accidental evaluation explode in TLC rather than yield a
14672        // plausible-looking value.
14673        let body = match &default {
14674            CaseDefault::ClosedEnum(expr) => expr.clone(),
14675            CaseDefault::FailClosed {
14676                component,
14677                require_mapping,
14678            } => {
14679                if *require_mapping {
14680                    return Err(CompositionTlaError::UnknownRouteComponent {
14681                        composition: composition.to_owned(),
14682                        component,
14683                    });
14684                }
14685                tla_string(format!("unresolved_{component}"))
14686            }
14687        };
14688        pushln!(out, "    {}", body);
14689        pushln!(out);
14690        return Ok(());
14691    }
14692
14693    let mut first = true;
14694    for (key, value) in mappings {
14695        if first {
14696            pushln!(out, "    CASE {} = {} -> {}", param, tla_string(key), value);
14697            first = false;
14698        } else {
14699            writeln!(out, "      [] {} = {} -> {}", param, tla_string(key), value);
14700        }
14701    }
14702    match default {
14703        CaseDefault::ClosedEnum(expr) => {
14704            writeln!(out, "      [] OTHER -> {}", expr);
14705        }
14706        CaseDefault::FailClosed { .. } => {
14707            // validate_routes() guarantees the CASE arms cover every declared
14708            // route, so an OTHER arm here would be a silent catch-all over an
14709            // undeclared route component. Drop it: an unmatched route name now
14710            // becomes a TLC evaluation error (fail closed) instead of a
14711            // fabricated sentinel.
14712        }
14713    }
14714    pushln!(out);
14715    Ok(())
14716}
14717
14718fn tla_ident(value: impl AsRef<str>) -> String {
14719    value
14720        .as_ref()
14721        .chars()
14722        .map(|ch| if ch.is_ascii_alphanumeric() { ch } else { '_' })
14723        .collect()
14724}
14725
14726fn tla_string(value: impl AsRef<str>) -> String {
14727    format!("\"{}\"", value.as_ref().replace('"', "\\\""))
14728}
14729
14730/// Wrap a rendered TLA+ expression in parentheses unless it is already an
14731/// atom (an identifier, field path, number or string, optionally applied with balanced
14732/// `(...)`/`[...]` suffixes, or one parenthesized group), so it can be spliced
14733/// as an operand without TLA+ operator precedence reaching into it.
14734fn tla_delimited(expr: &str) -> String {
14735    if tla_is_atom(expr) {
14736        expr.to_owned()
14737    } else {
14738        format!("({expr})")
14739    }
14740}
14741
14742fn tla_is_atom(expr: &str) -> bool {
14743    let bytes = expr.as_bytes();
14744    let mut index = 0;
14745    match bytes.first() {
14746        Some(b'(') => {}
14747        Some(b'"') => {
14748            index = 1;
14749            while index < bytes.len() && bytes[index] != b'"' {
14750                index += 1;
14751            }
14752            if index >= bytes.len() {
14753                return false;
14754            }
14755            index += 1;
14756        }
14757        Some(byte) if byte.is_ascii_alphanumeric() || *byte == b'_' => {
14758            // Identifiers and record field paths (`packet.payload.run_id`):
14759            // field access binds tighter than every operator.
14760            while index < bytes.len()
14761                && (bytes[index].is_ascii_alphanumeric()
14762                    || bytes[index] == b'_'
14763                    || bytes[index] == b'.')
14764            {
14765                index += 1;
14766            }
14767        }
14768        _ => return false,
14769    }
14770    // Zero or more balanced `(...)` / `[...]` groups, with nothing between.
14771    while index < bytes.len() {
14772        let (open, close) = match bytes[index] {
14773            b'(' => (b'(', b')'),
14774            b'[' => (b'[', b']'),
14775            _ => return false,
14776        };
14777        let mut depth = 0usize;
14778        let mut in_string = false;
14779        let mut end = None;
14780        for (offset, byte) in bytes[index..].iter().enumerate() {
14781            match *byte {
14782                b'"' => in_string = !in_string,
14783                b if b == open && !in_string => depth += 1,
14784                b if b == close && !in_string => {
14785                    depth -= 1;
14786                    if depth == 0 {
14787                        end = Some(index + offset);
14788                        break;
14789                    }
14790                }
14791                _ => {}
14792            }
14793        }
14794        match end {
14795            Some(end) => index = end + 1,
14796            None => return false,
14797        }
14798    }
14799    true
14800}
14801
14802/// The input variant a transition is triggered by, if it is input-triggered.
14803fn trigger_input_variant(transition: &TransitionSchema) -> Option<&str> {
14804    match &transition.on {
14805        TriggerMatch::Input { variant, .. } => Some(variant.as_str()),
14806        _ => None,
14807    }
14808}
14809
14810/// The default unsigned domain extended with declared additional values.
14811fn additional_values_domain(default: &str, values: &BTreeSet<u64>) -> String {
14812    let values = values
14813        .iter()
14814        .map(u64::to_string)
14815        .collect::<Vec<_>>()
14816        .join(", ");
14817    format!("({default} \\cup {{{values}}})")
14818}
14819
14820/// The model constant that a `CiValues` or `CiSamples` input field ranges
14821/// over in the generated model; each profile's config assigns it.
14822fn input_samples_constant_name(input: &str, field: &str) -> String {
14823    format!("InputSamples_{}_{}", tla_ident(input), tla_ident(field))
14824}
14825
14826/// The samples a `CiValues` input field keeps outside the CI profile (the
14827/// Deep profile and every composition): the declared values together with the
14828/// default unsigned domain (`0..2`).
14829fn broad_input_samples(ci_values: &BTreeSet<u64>) -> BTreeSet<u64> {
14830    (0..=2).chain(ci_values.iter().copied()).collect()
14831}
14832
14833fn render_u64_set(values: &BTreeSet<u64>) -> String {
14834    let values = values
14835        .iter()
14836        .map(u64::to_string)
14837        .collect::<Vec<_>>()
14838        .join(", ");
14839    format!("{{{values}}}")
14840}
14841
14842/// Every `CiValues` input field of a machine, in declaration order: the model
14843/// constant the field ranges over and the values the CI profile assigns it.
14844fn machine_input_sample_constants(schema: &MachineSchema) -> Vec<(String, &BTreeSet<u64>)> {
14845    schema
14846        .input_field_domains
14847        .iter()
14848        .filter_map(|declaration| match &declaration.domain {
14849            meerkat_machine_schema::InputFieldDomainKind::CiValues(values) => Some((
14850                input_samples_constant_name(declaration.input.as_str(), declaration.field.as_str()),
14851                values,
14852            )),
14853            meerkat_machine_schema::InputFieldDomainKind::AdditionalValues(_)
14854            | meerkat_machine_schema::InputFieldDomainKind::StateField(_)
14855            | meerkat_machine_schema::InputFieldDomainKind::CiSamples(_) => None,
14856        })
14857        .collect()
14858}
14859
14860/// Every `CiSamples` input field of a machine, in declaration order: the
14861/// model constant the field ranges over, the values the CI profile assigns
14862/// it, and the field's type, whose whole domain the Deep profile assigns it.
14863/// The schema's validation resolves every declared field.
14864fn machine_input_typed_sample_constants(
14865    schema: &MachineSchema,
14866) -> Vec<(String, &[meerkat_machine_schema::TlcValue], TypeRef)> {
14867    schema
14868        .input_field_domains
14869        .iter()
14870        .filter_map(|declaration| match &declaration.domain {
14871            meerkat_machine_schema::InputFieldDomainKind::CiSamples(samples) => {
14872                let field = schema
14873                    .inputs
14874                    .variant_named(declaration.input.as_str())
14875                    .ok()?
14876                    .fields
14877                    .iter()
14878                    .find(|field| field.name == declaration.field)?;
14879                Some((
14880                    input_samples_constant_name(
14881                        declaration.input.as_str(),
14882                        declaration.field.as_str(),
14883                    ),
14884                    samples.as_slice(),
14885                    field.ty.clone(),
14886                ))
14887            }
14888            meerkat_machine_schema::InputFieldDomainKind::AdditionalValues(_)
14889            | meerkat_machine_schema::InputFieldDomainKind::StateField(_)
14890            | meerkat_machine_schema::InputFieldDomainKind::CiValues(_) => None,
14891        })
14892        .collect()
14893}