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 widest member snapshot of a mob's operator instruction
4507        // records, and the widest a write changes with the write applied,
4508        // in records and in Active body bytes.
4509        Expr::Call { helper, .. }
4510            if helper == "mob_machine_instruction_widest_snapshot_slots"
4511                || helper == "mob_machine_instruction_widest_snapshot_active_bytes"
4512                || helper == "mob_machine_instruction_write_snapshot_slots"
4513                || helper == "mob_machine_instruction_write_snapshot_active_bytes" =>
4514        {
4515            Some(TypeRef::U64)
4516        }
4517        // The Active entries of a slot map: the type of the map it filters.
4518        Expr::Call { helper, args } if helper == "session_document_instruction_active_slots" => {
4519            args.get(1).and_then(|values| {
4520                infer_expr_type(values, field_types, helper_returns, binding_types)
4521            })
4522        }
4523        // The retired count per activation key: the type of the row counts.
4524        Expr::Call { helper, args } if helper == "session_document_activation_retired_after" => {
4525            args.first()
4526                .and_then(|rows| infer_expr_type(rows, field_types, helper_returns, binding_types))
4527        }
4528        Expr::Call { helper, .. } if helper == "runtime_delivery_recipient_outcomes_after_set" => {
4529            Some(TypeRef::Map(
4530                Box::new(TypeRef::String),
4531                Box::new(TypeRef::Enum(
4532                    meerkat_machine_schema::identity::EnumTypeId::parse("DeliveryRecipientOutcome")
4533                        .ok()?,
4534                )),
4535            ))
4536        }
4537        Expr::Call { helper, .. } if helper == "mob_machine_run_step_status_after_set" => {
4538            Some(TypeRef::Map(
4539                Box::new(TypeRef::Named(
4540                    meerkat_machine_schema::identity::NamedTypeId::parse("RunId").ok()?,
4541                )),
4542                Box::new(TypeRef::Map(
4543                    Box::new(TypeRef::Named(
4544                        meerkat_machine_schema::identity::NamedTypeId::parse("StepId").ok()?,
4545                    )),
4546                    Box::new(TypeRef::Option(Box::new(TypeRef::Enum(
4547                        meerkat_machine_schema::identity::EnumTypeId::parse("StepRunStatus")
4548                            .ok()?,
4549                    )))),
4550                )),
4551            ))
4552        }
4553        Expr::Call { helper, .. }
4554            if helper == "mob_machine_run_step_status_after_cancel_unfinished" =>
4555        {
4556            Some(TypeRef::Map(
4557                Box::new(TypeRef::Named(
4558                    meerkat_machine_schema::identity::NamedTypeId::parse("RunId").ok()?,
4559                )),
4560                Box::new(TypeRef::Map(
4561                    Box::new(TypeRef::Named(
4562                        meerkat_machine_schema::identity::NamedTypeId::parse("StepId").ok()?,
4563                    )),
4564                    Box::new(TypeRef::Option(Box::new(TypeRef::Enum(
4565                        meerkat_machine_schema::identity::EnumTypeId::parse("StepRunStatus")
4566                            .ok()?,
4567                    )))),
4568                )),
4569            ))
4570        }
4571        Expr::Call { helper, .. } if helper == "mob_machine_run_step_bool_after_set" => {
4572            Some(TypeRef::Map(
4573                Box::new(TypeRef::Named(
4574                    meerkat_machine_schema::identity::NamedTypeId::parse("RunId").ok()?,
4575                )),
4576                Box::new(TypeRef::Map(
4577                    Box::new(TypeRef::Named(
4578                        meerkat_machine_schema::identity::NamedTypeId::parse("StepId").ok()?,
4579                    )),
4580                    Box::new(TypeRef::Bool),
4581                )),
4582            ))
4583        }
4584        Expr::Call { helper, .. }
4585            if helper == "mob_machine_run_step_condition_result_after_set" =>
4586        {
4587            Some(TypeRef::Map(
4588                Box::new(TypeRef::Named(
4589                    meerkat_machine_schema::identity::NamedTypeId::parse("RunId").ok()?,
4590                )),
4591                Box::new(TypeRef::Map(
4592                    Box::new(TypeRef::Named(
4593                        meerkat_machine_schema::identity::NamedTypeId::parse("StepId").ok()?,
4594                    )),
4595                    Box::new(TypeRef::Option(Box::new(TypeRef::Bool))),
4596                )),
4597            ))
4598        }
4599        Expr::Call { helper, .. }
4600            if helper == "mob_machine_run_step_u64_after_set"
4601                || helper == "mob_machine_run_step_u64_after_increment" =>
4602        {
4603            Some(TypeRef::Map(
4604                Box::new(TypeRef::Named(
4605                    meerkat_machine_schema::identity::NamedTypeId::parse("RunId").ok()?,
4606                )),
4607                Box::new(TypeRef::Map(
4608                    Box::new(TypeRef::Named(
4609                        meerkat_machine_schema::identity::NamedTypeId::parse("StepId").ok()?,
4610                    )),
4611                    Box::new(TypeRef::U64),
4612                )),
4613            ))
4614        }
4615        Expr::Call { helper, .. } if helper == "mob_machine_run_retry_count_after_increment" => {
4616            Some(TypeRef::Map(
4617                Box::new(TypeRef::Named(
4618                    meerkat_machine_schema::identity::NamedTypeId::parse("RunId").ok()?,
4619                )),
4620                Box::new(TypeRef::Map(
4621                    Box::new(TypeRef::String),
4622                    Box::new(TypeRef::U64),
4623                )),
4624            ))
4625        }
4626        Expr::Call { helper, .. } if helper == "mob_machine_frame_node_bool_after_set" => {
4627            Some(TypeRef::Map(
4628                Box::new(TypeRef::Named(
4629                    meerkat_machine_schema::identity::NamedTypeId::parse("FrameId").ok()?,
4630                )),
4631                Box::new(TypeRef::Map(
4632                    Box::new(TypeRef::Named(
4633                        meerkat_machine_schema::identity::NamedTypeId::parse("FlowNodeId").ok()?,
4634                    )),
4635                    Box::new(TypeRef::Bool),
4636                )),
4637            ))
4638        }
4639        Expr::Call { helper, .. } => helper_returns.get(helper).cloned(),
4640        Expr::SeqLiteral(items) => items.first().and_then(|item| {
4641            infer_expr_type(item, field_types, helper_returns, binding_types)
4642                .map(|inner_ty| TypeRef::Seq(Box::new(inner_ty)))
4643        }),
4644        Expr::EmptySet => None,
4645        Expr::EmptyMap => None,
4646    }
4647}
4648
4649fn default_sample_cardinality(deep: bool) -> usize {
4650    if deep { 2 } else { 1 }
4651}
4652
4653fn type_sample_bucket(ty: &TypeRef) -> Option<String> {
4654    match ty {
4655        TypeRef::String => Some("String".into()),
4656        TypeRef::Named(name) => Some(name.as_str().to_owned()),
4657        TypeRef::Enum(name) => Some(name.as_str().to_owned()),
4658        _ => None,
4659    }
4660}
4661
4662fn collected_sample_literals(
4663    bucket: &str,
4664    sample_cardinality: usize,
4665    named_samples: &BTreeMap<String, BTreeSet<String>>,
4666) -> Option<Vec<String>> {
4667    let samples = named_samples.get(bucket)?;
4668    let limit = sample_cardinality.max(1);
4669    let rendered = samples
4670        .iter()
4671        .take(limit)
4672        .map(tla_string)
4673        .collect::<Vec<_>>();
4674    (!rendered.is_empty()).then_some(rendered)
4675}
4676
4677fn generic_string_samples(sample_cardinality: usize) -> Vec<String> {
4678    if sample_cardinality > 1 {
4679        vec!["alpha".into(), "beta".into()]
4680    } else {
4681        vec!["alpha".into()]
4682    }
4683}
4684
4685fn collected_string_samples(
4686    sample_cardinality: usize,
4687    named_samples: &BTreeMap<String, BTreeSet<String>>,
4688    include_named_samples: bool,
4689) -> Vec<String> {
4690    let mut values = generic_string_samples(sample_cardinality);
4691    if include_named_samples && let Some(samples) = named_samples.get("String") {
4692        for sample in samples {
4693            if !values.iter().any(|existing| existing == sample) {
4694                values.push(sample.clone());
4695            }
4696        }
4697    }
4698    values
4699}
4700
4701fn render_default_domain_assignment(
4702    ty: &TypeRef,
4703    sample_cardinality: usize,
4704    named_samples: &BTreeMap<String, BTreeSet<String>>,
4705    named_bindings: &BTreeMap<String, meerkat_machine_schema::RustTypeAtom>,
4706    include_string_samples: bool,
4707) -> String {
4708    match ty {
4709        TypeRef::Bool => "{TRUE, FALSE}".into(),
4710        TypeRef::U32 | TypeRef::U64 => {
4711            if sample_cardinality > 1 {
4712                "{0, 1, 2}".into()
4713            } else {
4714                // CI uses {1} to avoid state explosion from zero-as-unlimited
4715                // semantics in scheduler guards (Or(max==0, count<max)).
4716                // Counter fields that start at 0 get it via Init, not NatValues.
4717                // Deep uses {0, 1} to cover the full range.
4718                "{1}".into()
4719            }
4720        }
4721        TypeRef::String if sample_cardinality == 0 => "{}".into(),
4722        TypeRef::String => format!(
4723            "{{{}}}",
4724            collected_string_samples(sample_cardinality, named_samples, include_string_samples)
4725                .into_iter()
4726                .map(|sample| tla_string(&sample))
4727                .collect::<Vec<_>>()
4728                .join(", ")
4729        ),
4730        TypeRef::Named(name) => render_named_type_domain_assignment(
4731            name.as_str(),
4732            sample_cardinality,
4733            named_samples,
4734            named_bindings,
4735        ),
4736        TypeRef::Enum(name) => render_enum_type_domain_assignment(
4737            name.as_str(),
4738            sample_cardinality,
4739            named_samples,
4740            named_bindings,
4741        ),
4742        TypeRef::Seq(inner) => {
4743            let samples = sample_values(
4744                inner,
4745                sample_cardinality,
4746                named_samples,
4747                named_bindings,
4748                include_string_samples,
4749            );
4750            if samples.len() >= 2 {
4751                format!(
4752                    "{{<<>>, <<{}>>, <<{}, {}>>}}",
4753                    samples[0], samples[0], samples[1]
4754                )
4755            } else if let Some(sample) = samples.first() {
4756                format!("{{<<>>, <<{}>>}}", sample)
4757            } else {
4758                "{<<>>}".into()
4759            }
4760        }
4761        TypeRef::Set(inner) => {
4762            let samples = sample_values(
4763                inner,
4764                sample_cardinality,
4765                named_samples,
4766                named_bindings,
4767                include_string_samples,
4768            );
4769            if samples.len() >= 2 {
4770                format!(
4771                    "{{{{}}, {{{}}}, {{{}, {}}}}}",
4772                    samples[0], samples[0], samples[1]
4773                )
4774            } else if let Some(sample) = samples.first() {
4775                format!("{{{{}}, {{{}}}}}", sample)
4776            } else {
4777                "{{}}".into()
4778            }
4779        }
4780        TypeRef::Option(inner) => {
4781            let samples = sample_values(
4782                inner,
4783                sample_cardinality,
4784                named_samples,
4785                named_bindings,
4786                include_string_samples,
4787            )
4788            .into_iter()
4789            .map(|sample| format!("[tag |-> {}, value |-> {}]", tla_string("some"), sample))
4790            .collect::<Vec<_>>();
4791            if samples.is_empty() {
4792                format!(
4793                    "{{[tag |-> {}, value |-> {}]}}",
4794                    tla_string("none"),
4795                    tla_string("none")
4796                )
4797            } else {
4798                format!(
4799                    "{{[tag |-> {}, value |-> {}], {}}}",
4800                    tla_string("none"),
4801                    tla_string("none"),
4802                    samples.join(", ")
4803                )
4804            }
4805        }
4806        TypeRef::Map(_, _) => "{}".into(),
4807    }
4808}
4809
4810fn render_named_type_domain_assignment(
4811    name: impl AsRef<str>,
4812    sample_cardinality: usize,
4813    named_samples: &BTreeMap<String, BTreeSet<String>>,
4814    named_bindings: &BTreeMap<String, meerkat_machine_schema::RustTypeAtom>,
4815) -> String {
4816    use meerkat_machine_schema::RustTypeAtom;
4817
4818    let name = name.as_ref();
4819    if name == "OperationSource" {
4820        return format!(
4821            "{{{}}}",
4822            operation_source_samples(sample_cardinality).join(", ")
4823        );
4824    }
4825    match require_named_binding(named_bindings, name) {
4826        RustTypeAtom::U64 | RustTypeAtom::U32 | RustTypeAtom::U16 | RustTypeAtom::U8 => {
4827            if sample_cardinality > 1 {
4828                "{1, 2}".into()
4829            } else {
4830                "{1}".into()
4831            }
4832        }
4833        RustTypeAtom::Bool => "{TRUE, FALSE}".into(),
4834        RustTypeAtom::StringEnum { variants } => {
4835            format!(
4836                "{{{}}}",
4837                string_enum_variant_samples(name, variants).join(", ")
4838            )
4839        }
4840        RustTypeAtom::TypePathEnum {
4841            unit_variants,
4842            structural_variants,
4843            ..
4844        } => format!(
4845            "{{{}}}",
4846            type_path_enum_variant_samples(
4847                unit_variants,
4848                structural_variants,
4849                sample_cardinality,
4850                named_samples,
4851                named_bindings,
4852            )
4853            .join(", ")
4854        ),
4855        RustTypeAtom::TypePathFieldPresenceSet { fields, .. } => format!(
4856            "{{{}}}",
4857            field_presence_set_samples(fields, sample_cardinality).join(", ")
4858        ),
4859        RustTypeAtom::TypePathStruct { fields, .. } => format!(
4860            "{{{}}}",
4861            type_path_struct_samples(fields, sample_cardinality, named_samples, named_bindings)
4862                .join(", ")
4863        ),
4864        RustTypeAtom::String | RustTypeAtom::TypePath(_) => {
4865            if sample_cardinality == 0 {
4866                return "{}".into();
4867            }
4868
4869            if let Some(rendered) =
4870                collected_sample_literals(name, sample_cardinality, named_samples)
4871            {
4872                return format!("{{{}}}", rendered.join(", "));
4873            }
4874
4875            let values = (1..=sample_cardinality.max(1))
4876                .map(|idx| tla_string(format!("{}_{}", tla_ident(name).to_lowercase(), idx)))
4877                .collect::<Vec<_>>()
4878                .join(", ");
4879            format!("{{{values}}}")
4880        }
4881    }
4882}
4883
4884#[allow(clippy::panic)]
4885fn render_enum_type_domain_assignment(
4886    name: impl AsRef<str>,
4887    sample_cardinality: usize,
4888    named_samples: &BTreeMap<String, BTreeSet<String>>,
4889    named_bindings: &BTreeMap<String, meerkat_machine_schema::RustTypeAtom>,
4890) -> String {
4891    use meerkat_machine_schema::RustTypeAtom;
4892
4893    let name = name.as_ref();
4894    match require_named_binding(named_bindings, name) {
4895        RustTypeAtom::StringEnum { variants } => {
4896            format!(
4897                "{{{}}}",
4898                string_enum_variant_samples(name, variants).join(", ")
4899            )
4900        }
4901        RustTypeAtom::TypePathEnum {
4902            unit_variants,
4903            structural_variants,
4904            ..
4905        } => format!(
4906            "{{{}}}",
4907            type_path_enum_variant_samples(
4908                unit_variants,
4909                structural_variants,
4910                sample_cardinality,
4911                named_samples,
4912                named_bindings,
4913            )
4914            .join(", ")
4915        ),
4916        other => {
4917            panic!(
4918                "generated enum domain `{name}` requires StringEnum or TypePathEnum binding, found {other:?}"
4919            );
4920        }
4921    }
4922}
4923
4924fn sample_values(
4925    ty: &TypeRef,
4926    sample_cardinality: usize,
4927    named_samples: &BTreeMap<String, BTreeSet<String>>,
4928    named_bindings: &BTreeMap<String, meerkat_machine_schema::RustTypeAtom>,
4929    include_string_samples: bool,
4930) -> Vec<String> {
4931    match ty {
4932        TypeRef::Bool => vec!["TRUE".into(), "FALSE".into()],
4933        TypeRef::U32 | TypeRef::U64 => {
4934            if sample_cardinality > 1 {
4935                vec!["1".into(), "2".into()]
4936            } else {
4937                vec!["1".into()]
4938            }
4939        }
4940        TypeRef::String if sample_cardinality == 0 => Vec::new(),
4941        TypeRef::String => {
4942            collected_string_samples(sample_cardinality, named_samples, include_string_samples)
4943                .into_iter()
4944                .map(|sample| tla_string(&sample))
4945                .collect()
4946        }
4947        TypeRef::Named(name) if named_type_uses_nat_domain(named_bindings, name.as_str()) => {
4948            if sample_cardinality > 1 {
4949                vec!["1".into(), "2".into()]
4950            } else {
4951                vec!["1".into()]
4952            }
4953        }
4954        TypeRef::Named(name) => {
4955            let name = name.as_str();
4956            sample_values_for_named_type(name, sample_cardinality, named_samples, named_bindings)
4957        }
4958        TypeRef::Enum(name) => {
4959            let name = name.as_str();
4960            sample_values_for_enum_type(name, sample_cardinality, named_samples, named_bindings)
4961        }
4962        TypeRef::Option(inner) => {
4963            let mut values = vec![format!(
4964                "[tag |-> {}, value |-> {}]",
4965                tla_string("none"),
4966                tla_string("none")
4967            )];
4968            values.extend(
4969                sample_values(
4970                    inner,
4971                    sample_cardinality,
4972                    named_samples,
4973                    named_bindings,
4974                    include_string_samples,
4975                )
4976                .into_iter()
4977                .map(|sample| format!("[tag |-> {}, value |-> {}]", tla_string("some"), sample)),
4978            );
4979            values
4980        }
4981        TypeRef::Seq(inner) => sample_values(
4982            inner,
4983            sample_cardinality,
4984            named_samples,
4985            named_bindings,
4986            include_string_samples,
4987        ),
4988        TypeRef::Set(inner) => sample_values(
4989            inner,
4990            sample_cardinality,
4991            named_samples,
4992            named_bindings,
4993            include_string_samples,
4994        ),
4995        TypeRef::Map(_, _) => vec![],
4996    }
4997}
4998
4999fn sample_values_for_named_type(
5000    name: &str,
5001    sample_cardinality: usize,
5002    named_samples: &BTreeMap<String, BTreeSet<String>>,
5003    bindings: &BTreeMap<String, meerkat_machine_schema::RustTypeAtom>,
5004) -> Vec<String> {
5005    use meerkat_machine_schema::RustTypeAtom;
5006
5007    if name == "OperationSource" {
5008        return operation_source_samples(sample_cardinality);
5009    }
5010    match require_named_binding(bindings, name) {
5011        RustTypeAtom::U64 | RustTypeAtom::U32 | RustTypeAtom::U16 | RustTypeAtom::U8 => {
5012            if sample_cardinality > 1 {
5013                vec!["1".into(), "2".into()]
5014            } else {
5015                vec!["1".into()]
5016            }
5017        }
5018        RustTypeAtom::Bool => vec!["TRUE".into(), "FALSE".into()],
5019        RustTypeAtom::StringEnum { variants } => string_enum_variant_samples(name, variants),
5020        RustTypeAtom::TypePathEnum {
5021            unit_variants,
5022            structural_variants,
5023            ..
5024        } => type_path_enum_variant_samples(
5025            unit_variants,
5026            structural_variants,
5027            sample_cardinality,
5028            named_samples,
5029            bindings,
5030        ),
5031        RustTypeAtom::TypePathFieldPresenceSet { fields, .. } => {
5032            field_presence_set_samples(fields, sample_cardinality)
5033        }
5034        RustTypeAtom::TypePathStruct { fields, .. } => {
5035            type_path_struct_samples(fields, sample_cardinality, named_samples, bindings)
5036        }
5037        RustTypeAtom::String | RustTypeAtom::TypePath(_) => {
5038            if sample_cardinality == 0 {
5039                return Vec::new();
5040            }
5041            if let Some(samples) = named_samples.get(name) {
5042                let limit = sample_cardinality.max(1);
5043                let rendered = samples
5044                    .iter()
5045                    .take(limit)
5046                    .map(tla_string)
5047                    .collect::<Vec<_>>();
5048                if !rendered.is_empty() {
5049                    return rendered;
5050                }
5051            }
5052            (1..=sample_cardinality.max(1))
5053                .map(|idx| tla_string(format!("{}_{}", tla_ident(name).to_lowercase(), idx)))
5054                .collect()
5055        }
5056    }
5057}
5058
5059#[allow(clippy::panic)]
5060fn sample_values_for_enum_type(
5061    name: &str,
5062    sample_cardinality: usize,
5063    named_samples: &BTreeMap<String, BTreeSet<String>>,
5064    bindings: &BTreeMap<String, meerkat_machine_schema::RustTypeAtom>,
5065) -> Vec<String> {
5066    use meerkat_machine_schema::RustTypeAtom;
5067
5068    match require_named_binding(bindings, name) {
5069        RustTypeAtom::StringEnum { variants } => string_enum_variant_samples(name, variants),
5070        RustTypeAtom::TypePathEnum {
5071            unit_variants,
5072            structural_variants,
5073            ..
5074        } => type_path_enum_variant_samples(
5075            unit_variants,
5076            structural_variants,
5077            sample_cardinality,
5078            named_samples,
5079            bindings,
5080        ),
5081        other => {
5082            panic!(
5083                "generated enum domain `{name}` requires StringEnum or TypePathEnum binding, found {other:?}"
5084            );
5085        }
5086    }
5087}
5088
5089#[allow(clippy::panic)]
5090fn require_named_binding<'a>(
5091    bindings: &'a BTreeMap<String, meerkat_machine_schema::RustTypeAtom>,
5092    name: &str,
5093) -> &'a meerkat_machine_schema::RustTypeAtom {
5094    bindings
5095        .get(name)
5096        .unwrap_or_else(|| panic!("missing NamedTypeBinding for generated domain `{name}`"))
5097}
5098
5099fn string_enum_variant_samples(
5100    name: &str,
5101    variants: &[meerkat_machine_schema::identity::EnumVariantId],
5102) -> Vec<String> {
5103    variants
5104        .iter()
5105        .map(|variant| tla_string(string_enum_wire_label(name, variant.as_str())))
5106        .collect()
5107}
5108
5109fn render_named_variant_value(
5110    enum_name: &str,
5111    variant: &str,
5112    named_bindings: &BTreeMap<String, meerkat_machine_schema::RustTypeAtom>,
5113) -> String {
5114    let label = tla_string(string_enum_wire_label(enum_name, variant));
5115    if named_bindings
5116        .get(enum_name)
5117        .is_some_and(CfgRecordRendering::renders_cfg_hostile_record)
5118    {
5119        format!("[tag |-> {label}]")
5120    } else {
5121        label
5122    }
5123}
5124
5125fn type_path_enum_variant_samples(
5126    unit_variants: &[meerkat_machine_schema::identity::EnumVariantId],
5127    structural_variants: &[TypePathEnumStructuralVariant],
5128    sample_cardinality: usize,
5129    named_samples: &BTreeMap<String, BTreeSet<String>>,
5130    named_bindings: &BTreeMap<String, meerkat_machine_schema::RustTypeAtom>,
5131) -> Vec<String> {
5132    let unit_variants_are_records = !structural_variants.is_empty();
5133    let mut samples = unit_variants
5134        .iter()
5135        .map(|variant| {
5136            let tag = tla_string(variant.as_str());
5137            if unit_variants_are_records {
5138                format!("[tag |-> {tag}]")
5139            } else {
5140                tag
5141            }
5142        })
5143        .collect::<Vec<_>>();
5144    if sample_cardinality > 0 {
5145        samples.extend(structural_variants.iter().flat_map(|variant| {
5146            render_type_path_enum_structural_samples(
5147                variant,
5148                sample_cardinality,
5149                named_samples,
5150                named_bindings,
5151            )
5152        }));
5153    }
5154    samples
5155}
5156
5157fn field_presence_set_samples(
5158    fields: &[meerkat_machine_schema::identity::FieldId],
5159    sample_cardinality: usize,
5160) -> Vec<String> {
5161    if sample_cardinality == 0 {
5162        return Vec::new();
5163    }
5164    let limit = sample_cardinality.max(1);
5165    let rendered_fields = fields
5166        .iter()
5167        .map(|field| tla_string(field.as_str()))
5168        .collect::<Vec<_>>();
5169    let mut samples = rendered_fields
5170        .iter()
5171        .take(limit)
5172        .map(|field| format!("{{{field}}}"))
5173        .collect::<Vec<_>>();
5174    if limit > rendered_fields.len() && rendered_fields.len() >= 2 {
5175        samples.push(format!("{{{}}}", rendered_fields.join(", ")));
5176    }
5177    samples
5178}
5179
5180fn operation_source_samples(sample_cardinality: usize) -> Vec<String> {
5181    let mut samples = vec![
5182        format!(
5183            "[kind |-> {}, session_id |-> Some({}), peer_id |-> None, address |-> None]",
5184            tla_string("SessionChild"),
5185            tla_string("sessionid_1")
5186        ),
5187        format!(
5188            "[kind |-> {}, session_id |-> None, peer_id |-> Some({}), address |-> Some({})]",
5189            tla_string("BackendPeer"),
5190            tla_string("peerid_1"),
5191            tla_string("peeraddress_1")
5192        ),
5193    ];
5194    if sample_cardinality > 2 {
5195        samples.push(format!(
5196            "[kind |-> {}, session_id |-> Some({}), peer_id |-> None, address |-> None]",
5197            tla_string("SessionChild"),
5198            tla_string("sessionid_2")
5199        ));
5200    }
5201    samples
5202}
5203
5204fn type_path_struct_samples(
5205    fields: &[TypePathStructField],
5206    sample_cardinality: usize,
5207    named_samples: &BTreeMap<String, BTreeSet<String>>,
5208    bindings: &BTreeMap<String, meerkat_machine_schema::RustTypeAtom>,
5209) -> Vec<String> {
5210    if sample_cardinality == 0 {
5211        return Vec::new();
5212    }
5213    if fields.is_empty() {
5214        return vec!["[]".to_owned()];
5215    }
5216
5217    let limit = sample_cardinality.max(1);
5218    let mut field_values = Vec::new();
5219    for field in fields {
5220        let values =
5221            type_path_struct_field_samples(field, sample_cardinality, named_samples, bindings);
5222        if values.is_empty() {
5223            return Vec::new();
5224        }
5225        field_values.push((field.name.as_str().to_owned(), values));
5226    }
5227
5228    (0..limit)
5229        .map(|idx| {
5230            let fields = field_values
5231                .iter()
5232                .map(|(name, values)| {
5233                    let value = &values[idx % values.len()];
5234                    format!("{name} |-> {value}")
5235                })
5236                .collect::<Vec<_>>();
5237            format!("[{}]", fields.join(", "))
5238        })
5239        .collect()
5240}
5241
5242fn type_path_struct_field_samples(
5243    field: &TypePathStructField,
5244    sample_cardinality: usize,
5245    named_samples: &BTreeMap<String, BTreeSet<String>>,
5246    bindings: &BTreeMap<String, meerkat_machine_schema::RustTypeAtom>,
5247) -> Vec<String> {
5248    match &field.atom {
5249        TypePathStructFieldAtom::String => {
5250            if sample_cardinality == 0 {
5251                Vec::new()
5252            } else {
5253                generic_string_samples(sample_cardinality)
5254                    .into_iter()
5255                    .map(tla_string)
5256                    .collect()
5257            }
5258        }
5259        TypePathStructFieldAtom::Named(name) => {
5260            sample_values_for_named_type(name.as_str(), sample_cardinality, named_samples, bindings)
5261        }
5262        TypePathStructFieldAtom::OptionalNamed(name) => {
5263            let mut values = vec!["None".to_owned()];
5264            values.extend(
5265                sample_values_for_named_type(
5266                    name.as_str(),
5267                    sample_cardinality,
5268                    named_samples,
5269                    bindings,
5270                )
5271                .into_iter()
5272                .map(|value| format!("Some({value})")),
5273            );
5274            values
5275        }
5276    }
5277}
5278
5279fn render_type_path_enum_structural_samples(
5280    variant: &TypePathEnumStructuralVariant,
5281    sample_cardinality: usize,
5282    named_samples: &BTreeMap<String, BTreeSet<String>>,
5283    named_bindings: &BTreeMap<String, meerkat_machine_schema::RustTypeAtom>,
5284) -> Vec<String> {
5285    let mut samples = vec![vec![format!(
5286        "tag |-> {}",
5287        tla_string(variant.variant.as_str())
5288    )]];
5289    for field in &variant.fields {
5290        let values = match &field.atom {
5291            TypePathEnumPayloadAtom::StringSet => string_set_payload_samples(sample_cardinality),
5292            TypePathEnumPayloadAtom::NamedSet(type_name) => named_set_payload_samples(
5293                type_name.as_str(),
5294                sample_cardinality,
5295                named_samples,
5296                named_bindings,
5297            ),
5298            TypePathEnumPayloadAtom::String => {
5299                if sample_cardinality == 0 {
5300                    Vec::new()
5301                } else {
5302                    generic_string_samples(sample_cardinality)
5303                        .into_iter()
5304                        .map(tla_string)
5305                        .collect()
5306                }
5307            }
5308            TypePathEnumPayloadAtom::OptionalString => {
5309                let mut values = vec![format!(
5310                    "[tag |-> {}, value |-> {}]",
5311                    tla_string("none"),
5312                    tla_string("none")
5313                )];
5314                if sample_cardinality > 0 {
5315                    values.extend(generic_string_samples(sample_cardinality).into_iter().map(
5316                        |sample| {
5317                            format!(
5318                                "[tag |-> {}, value |-> {}]",
5319                                tla_string("some"),
5320                                tla_string(&sample)
5321                            )
5322                        },
5323                    ));
5324                }
5325                values
5326            }
5327            TypePathEnumPayloadAtom::Named(type_name) => sample_values_for_named_type(
5328                type_name.as_str(),
5329                sample_cardinality,
5330                named_samples,
5331                named_bindings,
5332            ),
5333        };
5334        let mut next_samples = Vec::new();
5335        for sample in &samples {
5336            for value in &values {
5337                let mut next = sample.clone();
5338                next.push(format!("{} |-> {value}", field.name));
5339                next_samples.push(next);
5340            }
5341        }
5342        samples = next_samples;
5343    }
5344    samples
5345        .into_iter()
5346        .map(|fields| format!("[{}]", fields.join(", ")))
5347        .collect()
5348}
5349
5350/// TLA sample sets for a structural enum payload carrying a finite set of
5351/// values from a named value domain. Mirrors [`string_set_payload_samples`]
5352/// shape (empty / one-member / two-member sets) over the named domain's
5353/// sample pool so payload sets stay aligned with catalog key domains.
5354fn named_set_payload_samples(
5355    type_name: &str,
5356    sample_cardinality: usize,
5357    named_samples: &BTreeMap<String, BTreeSet<String>>,
5358    named_bindings: &BTreeMap<String, meerkat_machine_schema::RustTypeAtom>,
5359) -> Vec<String> {
5360    let mut values = if sample_cardinality == 0 {
5361        Vec::new()
5362    } else {
5363        sample_values_for_named_type(type_name, sample_cardinality, named_samples, named_bindings)
5364    };
5365    // Pad the payload element pool with synthetic domain members up to the
5366    // requested cardinality so the deep model still covers differing
5367    // same-variant multi-member payloads when the collected named-sample
5368    // pool is smaller than the cardinality.
5369    let mut synthetic_idx = 0usize;
5370    while sample_cardinality > 0 && values.len() < sample_cardinality {
5371        synthetic_idx += 1;
5372        let synthetic = tla_string(format!(
5373            "{}_{synthetic_idx}",
5374            tla_ident(type_name).to_lowercase()
5375        ));
5376        if !values.contains(&synthetic) {
5377            values.push(synthetic);
5378        }
5379    }
5380    let mut samples = vec!["{}".to_owned()];
5381    if let Some(first) = values.first() {
5382        samples.push(format!("{{{first}}}"));
5383    }
5384    if values.len() >= 2 {
5385        samples.push(format!("{{{}, {}}}", values[0], values[1]));
5386    }
5387    samples
5388}
5389
5390fn string_set_payload_samples(sample_cardinality: usize) -> Vec<String> {
5391    let values = if sample_cardinality == 0 {
5392        Vec::new()
5393    } else {
5394        generic_string_samples(sample_cardinality)
5395            .into_iter()
5396            .map(tla_string)
5397            .collect::<Vec<_>>()
5398    };
5399    let mut samples = vec!["{}".to_owned()];
5400    if let Some(first) = values.first() {
5401        samples.push(format!("{{{first}}}"));
5402    }
5403    if values.len() >= 2 {
5404        samples.push(format!("{{{}, {}}}", values[0], values[1]));
5405    }
5406    samples
5407}
5408
5409fn string_enum_wire_label(name: &str, variant: &str) -> String {
5410    if name == meerkat_core::turn_execution_authority::ContentShape::SCHEMA_TYPE_NAME
5411        && let Some(shape) =
5412            meerkat_core::turn_execution_authority::ContentShape::from_schema_variant(variant)
5413    {
5414        return shape.as_str().to_owned();
5415    }
5416
5417    variant.to_owned()
5418}
5419
5420/// Consult the schema's named-type binding table to decide whether a
5421/// named type's TLA domain is `Nat` (numeric) rather than string-like.
5422///
5423/// A named type resolves to a `Nat` TLA domain when its Rust atom lowers
5424/// to an unsigned integer width — the TLA projection mirrors the Rust
5425/// atom. Schemas reach codegen only after validation, so every
5426/// referenced named type has a binding; an unbound name here is a
5427/// codegen invariant violation.
5428fn named_type_uses_nat_domain(
5429    bindings: &BTreeMap<String, meerkat_machine_schema::RustTypeAtom>,
5430    name: &str,
5431) -> bool {
5432    use meerkat_machine_schema::RustTypeAtom;
5433    matches!(
5434        bindings.get(name),
5435        Some(RustTypeAtom::U64 | RustTypeAtom::U32 | RustTypeAtom::U16 | RustTypeAtom::U8)
5436    )
5437}
5438
5439/// Collect the `NamedTypeId → RustTypeAtom` map for a single machine.
5440fn collect_machine_named_bindings(
5441    schema: &MachineSchema,
5442) -> BTreeMap<String, meerkat_machine_schema::RustTypeAtom> {
5443    assert_machine_named_bindings_match_canonical(schema);
5444    schema
5445        .named_types
5446        .iter()
5447        .map(|binding| (binding.name.as_str().to_owned(), binding.rust.clone()))
5448        .collect()
5449}
5450
5451/// A machine that shares a canonical machine's id must bind every canonical
5452/// struct named type, and bind each shared named type with the canonical
5453/// generated domain shape.
5454fn check_canonical_named_bindings(schema: &MachineSchema) -> Result<(), CompositionTlaError> {
5455    let Some(canonical) = canonical_machine_schemas()
5456        .into_iter()
5457        .find(|canonical| canonical.machine == schema.machine)
5458    else {
5459        return Ok(());
5460    };
5461    let mismatch = |named_type: &str, reason| CompositionTlaError::CanonicalNamedTypeMismatch {
5462        machine: schema.machine.as_str().to_owned(),
5463        named_type: named_type.to_owned(),
5464        reason,
5465    };
5466    for canonical_binding in canonical.named_types.iter().filter(|binding| {
5467        matches!(
5468            binding.rust,
5469            meerkat_machine_schema::RustTypeAtom::TypePathStruct { .. }
5470        )
5471    }) {
5472        if !schema
5473            .named_types
5474            .iter()
5475            .any(|binding| binding.name == canonical_binding.name)
5476        {
5477            return Err(mismatch(
5478                canonical_binding.name.as_str(),
5479                CanonicalNamedTypeMismatchKind::MissingStructBinding,
5480            ));
5481        }
5482    }
5483    for binding in &schema.named_types {
5484        let Some(canonical_binding) = canonical
5485            .named_types
5486            .iter()
5487            .find(|candidate| candidate.name == binding.name)
5488        else {
5489            continue;
5490        };
5491        if !canonical_binding
5492            .rust
5493            .has_same_composition_domain_shape(&binding.rust)
5494        {
5495            return Err(mismatch(
5496                binding.name.as_str(),
5497                CanonicalNamedTypeMismatchKind::DomainShape,
5498            ));
5499        }
5500    }
5501    Ok(())
5502}
5503
5504/// Internal invariant for the infallible renderers, whose callers pass
5505/// canonical machines; the public fallible entry points check first.
5506fn assert_machine_named_bindings_match_canonical(schema: &MachineSchema) {
5507    if let Err(CompositionTlaError::CanonicalNamedTypeMismatch {
5508        machine,
5509        named_type,
5510        reason,
5511    }) = check_canonical_named_bindings(schema)
5512    {
5513        assert!(
5514            reason != CanonicalNamedTypeMismatchKind::MissingStructBinding,
5515            "generated machine `{machine}` missing canonical named-type `{named_type}` binding"
5516        );
5517        assert!(
5518            reason != CanonicalNamedTypeMismatchKind::DomainShape,
5519            "generated machine `{machine}` named-type `{named_type}` binding must match canonical domain shape"
5520        );
5521    }
5522}
5523
5524/// Validate a caller-supplied machine catalog before rendering a composition
5525/// against it: every machine validates, ids are unique, no machine shadows a
5526/// canonical Meerkat machine with a different schema, the composition's
5527/// machines agree on shared named types, and the composition validates
5528/// against the catalog. The render paths behind this never panic on a
5529/// supplied catalog.
5530fn validate_supplied_catalog(
5531    schema: &CompositionSchema,
5532    machine_catalog: &[MachineSchema],
5533) -> Result<(), CompositionTlaError> {
5534    let canonical = canonical_machine_schemas();
5535    let mut seen = BTreeSet::new();
5536    for machine in machine_catalog {
5537        machine
5538            .validate()
5539            .map_err(|error| CompositionTlaError::InvalidSuppliedMachine {
5540                machine: machine.machine.as_str().to_owned(),
5541                error: error.to_string(),
5542            })?;
5543        if !seen.insert(machine.machine.as_str()) {
5544            return Err(CompositionTlaError::DuplicateSuppliedMachine {
5545                machine: machine.machine.as_str().to_owned(),
5546            });
5547        }
5548        if canonical
5549            .iter()
5550            .any(|candidate| candidate.machine == machine.machine && candidate != machine)
5551        {
5552            return Err(CompositionTlaError::ShadowsCanonicalMachine {
5553                machine: machine.machine.as_str().to_owned(),
5554            });
5555        }
5556    }
5557    let mut merged: BTreeMap<&str, &meerkat_machine_schema::RustTypeAtom> = BTreeMap::new();
5558    for instance in &schema.machines {
5559        let Some(machine) = machine_catalog
5560            .iter()
5561            .find(|machine| machine.machine.as_str() == instance.machine_name.as_str())
5562        else {
5563            continue;
5564        };
5565        for binding in &machine.named_types {
5566            match merged.get(binding.name.as_str()) {
5567                Some(existing) if !existing.has_same_composition_domain_shape(&binding.rust) => {
5568                    return Err(CompositionTlaError::DivergentNamedTypeBinding {
5569                        composition: schema.name.as_str().to_owned(),
5570                        named_type: binding.name.as_str().to_owned(),
5571                    });
5572                }
5573                Some(_) => {}
5574                None => {
5575                    merged.insert(binding.name.as_str(), &binding.rust);
5576                }
5577            }
5578        }
5579    }
5580    let machines = machine_catalog.iter().collect::<Vec<_>>();
5581    schema.validate_against(&machines).map_err(|error| {
5582        CompositionTlaError::InvalidCompositionForCatalog {
5583            composition: schema.name.as_str().to_owned(),
5584            error: error.to_string(),
5585        }
5586    })
5587}
5588
5589/// Merge every machine's named-type bindings into one map for
5590/// composition-level TLA rendering. Duplicate names must agree on generated
5591/// domain shape across machines (validation enforces this by construction).
5592fn collect_composition_named_bindings<'a>(
5593    machines_by_instance: impl IntoIterator<Item = &'a MachineSchema>,
5594) -> BTreeMap<String, meerkat_machine_schema::RustTypeAtom> {
5595    let mut merged: BTreeMap<String, meerkat_machine_schema::RustTypeAtom> = BTreeMap::new();
5596    for machine in machines_by_instance {
5597        assert_machine_named_bindings_match_canonical(machine);
5598        for binding in &machine.named_types {
5599            let slug = binding.name.as_str().to_owned();
5600            if let Some(existing) = merged.get(&slug) {
5601                assert!(
5602                    existing.has_same_composition_domain_shape(&binding.rust),
5603                    "composition named-type `{slug}` binding must agree across machine schemas"
5604                );
5605            } else {
5606                merged.insert(slug, binding.rust.clone());
5607            }
5608        }
5609    }
5610    merged
5611}
5612
5613#[cfg(test)]
5614mod tests {
5615    use super::*;
5616
5617    /// A populated witness map literal renders as a TLC function in both the
5618    /// witness-literal path and the expression path, never as the `None`
5619    /// fallback (#1811).
5620    #[test]
5621    fn a_witness_map_literal_renders_as_a_tlc_function() {
5622        let machines = meerkat_machine_schema::canonical_machine_schemas();
5623        let compositions = meerkat_machine_schema::canonical_composition_schemas();
5624        let composition = compositions
5625            .iter()
5626            .find(|candidate| candidate.name.as_str() == "job_runtime_delivery")
5627            .expect("job_runtime_delivery composition");
5628        let compiler =
5629            CompositionTlaCompiler::new(composition, &machines).expect("composition compiler");
5630        let literal = Expr::MapLiteral(vec![
5631            (
5632                Expr::String("alpha".into()),
5633                Expr::String("member-a".into()),
5634            ),
5635            (Expr::String("beta".into()), Expr::U64(2)),
5636        ]);
5637        assert_eq!(
5638            compiler.render_literal_expr(&literal),
5639            "(\"alpha\" :> \"member-a\" @@ \"beta\" :> 2)"
5640        );
5641        assert_eq!(
5642            crate::render::render_expr_for_tests(&literal),
5643            "(\"alpha\" :> \"member-a\" @@ \"beta\" :> 2)"
5644        );
5645    }
5646
5647    /// Every quantified Next disjunct leads with its transition's source-phase
5648    /// guard, so TLC rejects the whole disjunct in other phases instead of
5649    /// enumerating each parameter tuple per state (#1499 measured 464 s
5650    /// unhoisted against 158 s hoisted on work_graph_lifecycle ci, identical
5651    /// state counts).
5652    #[test]
5653    fn quantified_next_disjuncts_lead_with_the_source_phase_guard() {
5654        let model =
5655            render_machine_semantic_model(&meerkat_machine()).expect("render MeerkatMachine model");
5656        let next = model
5657            .split_once("\nNext ==\n")
5658            .map(|(_, rest)| rest.split("\n\n").next().unwrap_or(""))
5659            .expect("Next block");
5660        let quantified = next
5661            .lines()
5662            .filter(|line| line.contains("\\E "))
5663            .collect::<Vec<_>>();
5664        assert!(
5665            !quantified.is_empty(),
5666            "MeerkatMachine has quantified transitions"
5667        );
5668        for line in &quantified {
5669            assert!(
5670                line.starts_with("    \\/ (phase = "),
5671                "quantified Next disjunct without a leading phase guard: {line}"
5672            );
5673        }
5674        assert!(
5675            next.contains("    \\/ (phase = \"Running\") /\\ \\E run_id \\in RunIdValues : RequestCancelAfterBoundary(run_id)"),
5676            "the guard is the transition's own source phase"
5677        );
5678    }
5679
5680    fn next_disjunct_for<'a>(model: &'a str, action: &str) -> &'a str {
5681        let next = model
5682            .split_once("\nNext ==\n")
5683            .map(|(_, rest)| rest.split("\n\n").next().unwrap_or(""))
5684            .expect("Next block");
5685        next.lines()
5686            .find(|line| line.contains(&format!(" {action}(")))
5687            .expect("Next disjunct for the action")
5688    }
5689
5690    /// A declared domain, not a binding name, decides an input field's TLC
5691    /// domain: additional values extend the default unsigned range, a state
5692    /// binding explores exactly the state field, and an undeclared
5693    /// `expected_revision` gets the plain default (the old name match is gone).
5694    #[test]
5695    fn declared_input_field_domains_decide_the_rendered_domain() {
5696        use meerkat_machine_schema::catalog::dsl::dsl_workgraph_lifecycle_machine;
5697        use meerkat_machine_schema::identity::{FieldId, InputVariantId};
5698        use meerkat_machine_schema::{InputFieldDomain, InputFieldDomainKind};
5699
5700        let shipped = dsl_workgraph_lifecycle_machine();
5701        let model = render_machine_semantic_model(&shipped).expect("render workgraph model");
5702        assert!(
5703            next_disjunct_for(&model, "UpdateOpen")
5704                .contains("\\E expected_revision \\in {revision} : "),
5705            "a state-bound declaration explores exactly the state field"
5706        );
5707
5708        let mut sampled = shipped.clone();
5709        sampled.input_field_domains.push(InputFieldDomain {
5710            input: InputVariantId::parse("CreateOpen").expect("input slug"),
5711            field: FieldId::parse("unresolved_blocker_count").expect("field slug"),
5712            domain: InputFieldDomainKind::AdditionalValues([3, 8].into_iter().collect()),
5713        });
5714        let model = render_machine_semantic_model(&sampled).expect("render sampled model");
5715        assert!(
5716            next_disjunct_for(&model, "CreateOpen")
5717                .contains("\\E arg_unresolved_blocker_count \\in (0..2 \\cup {3, 8}) : "),
5718            "additional values extend the default unsigned domain"
5719        );
5720
5721        let mut undeclared = shipped;
5722        undeclared.input_field_domains.clear();
5723        let model = render_machine_semantic_model(&undeclared).expect("render undeclared model");
5724        assert!(
5725            next_disjunct_for(&model, "UpdateOpen").contains("\\E expected_revision \\in 0..2 : "),
5726            "without a declaration the binding name no longer selects a domain"
5727        );
5728    }
5729
5730    /// A `CiValues` declaration ranges the field over a model constant: the
5731    /// CI config assigns it exactly the declared values, the Deep config those
5732    /// and the default unsigned domain.
5733    #[test]
5734    fn ci_values_narrow_the_ci_profile_alone() {
5735        use meerkat_machine_schema::catalog::dsl::dsl_workgraph_lifecycle_machine;
5736        use meerkat_machine_schema::identity::{FieldId, InputVariantId};
5737        use meerkat_machine_schema::{InputFieldDomain, InputFieldDomainKind};
5738
5739        let mut sampled = dsl_workgraph_lifecycle_machine();
5740        sampled.input_field_domains.push(InputFieldDomain {
5741            input: InputVariantId::parse("CreateOpen").expect("input slug"),
5742            field: FieldId::parse("unresolved_blocker_count").expect("field slug"),
5743            domain: InputFieldDomainKind::CiValues([0, 5].into_iter().collect()),
5744        });
5745        let constant = "InputSamples_CreateOpen_unresolved_blocker_count";
5746        let model = render_machine_semantic_model(&sampled).expect("render sampled model");
5747        assert!(
5748            next_disjunct_for(&model, "CreateOpen").contains(&format!(
5749                "\\E arg_unresolved_blocker_count \\in {constant} : "
5750            )),
5751            "the field ranges over its samples constant"
5752        );
5753        let constants_line = model
5754            .lines()
5755            .find(|line| line.starts_with("CONSTANTS "))
5756            .expect("model constants");
5757        assert!(
5758            constants_line.contains(constant),
5759            "the model declares the samples constant: {constants_line}"
5760        );
5761        assert!(
5762            next_disjunct_for(&model, "UpdateOpen")
5763                .contains("\\E expected_revision \\in {revision} : "),
5764            "the machine's other declarations are unchanged"
5765        );
5766
5767        let ci = render_machine_ci_cfg(&sampled, false).expect("valid CI CFG");
5768        assert!(
5769            ci.contains(&format!("\n  {constant} = {{0, 5}}\n")),
5770            "the CI config assigns exactly the declared values:\n{ci}"
5771        );
5772        let deep = render_machine_ci_cfg(&sampled, true).expect("valid Deep CFG");
5773        assert!(
5774            deep.contains(&format!("\n  {constant} = {{0, 1, 2, 5}}\n")),
5775            "the Deep config keeps the default domain beside the declared values:\n{deep}"
5776        );
5777        assert_eq!(
5778            broad_input_samples(&[0, 5].into_iter().collect::<BTreeSet<u64>>()),
5779            [0, 1, 2, 5].into_iter().collect::<BTreeSet<u64>>(),
5780            "outside the CI profile the field keeps the default domain beside its values"
5781        );
5782    }
5783
5784    /// A `CiSamples` declaration ranges a field of any type over a model
5785    /// constant that each profile's config assigns through an operator of
5786    /// the model: the CI profile the declared values, the Deep profile the
5787    /// field type's whole domain. DurableDecisionMachine's carried
5788    /// presentation is the shipped case; Present declares nothing, so it
5789    /// keeps every link a presentation's link can serve.
5790    #[test]
5791    fn ci_samples_narrow_the_ci_profile_alone_for_a_field_of_any_type() {
5792        let schema = meerkat_machine_schema::catalog::dsl::dsl_durable_decision_machine();
5793        let model = render_machine_semantic_model(&schema).expect("render DurableDecisionMachine");
5794        let ci = render_machine_ci_cfg(&schema, false).expect("valid CI CFG");
5795        let deep = render_machine_ci_cfg(&schema, true).expect("valid Deep CFG");
5796        let next = model
5797            .split_once("\nNext ==\n")
5798            .map(|(_, rest)| rest.split("\n\n").next().unwrap_or(""))
5799            .expect("Next block");
5800        let constants_line = model
5801            .lines()
5802            .find(|line| line.starts_with("CONSTANTS "))
5803            .expect("model constants");
5804        let decide = next
5805            .lines()
5806            .filter(|line| line.contains(": Decide"))
5807            .collect::<Vec<_>>();
5808        assert!(!decide.is_empty(), "Decide has Next disjuncts");
5809        for (field, ci_values, deep_domain) in [
5810            (
5811                "carried_audience",
5812                "{Some(\"alpha\")}",
5813                "OptionDecisionPartyValues",
5814            ),
5815            (
5816                "carried_digest",
5817                "{Some(\"alpha\")}",
5818                "OptionDecisionDigestValues",
5819            ),
5820            ("carried_complete", "{FALSE}", "BOOLEAN"),
5821            (
5822                "carried_link_served_digest",
5823                "{Some(\"alpha\")}",
5824                "OptionDecisionDigestValues",
5825            ),
5826        ] {
5827            let constant = format!("InputSamples_Decide_{field}");
5828            for line in &decide {
5829                assert!(
5830                    line.contains(&format!("\\E {field} \\in {constant} : ")),
5831                    "Decide.{field} ranges over {constant}: {line}"
5832                );
5833            }
5834            assert!(
5835                constants_line.contains(&constant),
5836                "the model declares {constant}: {constants_line}"
5837            );
5838            assert!(
5839                model.contains(&format!("\n{constant}Ci == {ci_values}\n")),
5840                "the model defines the CI samples of Decide.{field}"
5841            );
5842            assert!(
5843                model.contains(&format!("\n{constant}Deep == {deep_domain}\n")),
5844                "the model defines the Deep domain of Decide.{field}"
5845            );
5846            assert!(
5847                ci.contains(&format!("\n  {constant} <- {constant}Ci\n")),
5848                "the CI config samples Decide.{field}:\n{ci}"
5849            );
5850            assert!(
5851                deep.contains(&format!("\n  {constant} <- {constant}Deep\n")),
5852                "the Deep config keeps the whole domain of Decide.{field}:\n{deep}"
5853            );
5854        }
5855        let present = next
5856            .lines()
5857            .filter(|line| line.contains(": Present"))
5858            .collect::<Vec<_>>();
5859        assert!(!present.is_empty(), "Present has Next disjuncts");
5860        for line in present {
5861            assert!(
5862                line.contains("\\E link_served_digest \\in OptionDecisionDigestValues : "),
5863                "Present keeps every served link: {line}"
5864            );
5865        }
5866    }
5867
5868    /// SessionDocumentMachine's CI bound: under a step bound of 5 the CI
5869    /// profile explores the samples it declares, in every Next disjunct of
5870    /// the input's transitions; the Deep profile keeps `0..2` for each of
5871    /// them and its step bound of 8.
5872    #[test]
5873    fn session_document_narrows_its_ci_samples_only() {
5874        let schema = meerkat_machine_schema::catalog::dsl::dsl_session_document_machine();
5875        let model = render_machine_semantic_model(&schema).expect("render SessionDocumentMachine");
5876        let ci = render_machine_ci_cfg(&schema, false).expect("valid CI CFG");
5877        let deep = render_machine_ci_cfg(&schema, true).expect("valid Deep CFG");
5878        let next = model
5879            .split_once("\nNext ==\n")
5880            .map(|(_, rest)| rest.split("\n\n").next().unwrap_or(""))
5881            .expect("Next block");
5882        for (input, field, ci_values) in [
5883            ("ClassifyDurableTail", "dangling_tool_use_count", "{0}"),
5884            ("ClassifyDurableTail", "orphan_tool_result_count", "{0}"),
5885            ("RecoverSessionInstructionState", "target_generation", "{2}"),
5886            ("RecoverSessionInstructionState", "entry_sequence", "{0}"),
5887            ("RecoverSessionInstructionEffective", "generation", "{0}"),
5888            (
5889                "RecoverSessionInstructionEffective",
5890                "last_entry_sequence",
5891                "{0, 1}",
5892            ),
5893            ("SetSessionInstruction", "body_bytes", "{1}"),
5894        ] {
5895            let constant = format!("InputSamples_{input}_{field}");
5896            let disjuncts = next
5897                .lines()
5898                .filter(|line| line.contains(&format!(": {input}")))
5899                .collect::<Vec<_>>();
5900            assert!(!disjuncts.is_empty(), "{input} has Next disjuncts");
5901            for line in disjuncts {
5902                assert!(
5903                    line.contains(&format!("\\E {field} \\in {constant} : ")),
5904                    "{input}.{field} ranges over {constant}: {line}"
5905                );
5906            }
5907            assert!(
5908                ci.contains(&format!("\n  {constant} = {ci_values}\n")),
5909                "the CI config samples {input}.{field} as {ci_values}:\n{ci}"
5910            );
5911            assert!(
5912                deep.contains(&format!("\n  {constant} = {{0, 1, 2}}\n")),
5913                "the Deep config keeps 0..2 for {input}.{field}:\n{deep}"
5914            );
5915        }
5916        assert!(
5917            model.contains("\nCiStateConstraint == /\\ model_step_count <= 5 "),
5918            "the CI step bound is 5"
5919        );
5920        assert!(
5921            model.contains("\nDeepStateConstraint == /\\ model_step_count <= 8 "),
5922            "the Deep step bound stays 8"
5923        );
5924    }
5925
5926    #[test]
5927    fn substituted_compound_values_are_delimited_and_atoms_are_not() {
5928        for atom in [
5929            "x",
5930            "packet.payload.run_id",
5931            "Some(run_id)",
5932            "MapSet(m, k, v)",
5933            "m[k]",
5934            "f(a)[b](c)",
5935            "(a + 1)",
5936            "\"a(b\"",
5937            "42",
5938        ] {
5939            assert_eq!(tla_delimited(atom), atom, "{atom} is already an operand");
5940        }
5941        for compound in [
5942            "IF c THEN a ELSE b",
5943            "x + 1",
5944            "s \\cup {x}",
5945            "(a) + (b)",
5946            "f(a) = b",
5947            "~x",
5948        ] {
5949            assert_eq!(
5950                tla_delimited(compound),
5951                format!("({compound})"),
5952                "{compound} must be delimited before splicing"
5953            );
5954        }
5955    }
5956
5957    /// A field assigned by a conditional update earlier in the same block is
5958    /// read through its pending value, a bare `IF c THEN a ELSE b`. Spliced
5959    /// unparenthesized into a later expression, TLA+ precedence captured the
5960    /// surrounding operator. Shipped instance: the meerkat_mob_seam
5961    /// `TurnRunFailed` payload unwraps the conditionally updated
5962    /// `terminal_cause_kind` as `IF "value" \in DOMAIN v THEN v["value"] ELSE
5963    /// None`; with `v` bare, `["value"]` applied to v's ELSE branch only, so
5964    /// the THEN branch emitted the Option record instead of its value.
5965    #[test]
5966    fn a_conditionally_updated_field_read_later_in_the_block_splices_as_one_operand() {
5967        let model = render_composition_semantic_model(&meerkat_mob_seam_composition())
5968            .expect("render meerkat_mob_seam model");
5969        assert!(
5970            model.contains(
5971                "terminal_cause_kind |-> (IF \"value\" \\in DOMAIN (IF (IF (meerkat_terminal_cause_kind = None)"
5972            ),
5973            "the TurnRunFailed unwrap must test the whole conditional value"
5974        );
5975        assert!(
5976            !model.contains("ELSE meerkat_terminal_cause_kind[\"value\"]"),
5977            "no index may bind to one branch of a spliced conditional"
5978        );
5979    }
5980
5981    /// A set insert or remove of a field that a conditional update already
5982    /// changed earlier in the same block takes the field's pending value, a
5983    /// bare `IF c THEN a ELSE b`, as its left operand. Spliced unparenthesized,
5984    /// the ELSE branch captured the set operator, so the THEN branch lost the
5985    /// second update. Shipped instance: MobMachine's topology convergence
5986    /// removes both absent identities from `pending_respawn_topology`; the
5987    /// model removed only `a_identity` when both were absent.
5988    #[test]
5989    fn a_set_update_after_a_conditional_update_takes_the_whole_conditional() {
5990        let model = render_machine_semantic_model(&mob_machine()).expect("render MobMachine model");
5991        assert!(
5992            model.contains(
5993                "((IF ((a_identity \\in DOMAIN identity_to_runtime) = FALSE) THEN (pending_respawn_topology \\ {a_identity}) ELSE pending_respawn_topology) \\ {b_identity})"
5994            ),
5995            "the second removal must apply to the whole conditional value"
5996        );
5997        assert!(
5998            !model.contains("ELSE pending_respawn_topology \\ {b_identity}"),
5999            "no set operator may bind to one branch of a spliced conditional"
6000        );
6001    }
6002
6003    /// Every update kind that reads a field's pending value must splice it so
6004    /// no operator after it can bind into one branch of a pending conditional
6005    /// (`IF c THEN a ELSE b`, left by an earlier conditional update in the
6006    /// same block): each occurrence must close an operand, followed only by
6007    /// `)`, `,` or the end of the value. The match is exhaustive, so a new
6008    /// `Update` kind must be classified here.
6009    #[test]
6010    fn every_update_kind_splices_a_pending_conditional_as_one_operand() {
6011        use meerkat_machine_schema::identity::FieldId;
6012        const PENDING: &str = "IF c THEN a ELSE b";
6013        let field = || FieldId::parse("f").expect("field slug");
6014        let x = || Expr::Binding("x".to_owned());
6015        let samples = vec![
6016            Update::Increment {
6017                field: field(),
6018                amount: 1,
6019            },
6020            Update::Decrement {
6021                field: field(),
6022                amount: 1,
6023            },
6024            Update::MapInsert {
6025                field: field(),
6026                key: x(),
6027                value: x(),
6028            },
6029            Update::MapIncrement {
6030                field: field(),
6031                key: x(),
6032                amount: 1,
6033            },
6034            Update::MapDecrement {
6035                field: field(),
6036                key: x(),
6037                amount: 1,
6038            },
6039            Update::MapRemove {
6040                field: field(),
6041                key: x(),
6042            },
6043            Update::SetInsert {
6044                field: field(),
6045                value: x(),
6046            },
6047            Update::SetRemove {
6048                field: field(),
6049                value: x(),
6050            },
6051            Update::SeqAppend {
6052                field: field(),
6053                value: x(),
6054            },
6055            Update::SeqPrepend {
6056                field: field(),
6057                values: x(),
6058            },
6059            Update::SeqPopFront { field: field() },
6060            Update::SeqRemoveValue {
6061                field: field(),
6062                value: x(),
6063            },
6064            Update::SeqRemoveAll {
6065                field: field(),
6066                values: x(),
6067            },
6068            Update::Conditional {
6069                condition: Expr::Binding("d".to_owned()),
6070                then_updates: vec![Update::SetInsert {
6071                    field: field(),
6072                    value: x(),
6073                }],
6074                else_updates: vec![Update::SetRemove {
6075                    field: field(),
6076                    value: x(),
6077                }],
6078            },
6079            Update::ForEach {
6080                binding: "y".to_owned(),
6081                over: x(),
6082                updates: vec![Update::SetInsert {
6083                    field: field(),
6084                    value: Expr::Binding("y".to_owned()),
6085                }],
6086            },
6087        ];
6088        let schema = mob_machine();
6089        for update in &samples {
6090            // Exhaustive: classify every kind. `Assign` does not read the
6091            // field's pending value, so it cannot splice it.
6092            match update {
6093                Update::Assign { .. } => continue,
6094                Update::Increment { .. }
6095                | Update::Decrement { .. }
6096                | Update::MapInsert { .. }
6097                | Update::MapIncrement { .. }
6098                | Update::MapDecrement { .. }
6099                | Update::MapRemove { .. }
6100                | Update::SetInsert { .. }
6101                | Update::SetRemove { .. }
6102                | Update::SeqAppend { .. }
6103                | Update::SeqPrepend { .. }
6104                | Update::SeqPopFront { .. }
6105                | Update::SeqRemoveValue { .. }
6106                | Update::SeqRemoveAll { .. }
6107                | Update::Conditional { .. }
6108                | Update::ForEach { .. } => {}
6109            }
6110            let mut compiler = MachineTlaCompiler::new(&schema);
6111            let mut env = BTreeMap::from([("f".to_owned(), PENDING.to_owned())]);
6112            let binding_types =
6113                BTreeMap::from([("x".to_owned(), TypeRef::Set(Box::new(TypeRef::U64)))]);
6114            compiler.apply_update("Probe", &mut env, &BTreeMap::new(), &binding_types, update);
6115            let rendered = env.get("f").expect("the update writes f");
6116            assert!(
6117                rendered.contains(PENDING),
6118                "{update:?} must read the pending value: {rendered}"
6119            );
6120            for (at, _) in rendered.match_indices(PENDING) {
6121                let after = rendered[at + PENDING.len()..].chars().next();
6122                assert!(
6123                    matches!(after, None | Some(')' | ',')),
6124                    "{update:?} lets {after:?} bind into the pending conditional: {rendered}"
6125                );
6126            }
6127        }
6128    }
6129
6130    /// A `for` loop lowers to one fold per touched field, and each fold must
6131    /// read the other fields as they were BEFORE the loop, as the sequential
6132    /// kernel does within an iteration. Writing each fold back into the env
6133    /// while lowering handed later folds an earlier field's post-loop value:
6134    /// the causal-tail batch then looked up already-removed cursors and left
6135    /// orphaned queued rows, which the generated outbox invariant caught. So
6136    /// no fold of a loop may take another fold of the same loop as an
6137    /// argument.
6138    #[test]
6139    fn a_for_each_fold_reads_the_other_fields_before_the_loop() {
6140        let model =
6141            render_machine_semantic_model(&meerkat_machine()).expect("render MeerkatMachine model");
6142        let mut checked = 0;
6143        for line in model.lines() {
6144            let Some(eq) = line.find("' = ") else {
6145                continue;
6146            };
6147            let rhs = &line[eq + 4..];
6148            let Some(open) = rhs.find('(') else {
6149                continue;
6150            };
6151            let head = &rhs[..open];
6152            let Some(pos) = head.find("_ForEach") else {
6153                continue;
6154            };
6155            let digits: String = head[pos + "_ForEach".len()..]
6156                .chars()
6157                .take_while(char::is_ascii_digit)
6158                .collect();
6159            let same_loop = format!("{}_ForEach{digits}_", &head[..pos]);
6160            assert!(
6161                !rhs[open..].contains(&same_loop),
6162                "a for-loop fold takes another fold of the same loop as an argument: {line}"
6163            );
6164            checked += 1;
6165        }
6166        assert!(
6167            checked > 0,
6168            "the MeerkatMachine model has for-loop folds to check"
6169        );
6170    }
6171    use meerkat_machine_schema::RustTypeAtom;
6172    use meerkat_machine_schema::catalog::dsl::{
6173        dsl_meerkat_machine as meerkat_machine, dsl_mob_machine as mob_machine,
6174    };
6175    use meerkat_machine_schema::catalog::meerkat_mob_seam_composition;
6176    use meerkat_machine_schema::identity::{
6177        EffectVariantId, MachineId, MachineInstanceId, TransitionId,
6178    };
6179
6180    fn string_domain_values(assignment: &str) -> BTreeSet<String> {
6181        assignment
6182            .trim_start_matches('{')
6183            .trim_end_matches('}')
6184            .split(", ")
6185            .filter(|value| !value.is_empty())
6186            .map(|value| value.trim_matches('"').to_owned())
6187            .collect()
6188    }
6189
6190    fn cfg_string_domain_values(cfg: &str, domain: &str) -> BTreeSet<String> {
6191        let prefix = format!("  {domain} = ");
6192        cfg.lines()
6193            .find_map(|line| line.strip_prefix(&prefix))
6194            .map(string_domain_values)
6195            .unwrap_or_default()
6196    }
6197
6198    fn default_string_domain_values(sample_cardinality: usize) -> BTreeSet<String> {
6199        string_domain_values(&render_default_domain_assignment(
6200            &TypeRef::String,
6201            sample_cardinality,
6202            &BTreeMap::new(),
6203            &BTreeMap::new(),
6204            false,
6205        ))
6206    }
6207
6208    fn assert_session_id_string_overlap(cfg: &str, profile: &str) {
6209        let session_ids = cfg_string_domain_values(cfg, "SessionIdValues");
6210        let strings = cfg_string_domain_values(cfg, "StringValues");
6211        assert!(
6212            !session_ids.is_empty() && !strings.is_empty(),
6213            "{profile} must sample both bridged domains"
6214        );
6215        assert!(
6216            !session_ids.is_disjoint(&strings),
6217            "{profile} must make the SessionId/string equality branch satisfiable"
6218        );
6219        assert!(
6220            strings
6221                .iter()
6222                .any(|candidate| !session_ids.contains(candidate)),
6223            "{profile} must retain a non-matching string candidate for the rejection branch"
6224        );
6225    }
6226
6227    #[test]
6228    fn conjunctive_bool_specialization_is_literal_only_and_conservative() {
6229        let expr = Expr::And(vec![
6230            Expr::Binding("required_true".to_owned()),
6231            Expr::Not(Box::new(Expr::Binding("required_false".to_owned()))),
6232            Expr::Eq(
6233                Box::new(Expr::Binding("equal_true".to_owned())),
6234                Box::new(Expr::Bool(true)),
6235            ),
6236            Expr::Neq(
6237                Box::new(Expr::Bool(true)),
6238                Box::new(Expr::Binding("not_equal_true".to_owned())),
6239            ),
6240            Expr::Or(vec![
6241                Expr::Binding("under_disjunction".to_owned()),
6242                Expr::Binding("alternative".to_owned()),
6243            ]),
6244            Expr::Binding("conflicting".to_owned()),
6245            Expr::Not(Box::new(Expr::Binding("conflicting".to_owned()))),
6246        ]);
6247        let mut requirements = BTreeMap::new();
6248
6249        collect_conjunctive_bool_requirements(&expr, &mut requirements);
6250
6251        assert_eq!(requirements.get("required_true"), Some(&Some(true)));
6252        assert_eq!(requirements.get("required_false"), Some(&Some(false)));
6253        assert_eq!(requirements.get("equal_true"), Some(&Some(true)));
6254        assert_eq!(requirements.get("not_equal_true"), Some(&Some(false)));
6255        assert!(!requirements.contains_key("under_disjunction"));
6256        assert!(!requirements.contains_key("alternative"));
6257        assert_eq!(requirements.get("conflicting"), Some(&None));
6258    }
6259
6260    #[test]
6261    #[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
6262    fn composition_semantic_model_fails_closed_on_undeclared_route_source_machine() {
6263        let mut schema = meerkat_mob_seam_composition();
6264        let route = schema
6265            .routes
6266            .first_mut()
6267            .expect("seam composition has at least one route");
6268        // Repoint the route source at an instance id that is not declared in
6269        // the composition. The CASE builder used to map this to an
6270        // `"unknown_machine"` sentinel; generation must now fail closed.
6271        route.from_machine =
6272            MachineInstanceId::parse("undeclared_source_instance").expect("valid slug");
6273
6274        let result = render_composition_semantic_model(&schema);
6275        assert!(
6276            matches!(
6277                result,
6278                Err(CompositionTlaError::UnknownRouteSourceMachine { .. })
6279            ),
6280            "expected UnknownRouteSourceMachine, got {result:?}"
6281        );
6282    }
6283
6284    #[test]
6285    #[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
6286    fn composition_semantic_model_fails_closed_on_undeclared_route_effect() {
6287        let mut schema = meerkat_mob_seam_composition();
6288        let route = schema
6289            .routes
6290            .first_mut()
6291            .expect("seam composition has at least one route");
6292        // Keep the (declared) source machine but reference an effect variant
6293        // that the source machine does not declare.
6294        route.effect_variant =
6295            EffectVariantId::parse("UndeclaredEffectVariant").expect("valid slug");
6296
6297        let result = render_composition_semantic_model(&schema);
6298        assert!(
6299            matches!(result, Err(CompositionTlaError::UnknownRouteEffect { .. })),
6300            "expected UnknownRouteEffect, got {result:?}"
6301        );
6302    }
6303
6304    #[test]
6305    #[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
6306    fn composition_semantic_model_fails_closed_on_undeclared_witness_transition() {
6307        let mut schema = meerkat_mob_seam_composition();
6308        schema
6309            .witnesses
6310            .first_mut()
6311            .expect("seam composition has at least one witness")
6312            .expected_transitions
6313            .first_mut()
6314            .expect("seam witness has at least one expected transition")
6315            .transition = TransitionId::parse("UndeclaredWitnessTransition").expect("valid slug");
6316
6317        let result = render_composition_semantic_model(&schema);
6318        assert!(
6319            matches!(
6320                result,
6321                Err(CompositionTlaError::UnknownWitnessTransition { .. })
6322            ),
6323            "expected UnknownWitnessTransition, got {result:?}"
6324        );
6325    }
6326
6327    #[test]
6328    #[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
6329    fn composition_semantic_model_renders_for_valid_schema() {
6330        // Sanity: the fail-closed gate does not reject a currently-valid
6331        // composition. (Byte-identity of the output is enforced separately by
6332        // `make machine-check-drift`.)
6333        let schema = meerkat_mob_seam_composition();
6334        let result = render_composition_semantic_model(&schema);
6335        assert!(
6336            result.is_ok(),
6337            "valid composition should render: {result:?}"
6338        );
6339    }
6340
6341    #[test]
6342    #[should_panic(
6343        expected = "composition named-type `AgentRuntimeId` binding must agree across machine schemas"
6344    )]
6345    fn composition_named_binding_merge_rejects_divergent_domain_shapes() {
6346        let mut meerkat = meerkat_machine();
6347        meerkat.machine = MachineId::parse("CompositionMergeLeft").expect("test machine id");
6348        let mut mob = mob_machine();
6349        mob.machine = MachineId::parse("CompositionMergeRight").expect("test machine id");
6350        let binding = mob
6351            .named_types
6352            .iter_mut()
6353            .find(|binding| binding.name.as_str() == "AgentRuntimeId")
6354            .expect("MobMachine AgentRuntimeId binding");
6355        binding.rust = RustTypeAtom::U64;
6356
6357        let _ = collect_composition_named_bindings([&meerkat, &mob]);
6358    }
6359
6360    #[test]
6361    fn composition_named_binding_merge_allows_machine_local_type_path_twins() {
6362        let meerkat = meerkat_machine();
6363        let mob = mob_machine();
6364
6365        let bindings = collect_composition_named_bindings([&meerkat, &mob]);
6366
6367        assert!(
6368            matches!(
6369                bindings.get("PeerAddress"),
6370                Some(RustTypeAtom::TypePath(path))
6371                    if path == "crate::catalog::dsl::meerkat_machine::PeerAddress"
6372            ),
6373            "path-only TypePath twins should not block composition-domain binding merge"
6374        );
6375    }
6376
6377    #[test]
6378    fn mob_generation_native_helper_declares_and_assigns_u64_boundary() {
6379        let schema = mob_machine();
6380        assert!(machine_uses_u64_max(&schema));
6381
6382        let model = render_machine_semantic_model(&schema).expect("render MobMachine model");
6383        let constants_line = model
6384            .lines()
6385            .find(|line| line.starts_with("CONSTANTS "))
6386            .expect("MobMachine model constants");
6387        assert!(constants_line.contains(TLA_RUST_U64_MAX_CONSTANT));
6388
6389        for deep in [false, true] {
6390            let cfg = render_machine_ci_cfg(&schema, deep).expect("valid machine CFG");
6391            assert!(
6392                cfg.contains(&format!(
6393                    "  {TLA_RUST_U64_MAX_CONSTANT} = {TLC_SAFE_RUST_U64_MAX_VALUE}"
6394                )),
6395                "{} config must assign the boundary",
6396                if deep { "deep" } else { "ci" }
6397            );
6398        }
6399    }
6400
6401    #[test]
6402    fn meerkat_deep_cfg_samples_the_native_session_id_string_bridge() {
6403        let schema = meerkat_machine();
6404        assert!(machine_uses_session_id_string_bridge(&schema));
6405
6406        let deep_cfg = render_machine_ci_cfg(&schema, true).expect("valid deep CFG");
6407        assert_session_id_string_overlap(&deep_cfg, "MeerkatMachine Deep config");
6408        assert_eq!(
6409            cfg_string_domain_values(&deep_cfg, "StringValues").len(),
6410            default_string_domain_values(default_sample_cardinality(true)).len(),
6411            "bridge reachability must substitute a Deep string sample, not add one"
6412        );
6413
6414        let ci_cfg = render_machine_ci_cfg(&schema, false).expect("valid CI CFG");
6415        assert!(
6416            cfg_string_domain_values(&ci_cfg, "SessionIdValues").is_empty()
6417                && cfg_string_domain_values(&ci_cfg, "StringValues").is_empty(),
6418            "the step-limit-one CI profile must remain uninflated"
6419        );
6420    }
6421
6422    #[test]
6423    fn mob_deep_cfg_does_not_inflate_unrelated_string_domains() {
6424        let schema = mob_machine();
6425        assert!(!machine_uses_session_id_string_bridge(&schema));
6426
6427        let deep_cfg = render_machine_ci_cfg(&schema, true).expect("valid deep CFG");
6428        let session_ids = cfg_string_domain_values(&deep_cfg, "SessionIdValues");
6429        let strings = cfg_string_domain_values(&deep_cfg, "StringValues");
6430        assert!(
6431            session_ids.is_disjoint(&strings),
6432            "a machine without the native bridge must retain independent domains"
6433        );
6434    }
6435
6436    #[test]
6437    fn mob_identity_classifier_uses_a_typed_tlc_lifecycle_representative() {
6438        let schema = mob_machine();
6439        assert_eq!(
6440            schema
6441                .tlc_representative_inputs
6442                .iter()
6443                .map(|input| input.as_str())
6444                .collect::<Vec<_>>(),
6445            vec!["ClassifyIdentityReconciliation"],
6446            "the schema must explicitly own the TLC-only classifier abstraction"
6447        );
6448
6449        let model = render_machine_semantic_model(&schema).expect("render MobMachine model");
6450        assert!(
6451            model.contains(
6452                "TlcRepresentativeDomain(values) == IF values = {} THEN {} ELSE {CHOOSE value \\in values : TRUE}"
6453            ),
6454            "the representative domain must remain typed and nonempty-aware"
6455        );
6456        assert!(
6457            model.contains(
6458                "\\E intent \\in TlcRepresentativeDomain(IdentityAuthorityConditionValues) : \\E lease \\in TlcRepresentativeDomain(IdentityLeaseConditionValues)"
6459            ),
6460            "MobMachine lifecycle Next must sample one typed identity-classifier tuple"
6461        );
6462        assert!(
6463            !model.contains(
6464                "\\E intent \\in IdentityAuthorityConditionValues : \\E lease \\in IdentityLeaseConditionValues : \\E external_binding_required \\in BOOLEAN"
6465            ),
6466            "MobMachine lifecycle Next must not reintroduce the exhaustive classifier cartesian product"
6467        );
6468
6469        let composition = render_composition_semantic_model(&meerkat_mob_seam_composition())
6470            .expect("render Meerkat/Mob composition");
6471        assert!(
6472            composition.contains(
6473                "\\E arg_intent \\in TlcRepresentativeDomain(IdentityAuthorityConditionValues) : \\E arg_lease \\in TlcRepresentativeDomain(IdentityLeaseConditionValues)"
6474            ),
6475            "composition lifecycle exploration must honor the same schema-owned abstraction"
6476        );
6477    }
6478
6479    #[test]
6480    fn meerkat_mob_composition_deep_cfg_samples_the_included_native_bridge() {
6481        let schema = meerkat_mob_seam_composition();
6482        let deep_cfg = render_composition_ci_cfg(&schema, true);
6483
6484        assert_session_id_string_overlap(&deep_cfg, "Meerkat/Mob composition Deep config");
6485        let string_cardinality = schema
6486            .deep_domain_overrides
6487            .get("StringValues")
6488            .copied()
6489            .unwrap_or(schema.deep_domain_cardinality);
6490        assert_eq!(
6491            cfg_string_domain_values(&deep_cfg, "StringValues").len(),
6492            default_string_domain_values(string_cardinality).len(),
6493            "composition bridge reachability must substitute a string sample, not add one"
6494        );
6495
6496        let ci_cfg = render_composition_ci_cfg(&schema, false);
6497        assert!(
6498            cfg_string_domain_values(&ci_cfg, "SessionIdValues")
6499                .is_disjoint(&cfg_string_domain_values(&ci_cfg, "StringValues")),
6500            "the composition CI profile must remain unchanged"
6501        );
6502    }
6503
6504    #[test]
6505    fn runtime_delivery_recipient_insert_has_identical_local_map_semantics_in_tla() {
6506        let schema = meerkat_machine_schema::catalog::dsl::dsl_runtime_delivery_machine();
6507        let model = render_machine_semantic_model(&schema).expect("render recipient model");
6508        let definition = "runtime_delivery_recipient_outcomes_after_set(current, recipient, outcome) ==\n    MapSet(current, recipient, outcome)\n";
6509        assert!(model.contains(definition));
6510        assert!(
6511            model
6512                .matches("runtime_delivery_recipient_outcomes_after_set(")
6513                .count()
6514                > 1,
6515            "the generated settlement must call the formally defined insert"
6516        );
6517        let composition = render_composition_semantic_model(
6518            &meerkat_machine_schema::catalog::job_runtime_delivery_composition(),
6519        )
6520        .expect("render embedded recipient model");
6521        assert!(
6522            composition.contains(&format!("runtime_delivery__{definition}")),
6523            "embedded delivery machines require their scoped helper definition too"
6524        );
6525    }
6526
6527    #[test]
6528    fn session_document_instruction_natives_have_the_rust_semantics_in_tla() {
6529        // The DSL authority, the kernel oracle and the Core mirror give these
6530        // natives one meaning, pinned here as the generated TLA renders it:
6531        // a slot map with one slot set (insert or replace), the body bytes of
6532        // a slot set's Active slots (a slot the bytes map does not name
6533        // counts nothing), and the entries of a slot map whose slot is
6534        // Active.
6535        let schema = meerkat_machine_schema::catalog::dsl::dsl_session_document_machine();
6536        let model = render_machine_semantic_model(&schema).expect("render model");
6537        let slot_after_set = r"session_document_instruction_slot_after_set(current, slot, value) ==
6538    MapSet(current, slot, value)
6539";
6540        let active_bytes = r#"session_document_instruction_active_bytes(slot_effect, slot_bytes) ==
6541    LET RECURSIVE SessionDocumentInstructionActiveBytesOver(_)
6542        SessionDocumentInstructionActiveBytesOver(instruction_slots) ==
6543            IF instruction_slots = {} THEN 0
6544            ELSE LET instruction_slot == CHOOSE candidate_slot \in instruction_slots : TRUE
6545                 IN (IF slot_effect[instruction_slot] = "Active" /\ instruction_slot \in DOMAIN slot_bytes
6546                     THEN slot_bytes[instruction_slot] ELSE 0)
6547                    + SessionDocumentInstructionActiveBytesOver(instruction_slots \ {instruction_slot})
6548    IN SessionDocumentInstructionActiveBytesOver(DOMAIN slot_effect)
6549"#;
6550        let active_slots = r#"session_document_instruction_active_slots(slot_effect, slot_values) ==
6551    [instruction_slot \in {candidate_slot \in DOMAIN slot_values :
6552            candidate_slot \in DOMAIN slot_effect /\ slot_effect[candidate_slot] = "Active"}
6553        |-> slot_values[instruction_slot]]
6554"#;
6555        let retired_after = r"session_document_activation_retired_after(activation_rows, activation_retired) ==
6556    [activation_key \in DOMAIN activation_rows |->
6557        LET retired_count == IF activation_key \in DOMAIN activation_retired THEN activation_retired[activation_key] ELSE 0
6558            superseded_count == IF activation_rows[activation_key] > 0 THEN activation_rows[activation_key] - 1 ELSE 0
6559        IN IF retired_count >= superseded_count THEN retired_count ELSE superseded_count]
6560";
6561        for (native, definition) in [
6562            (
6563                "session_document_instruction_slot_after_set",
6564                slot_after_set,
6565            ),
6566            ("session_document_instruction_active_bytes", active_bytes),
6567            ("session_document_instruction_active_slots", active_slots),
6568            ("session_document_activation_retired_after", retired_after),
6569        ] {
6570            assert!(
6571                model.contains(definition),
6572                "the generated model must define {native} with its Rust semantics"
6573            );
6574            assert!(
6575                model.matches(&format!("{native}(")).count() > 1,
6576                "the generated arms must call the formally defined {native}"
6577            );
6578        }
6579    }
6580
6581    #[test]
6582    fn mob_machine_instruction_snapshot_natives_have_the_rust_semantics_in_tla() {
6583        // The DSL authority, the kernel oracle and the generated TLA give
6584        // the operator-instruction natives one meaning: the widest member
6585        // snapshot the records allow, the shared records (every slot that
6586        // is not member-targeted) plus the most one name holds of its own,
6587        // alone or with what another name's records pass to its forks, in
6588        // records and in Active body bytes; and, with a write applied, the
6589        // widest snapshot of the maps the write leaves.
6590        let schema = meerkat_machine_schema::catalog::dsl::dsl_mob_machine();
6591        let model = render_machine_semantic_model(&schema).expect("render model");
6592        let widest_slots = r#"mob_machine_instruction_widest_snapshot_slots(target_kind, target_member) ==
6593    LET member_slots == {candidate_slot \in DOMAIN target_kind : target_kind[candidate_slot] \in {"Member", "MemberAndForks"} /\ candidate_slot \in DOMAIN target_member}
6594        instruction_fork_slots == {candidate_slot \in member_slots : target_kind[candidate_slot] = "MemberAndForks"}
6595        instruction_member_names == {target_member[named_slot] : named_slot \in member_slots}
6596        InstructionOwnOf(named_member) == Cardinality({own_slot \in member_slots : target_member[own_slot] = named_member})
6597        InstructionForForksOf(named_member) == Cardinality({own_slot \in instruction_fork_slots : target_member[own_slot] = named_member})
6598        instruction_snapshots == {InstructionOwnOf(named_member) : named_member \in instruction_member_names} \cup {InstructionOwnOf(name_pair[1]) + InstructionForForksOf(name_pair[2]) : name_pair \in {candidate_pair \in instruction_member_names \X instruction_member_names : candidate_pair[1] # candidate_pair[2]}}
6599        widest_own == IF instruction_snapshots = {} THEN 0 ELSE CHOOSE snapshot_size \in instruction_snapshots : \A other_size \in instruction_snapshots : snapshot_size >= other_size
6600    IN Cardinality(DOMAIN target_kind \ member_slots) + widest_own
6601"#;
6602        let widest_bytes = r#"mob_machine_instruction_widest_snapshot_active_bytes(slot_effect, slot_bytes, target_kind, target_member) ==
6603    LET member_slots == {candidate_slot \in DOMAIN slot_effect : candidate_slot \in DOMAIN target_kind /\ target_kind[candidate_slot] \in {"Member", "MemberAndForks"} /\ candidate_slot \in DOMAIN target_member}
6604        instruction_fork_slots == {candidate_slot \in member_slots : target_kind[candidate_slot] = "MemberAndForks"}
6605        instruction_member_names == {target_member[named_slot] : named_slot \in member_slots}
6606        ActiveBytesOf(instruction_slots) == session_document_instruction_active_bytes([instruction_slot \in instruction_slots |-> slot_effect[instruction_slot]], slot_bytes)
6607        InstructionOwnOf(named_member) == ActiveBytesOf({own_slot \in member_slots : target_member[own_slot] = named_member})
6608        InstructionForForksOf(named_member) == ActiveBytesOf({own_slot \in instruction_fork_slots : target_member[own_slot] = named_member})
6609        instruction_snapshots == {InstructionOwnOf(named_member) : named_member \in instruction_member_names} \cup {InstructionOwnOf(name_pair[1]) + InstructionForForksOf(name_pair[2]) : name_pair \in {candidate_pair \in instruction_member_names \X instruction_member_names : candidate_pair[1] # candidate_pair[2]}}
6610        widest_own == IF instruction_snapshots = {} THEN 0 ELSE CHOOSE snapshot_size \in instruction_snapshots : \A other_size \in instruction_snapshots : snapshot_size >= other_size
6611    IN ActiveBytesOf(DOMAIN slot_effect \ member_slots) + widest_own
6612"#;
6613        let write_slots = r"mob_machine_instruction_write_snapshot_slots(target_kind, target_member, slot, kind, member) ==
6614    LET kind_after == MapSet(target_kind, slot, kind)
6615        member_after == IF member = None THEN [other_slot \in DOMAIN target_member \ {slot} |-> target_member[other_slot]] ELSE MapSet(target_member, slot, member.value)
6616    IN mob_machine_instruction_widest_snapshot_slots(kind_after, member_after)
6617";
6618        let write_bytes = r#"mob_machine_instruction_write_snapshot_active_bytes(slot_effect, slot_bytes, target_kind, target_member, slot, body_bytes, kind, member) ==
6619    LET effect_after == MapSet(slot_effect, slot, "Active")
6620        bytes_after == MapSet(slot_bytes, slot, body_bytes)
6621        kind_after == MapSet(target_kind, slot, kind)
6622        member_after == IF member = None THEN [other_slot \in DOMAIN target_member \ {slot} |-> target_member[other_slot]] ELSE MapSet(target_member, slot, member.value)
6623    IN mob_machine_instruction_widest_snapshot_active_bytes(effect_after, bytes_after, kind_after, member_after)
6624"#;
6625
6626        for (native, definition) in [
6627            (
6628                "mob_machine_instruction_widest_snapshot_slots",
6629                widest_slots,
6630            ),
6631            (
6632                "mob_machine_instruction_widest_snapshot_active_bytes",
6633                widest_bytes,
6634            ),
6635            ("mob_machine_instruction_write_snapshot_slots", write_slots),
6636            (
6637                "mob_machine_instruction_write_snapshot_active_bytes",
6638                write_bytes,
6639            ),
6640        ] {
6641            assert!(
6642                model.contains(definition),
6643                "the generated model must define {native} with its Rust semantics"
6644            );
6645            assert!(
6646                model.matches(&format!("{native}(")).count() > 1,
6647                "the generated arms must call the formally defined {native}"
6648            );
6649        }
6650    }
6651
6652    #[test]
6653    fn meerkat_session_id_native_helper_matches_typed_option_contract() {
6654        let model =
6655            render_machine_semantic_model(&meerkat_machine()).expect("render MeerkatMachine model");
6656        let expected = r"meerkat_machine_session_id_matches_string(current, candidate) ==
6657    current # None /\ current.value = candidate
6658";
6659
6660        assert!(
6661            model.contains(expected),
6662            "MeerkatMachine TLA session identity operator must preserve the Rust typed-option/string comparison contract"
6663        );
6664    }
6665
6666    #[test]
6667    fn mob_placed_native_helpers_are_defined_in_the_tla_model() {
6668        let model = render_machine_semantic_model(&mob_machine()).expect("render MobMachine model");
6669
6670        for operator in [
6671            "mob_machine_finalized_placed_kickoff_recovery_well_formed(",
6672            "mob_machine_placed_completion_obligation_well_formed(",
6673            "mob_machine_placed_completion_custody_admits(",
6674            "mob_machine_adaptive_lifecycle_drained(",
6675            "mob_machine_adaptive_run_custody_drained(",
6676            "mob_machine_placed_kickoff_obligation_well_formed(",
6677            "mob_machine_placed_kickoff_correlation_available(",
6678            "mob_machine_placed_kickoff_custody_absent_for_identity(",
6679            "mob_machine_placed_kickoff_custody_absent_for_host(",
6680            "mob_machine_remote_turn_input_id_available_to_kickoff(",
6681            "mob_machine_placed_carrier_binding_active(",
6682            "mob_machine_placed_carrier_binding_confirmed_revoked(",
6683            "mob_machine_host_binding_generation_tombstone(",
6684        ] {
6685            assert!(
6686                model
6687                    .lines()
6688                    .any(|line| line.starts_with(operator) && line.ends_with(" ==")),
6689                "MobMachine TLA model must define native operator {operator}"
6690            );
6691        }
6692    }
6693
6694    /// The two peer id invariants call a native predicate each. The Rust
6695    /// natives read each endpoint once; the model keeps the pairwise
6696    /// statement, so TLC checks the property as it was stated before.
6697    #[test]
6698    fn mob_peer_id_invariant_natives_are_stated_pairwise_in_the_tla_model() {
6699        let model = render_machine_semantic_model(&mob_machine()).expect("render MobMachine model");
6700        let body_after = |definition: &str| {
6701            let mut lines = model.lines().skip_while(|line| *line != definition);
6702            assert_eq!(lines.next(), Some(definition), "the model defines it");
6703            lines
6704                .take_while(|line| line.starts_with("    "))
6705                .collect::<Vec<_>>()
6706        };
6707
6708        assert_eq!(
6709            body_after(
6710                "mob_machine_member_peer_id_ownership_is_global(current_endpoints, prior_endpoints) =="
6711            ),
6712            [
6713                "    /\\ \\A agent_identity \\in DOMAIN current_endpoints : mob_machine_member_peer_id_available_for_identity(current_endpoints, prior_endpoints, agent_identity, current_endpoints[agent_identity])",
6714                "    /\\ \\A agent_identity \\in DOMAIN prior_endpoints : \\A prior_endpoint \\in prior_endpoints[agent_identity] : mob_machine_member_peer_id_available_for_identity(current_endpoints, prior_endpoints, agent_identity, prior_endpoint)",
6715            ]
6716        );
6717        assert_eq!(
6718            body_after("mob_machine_live_member_peer_ids_are_unique(current_endpoints) =="),
6719            [
6720                "    \\A agent_identity \\in DOMAIN current_endpoints : \\A other_identity \\in DOMAIN current_endpoints : agent_identity = other_identity \\/ current_endpoints[agent_identity].peer_id /= current_endpoints[other_identity].peer_id",
6721            ]
6722        );
6723        for invariant in [
6724            "member_peer_id_ownership_is_global_across_generations == mob_machine_member_peer_id_ownership_is_global(member_peer_endpoints, member_prior_peer_endpoints)",
6725            "live_member_peer_ids_are_unique == mob_machine_live_member_peer_ids_are_unique(member_peer_endpoints)",
6726        ] {
6727            assert!(
6728                model.lines().any(|line| line == invariant),
6729                "the model states the invariant as one call: {invariant}"
6730            );
6731        }
6732    }
6733
6734    #[test]
6735    fn mob_placed_kickoff_correlation_tla_helper_covers_every_shared_input_namespace() {
6736        let model = render_machine_semantic_model(&mob_machine()).expect("render MobMachine model");
6737        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) ==
6738    /\ \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)
6739    /\ \A identity \in DOMAIN retained_kickoffs : retained_kickoffs[identity].agent_identity # candidate.agent_identity
6740    /\ \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)
6741    /\ \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)
6742";
6743
6744        assert!(
6745            model.contains(expected),
6746            "MobMachine TLA kickoff-correlation helper must reject collisions across kickoff, remote-turn, and placed-completion custody"
6747        );
6748    }
6749
6750    #[test]
6751    fn mob_placed_kickoff_recovery_tla_helper_does_not_shadow_machine_phase() {
6752        let model = render_machine_semantic_model(&mob_machine()).expect("render MobMachine model");
6753        assert!(
6754            model.contains(
6755                r#"Cardinality({ kickoff_phase \in {"Started", "CallbackPending", "Failed", "Cancelled"} :"#
6756            ),
6757            "kickoff recovery helper must bind a helper-local identifier"
6758        );
6759        assert!(
6760            !model.contains(
6761                r#"Cardinality({ phase \in {"Started", "CallbackPending", "Failed", "Cancelled"} :"#
6762            ),
6763            "TLA forbids the helper-local binder from shadowing the machine's phase variable"
6764        );
6765    }
6766
6767    #[test]
6768    fn mob_adaptive_run_custody_native_helper_matches_rust_contract() {
6769        let model = render_machine_semantic_model(&mob_machine()).expect("render MobMachine model");
6770        let expected = r#"mob_machine_adaptive_run_custody_drained(adaptive_run_id, active_layer, active_members, layer_run, layer_phases, layer_dispositions) ==
6771    /\ adaptive_run_id \notin DOMAIN active_layer
6772    /\ (IF adaptive_run_id \in DOMAIN active_members THEN active_members[adaptive_run_id] ELSE 0) = 0
6773    /\ \A layer_id \in DOMAIN layer_run :
6774           \/ layer_run[layer_id] # adaptive_run_id
6775           \/ /\ layer_id \in DOMAIN layer_dispositions
6776              /\ layer_id \in DOMAIN layer_phases
6777              /\ layer_phases[layer_id] \in {"Completed", "SetupFailed", "RunFailed", "ResultInvalid", "Canceled"}
6778"#;
6779
6780        assert!(
6781            model.contains(expected),
6782            "MobMachine TLA adaptive-run custody operator must preserve the Rust absence, zero-active-member, and terminal-layer contract"
6783        );
6784    }
6785
6786    /// Every conjunct of the option-order ASSUME table states what Rust's
6787    /// `Option` order computes, so a TLC run that accepts the ASSUMEs proves
6788    /// `OptionLt` / `OptionLe` right. The table covers both operators over
6789    /// None/None, None/Some, Some/None and Some/Some below, equal and above.
6790    #[test]
6791    #[allow(clippy::panic)]
6792    fn the_option_order_assume_table_is_rusts_option_order() {
6793        use std::cmp::Ordering;
6794
6795        fn operand(text: &str) -> Option<u64> {
6796            if text == "None" {
6797                return None;
6798            }
6799            let value = text
6800                .strip_prefix("Some(")
6801                .and_then(|rest| rest.strip_suffix(')'))
6802                .unwrap_or_else(|| panic!("unexpected operand {text}"));
6803            Some(
6804                value
6805                    .parse()
6806                    .unwrap_or_else(|_| panic!("unexpected operand {text}")),
6807            )
6808        }
6809
6810        // TLC evaluates every disjunct of an action-level `\/`, so a `\/` in
6811        // either definition would read a `None` record's `value` inside a
6812        // guard; the ASSUMEs alone cannot see that.
6813        for line in TLA_OPTION_ORDER_DEFINITIONS
6814            .lines()
6815            .filter(|line| line.starts_with("OptionL"))
6816        {
6817            assert!(!line.contains("\\/"), "{line} branches with a disjunction");
6818        }
6819
6820        let mut covered = BTreeSet::new();
6821        for line in TLA_OPTION_ORDER_DEFINITIONS.lines() {
6822            let Some(table) = line.strip_prefix("ASSUME ") else {
6823                continue;
6824            };
6825            for conjunct in table.split(" /\\ ") {
6826                let (expected, call) = match conjunct.strip_prefix('~') {
6827                    Some(call) => (false, call),
6828                    None => (true, conjunct),
6829                };
6830                let (operator, operands) = call.split_once('(').expect("an operator call");
6831                let (left, right) = operands
6832                    .strip_suffix(')')
6833                    .and_then(|operands| operands.split_once(", "))
6834                    .expect("two operands");
6835                let (left, right) = (operand(left), operand(right));
6836                let rust = match operator {
6837                    "OptionLt" => left < right,
6838                    "OptionLe" => left <= right,
6839                    other => panic!("unexpected operator {other}"),
6840                };
6841                assert_eq!(
6842                    expected, rust,
6843                    "{conjunct} disagrees with Rust's Option order"
6844                );
6845                covered.insert((operator, left.is_some(), right.is_some(), left.cmp(&right)));
6846            }
6847        }
6848        for operator in ["OptionLt", "OptionLe"] {
6849            for case in [
6850                (false, false, Ordering::Equal),
6851                (false, true, Ordering::Less),
6852                (true, false, Ordering::Greater),
6853                (true, true, Ordering::Less),
6854                (true, true, Ordering::Equal),
6855                (true, true, Ordering::Greater),
6856            ] {
6857                assert!(
6858                    covered.contains(&(operator, case.0, case.1, case.2)),
6859                    "the ASSUME table misses {operator} over {case:?}"
6860                );
6861            }
6862        }
6863    }
6864
6865    /// An ordering comparison with an option operand renders through
6866    /// `OptionLt` / `OptionLe` (`>` and `>=` with the operands swapped) for
6867    /// every way an operand is an option, on either side; a plain ordering
6868    /// keeps its TLA+ operator and leaves the module without the definitions.
6869    #[test]
6870    fn an_ordering_with_an_option_operand_renders_in_rusts_option_order() {
6871        let mut schema = mob_machine();
6872        schema.helpers.push(HelperSchema {
6873            name: "maybe_epoch".into(),
6874            params: Vec::new(),
6875            returns: TypeRef::Option(Box::new(TypeRef::U64)),
6876            body: Expr::None,
6877        });
6878        let field = |name: &str| {
6879            Box::new(Expr::Field(
6880                meerkat_machine_schema::identity::FieldId::parse(name).expect("field id"),
6881            ))
6882        };
6883        let binding = |name: &str| Box::new(Expr::Binding(name.to_owned()));
6884        let binding_types = BTreeMap::from([
6885            ("agent_identity".to_owned(), TypeRef::String),
6886            ("maybe".to_owned(), TypeRef::Option(Box::new(TypeRef::U64))),
6887            ("n".to_owned(), TypeRef::U64),
6888            ("run_id".to_owned(), TypeRef::String),
6889        ]);
6890        let options = [
6891            ("a None literal", Expr::None),
6892            ("a Some literal", Expr::Some(Box::new(Expr::U64(3)))),
6893            ("an option binding", Expr::Binding("maybe".to_owned())),
6894            ("an option field", *field("supervisor_authority_epoch")),
6895            (
6896                "the get_copied lowering",
6897                Expr::IfElse {
6898                    condition: Box::new(Expr::MapContainsKey {
6899                        map: field("member_last_observed_at_ms"),
6900                        key: binding("agent_identity"),
6901                    }),
6902                    then_expr: Box::new(Expr::Some(Box::new(Expr::MapGet {
6903                        map: field("member_last_observed_at_ms"),
6904                        key: binding("agent_identity"),
6905                    }))),
6906                    else_expr: Box::new(Expr::None),
6907                },
6908            ),
6909            (
6910                "a read of a map with option values",
6911                Expr::MapGet {
6912                    map: field("run_last_granted_frame"),
6913                    key: binding("run_id"),
6914                },
6915            ),
6916            (
6917                "a helper returning an option",
6918                Expr::Call {
6919                    helper: "maybe_epoch".to_owned(),
6920                    args: Vec::new(),
6921                },
6922            ),
6923        ];
6924        let other = Expr::Some(binding("n"));
6925        for (shape, option) in &options {
6926            let compiler = MachineTlaCompiler::new(&schema);
6927            let render = |expr: &Expr| {
6928                compiler.render_expr_with_types(
6929                    expr,
6930                    &BTreeMap::new(),
6931                    &BTreeMap::new(),
6932                    &binding_types,
6933                )
6934            };
6935            let (a, b) = (render(option), render(&other));
6936            let pair = || (Box::new(option.clone()), Box::new(other.clone()));
6937            let swapped = || (Box::new(other.clone()), Box::new(option.clone()));
6938            for (expr, expected) in [
6939                (Expr::Lt(pair().0, pair().1), format!("OptionLt({a}, {b})")),
6940                (Expr::Lte(pair().0, pair().1), format!("OptionLe({a}, {b})")),
6941                (Expr::Gt(pair().0, pair().1), format!("OptionLt({b}, {a})")),
6942                (Expr::Gte(pair().0, pair().1), format!("OptionLe({b}, {a})")),
6943                (
6944                    Expr::Lt(swapped().0, swapped().1),
6945                    format!("OptionLt({b}, {a})"),
6946                ),
6947                (
6948                    Expr::Gte(swapped().0, swapped().1),
6949                    format!("OptionLe({a}, {b})"),
6950                ),
6951            ] {
6952                assert_eq!(render(&expr), expected, "{shape}: {expr:?}");
6953            }
6954            assert!(compiler.option_order_used.get(), "{shape} marks the module");
6955        }
6956
6957        let compiler = MachineTlaCompiler::new(&schema);
6958        let render = |expr: Expr| {
6959            compiler.render_expr_with_types(
6960                &expr,
6961                &BTreeMap::new(),
6962                &BTreeMap::new(),
6963                &binding_types,
6964            )
6965        };
6966        let one = || Box::new(Expr::U64(1));
6967        assert_eq!(render(Expr::Lt(binding("n"), one())), "(n < 1)");
6968        assert_eq!(render(Expr::Lte(binding("n"), one())), "(n <= 1)");
6969        assert_eq!(render(Expr::Gt(binding("n"), one())), "(n > 1)");
6970        assert_eq!(render(Expr::Gte(binding("n"), one())), "(n >= 1)");
6971        assert!(
6972            !compiler.option_order_used.get(),
6973            "a plain ordering needs no option-order definitions"
6974        );
6975    }
6976
6977    /// A machine or composition module defines `OptionLt` / `OptionLe` if
6978    /// and only if it calls them, so the definitions land only beside an
6979    /// option ordering.
6980    #[test]
6981    fn a_module_defines_the_option_order_operators_iff_it_calls_them() {
6982        let calls_operators = |module: &str, model: &str| {
6983            let defined = model.matches(TLA_OPTION_ORDER_DEFINITIONS).count();
6984            assert!(
6985                defined <= 1,
6986                "{module} defines the operators {defined} times"
6987            );
6988            let body = model.replacen(TLA_OPTION_ORDER_DEFINITIONS, "", 1);
6989            let called = body.contains("OptionLt(") || body.contains("OptionLe(");
6990            assert_eq!(
6991                defined == 1,
6992                called,
6993                "{module}: defined {defined} time(s), called: {called}"
6994            );
6995            called
6996        };
6997        let mut callers = Vec::new();
6998        for machine in canonical_machine_schemas() {
6999            let model = render_machine_semantic_model(&machine).expect("render machine model");
7000            if calls_operators(machine.machine.as_str(), &model) {
7001                callers.push(machine.machine.as_str().to_owned());
7002            }
7003        }
7004        for composition in meerkat_machine_schema::canonical_composition_schemas() {
7005            // meerkat_mob_seam takes about 45 s to render. Its MobMachine part
7006            // goes through the same per-instance compilers as
7007            // adaptive_mob_bundle's two MobMachine instances below, and
7008            // machine-check-drift holds its regenerated model.
7009            if composition.name.as_str() == "meerkat_mob_seam" {
7010                continue;
7011            }
7012            let model =
7013                render_composition_semantic_model(&composition).expect("render composition model");
7014            if calls_operators(composition.name.as_str(), &model) {
7015                callers.push(composition.name.as_str().to_owned());
7016            }
7017        }
7018        for caller in ["MobMachine", "adaptive_mob_bundle"] {
7019            assert!(
7020                callers.iter().any(|candidate| candidate == caller),
7021                "{caller} orders options (MobMachine's member progress guards): {callers:?}"
7022            );
7023        }
7024    }
7025
7026    /// The option-ordering contract: every ordering comparison in a
7027    /// canonical machine whose operand is option-shaped renders through
7028    /// `OptionLt` / `OptionLe`, never as a plain comparison TLC cannot
7029    /// evaluate. The walk decides "option-shaped" from the schema's declared
7030    /// types (state fields, trigger bindings, helper parameters and returns,
7031    /// map value types, `Some` / `None` literals), independently of the
7032    /// renderer's own inference, so a new guard cannot bring the class back
7033    /// through a shape the renderer misses.
7034    #[test]
7035    fn every_canonical_option_ordering_renders_in_rusts_option_order() {
7036        struct Walk<'a> {
7037            schema: &'a MachineSchema,
7038            compiler: MachineTlaCompiler<'a>,
7039            checked: usize,
7040            plain: Vec<String>,
7041        }
7042
7043        impl Walk<'_> {
7044            fn declared<'t>(
7045                &'t self,
7046                expr: &Expr,
7047                bindings: &'t BTreeMap<String, TypeRef>,
7048            ) -> Option<&'t TypeRef> {
7049                match expr {
7050                    Expr::Field(field) => self
7051                        .schema
7052                        .state
7053                        .fields
7054                        .iter()
7055                        .find(|candidate| candidate.name == *field)
7056                        .map(|candidate| &candidate.ty),
7057                    Expr::Binding(name) => bindings.get(name),
7058                    Expr::Call { helper, .. } => self
7059                        .schema
7060                        .helpers
7061                        .iter()
7062                        .chain(self.schema.derived.iter())
7063                        .find(|candidate| candidate.name == *helper)
7064                        .map(|candidate| &candidate.returns),
7065                    Expr::MapGet { map, .. } | Expr::MapValue { map, .. } => {
7066                        match self.declared(map, bindings)? {
7067                            TypeRef::Map(_, value) => Some(value.as_ref()),
7068                            _ => None,
7069                        }
7070                    }
7071                    _ => None,
7072                }
7073            }
7074
7075            fn option_shaped(&self, expr: &Expr, bindings: &BTreeMap<String, TypeRef>) -> bool {
7076                match expr {
7077                    Expr::Some(_) | Expr::None => true,
7078                    Expr::IfElse {
7079                        then_expr,
7080                        else_expr,
7081                        ..
7082                    } => {
7083                        self.option_shaped(then_expr, bindings)
7084                            || self.option_shaped(else_expr, bindings)
7085                    }
7086                    other => matches!(self.declared(other, bindings), Some(TypeRef::Option(_))),
7087                }
7088            }
7089
7090            fn walk(&mut self, site: &str, expr: &Expr, bindings: &BTreeMap<String, TypeRef>) {
7091                match expr {
7092                    Expr::Lt(left, right)
7093                    | Expr::Lte(left, right)
7094                    | Expr::Gt(left, right)
7095                    | Expr::Gte(left, right) => {
7096                        if self.option_shaped(left, bindings) || self.option_shaped(right, bindings)
7097                        {
7098                            self.checked += 1;
7099                            let rendered = self.compiler.render_expr_with_types(
7100                                expr,
7101                                &BTreeMap::new(),
7102                                &BTreeMap::new(),
7103                                bindings,
7104                            );
7105                            if !rendered.starts_with("OptionLt(")
7106                                && !rendered.starts_with("OptionLe(")
7107                            {
7108                                self.plain
7109                                    .push(format!("{} {site}: {rendered}", self.schema.machine));
7110                            }
7111                        }
7112                        self.walk(site, left, bindings);
7113                        self.walk(site, right, bindings);
7114                    }
7115                    Expr::Bool(_)
7116                    | Expr::U64(_)
7117                    | Expr::U64Max
7118                    | Expr::String(_)
7119                    | Expr::NamedVariant { .. }
7120                    | Expr::EmptySet
7121                    | Expr::EmptyMap
7122                    | Expr::CurrentPhase
7123                    | Expr::Phase(_)
7124                    | Expr::Field(_)
7125                    | Expr::Binding(_)
7126                    | Expr::Variant(_)
7127                    | Expr::None => {}
7128                    Expr::FieldAccess { base, .. } => self.walk(site, base, bindings),
7129                    Expr::EnumVariantIs { value, .. }
7130                    | Expr::EnumStringSetPayload { value, .. } => self.walk(site, value, bindings),
7131                    Expr::SeqLiteral(items) | Expr::And(items) | Expr::Or(items) => {
7132                        for item in items {
7133                            self.walk(site, item, bindings);
7134                        }
7135                    }
7136                    Expr::IfElse {
7137                        condition,
7138                        then_expr,
7139                        else_expr,
7140                    } => {
7141                        self.walk(site, condition, bindings);
7142                        self.walk(site, then_expr, bindings);
7143                        self.walk(site, else_expr, bindings);
7144                    }
7145                    Expr::Not(inner)
7146                    | Expr::SeqElements(inner)
7147                    | Expr::Len(inner)
7148                    | Expr::Head(inner)
7149                    | Expr::MapKeys(inner)
7150                    | Expr::Some(inner) => self.walk(site, inner, bindings),
7151                    Expr::Eq(left, right)
7152                    | Expr::Neq(left, right)
7153                    | Expr::Add(left, right)
7154                    | Expr::Sub(left, right) => {
7155                        self.walk(site, left, bindings);
7156                        self.walk(site, right, bindings);
7157                    }
7158                    Expr::Contains { collection, value } | Expr::Count { collection, value } => {
7159                        self.walk(site, collection, bindings);
7160                        self.walk(site, value, bindings);
7161                    }
7162                    Expr::MapContainsKey { map, key }
7163                    | Expr::MapGet { map, key }
7164                    | Expr::MapValue { map, key } => {
7165                        self.walk(site, map, bindings);
7166                        self.walk(site, key, bindings);
7167                    }
7168                    Expr::SeqStartsWith { seq, prefix } => {
7169                        self.walk(site, seq, bindings);
7170                        self.walk(site, prefix, bindings);
7171                    }
7172                    Expr::MapLiteral(entries) => {
7173                        for (key, value) in entries {
7174                            self.walk(site, key, bindings);
7175                            self.walk(site, value, bindings);
7176                        }
7177                    }
7178                    Expr::Call { args, .. } => {
7179                        for arg in args {
7180                            self.walk(site, arg, bindings);
7181                        }
7182                    }
7183                    Expr::Quantified { over, body, .. } => {
7184                        self.walk(site, over, bindings);
7185                        self.walk(site, body, bindings);
7186                    }
7187                }
7188            }
7189
7190            fn walk_updates(
7191                &mut self,
7192                site: &str,
7193                updates: &[Update],
7194                bindings: &BTreeMap<String, TypeRef>,
7195            ) {
7196                for update in updates {
7197                    match update {
7198                        Update::Assign { expr, .. } => self.walk(site, expr, bindings),
7199                        Update::Increment { .. }
7200                        | Update::Decrement { .. }
7201                        | Update::SeqPopFront { .. } => {}
7202                        Update::MapInsert { key, value, .. } => {
7203                            self.walk(site, key, bindings);
7204                            self.walk(site, value, bindings);
7205                        }
7206                        Update::MapIncrement { key, .. }
7207                        | Update::MapDecrement { key, .. }
7208                        | Update::MapRemove { key, .. } => self.walk(site, key, bindings),
7209                        Update::SetInsert { value, .. }
7210                        | Update::SetRemove { value, .. }
7211                        | Update::SeqAppend { value, .. }
7212                        | Update::SeqRemoveValue { value, .. } => self.walk(site, value, bindings),
7213                        Update::SeqPrepend { values, .. } | Update::SeqRemoveAll { values, .. } => {
7214                            self.walk(site, values, bindings)
7215                        }
7216                        Update::Conditional {
7217                            condition,
7218                            then_updates,
7219                            else_updates,
7220                        } => {
7221                            self.walk(site, condition, bindings);
7222                            self.walk_updates(site, then_updates, bindings);
7223                            self.walk_updates(site, else_updates, bindings);
7224                        }
7225                        Update::ForEach { over, updates, .. } => {
7226                            self.walk(site, over, bindings);
7227                            self.walk_updates(site, updates, bindings);
7228                        }
7229                    }
7230                }
7231            }
7232        }
7233
7234        let mut checked = 0;
7235        let mut plain = Vec::new();
7236        for schema in canonical_machine_schemas() {
7237            let mut walk = Walk {
7238                schema: &schema,
7239                compiler: MachineTlaCompiler::new(&schema),
7240                checked: 0,
7241                plain: Vec::new(),
7242            };
7243            let none = BTreeMap::new();
7244            for transition in &schema.transitions {
7245                let bindings = walk.compiler.binding_type_map(transition);
7246                let site = transition.name.as_str();
7247                for guard in &transition.guards {
7248                    walk.walk(site, &guard.expr, &bindings);
7249                }
7250                walk.walk_updates(site, &transition.updates, &bindings);
7251                for emit in &transition.emit {
7252                    for expr in emit.fields.values() {
7253                        walk.walk(site, expr, &bindings);
7254                    }
7255                }
7256            }
7257            for invariant in &schema.invariants {
7258                walk.walk(&invariant.name, &invariant.expr, &none);
7259            }
7260            for helper in schema.helpers.iter().chain(schema.derived.iter()) {
7261                let params = helper
7262                    .params
7263                    .iter()
7264                    .map(|param| (param.name.as_str().to_owned(), param.ty.clone()))
7265                    .collect::<BTreeMap<_, _>>();
7266                walk.walk(&helper.name, &helper.body, &params);
7267            }
7268            checked += walk.checked;
7269            plain.extend(walk.plain);
7270        }
7271        assert!(
7272            plain.is_empty(),
7273            "option orderings rendered as plain comparisons (TLC cannot order option records):\n{}",
7274            plain.join("\n")
7275        );
7276        // MobMachine's seven member-progress guards order options: the walk
7277        // must find them, or the contract passes vacuously.
7278        assert!(checked >= 7, "the walk found {checked} option orderings");
7279    }
7280}
7281
7282fn render_sequence_domain_definition(inner: &TypeRef) -> String {
7283    let inner_domain = render_type_domain_expr(inner);
7284    format!(
7285        "{{<<>>}} \\cup {{<<x>> : x \\in {inner_domain}}} \\cup {{<<x, y>> : x \\in {inner_domain}, y \\in {inner_domain}}}"
7286    )
7287}
7288
7289fn render_option_domain_definition(inner: &TypeRef) -> String {
7290    let inner_domain = render_type_domain_expr(inner);
7291    format!("{{None}} \\cup {{Some(x) : x \\in {inner_domain}}}")
7292}
7293
7294fn render_map_domain_definition(key: &TypeRef, value: &TypeRef) -> String {
7295    let key_domain = render_type_domain_expr(key);
7296    let value_domain = render_type_domain_expr(value);
7297    let empty_map = "[x \\in {} |-> None]";
7298    format!(
7299        "{{{empty_map}}} \\cup {{ [x \\in {{k}} |-> v] : k \\in {key_domain}, v \\in {value_domain} }}"
7300    )
7301}
7302
7303fn ordered_composite_domain_definitions(
7304    constants: &BTreeMap<String, TypeRef>,
7305) -> Vec<(&String, &TypeRef)> {
7306    let mut domains = constants
7307        .iter()
7308        .filter(|(_, ty)| {
7309            matches!(
7310                ty,
7311                TypeRef::Seq(_) | TypeRef::Option(_) | TypeRef::Map(_, _)
7312            )
7313        })
7314        .collect::<Vec<_>>();
7315    domains.sort_by_key(|(name, ty)| (domain_dependency_depth(ty), (*name).clone()));
7316    domains
7317}
7318
7319fn domain_dependency_depth(ty: &TypeRef) -> usize {
7320    match ty {
7321        TypeRef::Option(inner) | TypeRef::Seq(inner) | TypeRef::Set(inner) => {
7322            1 + domain_dependency_depth(inner)
7323        }
7324        TypeRef::Map(key, value) => {
7325            1 + domain_dependency_depth(key).max(domain_dependency_depth(value))
7326        }
7327        TypeRef::Bool
7328        | TypeRef::U32
7329        | TypeRef::U64
7330        | TypeRef::String
7331        | TypeRef::Named(_)
7332        | TypeRef::Enum(_) => 0,
7333    }
7334}
7335
7336/// The rendered payload of one owner feedback input.
7337struct FeedbackPayload {
7338    payload_expr: String,
7339    quantifiers: Vec<String>,
7340    /// `(obligation field, bound member variable)` per `ObligationMember`.
7341    members: Vec<(String, String)>,
7342}
7343
7344/// Whether `NoOpenObligationsOnTerminal_<protocol>` applies: the producer has
7345/// terminal phases and the protocol is `AckRequired`, so only owner feedback
7346/// closes its obligations. Under `AckOrAbort` and `TerminalClosure` the
7347/// terminal phase is itself the closure, and a `PublicationOnly` protocol has
7348/// no feedback (the publication closes it), so for those the invariant would be
7349/// unsatisfiable once the producer reaches a terminal phase.
7350fn terminal_closure_required(
7351    protocol: &meerkat_machine_schema::EffectHandoffProtocol,
7352    producer: &MachineSchema,
7353) -> bool {
7354    !producer.state.terminal_phases.is_empty()
7355        && matches!(
7356            protocol.closure_policy,
7357            meerkat_machine_schema::ClosurePolicy::AckRequired
7358        )
7359}
7360
7361fn render_type_domain_expr(ty: &TypeRef) -> String {
7362    match ty {
7363        TypeRef::Bool => "BOOLEAN".into(),
7364        // dogma #172 (codegen half): U32 and U64 are distinct bounded domains,
7365        // not one collapsed `NatValues`. The domains-map machinery auto-declares
7366        // the `U32Values` CONSTANT and emits its .cfg sample assignment, so a
7367        // u32 field references its own domain (matching the kernel's u32 width
7368        // check) rather than aliasing the unbounded u64 domain.
7369        TypeRef::U32 => "U32Values".into(),
7370        TypeRef::U64 => "NatValues".into(),
7371        TypeRef::String => "StringValues".into(),
7372        TypeRef::Named(_)
7373        | TypeRef::Enum(_)
7374        | TypeRef::Set(_)
7375        | TypeRef::Seq(_)
7376        | TypeRef::Option(_)
7377        | TypeRef::Map(_, _) => domain_constant_name(ty),
7378    }
7379}
7380
7381fn domain_constant_name(ty: &TypeRef) -> String {
7382    match ty {
7383        TypeRef::Named(name) => format!("{}Values", tla_ident(name)),
7384        TypeRef::Enum(name) => format!("{}Values", tla_ident(name)),
7385        TypeRef::Seq(inner) => format!("SeqOf{}Values", tla_ident(type_ref_name(inner))),
7386        TypeRef::Set(inner) => format!("SetOf{}Values", tla_ident(type_ref_name(inner))),
7387        TypeRef::String => "StringValues".into(),
7388        TypeRef::Bool => "BooleanValues".into(),
7389        TypeRef::U32 => "U32Values".into(),
7390        TypeRef::U64 => "NatValues".into(),
7391        TypeRef::Option(inner) => format!("Option{}Values", tla_ident(type_ref_name(inner))),
7392        TypeRef::Map(key, value) => {
7393            format!(
7394                "Map{}{}Values",
7395                tla_ident(type_ref_name(key)),
7396                tla_ident(type_ref_name(value))
7397            )
7398        }
7399    }
7400}
7401
7402fn type_ref_name(ty: &TypeRef) -> String {
7403    match ty {
7404        TypeRef::Bool => "Bool".into(),
7405        TypeRef::U32 => "U32".into(),
7406        TypeRef::U64 => "U64".into(),
7407        TypeRef::String => "String".into(),
7408        TypeRef::Named(name) => name.as_str().to_owned(),
7409        TypeRef::Enum(name) => name.as_str().to_owned(),
7410        TypeRef::Option(inner) => format!("Option{}", type_ref_name(inner)),
7411        TypeRef::Set(inner) => format!("Set{}", type_ref_name(inner)),
7412        TypeRef::Seq(inner) => format!("Seq{}", type_ref_name(inner)),
7413        TypeRef::Map(key, value) => format!("Map{}{}", type_ref_name(key), type_ref_name(value)),
7414    }
7415}
7416
7417struct CompositionTlaCompiler<'a> {
7418    schema: &'a CompositionSchema,
7419    machine_by_instance: BTreeMap<&'a str, &'a MachineSchema>,
7420    named_bindings: BTreeMap<String, meerkat_machine_schema::RustTypeAtom>,
7421    fallback_machine: &'a MachineSchema,
7422    unchanged_frames: RefCell<UnchangedFrameInterner>,
7423    /// Shared with every machine compiler that renders into this module (see
7424    /// `MachineTlaCompiler::option_order_used`).
7425    option_order_used: Rc<Cell<bool>>,
7426}
7427
7428const COMPOSITION_UNCHANGED_CHUNK_SIZE: usize = 64;
7429const COMPOSITION_UNCHANGED_SPLIT_THRESHOLD: usize = 96;
7430
7431/// Prefix for the generated named UNCHANGED frame operators.
7432///
7433/// Deliberately upper-camel: the machine-poster TLA reader treats a
7434/// `^[a-z_][A-Za-z0-9_]* == ...` line before `THEOREM` as a machine invariant,
7435/// and a line ending in bare `==` as the head of a multi-line definition. An
7436/// upper-case name on a single line is invisible to both.
7437const UNCHANGED_FRAME_PREFIX: &str = "UnchangedFrame_";
7438
7439/// Stable 64-bit FNV-1a.
7440///
7441/// Frame operator names are derived from frame content so that adding or
7442/// removing a transition perturbs exactly the frames it touches instead of
7443/// renumbering every later one. That only holds if the hash itself is stable:
7444/// `std::collections::hash_map::DefaultHasher` is explicitly documented as not
7445/// stable across Rust releases, so a toolchain bump would rename every frame
7446/// and turn `machine-check-drift` red with no source change. FNV-1a is pinned
7447/// here for that reason.
7448fn fnv1a64(bytes: &[u8]) -> u64 {
7449    const OFFSET_BASIS: u64 = 0xcbf2_9ce4_8422_2325;
7450    const PRIME: u64 = 0x0000_0100_0000_01b3;
7451    let mut hash = OFFSET_BASIS;
7452    for byte in bytes {
7453        hash ^= u64::from(*byte);
7454        hash = hash.wrapping_mul(PRIME);
7455    }
7456    hash
7457}
7458
7459/// Renders one UNCHANGED frame as a single TLA line.
7460///
7461/// `chunking` carries the composition-only `(split_threshold, chunk_size)`
7462/// policy: TLC's semantic pass can overflow on very large tuple frames, so a
7463/// composition frame past the threshold is expressed as a conjunction of
7464/// smaller tuples. `/\` is an ordinary infix operator, so the conjunction is
7465/// the same formula as the previously emitted bulleted list. Machines pass
7466/// `None` and keep their single-tuple frame verbatim.
7467fn unchanged_frame_body(vars: &[String], chunking: Option<(usize, usize)>) -> String {
7468    if let Some((split_threshold, chunk_size)) = chunking
7469        && vars.len() > split_threshold
7470    {
7471        return vars
7472            .chunks(chunk_size)
7473            .map(|chunk| format!("UNCHANGED << {} >>", chunk.join(", ")))
7474            .collect::<Vec<_>>()
7475            .join(" /\\ ");
7476    }
7477    format!("UNCHANGED << {} >>", vars.join(", "))
7478}
7479
7480/// Interns the distinct UNCHANGED frames of one generated TLA module.
7481///
7482/// The renderer used to expand a full frame tuple inline at every action. On
7483/// the largest composition that was 32,850 expansions of 650 distinct frames,
7484/// which is where ~85% of the emitted bytes went. Each distinct frame is now
7485/// emitted once as a named operator and referenced by name.
7486#[derive(Default)]
7487struct UnchangedFrameInterner {
7488    /// Frame operator name -> single-line frame body. Names are derived from
7489    /// the body, so a name already bound to a *different* body is a hash
7490    /// collision, never a rename.
7491    frames: BTreeMap<String, String>,
7492    /// First observed collision, if any. Recorded rather than resolved: a
7493    /// counter suffix would be order-dependent across schema edits and, worse,
7494    /// would silently hand one action a different frame condition than it had.
7495    /// The owning `render` turns this into a typed error and emits nothing.
7496    collision: Option<UnchangedFrameCollision>,
7497}
7498
7499/// Two distinct frames that derive the same operator name.
7500#[derive(Debug, Clone, PartialEq, Eq)]
7501pub struct UnchangedFrameCollision {
7502    pub name: String,
7503    pub first: String,
7504    pub second: String,
7505}
7506
7507impl std::fmt::Display for UnchangedFrameCollision {
7508    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
7509        write!(
7510            f,
7511            "frame operator `{}` derives from two different frames:\n  {}\n  {}",
7512            self.name, self.first, self.second
7513        )
7514    }
7515}
7516
7517impl UnchangedFrameInterner {
7518    /// Returns the operator name for `body`, registering the definition on
7519    /// first sight.
7520    fn intern(&mut self, body: String) -> String {
7521        let name = format!("{UNCHANGED_FRAME_PREFIX}{:016x}", fnv1a64(body.as_bytes()));
7522        match self.frames.get(&name) {
7523            Some(existing) if *existing == body => {}
7524            Some(existing) => {
7525                if self.collision.is_none() {
7526                    self.collision = Some(UnchangedFrameCollision {
7527                        name: name.clone(),
7528                        first: existing.clone(),
7529                        second: body,
7530                    });
7531                }
7532            }
7533            None => {
7534                self.frames.insert(name.clone(), body);
7535            }
7536        }
7537        name
7538    }
7539
7540    fn collision(&self) -> Option<&UnchangedFrameCollision> {
7541        self.collision.as_ref()
7542    }
7543
7544    /// Renders the definition block, sorted by operator name.
7545    ///
7546    /// Sorted rather than first-use order so that a later schema edit inserts
7547    /// or drops a single definition line instead of shifting every definition
7548    /// after it. Returns `String::new()` when the module has no frames.
7549    fn definitions_block(&self) -> String {
7550        if self.frames.is_empty() {
7551            return String::new();
7552        }
7553        let mut out = String::new();
7554        pushln!(
7555            &mut out,
7556            "\\* Named UNCHANGED frames. One definition per distinct frame; every action"
7557        );
7558        pushln!(
7559            &mut out,
7560            "\\* that leaves those variables unchanged references the definition by name."
7561        );
7562        for (name, body) in &self.frames {
7563            pushln!(&mut out, "{name} == {body}");
7564        }
7565        pushln!(&mut out);
7566        out
7567    }
7568}
7569
7570impl<'a> CompositionTlaCompiler<'a> {
7571    fn new(
7572        schema: &'a CompositionSchema,
7573        machine_catalog: &'a [MachineSchema],
7574    ) -> Result<Self, String> {
7575        let machine_catalog_by_name = machine_catalog
7576            .iter()
7577            .map(|machine| (machine.machine.as_str(), machine))
7578            .collect::<BTreeMap<_, _>>();
7579
7580        let mut machine_by_instance = BTreeMap::new();
7581        for instance in &schema.machines {
7582            let machine = machine_catalog_by_name
7583                .get(instance.machine_name.as_str())
7584                .copied()
7585                .ok_or_else(|| {
7586                    format!(
7587                        "unknown machine schema `{}` for composition `{}`",
7588                        instance.machine_name, schema.name
7589                    )
7590                })?;
7591            machine_by_instance.insert(instance.instance_id.as_str(), machine);
7592        }
7593        let named_bindings =
7594            collect_composition_named_bindings(machine_by_instance.values().copied());
7595
7596        Ok(Self {
7597            schema,
7598            machine_by_instance,
7599            named_bindings,
7600            fallback_machine: machine_catalog.first().ok_or_else(|| {
7601                format!(
7602                    "no machine catalog available for composition `{}`",
7603                    schema.name
7604                )
7605            })?,
7606            unchanged_frames: RefCell::new(UnchangedFrameInterner::default()),
7607            option_order_used: Rc::default(),
7608        })
7609    }
7610
7611    /// The machine compiler for one instance's part of this module. Every
7612    /// compiler that renders into the module shares its option-order flag, so
7613    /// an `OptionLt` / `OptionLe` call never reaches the module without the
7614    /// definitions.
7615    fn instance_compiler(
7616        &self,
7617        instance_id: &str,
7618        helper_prefix: String,
7619    ) -> MachineTlaCompiler<'_> {
7620        MachineTlaCompiler::new_with_helper_prefix(self.machine(instance_id), helper_prefix)
7621            .with_phase_symbol(self.phase_var(instance_id))
7622            .with_field_env_override(self.machine_field_env(instance_id))
7623            .with_option_order_flag(Rc::clone(&self.option_order_used))
7624    }
7625
7626    fn render_unchanged_vars(&self, out: &mut String, prefix: &str, vars: &[String]) {
7627        if vars.is_empty() {
7628            return;
7629        }
7630        // The frame is interned on its variable list alone and referenced at
7631        // the caller's own `prefix`, so the conjunct keeps its original column.
7632        // Indentation is semantically load-bearing in TLA bulleted lists.
7633        let body = unchanged_frame_body(
7634            vars,
7635            Some((
7636                COMPOSITION_UNCHANGED_SPLIT_THRESHOLD,
7637                COMPOSITION_UNCHANGED_CHUNK_SIZE,
7638            )),
7639        );
7640        let name = self.unchanged_frames.borrow_mut().intern(body);
7641        writeln!(out, "{prefix}{name}").expect("write to string");
7642    }
7643
7644    fn render(&self) -> std::result::Result<String, CompositionTlaError> {
7645        // Fail-closed gate: every route component must resolve against the
7646        // composition schema before any CASE expression is emitted. This makes
7647        // the defensive `OTHER -> "unknown_*"` branches in the generated TLA
7648        // provably unreachable rather than silent catch-alls.
7649        self.validate_routes()?;
7650
7651        let mut out = String::new();
7652        let constants = self.collect_binding_domains();
7653        let named_samples =
7654            collect_composition_named_type_samples(self.schema, &self.machine_by_instance);
7655        let machine_vars = self.machine_vars();
7656        let obligation_vars = self.obligation_vars();
7657        let mut machine_invariant_names = Vec::new();
7658
7659        pushln!(&mut out, "---- MODULE model ----");
7660        pushln!(&mut out, "EXTENDS TLC, Naturals, Sequences, FiniteSets");
7661        pushln!(&mut out);
7662        writeln!(
7663            &mut out,
7664            "\\* Generated composition model for {}.",
7665            self.schema.name
7666        )
7667        .expect("write to string");
7668        pushln!(&mut out);
7669
7670        let mut model_constants = constants
7671            .iter()
7672            .filter(|(_, ty)| {
7673                !matches!(
7674                    ty,
7675                    TypeRef::Seq(_) | TypeRef::Option(_) | TypeRef::Map(_, _)
7676                )
7677            })
7678            .map(|(name, _)| name)
7679            .cloned()
7680            .collect::<Vec<_>>();
7681        if composition_uses_u64_max(self.schema, &self.machine_by_instance) {
7682            model_constants.push(TLA_RUST_U64_MAX_CONSTANT.to_owned());
7683        }
7684        if !model_constants.is_empty() {
7685            if model_constants
7686                .iter()
7687                .any(|constant| constant == TLA_RUST_U64_MAX_CONSTANT)
7688            {
7689                pushln!(
7690                    &mut out,
7691                    "\\* RustU64Max is the TLA boundary for Expr::U64Max; production generated Rust renders u64::MAX."
7692                );
7693            }
7694            writeln!(&mut out, "CONSTANTS {}", model_constants.join(", "))
7695                .expect("write to string");
7696            pushln!(&mut out);
7697        }
7698
7699        writeln!(&mut out, "None == [tag |-> \"none\", value |-> \"none\"]")
7700            .expect("write to string");
7701        writeln!(&mut out, "Some(v) == [tag |-> \"some\", value |-> v]");
7702        pushln!(&mut out);
7703        let option_order_anchor = out.len();
7704
7705        push_cfg_assignment_operator_definitions(
7706            &mut out,
7707            &constants,
7708            &self.named_bindings,
7709            &CfgAssignmentOperatorProfile {
7710                suffix: "Ci".to_owned(),
7711                explicit_values: None,
7712                sample_cardinality: default_sample_cardinality(false),
7713                domain_overrides: None,
7714                named_samples: &named_samples,
7715                include_string_samples: false,
7716            },
7717        );
7718        push_cfg_assignment_operator_definitions(
7719            &mut out,
7720            &constants,
7721            &self.named_bindings,
7722            &CfgAssignmentOperatorProfile {
7723                suffix: "Deep".to_owned(),
7724                explicit_values: None,
7725                sample_cardinality: self.schema.deep_domain_cardinality,
7726                domain_overrides: Some(&self.schema.deep_domain_overrides),
7727                named_samples: &named_samples,
7728                include_string_samples: false,
7729            },
7730        );
7731        for witness in &self.schema.witnesses {
7732            let witness_samples = collect_composition_witness_named_type_samples(
7733                self.schema,
7734                witness,
7735                &self.machine_by_instance,
7736            );
7737            push_cfg_assignment_operator_definitions(
7738                &mut out,
7739                &constants,
7740                &self.named_bindings,
7741                &CfgAssignmentOperatorProfile {
7742                    suffix: witness_cfg_operator_suffix(witness),
7743                    explicit_values: None,
7744                    sample_cardinality: self
7745                        .schema
7746                        .witness_domain_cardinality
7747                        .max(max_named_sample_cardinality(&witness_samples)),
7748                    domain_overrides: None,
7749                    named_samples: &witness_samples,
7750                    include_string_samples: true,
7751                },
7752            );
7753        }
7754        for (name, ty) in ordered_composite_domain_definitions(&constants) {
7755            let definition = match ty {
7756                TypeRef::Seq(inner) => render_sequence_domain_definition(inner),
7757                TypeRef::Option(inner) => render_option_domain_definition(inner),
7758                TypeRef::Map(key, value) => render_map_domain_definition(key, value),
7759                _ => continue,
7760            };
7761            writeln!(&mut out, "{} == {}", name, definition).expect("write to string");
7762        }
7763        if constants.values().any(|ty| {
7764            matches!(
7765                ty,
7766                TypeRef::Seq(_) | TypeRef::Option(_) | TypeRef::Map(_, _)
7767            )
7768        }) {
7769            pushln!(&mut out);
7770        }
7771        writeln!(
7772            &mut out,
7773            "MapLookup(map, key) == IF key \\in DOMAIN map THEN map[key] ELSE None"
7774        )
7775        .expect("write to string");
7776        writeln!(
7777            &mut out,
7778            "MapSet(map, key, value) == [x \\in DOMAIN map \\cup {{key}} |-> IF x = key THEN value ELSE map[x]]"
7779        )
7780        .expect("write to string");
7781        writeln!(
7782            &mut out,
7783            "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]]"
7784        )
7785        .expect("write to string");
7786        writeln!(
7787            &mut out,
7788            "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]]"
7789        )
7790        .expect("write to string");
7791        writeln!(
7792            &mut out,
7793            "MapRemove(map, key) == [x \\in DOMAIN map \\ {{key}} |-> map[x]]"
7794        )
7795        .expect("write to string");
7796        writeln!(
7797            &mut out,
7798            "StartsWith(seq, prefix) == /\\ Len(prefix) <= Len(seq) /\\ SubSeq(seq, 1, Len(prefix)) = prefix"
7799        )
7800        .expect("write to string");
7801        writeln!(
7802            &mut out,
7803            "SeqElements(seq) == {{seq[i] : i \\in 1..Len(seq)}}"
7804        )
7805        .expect("write to string");
7806        writeln!(
7807            &mut out,
7808            "Count(seq, value) == Cardinality({{i \\in DOMAIN seq : seq[i] = value}})"
7809        )
7810        .expect("write to string");
7811        if self.schema.machines.iter().any(|instance| {
7812            !self
7813                .machine(instance.instance_id.as_str())
7814                .tlc_representative_inputs
7815                .is_empty()
7816        }) {
7817            writeln!(
7818                &mut out,
7819                "{TLC_REPRESENTATIVE_DOMAIN_HELPER}(values) == IF values = {{}} THEN {{}} ELSE {{CHOOSE value \\in values : TRUE}}"
7820            )
7821            .expect("write to string");
7822        }
7823        writeln!(
7824            &mut out,
7825            "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)"
7826        )
7827        .expect("write to string");
7828        writeln!(
7829            &mut out,
7830            "RECURSIVE SeqRemoveAll(_, _)\nSeqRemoveAll(seq, values) == IF Len(values) = 0 THEN seq ELSE SeqRemoveAll(SeqRemove(seq, Head(values)), Tail(values))"
7831        )
7832        .expect("write to string");
7833        writeln!(
7834            &mut out,
7835            "AppendIfMissing(seq, value) == IF value \\in SeqElements(seq) THEN seq ELSE Append(seq, value)"
7836        )
7837        .expect("write to string");
7838        self.render_static_sets(&mut out)?;
7839
7840        let all_vars = {
7841            let mut v = machine_vars;
7842            v.extend(obligation_vars.clone());
7843            v.push("model_step_count".into());
7844            v.push("pending_inputs".into());
7845            v.push("observed_inputs".into());
7846            v.push("pending_routes".into());
7847            v.push("delivered_routes".into());
7848            v.push("emitted_effects".into());
7849            v.push("observed_transitions".into());
7850            v.push("witness_current_script_input".into());
7851            v.push("witness_remaining_script_inputs".into());
7852            v
7853        };
7854        writeln!(&mut out, "VARIABLES {}", all_vars.join(", ")).expect("write to string");
7855        writeln!(&mut out, "vars == << {} >>", all_vars.join(", ")).expect("write to string");
7856        pushln!(&mut out);
7857
7858        // Named UNCHANGED frames are spliced back in here once the whole module
7859        // body is rendered: the frames are discovered while rendering actions,
7860        // but TLA requires an operator to be defined before it is referenced.
7861        // This is the first point where every frame variable is in scope.
7862        let unchanged_frame_anchor = out.len();
7863
7864        writeln!(
7865            &mut out,
7866            "RoutePackets == SeqElements(pending_routes) \\cup delivered_routes"
7867        )
7868        .expect("write to string");
7869        writeln!(
7870            &mut out,
7871            "PendingActors == {{ActorOfMachine(packet.machine) : packet \\in SeqElements(pending_inputs)}}"
7872        )
7873        .expect("write to string");
7874        writeln!(
7875            &mut out,
7876            "HigherPriorityReady(actor) == \\E priority \\in ActorPriorities : /\\ priority[2] = actor /\\ priority[1] \\in PendingActors"
7877        )
7878        .expect("write to string");
7879        pushln!(&mut out);
7880
7881        pushln!(&mut out, "BaseInit ==");
7882        for instance in &self.schema.machines {
7883            let machine = self.machine(instance.instance_id.as_str());
7884            writeln!(
7885                &mut out,
7886                "    /\\ {} = {}",
7887                self.phase_var(instance.instance_id.as_str()),
7888                tla_string(&machine.state.init.phase)
7889            )
7890            .expect("write to string");
7891            for field in &machine.state.fields {
7892                let init_expr = machine
7893                    .state
7894                    .init
7895                    .fields
7896                    .iter()
7897                    .find(|item| item.field == field.name)
7898                    .map(|item| {
7899                        let compiler = self.instance_compiler(
7900                            instance.instance_id.as_str(),
7901                            format!("{}__", tla_ident(&instance.instance_id)),
7902                        );
7903                        compiler.render_expr(&item.expr, &BTreeMap::new(), &BTreeMap::new())
7904                    })
7905                    .unwrap_or_else(|| default_state_init_expr(&field.ty));
7906                writeln!(
7907                    &mut out,
7908                    "    /\\ {} = {}",
7909                    self.field_var(instance.instance_id.as_str(), field.name.as_str()),
7910                    init_expr
7911                )
7912                .expect("write to string");
7913            }
7914        }
7915        for var in &obligation_vars {
7916            pushln!(&mut out, "    /\\ {} = {{}}", var);
7917        }
7918        pushln!(&mut out, "    /\\ model_step_count = 0");
7919        pushln!(&mut out, "    /\\ pending_routes = <<>>");
7920        pushln!(&mut out, "    /\\ delivered_routes = {{}}");
7921        pushln!(&mut out, "    /\\ emitted_effects = {{}}");
7922        pushln!(&mut out, "    /\\ observed_transitions = {{}}");
7923        pushln!(&mut out);
7924
7925        pushln!(&mut out, "Init ==");
7926        pushln!(&mut out, "    /\\ BaseInit");
7927        pushln!(&mut out, "    /\\ pending_inputs = <<>>");
7928        pushln!(&mut out, "    /\\ observed_inputs = {{}}");
7929        pushln!(&mut out, "    /\\ witness_current_script_input = None");
7930        pushln!(&mut out, "    /\\ witness_remaining_script_inputs = <<>>");
7931        pushln!(&mut out);
7932
7933        for witness in &self.schema.witnesses {
7934            writeln!(
7935                &mut out,
7936                "{} ==",
7937                composition_witness_init_name(&witness.name)
7938            )
7939            .expect("write to string");
7940            writeln!(&mut out, "    /\\ BaseInit");
7941            writeln!(
7942                &mut out,
7943                "    /\\ pending_inputs = {}",
7944                self.witness_initial_pending_inputs_expr(witness)
7945            )
7946            .expect("write to string");
7947            writeln!(
7948                &mut out,
7949                "    /\\ observed_inputs = {}",
7950                self.witness_initial_observed_inputs_expr(witness)
7951            )
7952            .expect("write to string");
7953            writeln!(
7954                &mut out,
7955                "    /\\ witness_current_script_input = {}",
7956                self.witness_current_script_input_expr(witness)
7957            )
7958            .expect("write to string");
7959            writeln!(
7960                &mut out,
7961                "    /\\ witness_remaining_script_inputs = {}",
7962                self.witness_remaining_script_inputs_expr(witness)
7963            )
7964            .expect("write to string");
7965            pushln!(&mut out);
7966        }
7967
7968        for instance in &self.schema.machines {
7969            let machine = self.machine(instance.instance_id.as_str());
7970            let helper_prefix = format!("{}__", tla_ident(&instance.instance_id));
7971            let mut compiler = self.instance_compiler(instance.instance_id.as_str(), helper_prefix);
7972            for derived in helper_dependency_order(machine)? {
7973                compiler.render_helper(&mut out, derived);
7974                pushln!(&mut out);
7975            }
7976            if machine.machine.as_str() == "MobMachine" {
7977                compiler.render_mob_machine_native_helpers(&mut out);
7978                pushln!(&mut out);
7979            }
7980            if machine.machine.as_str() == "MeerkatMachine" {
7981                compiler.render_meerkat_machine_native_helpers(&mut out);
7982                pushln!(&mut out);
7983            }
7984            if machine.machine.as_str() == "RuntimeDeliveryMachine" {
7985                compiler.render_runtime_delivery_native_helpers(&mut out);
7986                pushln!(&mut out);
7987            }
7988            if machine.machine.as_str() == "SessionDocumentMachine" {
7989                compiler.render_session_document_native_helpers(&mut out);
7990                pushln!(&mut out);
7991            }
7992
7993            let mut rendered_actions = Vec::new();
7994            for transition in &machine.transitions {
7995                let mut action = String::new();
7996                self.render_machine_transition_action(
7997                    &mut compiler,
7998                    instance.instance_id.as_str(),
7999                    transition,
8000                    &mut action,
8001                )?;
8002                rendered_actions.push(action);
8003            }
8004
8005            for helper in &compiler.helper_defs {
8006                pushln!(&mut out, "{helper}");
8007                pushln!(&mut out);
8008            }
8009
8010            for action in &rendered_actions {
8011                pushln!(&mut out, "{action}");
8012                pushln!(&mut out);
8013            }
8014
8015            let invariant_field_env = self.machine_field_env(instance.instance_id.as_str());
8016            let invariant_binding_env = BTreeMap::new();
8017            let invariant_types = BTreeMap::new();
8018            for invariant in &machine.invariants {
8019                let invariant_name =
8020                    self.machine_invariant_name(instance.instance_id.as_str(), &invariant.name);
8021                machine_invariant_names.push(invariant_name.clone());
8022                writeln!(
8023                    &mut out,
8024                    "{} == {}",
8025                    invariant_name,
8026                    compiler.render_expr_with_types(
8027                        &invariant.expr,
8028                        &invariant_field_env,
8029                        &invariant_binding_env,
8030                        &invariant_types
8031                    )
8032                )
8033                .expect("write to string");
8034            }
8035            if !machine.invariants.is_empty() {
8036                pushln!(&mut out);
8037            }
8038        }
8039
8040        self.render_entry_packet_admissibility_helpers(&mut out)?;
8041        self.render_entry_input_actions(&mut out);
8042        self.render_deliver_queued_route_action(&mut out);
8043        self.render_reject_pending_entry_input_action(&mut out);
8044        self.render_quiescent_stutter(&mut out);
8045        self.render_witness_inject_actions(&mut out);
8046        self.render_witness_completion_operators(&mut out);
8047        self.render_witness_action_constraint_operators(&mut out);
8048        self.render_witness_satisfied_stutter_actions(&mut out);
8049        // TLA+ does not permit action references before their definitions.
8050        // Owner-feedback actions participate in CoreNext and witness Next, so
8051        // render them before either dispatcher is declared.
8052        self.render_owner_actor_processes(&mut out)?;
8053
8054        let core_next_branches = self.core_next_branches();
8055
8056        pushln!(&mut out, "CoreNext ==");
8057        for branch in &core_next_branches {
8058            pushln!(&mut out, "    \\/ {branch}");
8059        }
8060        pushln!(&mut out);
8061
8062        let inject_branches = self
8063            .schema
8064            .entry_inputs
8065            .iter()
8066            .map(|entry_input| self.render_entry_input_call(entry_input))
8067            .collect::<Vec<_>>();
8068
8069        pushln!(&mut out, "InjectNext ==");
8070        if inject_branches.is_empty() {
8071            pushln!(&mut out, "    FALSE");
8072        } else {
8073            for branch in &inject_branches {
8074                pushln!(&mut out, "    \\/ {branch}");
8075            }
8076        }
8077        pushln!(&mut out);
8078
8079        pushln!(&mut out, "Next ==");
8080        pushln!(&mut out, "    \\/ CoreNext");
8081        if !inject_branches.is_empty() {
8082            pushln!(&mut out, "    \\/ InjectNext");
8083        }
8084        pushln!(&mut out);
8085
8086        for witness in &self.schema.witnesses {
8087            let witness_branches = self.witness_next_branches(witness)?;
8088            writeln!(
8089                &mut out,
8090                "{} ==",
8091                composition_witness_next_name(&witness.name)
8092            )
8093            .expect("write to string");
8094            for branch in &witness_branches {
8095                pushln!(&mut out, "    \\/ {branch}");
8096            }
8097            writeln!(
8098                &mut out,
8099                "    \\/ {}",
8100                self.render_witness_inject_next_call(witness)
8101            )
8102            .expect("write to string");
8103            pushln!(&mut out);
8104        }
8105        pushln!(&mut out);
8106
8107        for invariant in &self.schema.invariants {
8108            writeln!(
8109                &mut out,
8110                "{} == {}",
8111                invariant.name,
8112                render_composition_invariant_formula(self.schema, &invariant.kind)
8113            )
8114            .expect("write to string");
8115        }
8116        if !self.schema.invariants.is_empty() {
8117            pushln!(&mut out);
8118        }
8119
8120        self.render_obligation_invariants(&mut out, &mut machine_invariant_names)?;
8121
8122        self.render_coverage_instrumentation(&mut out);
8123
8124        writeln!(
8125            &mut out,
8126            "CiStateConstraint == {}",
8127            render_composition_state_constraint(
8128                self.schema,
8129                self.schema
8130                    .ci_limits
8131                    .as_ref()
8132                    .unwrap_or(&CompositionStateLimits::ci_defaults()),
8133                self
8134            )
8135        )
8136        .expect("write to string");
8137        writeln!(
8138            &mut out,
8139            "DeepStateConstraint == {}",
8140            render_composition_state_constraint(
8141                self.schema,
8142                &composition_deep_state_limits(self.schema),
8143                self
8144            )
8145        )
8146        .expect("write to string");
8147        for witness in &self.schema.witnesses {
8148            writeln!(
8149                &mut out,
8150                "{} == {}",
8151                composition_witness_state_constraint_name(&witness.name),
8152                render_composition_state_constraint(
8153                    self.schema,
8154                    &effective_composition_state_limits(&witness.state_limits, Some(witness)),
8155                    self
8156                )
8157            )
8158            .expect("write to string");
8159        }
8160        pushln!(&mut out);
8161
8162        pushln!(&mut out, "Spec ==");
8163        pushln!(&mut out, "    /\\ Init");
8164        pushln!(&mut out, "    /\\ [][Next]_vars");
8165        pushln!(&mut out);
8166
8167        for witness in &self.schema.witnesses {
8168            let fairness_clauses = self.witness_fairness_clauses(witness)?;
8169            let fairness_chunk_names = fairness_clauses
8170                .chunks(24)
8171                .enumerate()
8172                .map(|(index, chunk)| {
8173                    let chunk_name = composition_witness_fairness_name(&witness.name, index);
8174                    writeln!(&mut out, "{chunk_name} ==").expect("write to string");
8175                    for clause in chunk {
8176                        writeln!(&mut out, "    /\\ WF_vars({clause})").expect("write to string");
8177                    }
8178                    pushln!(&mut out);
8179                    chunk_name
8180                })
8181                .collect::<Vec<_>>();
8182
8183            writeln!(
8184                &mut out,
8185                "{} ==",
8186                composition_witness_spec_name(&witness.name),
8187            )
8188            .expect("write to string");
8189            writeln!(
8190                &mut out,
8191                "    /\\ {}",
8192                composition_witness_init_name(&witness.name),
8193            )
8194            .expect("write to string");
8195            writeln!(
8196                &mut out,
8197                "    /\\ [] [{}]_vars",
8198                composition_witness_next_name(&witness.name)
8199            )
8200            .expect("write to string");
8201            for chunk_name in fairness_chunk_names {
8202                writeln!(&mut out, "    /\\ {chunk_name}").expect("write to string");
8203            }
8204            pushln!(&mut out);
8205        }
8206        for witness in &self.schema.witnesses {
8207            for route in &witness.expected_routes {
8208                let formula = composition_route_observed_operator_name(route);
8209                writeln!(
8210                    &mut out,
8211                    "{} == {}",
8212                    composition_witness_route_property_name(&witness.name, route),
8213                    self.render_witness_obligation_formula(witness, formula)
8214                )
8215                .expect("write to string");
8216            }
8217            for rule in &witness.expected_scheduler_rules {
8218                let formula = composition_scheduler_triggered_operator_name(rule);
8219                writeln!(
8220                    &mut out,
8221                    "{} == {}",
8222                    composition_witness_scheduler_property_name(&witness.name, rule),
8223                    self.render_witness_obligation_formula(witness, formula)
8224                )
8225                .expect("write to string");
8226            }
8227            for (idx, state) in witness.expected_states.iter().enumerate() {
8228                let formula = self.render_witness_state_formula(state);
8229                writeln!(
8230                    &mut out,
8231                    "{} == {}",
8232                    composition_witness_state_property_name(&witness.name, idx),
8233                    self.render_witness_obligation_formula(witness, formula)
8234                )
8235                .expect("write to string");
8236            }
8237            for transition in &witness.expected_transitions {
8238                let formula = self.render_witness_transition_formula(transition);
8239                writeln!(
8240                    &mut out,
8241                    "{} == {}",
8242                    composition_witness_transition_property_name(
8243                        &witness.name,
8244                        &transition.machine,
8245                        &transition.transition,
8246                    ),
8247                    self.render_witness_obligation_formula(witness, formula)
8248                )
8249                .expect("write to string");
8250            }
8251            for (idx, ordering) in witness.expected_transition_order.iter().enumerate() {
8252                let formula = self.render_witness_transition_order_formula(ordering);
8253                writeln!(
8254                    &mut out,
8255                    "{} == {}",
8256                    composition_witness_transition_order_property_name(&witness.name, idx),
8257                    self.render_witness_obligation_formula(witness, formula)
8258                )
8259                .expect("write to string");
8260            }
8261        }
8262        if !self.schema.witnesses.is_empty() {
8263            pushln!(&mut out);
8264        }
8265        for invariant in &self.schema.invariants {
8266            pushln!(&mut out, "THEOREM Spec => []{}", invariant.name);
8267        }
8268        for invariant_name in &machine_invariant_names {
8269            pushln!(&mut out, "THEOREM Spec => []{}", invariant_name);
8270        }
8271        pushln!(&mut out);
8272        writeln!(
8273            &mut out,
8274            "============================================================================="
8275        )
8276        .expect("write to string");
8277
8278        // Fail closed on a frame-name collision: the rendered body already
8279        // references one name for two different frames, so returning it would
8280        // silently give an action the wrong frame condition.
8281        let frames = self.unchanged_frames.borrow();
8282        if let Some(collision) = frames.collision() {
8283            return Err(CompositionTlaError::UnchangedFrameCollision {
8284                composition: self.schema.name.as_str().to_owned(),
8285                collision: collision.clone(),
8286            });
8287        }
8288        out.insert_str(unchanged_frame_anchor, &frames.definitions_block());
8289        // Before the frame anchor, so inserting it last leaves that one valid.
8290        if self.option_order_used.get() {
8291            out.insert_str(option_order_anchor, TLA_OPTION_ORDER_DEFINITIONS);
8292        }
8293
8294        Ok(out)
8295    }
8296
8297    fn collect_binding_domains(&self) -> BTreeMap<String, TypeRef> {
8298        collect_composition_binding_domains(self.schema, &self.machine_by_instance)
8299    }
8300
8301    fn machine(&self, instance_id: impl AsRef<str>) -> &MachineSchema {
8302        self.machine_by_instance
8303            .get(instance_id.as_ref())
8304            .copied()
8305            .unwrap_or(self.fallback_machine)
8306    }
8307
8308    fn actor(&self, instance_id: impl AsRef<str>) -> &str {
8309        let instance_id = instance_id.as_ref();
8310        self.schema
8311            .machines
8312            .iter()
8313            .find(|machine| machine.instance_id.as_str() == instance_id)
8314            .map(|machine| machine.actor.as_str())
8315            .unwrap_or("")
8316    }
8317
8318    fn phase_var(&self, instance_id: impl AsRef<str>) -> String {
8319        format!("{}_phase", tla_ident(instance_id))
8320    }
8321
8322    fn field_var(&self, instance_id: impl AsRef<str>, field: impl AsRef<str>) -> String {
8323        format!("{}_{}", tla_ident(instance_id), tla_ident(field))
8324    }
8325
8326    fn machine_invariant_name(
8327        &self,
8328        instance_id: impl AsRef<str>,
8329        invariant: impl AsRef<str>,
8330    ) -> String {
8331        format!("{}_{}", tla_ident(instance_id), tla_ident(invariant))
8332    }
8333
8334    fn machine_transition_name(
8335        &self,
8336        instance_id: impl AsRef<str>,
8337        transition: &TransitionSchema,
8338    ) -> String {
8339        format!("{}_{}", tla_ident(instance_id), tla_ident(&transition.name))
8340    }
8341
8342    fn machine_transition_call(&self, instance_id: &str, transition: &TransitionSchema) -> String {
8343        if transition.on.bindings().is_empty() {
8344            self.machine_transition_name(instance_id, transition)
8345        } else {
8346            let binding_types = transition_trigger_variant(self.machine(instance_id), transition)
8347                .map(|variant| {
8348                    variant
8349                        .fields
8350                        .iter()
8351                        .filter(|field| {
8352                            transition
8353                                .on
8354                                .bindings()
8355                                .iter()
8356                                .any(|binding| binding == &field.name)
8357                        })
8358                        .map(|field| (field.name.as_str().to_owned(), field.ty.clone()))
8359                        .collect::<BTreeMap<_, _>>()
8360                })
8361                .unwrap_or_default();
8362            let forced_bool_literals = transition_forced_bool_literals(transition, &binding_types);
8363            let mut prefix = String::new();
8364            for binding in transition.on.bindings() {
8365                if forced_bool_literals.contains_key(binding.as_str()) {
8366                    continue;
8367                }
8368                let local = format!("arg_{}", tla_ident(binding.as_str()));
8369                let Some(ty) = binding_types.get(binding.as_str()) else {
8370                    return self.machine_transition_name(instance_id, transition);
8371                };
8372                let domain = self.binding_domain_for_binding(
8373                    instance_id,
8374                    trigger_input_variant(transition),
8375                    binding.as_str(),
8376                    ty,
8377                );
8378                let domain = if transition_uses_tlc_representative_payload(
8379                    self.machine(instance_id),
8380                    transition,
8381                ) {
8382                    tlc_representative_domain(domain)
8383                } else {
8384                    domain
8385                };
8386                push_fmt(&mut prefix, format_args!("\\E {local} \\in {domain} : "));
8387            }
8388            let args = transition
8389                .on
8390                .bindings()
8391                .iter()
8392                .map(|binding| {
8393                    forced_bool_literals
8394                        .get(binding.as_str())
8395                        .map(|value| tla_bool_literal(*value).to_owned())
8396                        .unwrap_or_else(|| format!("arg_{}", tla_ident(binding.as_str())))
8397                })
8398                .collect::<Vec<_>>()
8399                .join(", ");
8400            format!(
8401                "{prefix}{}({args})",
8402                self.machine_transition_name(instance_id, transition)
8403            )
8404        }
8405    }
8406
8407    fn binding_domain_for_type(&self, ty: &TypeRef) -> String {
8408        match ty {
8409            TypeRef::Bool => "BOOLEAN".into(),
8410            TypeRef::U32 | TypeRef::U64 => "0..2".into(),
8411            TypeRef::String => "StringValues".into(),
8412            TypeRef::Named(_)
8413            | TypeRef::Enum(_)
8414            | TypeRef::Seq(_)
8415            | TypeRef::Set(_)
8416            | TypeRef::Option(_)
8417            | TypeRef::Map(_, _) => domain_constant_name(ty),
8418        }
8419    }
8420
8421    /// Payload domain for one bound field of `input` on `instance_id`: the
8422    /// machine's declared input field domain if it has one, otherwise the
8423    /// type's default domain.
8424    fn binding_domain_for_binding(
8425        &self,
8426        instance_id: &str,
8427        input: Option<&str>,
8428        binding: &str,
8429        ty: &TypeRef,
8430    ) -> String {
8431        let declared =
8432            input.and_then(|input| self.machine(instance_id).input_field_domain(input, binding));
8433        match declared {
8434            Some(meerkat_machine_schema::InputFieldDomainKind::StateField(state_field)) => {
8435                format!("{{{}}}", self.field_var(instance_id, state_field.as_str()))
8436            }
8437            Some(meerkat_machine_schema::InputFieldDomainKind::AdditionalValues(values)) => {
8438                additional_values_domain(&self.binding_domain_for_type(ty), values)
8439            }
8440            // A composition has no machine CI profile: it explores the
8441            // field's Deep samples, the declared values and `0..2`.
8442            Some(meerkat_machine_schema::InputFieldDomainKind::CiValues(values)) => {
8443                render_u64_set(&broad_input_samples(values))
8444            }
8445            // ... and the whole type domain of a `CiSamples` field.
8446            Some(meerkat_machine_schema::InputFieldDomainKind::CiSamples(_)) | None => {
8447                self.binding_domain_for_type(ty)
8448            }
8449        }
8450    }
8451
8452    fn machine_vars(&self) -> Vec<String> {
8453        let mut vars = Vec::new();
8454        for instance in &self.schema.machines {
8455            vars.push(self.phase_var(instance.instance_id.as_str()));
8456            let machine = self.machine(instance.instance_id.as_str());
8457            for field in &machine.state.fields {
8458                vars.push(self.field_var(instance.instance_id.as_str(), field.name.as_str()));
8459            }
8460        }
8461        vars
8462    }
8463
8464    fn machine_field_env(&self, instance_id: &str) -> BTreeMap<String, String> {
8465        let machine = self.machine(instance_id);
8466        machine
8467            .state
8468            .fields
8469            .iter()
8470            .map(|field| {
8471                (
8472                    field.name.as_str().to_owned(),
8473                    self.field_var(instance_id, field.name.as_str()),
8474                )
8475            })
8476            .collect()
8477    }
8478
8479    fn obligation_symbol_suffix(
8480        &self,
8481        protocol: &meerkat_machine_schema::EffectHandoffProtocol,
8482    ) -> String {
8483        format!(
8484            "{}_{}",
8485            tla_ident(&protocol.producer_instance),
8486            tla_ident(&protocol.name)
8487        )
8488    }
8489
8490    fn obligation_var(&self, protocol: &meerkat_machine_schema::EffectHandoffProtocol) -> String {
8491        format!("obligation_{}", self.obligation_symbol_suffix(protocol))
8492    }
8493
8494    /// Returns TLA+ variable names for obligation tracking — one per
8495    /// concrete producer/protocol pair.
8496    fn obligation_vars(&self) -> Vec<String> {
8497        self.schema
8498            .handoff_protocols
8499            .iter()
8500            .map(|protocol| self.obligation_var(protocol))
8501            .collect()
8502    }
8503
8504    fn feedback_variant(
8505        &self,
8506        feedback: &FeedbackInputRef,
8507    ) -> std::result::Result<&VariantSchema, String> {
8508        self.machine(&feedback.machine_instance)
8509            .inputs
8510            .variant_named(&feedback.input_variant)
8511            .map_err(|_| {
8512                format!(
8513                    "feedback variant `{}` not found for machine `{}`",
8514                    feedback.input_variant, feedback.machine_instance
8515                )
8516            })
8517    }
8518
8519    /// The feedback input's payload record, the quantifiers over the values it
8520    /// leaves open, and the obligation members it names. An `ObligationMember`
8521    /// value ranges over that set field of the obligation token, so the owner
8522    /// can only name a member the obligation actually carries.
8523    fn feedback_payload_expr(
8524        &self,
8525        feedback: &FeedbackInputRef,
8526        token_var: &str,
8527    ) -> std::result::Result<FeedbackPayload, String> {
8528        let variant = self.feedback_variant(feedback)?;
8529        let mut owner_context_quantifiers = Vec::new();
8530        let mut payload_fields = Vec::new();
8531        let mut members = Vec::new();
8532
8533        for field in &variant.fields {
8534            let binding = feedback
8535                .field_bindings
8536                .iter()
8537                .find(|binding| binding.input_field == field.name)
8538                .ok_or_else(|| format!("feedback binding for field `{}` not found", field.name))?;
8539            let expr = match &binding.source {
8540                FeedbackFieldSource::ObligationField(source_field) => {
8541                    format!("{token_var}.{}", tla_ident(source_field))
8542                }
8543                FeedbackFieldSource::ObligationMember(source_field) => {
8544                    let var_name = format!("member_{}", tla_ident(source_field));
8545                    owner_context_quantifiers.push(format!(
8546                        "{var_name} \\in {token_var}.{}",
8547                        tla_ident(source_field)
8548                    ));
8549                    members.push((tla_ident(source_field), var_name.clone()));
8550                    var_name
8551                }
8552                FeedbackFieldSource::OwnerContext(name) => {
8553                    let var_name = format!("owner_ctx_{}", tla_ident(name));
8554                    let domain = render_type_domain_expr(&field.ty);
8555                    owner_context_quantifiers.push(format!("{var_name} \\in {domain}"));
8556                    var_name
8557                }
8558            };
8559            payload_fields.push(format!("{} |-> {}", tla_ident(&field.name), expr));
8560        }
8561
8562        let payload_expr = if payload_fields.is_empty() {
8563            "[tag |-> \"unit\"]".to_string()
8564        } else {
8565            format!("[{}]", payload_fields.join(", "))
8566        };
8567
8568        Ok(FeedbackPayload {
8569            payload_expr,
8570            quantifiers: owner_context_quantifiers,
8571            members,
8572        })
8573    }
8574
8575    /// Obligation fields some feedback input of `protocol` names members of.
8576    /// The obligation token stays open while any of them is non-empty.
8577    fn protocol_member_fields(
8578        protocol: &meerkat_machine_schema::EffectHandoffProtocol,
8579    ) -> BTreeSet<String> {
8580        protocol
8581            .allowed_feedback_inputs
8582            .iter()
8583            .flat_map(|feedback| feedback.field_bindings.iter())
8584            .filter_map(|binding| match &binding.source {
8585                FeedbackFieldSource::ObligationMember(field) => Some(tla_ident(field)),
8586                _ => None,
8587            })
8588            .collect()
8589    }
8590
8591    /// Renders obligation closure invariants into the TLA+ output.
8592    ///
8593    /// For each handoff protocol, generates:
8594    /// - `NoOpenObligationsOnTerminal_<protocol>`: when the producer machine is
8595    ///   in a terminal phase, the obligation set must be empty.
8596    /// - `NoFeedbackWithoutObligation_<protocol>`: a feedback input can only be
8597    ///   observed if there's a corresponding outstanding obligation.
8598    fn render_obligation_invariants(
8599        &self,
8600        out: &mut String,
8601        invariant_names: &mut Vec<String>,
8602    ) -> std::result::Result<(), String> {
8603        for protocol in &self.schema.handoff_protocols {
8604            let suffix = self.obligation_symbol_suffix(protocol);
8605            let var = self.obligation_var(protocol);
8606            let phase_var = self.phase_var(&protocol.producer_instance);
8607
8608            // Find terminal phases for the producer machine.
8609            let machine = self.machine(&protocol.producer_instance);
8610            let terminal_phases: Vec<&str> = machine
8611                .state
8612                .terminal_phases
8613                .iter()
8614                .map(meerkat_machine_schema::identity::PhaseId::as_str)
8615                .collect();
8616
8617            // NoOpenObligationsOnTerminal: terminal phase => obligation set is
8618            // empty. Only an AckRequired protocol needs owner feedback to close
8619            // its obligations; under AckOrAbort and TerminalClosure the terminal
8620            // phase is itself the closure, and a PublicationOnly protocol has no
8621            // feedback (the publication closes it), so for those the invariant
8622            // would be unsatisfiable once the producer reaches a terminal phase.
8623            if terminal_closure_required(protocol, machine) {
8624                let inv_name = format!("NoOpenObligationsOnTerminal_{}", suffix);
8625                let terminal_disjuncts: Vec<String> = terminal_phases
8626                    .iter()
8627                    .map(|phase| format!("{} = {}", phase_var, tla_string(phase)))
8628                    .collect();
8629                writeln!(
8630                    out,
8631                    "{} == ({}) => {} = {{}}",
8632                    inv_name,
8633                    terminal_disjuncts.join(" \\/ "),
8634                    var
8635                )
8636                .expect("write to string");
8637                invariant_names.push(inv_name);
8638            }
8639        }
8640
8641        let owner_feedback_sources = self
8642            .schema
8643            .handoff_protocols
8644            .iter()
8645            .flat_map(|protocol| {
8646                protocol.allowed_feedback_inputs.iter().map(move |feedback| {
8647                    format!(
8648                        "(/\\ 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)",
8649                        tla_string(&feedback.machine_instance),
8650                        tla_string(&feedback.input_variant),
8651                        tla_string(&protocol.producer_instance),
8652                        tla_string(&protocol.effect_variant),
8653                        tla_string(&protocol.producer_instance),
8654                        tla_string(&protocol.effect_variant),
8655                    )
8656                })
8657            })
8658            .collect::<Vec<_>>();
8659        if !owner_feedback_sources.is_empty() {
8660            pushln!(out, "OwnerFeedbackHasProtocolProvenance ==");
8661            pushln!(out, "    \\A input_packet \\in observed_inputs :");
8662            pushln!(out, "        input_packet.source_kind /= \"owner\"");
8663            writeln!(
8664                out,
8665                "        \\/ ({})",
8666                owner_feedback_sources.join(" \\/ ")
8667            )
8668            .expect("write to string");
8669            invariant_names.push("OwnerFeedbackHasProtocolProvenance".to_string());
8670        }
8671
8672        if !self.schema.handoff_protocols.is_empty() {
8673            pushln!(out);
8674        }
8675        Ok(())
8676    }
8677
8678    /// Renders owner-actor process definitions: nondeterministic actions that
8679    /// model the owner choosing to submit protocol-allowed feedback when an
8680    /// obligation is outstanding.
8681    ///
8682    /// Each allowed feedback input generates an
8683    /// `OwnerFeedback_<protocol>_<input>` action that:
8684    /// - Is enabled when the obligation set is non-empty
8685    /// - Nondeterministically picks one of the allowed feedback inputs
8686    /// - Removes one obligation token from the set
8687    /// - Injects the feedback as a pending input
8688    ///
8689    /// If any protocols have `liveness_annotation`, fairness comments are added.
8690    fn render_owner_actor_processes(&self, out: &mut String) -> std::result::Result<(), String> {
8691        for protocol in &self.schema.handoff_protocols {
8692            let var = self.obligation_var(protocol);
8693
8694            if protocol.allowed_feedback_inputs.is_empty() {
8695                continue;
8696            }
8697
8698            if let Some(liveness) = &protocol.liveness_annotation {
8699                writeln!(out, "\\* Liveness: {liveness}").expect("write to string");
8700            }
8701
8702            for feedback in &protocol.allowed_feedback_inputs {
8703                let action_name = self.owner_feedback_action_name(protocol, feedback);
8704                let FeedbackPayload {
8705                    payload_expr,
8706                    quantifiers: owner_context_quantifiers,
8707                    members,
8708                } = self.feedback_payload_expr(feedback, "token")?;
8709                let input_expr = format!(
8710                    "[machine |-> {}, variant |-> {}, source_kind |-> \"owner\", source_machine |-> {}, source_effect |-> {}, source_route |-> \"none\", effect_id |-> token.effect_id, payload |-> {}]",
8711                    tla_string(&feedback.machine_instance),
8712                    tla_string(&feedback.input_variant),
8713                    tla_string(&protocol.producer_instance),
8714                    tla_string(&protocol.effect_variant),
8715                    payload_expr,
8716                );
8717
8718                writeln!(out, "{action_name} ==").expect("write to string");
8719                writeln!(out, "    /\\ {} /= {{}}", var).expect("write to string");
8720                writeln!(out, "    /\\ \\E token \\in {} :", var).expect("write to string");
8721                let quantifier_prefix = if owner_context_quantifiers.is_empty() {
8722                    String::new()
8723                } else {
8724                    format!("\\E {} : ", owner_context_quantifiers.join(", "))
8725                };
8726                // Feedback naming obligation members discharges only those
8727                // members; the token closes once every member-bearing field of
8728                // the protocol is empty. Other feedback closes the token.
8729                let obligation_update = if members.is_empty() {
8730                    format!("{var}' = {var} \\ {{token}}")
8731                } else {
8732                    let residual = format!(
8733                        "[token EXCEPT {}]",
8734                        members
8735                            .iter()
8736                            .map(|(field, member)| format!("!.{field} = @ \\ {{{member}}}"))
8737                            .collect::<Vec<_>>()
8738                            .join(", ")
8739                    );
8740                    let drained = Self::protocol_member_fields(protocol)
8741                        .iter()
8742                        .map(|field| format!("{residual}.{field} = {{}}"))
8743                        .collect::<Vec<_>>()
8744                        .join(" /\\ ");
8745                    // Parenthesised: an unbracketed ELSE would swallow the
8746                    // conjuncts that follow it in the action.
8747                    format!(
8748                        "{var}' = (IF {drained} THEN {var} \\ {{token}} ELSE ({var} \\ {{token}}) \\cup {{{residual}}})"
8749                    )
8750                };
8751                writeln!(
8752                    out,
8753                    "        /\\ {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)"
8754                )
8755                .expect("write to string");
8756
8757                let unchanged_vars: Vec<String> = self
8758                    .machine_vars()
8759                    .into_iter()
8760                    .chain(self.obligation_vars().into_iter().filter(|v| *v != var))
8761                    .chain(
8762                        [
8763                            "pending_routes",
8764                            "delivered_routes",
8765                            "emitted_effects",
8766                            "observed_transitions",
8767                            "witness_current_script_input",
8768                            "witness_remaining_script_inputs",
8769                        ]
8770                        .iter()
8771                        .map(std::string::ToString::to_string),
8772                    )
8773                    .collect();
8774                self.render_unchanged_vars(out, "    /\\ ", &unchanged_vars);
8775                pushln!(out);
8776            }
8777        }
8778        Ok(())
8779    }
8780
8781    fn render_coverage_instrumentation(&self, out: &mut String) {
8782        let route_ops = self
8783            .schema
8784            .routes
8785            .iter()
8786            .map(|route| composition_route_coverage_operator_name(&route.name))
8787            .collect::<Vec<_>>();
8788        let scheduler_ops = self
8789            .schema
8790            .scheduler_rules
8791            .iter()
8792            .map(composition_scheduler_coverage_operator_name)
8793            .collect::<Vec<_>>();
8794
8795        for route in &self.schema.routes {
8796            writeln!(
8797                out,
8798                "{} == \\E packet \\in delivered_routes : packet.route = {}",
8799                composition_route_observed_operator_name(&route.name),
8800                tla_string(&route.name)
8801            )
8802            .expect("write to string");
8803            writeln!(
8804                out,
8805                "{} == ({} \\/ ~{})",
8806                composition_route_coverage_operator_name(&route.name),
8807                composition_route_observed_operator_name(&route.name),
8808                composition_route_observed_operator_name(&route.name)
8809            )
8810            .expect("write to string");
8811        }
8812        for rule in &self.schema.scheduler_rules {
8813            writeln!(
8814                out,
8815                "{} == {}",
8816                composition_scheduler_triggered_operator_name(rule),
8817                render_scheduler_trigger_formula(rule)
8818            )
8819            .expect("write to string");
8820            writeln!(
8821                out,
8822                "{} == ({} \\/ ~{})",
8823                composition_scheduler_coverage_operator_name(rule),
8824                composition_scheduler_triggered_operator_name(rule),
8825                composition_scheduler_triggered_operator_name(rule)
8826            )
8827            .expect("write to string");
8828        }
8829
8830        let mut instrumentation_terms = Vec::new();
8831        instrumentation_terms.extend(route_ops.into_iter());
8832        instrumentation_terms.extend(scheduler_ops.into_iter());
8833
8834        let instrumentation = if instrumentation_terms.is_empty() {
8835            "TRUE".to_string()
8836        } else {
8837            instrumentation_terms.join(" /\\ ")
8838        };
8839
8840        pushln!(out, "CoverageInstrumentation == {instrumentation}");
8841        pushln!(out);
8842    }
8843
8844    /// Fail-closed resolution check for every route in the composition.
8845    ///
8846    /// Confirms that each route's `from_machine` and `to.machine` is a declared
8847    /// machine instance, that `effect_variant` is a declared effect on the
8848    /// source machine, and that `to.input_variant` is a declared input/signal
8849    /// (per `to.kind`) on the target machine. The composition CASE builders
8850    /// (`ActorOfMachine`, `RouteSource`, `RouteEffect`, `RouteTargetMachine`,
8851    /// `RouteTargetInput`) used to map an unresolved component to a sentinel
8852    /// (`"unknown_*"`) default; with this gate run first, those sentinels are
8853    /// unreachable-by-construction for valid input, and malformed input fails
8854    /// closed instead of silently emitting a broken model.
8855    fn validate_routes(&self) -> std::result::Result<(), CompositionTlaError> {
8856        let composition = self.schema.name.as_str();
8857        for route in &self.schema.routes {
8858            let route_name = route.name.as_str();
8859
8860            // Source machine instance must be declared.
8861            let source = self
8862                .machine_by_instance
8863                .get(route.from_machine.as_str())
8864                .copied()
8865                .ok_or_else(|| CompositionTlaError::UnknownRouteSourceMachine {
8866                    composition: composition.to_owned(),
8867                    route: route_name.to_owned(),
8868                    machine: route.from_machine.as_str().to_owned(),
8869                })?;
8870
8871            // Effect variant must be declared on the source machine.
8872            if source
8873                .effects
8874                .variant_named(route.effect_variant.as_str())
8875                .is_err()
8876            {
8877                return Err(CompositionTlaError::UnknownRouteEffect {
8878                    composition: composition.to_owned(),
8879                    route: route_name.to_owned(),
8880                    machine: route.from_machine.as_str().to_owned(),
8881                    effect: route.effect_variant.as_str().to_owned(),
8882                });
8883            }
8884
8885            // Target machine instance must be declared.
8886            let target = self
8887                .machine_by_instance
8888                .get(route.to.machine.as_str())
8889                .copied()
8890                .ok_or_else(|| CompositionTlaError::UnknownRouteTargetMachine {
8891                    composition: composition.to_owned(),
8892                    route: route_name.to_owned(),
8893                    machine: route.to.machine.as_str().to_owned(),
8894                })?;
8895
8896            // Target input/signal variant must be declared on the target
8897            // machine, dispatching on the route's structural kind.
8898            match route.to.kind {
8899                RouteTargetKind::Input => {
8900                    if target
8901                        .inputs
8902                        .variant_named(route.to.input_variant.as_str())
8903                        .is_err()
8904                    {
8905                        return Err(CompositionTlaError::UnknownRouteTargetInput {
8906                            composition: composition.to_owned(),
8907                            route: route_name.to_owned(),
8908                            machine: route.to.machine.as_str().to_owned(),
8909                            input: route.to.input_variant.as_str().to_owned(),
8910                        });
8911                    }
8912                }
8913                RouteTargetKind::Signal => {
8914                    if target
8915                        .signals
8916                        .variant_named(route.to.input_variant.as_str())
8917                        .is_err()
8918                    {
8919                        return Err(CompositionTlaError::UnknownRouteTargetSignal {
8920                            composition: composition.to_owned(),
8921                            route: route_name.to_owned(),
8922                            machine: route.to.machine.as_str().to_owned(),
8923                            signal: route.to.input_variant.as_str().to_owned(),
8924                        });
8925                    }
8926                }
8927            }
8928        }
8929        Ok(())
8930    }
8931
8932    fn render_static_sets(&self, out: &mut String) -> std::result::Result<(), CompositionTlaError> {
8933        pushln!(out, "Machines == {{");
8934        for (idx, machine) in self.schema.machines.iter().enumerate() {
8935            let suffix = if idx + 1 == self.schema.machines.len() {
8936                ""
8937            } else {
8938                ","
8939            };
8940            writeln!(
8941                out,
8942                "    <<{}, {}, {}>>{}",
8943                tla_string(&machine.instance_id),
8944                tla_string(&machine.machine_name),
8945                tla_string(&machine.actor),
8946                suffix
8947            )
8948            .expect("write to string");
8949        }
8950        pushln!(out, "}}");
8951        pushln!(out);
8952
8953        pushln!(out, "RouteNames == {{");
8954        for (idx, route) in self.schema.routes.iter().enumerate() {
8955            let suffix = if idx + 1 == self.schema.routes.len() {
8956                ""
8957            } else {
8958                ","
8959            };
8960            pushln!(out, "    {}{}", tla_string(&route.name), suffix);
8961        }
8962        pushln!(out, "}}");
8963        pushln!(out);
8964
8965        pushln!(out, "Actors == {{");
8966        for (idx, machine) in self.schema.machines.iter().enumerate() {
8967            let suffix = if idx + 1 == self.schema.machines.len() {
8968                ""
8969            } else {
8970                ","
8971            };
8972            pushln!(out, "    {}{}", tla_string(&machine.actor), suffix);
8973        }
8974        pushln!(out, "}}");
8975        pushln!(out);
8976
8977        pushln!(out, "ActorPriorities == {{");
8978        for (idx, priority) in self.schema.actor_priorities.iter().enumerate() {
8979            let suffix = if idx + 1 == self.schema.actor_priorities.len() {
8980                ""
8981            } else {
8982                ","
8983            };
8984            writeln!(
8985                out,
8986                "    <<{}, {}>>{}",
8987                tla_string(&priority.higher),
8988                tla_string(&priority.lower),
8989                suffix
8990            )
8991            .expect("write to string");
8992        }
8993        pushln!(out, "}}");
8994        pushln!(out);
8995
8996        pushln!(out, "SchedulerRules == {{");
8997        for (idx, rule) in self.schema.scheduler_rules.iter().enumerate() {
8998            let suffix = if idx + 1 == self.schema.scheduler_rules.len() {
8999                ""
9000            } else {
9001                ","
9002            };
9003            pushln!(out, "    {}{}", render_scheduler_rule_tuple(rule), suffix);
9004        }
9005        writeln!(out, "}}");
9006        pushln!(out);
9007
9008        let composition_name = self.schema.name.as_str();
9009        render_composition_case_fn(
9010            out,
9011            composition_name,
9012            "ActorOfMachine",
9013            "machine_id",
9014            self.schema
9015                .machines
9016                .iter()
9017                .map(|machine| (machine.instance_id.as_str(), tla_string(&machine.actor)))
9018                .collect(),
9019            CaseDefault::FailClosed {
9020                component: "actor",
9021                require_mapping: true,
9022            },
9023        )?;
9024        render_composition_case_fn(
9025            out,
9026            composition_name,
9027            "RouteSource",
9028            "route_name",
9029            self.schema
9030                .routes
9031                .iter()
9032                .map(|route| (route.name.as_str(), tla_string(&route.from_machine)))
9033                .collect(),
9034            CaseDefault::FailClosed {
9035                component: "route_source_machine",
9036                require_mapping: false,
9037            },
9038        )?;
9039        render_composition_case_fn(
9040            out,
9041            composition_name,
9042            "RouteEffect",
9043            "route_name",
9044            self.schema
9045                .routes
9046                .iter()
9047                .map(|route| (route.name.as_str(), tla_string(&route.effect_variant)))
9048                .collect(),
9049            CaseDefault::FailClosed {
9050                component: "route_effect",
9051                require_mapping: false,
9052            },
9053        )?;
9054        render_composition_case_fn(
9055            out,
9056            composition_name,
9057            "RouteTargetMachine",
9058            "route_name",
9059            self.schema
9060                .routes
9061                .iter()
9062                .map(|route| (route.name.as_str(), tla_string(&route.to.machine)))
9063                .collect(),
9064            CaseDefault::FailClosed {
9065                component: "route_target_machine",
9066                require_mapping: false,
9067            },
9068        )?;
9069        render_composition_case_fn(
9070            out,
9071            composition_name,
9072            "RouteTargetInput",
9073            "route_name",
9074            self.schema
9075                .routes
9076                .iter()
9077                .map(|route| (route.name.as_str(), tla_string(&route.to.input_variant)))
9078                .collect(),
9079            CaseDefault::FailClosed {
9080                component: "route_target_input",
9081                require_mapping: false,
9082            },
9083        )?;
9084        render_composition_case_fn(
9085            out,
9086            composition_name,
9087            "RouteTargetKind",
9088            "route_name",
9089            self.schema
9090                .routes
9091                .iter()
9092                .map(|route| {
9093                    (
9094                        route.name.as_str(),
9095                        tla_string(match route.to.kind {
9096                            RouteTargetKind::Input => "Input",
9097                            RouteTargetKind::Signal => "Signal",
9098                        }),
9099                    )
9100                })
9101                .collect(),
9102            CaseDefault::ClosedEnum(tla_string("Unknown")),
9103        )?;
9104        render_composition_case_fn(
9105            out,
9106            composition_name,
9107            "RouteDeliveryKind",
9108            "route_name",
9109            self.schema
9110                .routes
9111                .iter()
9112                .map(|route| {
9113                    (
9114                        route.name.as_str(),
9115                        tla_string(match route.delivery {
9116                            RouteDelivery::Immediate => "Immediate",
9117                            RouteDelivery::Enqueue => "Enqueue",
9118                        }),
9119                    )
9120                })
9121                .collect(),
9122            CaseDefault::ClosedEnum(tla_string("Unknown")),
9123        )?;
9124        writeln!(
9125            out,
9126            "RouteTargetActor(route_name) == ActorOfMachine(RouteTargetMachine(route_name))"
9127        );
9128        pushln!(out);
9129        Ok(())
9130    }
9131
9132    fn render_entry_input_actions(&self, out: &mut String) {
9133        for entry_input in &self.schema.entry_inputs {
9134            let machine = self.machine(entry_input.machine.as_str());
9135            let Ok(variant) = machine.inputs.variant_named(&entry_input.input_variant) else {
9136                continue;
9137            };
9138            let action_name = self.entry_input_action_name(entry_input);
9139            let params = variant
9140                .fields
9141                .iter()
9142                .map(|field| format!("arg_{}", tla_ident(&field.name)))
9143                .collect::<Vec<_>>();
9144            let packet_expr = self.input_packet_expr(
9145                entry_input.machine.as_str(),
9146                &entry_input.input_variant,
9147                &variant
9148                    .fields
9149                    .iter()
9150                    .map(|field| {
9151                        (
9152                            field.name.as_str().to_owned(),
9153                            format!("arg_{}", tla_ident(&field.name)),
9154                        )
9155                    })
9156                    .collect::<BTreeMap<String, _>>(),
9157                "entry",
9158                &entry_input.name,
9159                "external_entry",
9160                &entry_input.input_variant,
9161                "0",
9162            );
9163
9164            if params.is_empty() {
9165                pushln!(out, "{} ==", action_name);
9166            } else {
9167                pushln!(out, "{}({}) ==", action_name, params.join(", "));
9168            }
9169            writeln!(
9170                out,
9171                "    /\\ ~({} \\in SeqElements(pending_inputs))",
9172                packet_expr
9173            )
9174            .expect("write to string");
9175            writeln!(out, "    /\\ EntryPacketAdmissible({packet_expr})").expect("write to string");
9176            writeln!(
9177                out,
9178                "    /\\ pending_inputs' = Append(pending_inputs, {})",
9179                packet_expr
9180            )
9181            .expect("write to string");
9182            writeln!(
9183                out,
9184                "    /\\ observed_inputs' = observed_inputs \\cup {{{}}}",
9185                packet_expr
9186            )
9187            .expect("write to string");
9188            writeln!(out, "    /\\ model_step_count' = model_step_count + 1")
9189                .expect("write to string");
9190            {
9191                let mut unchanged = self.machine_vars();
9192                unchanged.extend(self.obligation_vars());
9193                unchanged.extend([
9194                    "pending_routes".into(),
9195                    "delivered_routes".into(),
9196                    "emitted_effects".into(),
9197                    "observed_transitions".into(),
9198                    "witness_current_script_input".into(),
9199                    "witness_remaining_script_inputs".into(),
9200                ]);
9201                self.render_unchanged_vars(out, "    /\\ ", &unchanged);
9202            }
9203            pushln!(out);
9204        }
9205    }
9206
9207    fn render_entry_input_call(&self, entry_input: &EntryInput) -> String {
9208        let machine = self.machine(entry_input.machine.as_str());
9209        let Ok(variant) = machine.inputs.variant_named(&entry_input.input_variant) else {
9210            return self.entry_input_action_name(entry_input);
9211        };
9212        let action_name = self.entry_input_action_name(entry_input);
9213        if variant.fields.is_empty() {
9214            action_name
9215        } else {
9216            let prefix = variant
9217                .fields
9218                .iter()
9219                .map(|field| {
9220                    let local = format!("arg_{}", tla_ident(&field.name));
9221                    let domain = self.binding_domain_for_type(&field.ty);
9222                    format!("\\E {local} \\in {domain} : ")
9223                })
9224                .collect::<String>();
9225            let args = variant
9226                .fields
9227                .iter()
9228                .map(|field| format!("arg_{}", tla_ident(&field.name)))
9229                .collect::<Vec<_>>()
9230                .join(", ");
9231            format!("{prefix}{action_name}({args})")
9232        }
9233    }
9234
9235    fn render_deliver_queued_route_action(&self, out: &mut String) {
9236        writeln!(out, "DeliverQueuedRoute ==");
9237        pushln!(out, "    /\\ Len(pending_routes) > 0");
9238        pushln!(out, "    /\\ LET route == Head(pending_routes) IN");
9239        pushln!(out, "       /\\ pending_routes' = Tail(pending_routes)");
9240        writeln!(
9241            out,
9242            "       /\\ delivered_routes' = delivered_routes \\cup {{route}}"
9243        )
9244        .expect("write to string");
9245        writeln!(out, "       /\\ model_step_count' = model_step_count + 1")
9246            .expect("write to string");
9247        writeln!(
9248            out,
9249            "       /\\ 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])"
9250        )
9251        .expect("write to string");
9252        writeln!(
9253            out,
9254            "       /\\ 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]}}"
9255        )
9256        .expect("write to string");
9257        {
9258            let mut unchanged = self.machine_vars();
9259            unchanged.extend(self.obligation_vars());
9260            unchanged.extend([
9261                "emitted_effects".into(),
9262                "observed_transitions".into(),
9263                "witness_current_script_input".into(),
9264                "witness_remaining_script_inputs".into(),
9265            ]);
9266            self.render_unchanged_vars(out, "       /\\ ", &unchanged);
9267        }
9268        pushln!(out);
9269    }
9270
9271    fn entry_packet_admissibility_name(&self, instance_id: &str) -> String {
9272        format!("EntryPacketAdmissible_{}", tla_ident(instance_id))
9273    }
9274
9275    fn render_entry_packet_admissibility_helpers(
9276        &self,
9277        out: &mut String,
9278    ) -> std::result::Result<(), CompositionTlaError> {
9279        if self.schema.entry_inputs.is_empty()
9280            && !self
9281                .schema
9282                .witnesses
9283                .iter()
9284                .any(|witness| !witness.preload_inputs.is_empty())
9285        {
9286            return Ok(());
9287        }
9288
9289        for instance in &self.schema.machines {
9290            let machine = self.machine(instance.instance_id.as_str());
9291            let helper_prefix = format!("{}__entry_packet__", tla_ident(&instance.instance_id));
9292            let mut compiler = self.instance_compiler(instance.instance_id.as_str(), helper_prefix);
9293
9294            for derived in helper_dependency_order(machine)? {
9295                compiler.render_helper(out, derived);
9296                pushln!(out);
9297            }
9298            if machine.machine.as_str() == "MobMachine" {
9299                compiler.render_mob_machine_native_helpers(out);
9300                pushln!(out);
9301            }
9302            if machine.machine.as_str() == "MeerkatMachine" {
9303                compiler.render_meerkat_machine_native_helpers(out);
9304                pushln!(out);
9305            }
9306            if machine.machine.as_str() == "RuntimeDeliveryMachine" {
9307                compiler.render_runtime_delivery_native_helpers(out);
9308                pushln!(out);
9309            }
9310            if machine.machine.as_str() == "SessionDocumentMachine" {
9311                compiler.render_session_document_native_helpers(out);
9312                pushln!(out);
9313            }
9314
9315            let branches = machine
9316                .transitions
9317                .iter()
9318                .map(|transition| {
9319                    self.render_machine_packet_admissibility_branch(
9320                        &mut compiler,
9321                        instance.instance_id.as_str(),
9322                        transition,
9323                    )
9324                })
9325                .collect::<Vec<_>>();
9326
9327            for helper in &compiler.helper_defs {
9328                pushln!(out, "{helper}");
9329                pushln!(out);
9330            }
9331
9332            writeln!(
9333                out,
9334                "{}(packet) ==",
9335                self.entry_packet_admissibility_name(instance.instance_id.as_str())
9336            )
9337            .expect("write to string");
9338            if branches.is_empty() {
9339                pushln!(out, "    FALSE");
9340            } else {
9341                for branch in &branches {
9342                    pushln!(out, "    \\/ {branch}");
9343                }
9344            }
9345            pushln!(out);
9346        }
9347
9348        writeln!(out, "EntryPacketAdmissible(packet) ==").expect("write to string");
9349        pushln!(out, "    CASE");
9350        for (idx, instance) in self.schema.machines.iter().enumerate() {
9351            let prefix = if idx == 0 { "      " } else { "      [] " };
9352            writeln!(
9353                out,
9354                "{}packet.machine = {} -> {}(packet)",
9355                prefix,
9356                tla_string(&instance.instance_id),
9357                self.entry_packet_admissibility_name(instance.instance_id.as_str())
9358            )
9359            .expect("write to string");
9360        }
9361        pushln!(out, "      [] OTHER -> FALSE");
9362        pushln!(out);
9363        Ok(())
9364    }
9365
9366    fn render_machine_packet_admissibility_branch(
9367        &self,
9368        compiler: &mut MachineTlaCompiler<'_>,
9369        instance_id: &str,
9370        transition: &TransitionSchema,
9371    ) -> String {
9372        let phase_var = self.phase_var(instance_id);
9373        let from_guard = if transition.from.len() == 1 {
9374            format!("{phase_var} = {}", tla_string(&transition.from[0]))
9375        } else {
9376            transition
9377                .from
9378                .iter()
9379                .map(|phase| format!("{phase_var} = {}", tla_string(phase)))
9380                .collect::<Vec<_>>()
9381                .join(" \\/ ")
9382        };
9383
9384        let binding_types = compiler.binding_type_map(transition);
9385        let binding_env = transition
9386            .on
9387            .bindings()
9388            .iter()
9389            .map(|binding| {
9390                (
9391                    binding.as_str().to_owned(),
9392                    format!("packet.payload.{}", tla_ident(binding)),
9393                )
9394            })
9395            .collect::<BTreeMap<_, _>>();
9396        let field_env = self.machine_field_env(instance_id);
9397
9398        let mut clauses = vec![
9399            format!(
9400                "packet.variant = {}",
9401                tla_string(transition.on.variant_str())
9402            ),
9403            from_guard,
9404        ];
9405        clauses.extend(
9406            transition.guards.iter().map(|guard| {
9407                compiler.render_guard(guard, &field_env, &binding_env, &binding_types)
9408            }),
9409        );
9410
9411        format!(
9412            "/\\ {}",
9413            clauses
9414                .into_iter()
9415                .map(|clause| format!("({clause})"))
9416                .collect::<Vec<_>>()
9417                .join(" /\\ ")
9418        )
9419    }
9420
9421    fn render_reject_pending_entry_input_action(&self, out: &mut String) {
9422        if self.schema.entry_inputs.is_empty() {
9423            return;
9424        }
9425
9426        writeln!(out, "RejectPendingEntryInput ==").expect("write to string");
9427        pushln!(out, "    /\\ \\E packet \\in SeqElements(pending_inputs) :");
9428        pushln!(out, "       /\\ packet.source_kind = \"entry\"");
9429        pushln!(out, "       /\\ ~EntryPacketAdmissible(packet)");
9430        pushln!(
9431            out,
9432            "       /\\ pending_inputs' = SeqRemove(pending_inputs, packet)"
9433        );
9434        pushln!(out, "       /\\ observed_inputs' = observed_inputs");
9435        pushln!(out, "       /\\ pending_routes' = pending_routes");
9436        pushln!(out, "       /\\ delivered_routes' = delivered_routes");
9437        pushln!(out, "       /\\ emitted_effects' = emitted_effects");
9438        pushln!(
9439            out,
9440            "       /\\ observed_transitions' = observed_transitions"
9441        );
9442        writeln!(out, "       /\\ model_step_count' = model_step_count + 1")
9443            .expect("write to string");
9444        let mut unchanged = self.machine_vars();
9445        unchanged.extend(self.obligation_vars());
9446        unchanged.extend([
9447            "witness_current_script_input".into(),
9448            "witness_remaining_script_inputs".into(),
9449        ]);
9450        self.render_unchanged_vars(out, "       /\\ ", &unchanged);
9451        pushln!(out);
9452    }
9453
9454    fn render_quiescent_stutter(&self, out: &mut String) {
9455        writeln!(out, "QuiescentStutter ==");
9456        pushln!(out, "    /\\ Len(pending_routes) = 0");
9457        pushln!(out, "    /\\ Len(pending_inputs) = 0");
9458        pushln!(out, "    /\\ UNCHANGED vars");
9459        pushln!(out);
9460    }
9461
9462    fn render_witness_inject_next_call(&self, witness: &CompositionWitness) -> String {
9463        format!("WitnessInjectNext_{}", tla_ident(&witness.name))
9464    }
9465
9466    fn render_witness_satisfied_stutter_call(&self, witness: &CompositionWitness) -> String {
9467        format!("WitnessSatisfiedStutter_{}", tla_ident(&witness.name))
9468    }
9469
9470    fn core_next_branches(&self) -> Vec<String> {
9471        let mut branches = Vec::new();
9472        if !self.schema.routes.is_empty() {
9473            branches.push("DeliverQueuedRoute".into());
9474        }
9475        if !self.schema.entry_inputs.is_empty() {
9476            branches.push("RejectPendingEntryInput".into());
9477        }
9478        for instance in &self.schema.machines {
9479            let machine = self.machine(instance.instance_id.as_str());
9480            for transition in &machine.transitions {
9481                branches
9482                    .push(self.machine_transition_call(instance.instance_id.as_str(), transition));
9483            }
9484        }
9485        branches.extend(self.owner_feedback_branches());
9486        branches.push("QuiescentStutter".into());
9487        branches
9488    }
9489
9490    fn owner_feedback_branches(&self) -> Vec<String> {
9491        self.schema
9492            .handoff_protocols
9493            .iter()
9494            .flat_map(|protocol| {
9495                protocol
9496                    .allowed_feedback_inputs
9497                    .iter()
9498                    .map(move |feedback| self.owner_feedback_action_name(protocol, feedback))
9499            })
9500            .collect()
9501    }
9502
9503    fn owner_feedback_action_name(
9504        &self,
9505        protocol: &meerkat_machine_schema::EffectHandoffProtocol,
9506        feedback: &FeedbackInputRef,
9507    ) -> String {
9508        format!(
9509            "OwnerFeedback_{}_{}",
9510            self.obligation_symbol_suffix(protocol),
9511            tla_ident(&feedback.input_variant)
9512        )
9513    }
9514
9515    fn witness_owner_feedback_branches(&self, witness: &CompositionWitness) -> Vec<String> {
9516        let expected_inputs = witness
9517            .expected_transitions
9518            .iter()
9519            .filter_map(|expected| {
9520                let machine = self.machine_by_instance.get(expected.machine.as_str())?;
9521                let transition = machine
9522                    .transitions
9523                    .iter()
9524                    .find(|transition| transition.name == expected.transition)?;
9525                match &transition.on {
9526                    TriggerMatch::Input { variant, .. } => {
9527                        Some((expected.machine.clone(), variant.clone()))
9528                    }
9529                    TriggerMatch::Signal { .. } => None,
9530                }
9531            })
9532            .collect::<BTreeSet<_>>();
9533
9534        let ordered_predecessor_effects = witness
9535            .expected_transition_order
9536            .iter()
9537            .filter_map(|order| {
9538                let predecessor_machine = self
9539                    .machine_by_instance
9540                    .get(order.earlier.machine.as_str())?;
9541                let predecessor = predecessor_machine
9542                    .transitions
9543                    .iter()
9544                    .find(|transition| transition.name == order.earlier.transition)?;
9545                Some((
9546                    (order.later.machine.clone(), order.later.transition.clone()),
9547                    predecessor
9548                        .emit
9549                        .iter()
9550                        .map(|effect| (order.earlier.machine.clone(), effect.variant.clone()))
9551                        .collect::<BTreeSet<_>>(),
9552                ))
9553            })
9554            .fold(
9555                BTreeMap::<_, BTreeSet<_>>::new(),
9556                |mut effects, (transition, predecessor_effects)| {
9557                    effects
9558                        .entry(transition)
9559                        .or_default()
9560                        .extend(predecessor_effects);
9561                    effects
9562                },
9563            );
9564
9565        self.schema
9566            .handoff_protocols
9567            .iter()
9568            .flat_map(|protocol| {
9569                protocol
9570                    .allowed_feedback_inputs
9571                    .iter()
9572                    .filter_map(|feedback| {
9573                        let input = (
9574                            feedback.machine_instance.clone(),
9575                            feedback.input_variant.clone(),
9576                        );
9577                        if !expected_inputs.contains(&input) {
9578                            return None;
9579                        }
9580                        let receiver_machine = self
9581                            .machine_by_instance
9582                            .get(feedback.machine_instance.as_str())?;
9583                        let receiver = receiver_machine.transitions.iter().find(|transition| {
9584                            matches!(
9585                                &transition.on,
9586                                TriggerMatch::Input { variant, .. }
9587                                    if variant == &feedback.input_variant
9588                            )
9589                        })?;
9590                        let receiver_key =
9591                            (feedback.machine_instance.clone(), receiver.name.clone());
9592                        if let Some(predecessor_effects) =
9593                            ordered_predecessor_effects.get(&receiver_key)
9594                        {
9595                            let producer = (
9596                                protocol.producer_instance.clone(),
9597                                protocol.effect_variant.clone(),
9598                            );
9599                            if !predecessor_effects.contains(&producer) {
9600                                return None;
9601                            }
9602                        }
9603                        Some(self.owner_feedback_action_name(protocol, feedback))
9604                    })
9605            })
9606            .collect::<BTreeSet<_>>()
9607            .into_iter()
9608            .collect()
9609    }
9610
9611    fn witness_next_branches(
9612        &self,
9613        witness: &CompositionWitness,
9614    ) -> Result<Vec<String>, CompositionTlaError> {
9615        if !Self::witness_has_explicit_progress(witness) {
9616            let mut branches = vec!["CoreNext".into()];
9617            branches.push(self.render_witness_satisfied_stutter_call(witness));
9618            return Ok(branches);
9619        }
9620        let mut branches = self.witness_progress_branches(witness)?;
9621        branches.push(self.render_witness_satisfied_stutter_call(witness));
9622        Ok(branches)
9623    }
9624
9625    fn witness_progress_branches(
9626        &self,
9627        witness: &CompositionWitness,
9628    ) -> Result<Vec<String>, CompositionTlaError> {
9629        let mut branches = Vec::new();
9630        if !witness.expected_routes.is_empty() {
9631            branches.push("DeliverQueuedRoute".into());
9632        }
9633        for expected in &witness.expected_transitions {
9634            branches.push(self.witness_transition_call(witness, expected)?);
9635        }
9636        branches.extend(self.witness_owner_feedback_branches(witness));
9637        Ok(branches)
9638    }
9639
9640    fn witness_transition_call(
9641        &self,
9642        witness: &CompositionWitness,
9643        expected: &meerkat_machine_schema::CompositionWitnessTransition,
9644    ) -> Result<String, CompositionTlaError> {
9645        let machine = self
9646            .machine_by_instance
9647            .get(expected.machine.as_str())
9648            .ok_or_else(|| CompositionTlaError::UnknownWitnessMachine {
9649                composition: self.schema.name.to_string(),
9650                witness: witness.name.to_string(),
9651                machine: expected.machine.to_string(),
9652            })?;
9653        let transition = machine
9654            .transitions
9655            .iter()
9656            .find(|transition| transition.name == expected.transition)
9657            .ok_or_else(|| CompositionTlaError::UnknownWitnessTransition {
9658                composition: self.schema.name.to_string(),
9659                witness: witness.name.to_string(),
9660                machine: expected.machine.to_string(),
9661                transition: expected.transition.to_string(),
9662            })?;
9663        if transition.on.bindings().is_empty() {
9664            return Ok(self.machine_transition_name(expected.machine.as_str(), transition));
9665        }
9666        // A scripted witness supplies exact typed packets. Sampling the ordinary
9667        // exploration domains again can make those packets impossible to consume
9668        // (for example, revisions 3 and 4 outside the bounded 0..2 sample).
9669        // Reuse the same guarded action with the queued payload, without changing
9670        // ordinary exploration bounds or bypassing action admission checks.
9671        let args = transition
9672            .on
9673            .bindings()
9674            .iter()
9675            .map(|binding| format!("witness_packet.payload.{}", tla_ident(binding)))
9676            .collect::<Vec<_>>()
9677            .join(", ");
9678        Ok(format!(
9679            "\\E witness_packet \\in SeqElements(pending_inputs) : /\\ witness_packet.machine = {} /\\ witness_packet.variant = {} /\\ {}({args})",
9680            tla_string(expected.machine.as_str()),
9681            tla_string(transition.on.variant_str()),
9682            self.machine_transition_name(expected.machine.as_str(), transition),
9683        ))
9684    }
9685
9686    fn witness_fairness_clauses(
9687        &self,
9688        witness: &CompositionWitness,
9689    ) -> Result<Vec<String>, CompositionTlaError> {
9690        if Self::witness_has_explicit_progress(witness) {
9691            return Ok(Vec::new());
9692        }
9693
9694        let mut clauses = self.core_fairness_clauses();
9695        if witness.preload_inputs.len() > 1 {
9696            clauses.push(self.render_witness_inject_next_call(witness));
9697        }
9698        Ok(clauses)
9699    }
9700
9701    fn core_fairness_clauses(&self) -> Vec<String> {
9702        let mut clauses = Vec::new();
9703        if !self.schema.routes.is_empty() {
9704            clauses.push("DeliverQueuedRoute".into());
9705        }
9706        if !self.schema.entry_inputs.is_empty() {
9707            clauses.push("RejectPendingEntryInput".into());
9708        }
9709        clauses.extend(self.schema.machines.iter().flat_map(|instance| {
9710            let machine = self.machine(instance.instance_id.as_str());
9711            machine
9712                .transitions
9713                .iter()
9714                .map(|transition| {
9715                    self.machine_transition_call(instance.instance_id.as_str(), transition)
9716                })
9717                .collect::<Vec<_>>()
9718        }));
9719        clauses
9720    }
9721
9722    fn witness_has_explicit_progress(witness: &CompositionWitness) -> bool {
9723        !witness.preload_inputs.is_empty() || !witness.expected_transitions.is_empty()
9724    }
9725
9726    fn entry_input_action_name(&self, entry_input: &EntryInput) -> String {
9727        format!("Inject_{}", tla_ident(&entry_input.name))
9728    }
9729
9730    fn input_packet_expr(
9731        &self,
9732        machine_id: impl AsRef<str>,
9733        input_variant: impl AsRef<str>,
9734        payload_fields: &BTreeMap<String, String>,
9735        source_kind: impl AsRef<str>,
9736        source_route: impl AsRef<str>,
9737        source_machine: impl AsRef<str>,
9738        source_effect: impl AsRef<str>,
9739        effect_id: impl AsRef<str>,
9740    ) -> String {
9741        format!(
9742            "[machine |-> {}, variant |-> {}, payload |-> {}, source_kind |-> {}, source_route |-> {}, source_machine |-> {}, source_effect |-> {}, effect_id |-> {}]",
9743            tla_string(machine_id),
9744            tla_string(input_variant),
9745            self.payload_record_expr(payload_fields),
9746            tla_string(source_kind),
9747            tla_string(source_route),
9748            tla_string(source_machine),
9749            tla_string(source_effect),
9750            effect_id.as_ref()
9751        )
9752    }
9753
9754    fn input_packet_expr_from_payload_expr(
9755        &self,
9756        machine_id: impl AsRef<str>,
9757        input_variant: impl AsRef<str>,
9758        payload_expr: &str,
9759        source_kind: impl AsRef<str>,
9760        source_route: impl AsRef<str>,
9761        source_machine: impl AsRef<str>,
9762        source_effect: impl AsRef<str>,
9763        effect_id: impl AsRef<str>,
9764    ) -> String {
9765        format!(
9766            "[machine |-> {}, variant |-> {}, payload |-> {}, source_kind |-> {}, source_route |-> {}, source_machine |-> {}, source_effect |-> {}, effect_id |-> {}]",
9767            tla_string(machine_id),
9768            tla_string(input_variant),
9769            payload_expr,
9770            tla_string(source_kind),
9771            tla_string(source_route),
9772            tla_string(source_machine),
9773            tla_string(source_effect),
9774            effect_id.as_ref()
9775        )
9776    }
9777
9778    fn payload_record_expr(&self, payload_fields: &BTreeMap<String, String>) -> String {
9779        if payload_fields.is_empty() {
9780            "[tag |-> \"unit\"]".into()
9781        } else {
9782            format!(
9783                "[{}]",
9784                payload_fields
9785                    .iter()
9786                    .map(|(field, expr)| format!("{field} |-> {expr}"))
9787                    .collect::<Vec<_>>()
9788                    .join(", ")
9789            )
9790        }
9791    }
9792
9793    fn witness_packet_exprs(&self, witness: &CompositionWitness) -> Vec<String> {
9794        witness
9795            .preload_inputs
9796            .iter()
9797            .enumerate()
9798            .map(|(idx, packet)| {
9799                let payload_fields = packet
9800                    .fields
9801                    .iter()
9802                    .map(|field| {
9803                        (
9804                            field.field.as_str().to_owned(),
9805                            self.render_literal_expr(&field.expr),
9806                        )
9807                    })
9808                    .collect::<BTreeMap<String, _>>();
9809                self.input_packet_expr(
9810                    packet.machine.as_str(),
9811                    packet.input_variant.as_str(),
9812                    &payload_fields,
9813                    "entry",
9814                    format!("witness:{}:{}", witness.name, idx + 1),
9815                    "external_entry",
9816                    &packet.input_variant,
9817                    "0",
9818                )
9819            })
9820            .collect()
9821    }
9822
9823    fn witness_initial_batch_size(&self, witness: &CompositionWitness) -> usize {
9824        if witness.expected_scheduler_rules.is_empty() {
9825            1
9826        } else {
9827            witness.preload_inputs.len().min(2).max(1)
9828        }
9829    }
9830
9831    fn witness_initial_observed_inputs_expr(&self, witness: &CompositionWitness) -> String {
9832        let packets = self.witness_packet_exprs(witness);
9833        let batch_size = self.witness_initial_batch_size(witness);
9834        if packets.is_empty() {
9835            "{}".into()
9836        } else {
9837            format!(
9838                "{{{}}}",
9839                packets
9840                    .into_iter()
9841                    .take(batch_size)
9842                    .collect::<Vec<_>>()
9843                    .join(", ")
9844            )
9845        }
9846    }
9847
9848    fn witness_initial_pending_inputs_expr(&self, witness: &CompositionWitness) -> String {
9849        let packets = self.witness_packet_exprs(witness);
9850        let batch_size = self.witness_initial_batch_size(witness);
9851        if packets.is_empty() {
9852            "<<>>".into()
9853        } else {
9854            format!(
9855                "<<{}>>",
9856                packets
9857                    .into_iter()
9858                    .take(batch_size)
9859                    .collect::<Vec<_>>()
9860                    .join(", ")
9861            )
9862        }
9863    }
9864
9865    fn witness_current_script_input_expr(&self, witness: &CompositionWitness) -> String {
9866        let packets = self.witness_packet_exprs(witness);
9867        let batch_size = self.witness_initial_batch_size(witness);
9868        packets
9869            .into_iter()
9870            .take(batch_size)
9871            .last()
9872            .unwrap_or_else(|| "None".into())
9873    }
9874
9875    fn witness_remaining_script_inputs_expr(&self, witness: &CompositionWitness) -> String {
9876        let packets = self.witness_packet_exprs(witness);
9877        let batch_size = self.witness_initial_batch_size(witness);
9878        if packets.len() <= batch_size {
9879            return "<<>>".into();
9880        }
9881
9882        format!(
9883            "<<{}>>",
9884            packets
9885                .into_iter()
9886                .skip(batch_size)
9887                .collect::<Vec<_>>()
9888                .join(", ")
9889        )
9890    }
9891
9892    fn render_witness_inject_actions(&self, out: &mut String) {
9893        for witness in &self.schema.witnesses {
9894            let action_name = self.render_witness_inject_next_call(witness);
9895            pushln!(out, "{action_name} ==");
9896            if witness.preload_inputs.len() <= 1 {
9897                pushln!(out, "    FALSE");
9898                pushln!(out);
9899                continue;
9900            }
9901
9902            pushln!(
9903                out,
9904                "    LET next_script_input == IF Len(witness_remaining_script_inputs) > 0 THEN Head(witness_remaining_script_inputs) ELSE witness_current_script_input"
9905            );
9906            pushln!(
9907                out,
9908                "        next_remaining_script_inputs == IF Len(witness_remaining_script_inputs) > 0 THEN Tail(witness_remaining_script_inputs) ELSE <<>>"
9909            );
9910            pushln!(out, "    IN");
9911            pushln!(out, "    /\\ witness_current_script_input # None");
9912            writeln!(
9913                out,
9914                "    /\\ ~(witness_current_script_input \\in SeqElements(pending_inputs))"
9915            )
9916            .expect("write to string");
9917            pushln!(out, "    /\\ EntryPacketAdmissible(next_script_input)");
9918            pushln!(out, "    /\\ Len(pending_inputs) = 0");
9919            pushln!(out, "    /\\ Len(pending_routes) = 0");
9920            pushln!(out, "    /\\ Len(witness_remaining_script_inputs) > 0");
9921            writeln!(
9922                out,
9923                "    /\\ pending_inputs' = Append(pending_inputs, next_script_input)"
9924            )
9925            .expect("write to string");
9926            writeln!(
9927                out,
9928                "    /\\ observed_inputs' = observed_inputs \\cup {{next_script_input}}"
9929            )
9930            .expect("write to string");
9931            writeln!(
9932                out,
9933                "    /\\ witness_current_script_input' = next_script_input"
9934            )
9935            .expect("write to string");
9936            writeln!(
9937                out,
9938                "    /\\ witness_remaining_script_inputs' = next_remaining_script_inputs"
9939            )
9940            .expect("write to string");
9941            writeln!(out, "    /\\ model_step_count' = model_step_count + 1")
9942                .expect("write to string");
9943            {
9944                let mut unchanged = self.machine_vars();
9945                unchanged.extend(self.obligation_vars());
9946                unchanged.extend([
9947                    "pending_routes".into(),
9948                    "delivered_routes".into(),
9949                    "emitted_effects".into(),
9950                    "observed_transitions".into(),
9951                ]);
9952                self.render_unchanged_vars(out, "    /\\ ", &unchanged);
9953            }
9954            pushln!(out);
9955        }
9956    }
9957
9958    fn render_witness_satisfied_stutter_actions(&self, out: &mut String) {
9959        for witness in &self.schema.witnesses {
9960            let action_name = self.render_witness_satisfied_stutter_call(witness);
9961            pushln!(out, "{action_name} ==");
9962            let mut conditions = self.witness_satisfaction_conditions(witness);
9963            if Self::witness_has_explicit_progress(witness) {
9964                conditions.insert(0, composition_witness_completion_name(&witness.name));
9965            }
9966            if conditions.is_empty() {
9967                pushln!(out, "    /\\ FALSE");
9968            } else {
9969                for condition in conditions {
9970                    pushln!(out, "    /\\ {condition}");
9971                }
9972                pushln!(out, "    /\\ UNCHANGED vars");
9973            }
9974            pushln!(out);
9975        }
9976    }
9977
9978    fn render_witness_completion_operators(&self, out: &mut String) {
9979        for witness in &self.schema.witnesses {
9980            if !Self::witness_has_explicit_progress(witness) {
9981                continue;
9982            }
9983            writeln!(
9984                out,
9985                "{} ==",
9986                composition_witness_completion_name(&witness.name)
9987            )
9988            .expect("write to string");
9989            pushln!(out, "    /\\ Len(witness_remaining_script_inputs) = 0");
9990            pushln!(
9991                out,
9992                "    /\\ ~(witness_current_script_input \\in SeqElements(pending_inputs))"
9993            );
9994            pushln!(out, "    /\\ Len(pending_routes) = 0");
9995            for condition in self.witness_satisfaction_conditions(witness) {
9996                pushln!(out, "    /\\ {condition}");
9997            }
9998            pushln!(out);
9999        }
10000    }
10001
10002    fn render_witness_action_constraint_operators(&self, out: &mut String) {
10003        for witness in &self.schema.witnesses {
10004            if !Self::witness_has_explicit_progress(witness) {
10005                continue;
10006            }
10007            writeln!(
10008                out,
10009                "{} ==",
10010                composition_witness_action_constraint_name(&witness.name)
10011            )
10012            .expect("write to string");
10013            writeln!(
10014                out,
10015                "    \\/ {}",
10016                composition_witness_completion_name(&witness.name)
10017            )
10018            .expect("write to string");
10019            pushln!(out, "    \\/ model_step_count' # model_step_count");
10020            pushln!(out);
10021        }
10022    }
10023
10024    fn witness_satisfaction_conditions(&self, witness: &CompositionWitness) -> Vec<String> {
10025        let mut conditions = Vec::new();
10026        conditions.extend(witness.expected_routes.iter().map(|route| {
10027            format!(
10028                "\\E packet \\in delivered_routes : packet.route = {}",
10029                tla_string(route)
10030            )
10031        }));
10032        conditions.extend(
10033            witness
10034                .expected_scheduler_rules
10035                .iter()
10036                .map(render_scheduler_trigger_formula),
10037        );
10038        conditions.extend(
10039            witness
10040                .expected_states
10041                .iter()
10042                .map(|state| format!("({})", self.render_witness_state_formula(state))),
10043        );
10044        conditions.extend(
10045            witness.expected_transitions.iter().map(|transition| {
10046                format!("({})", self.render_witness_transition_formula(transition))
10047            }),
10048        );
10049        conditions.extend(
10050            witness
10051                .expected_transition_order
10052                .iter()
10053                .map(|order| format!("({})", self.render_witness_transition_order_formula(order))),
10054        );
10055        conditions
10056    }
10057
10058    fn render_witness_obligation_formula(
10059        &self,
10060        witness: &CompositionWitness,
10061        formula: String,
10062    ) -> String {
10063        if Self::witness_has_explicit_progress(witness) {
10064            format!(
10065                "{} => ({formula})",
10066                composition_witness_completion_name(&witness.name)
10067            )
10068        } else {
10069            format!("<> ({formula})")
10070        }
10071    }
10072
10073    fn render_literal_expr(&self, expr: &Expr) -> String {
10074        match expr {
10075            Expr::Bool(value) => {
10076                if *value {
10077                    "TRUE".into()
10078                } else {
10079                    "FALSE".into()
10080                }
10081            }
10082            Expr::U64(value) => value.to_string(),
10083            Expr::U64Max => TLA_RUST_U64_MAX_CONSTANT.to_owned(),
10084            Expr::String(value) => tla_string(value),
10085            Expr::NamedVariant { enum_name, variant } => render_named_variant_value(
10086                enum_name.as_str(),
10087                variant.as_str(),
10088                &self.named_bindings,
10089            ),
10090            Expr::None => "None".into(),
10091            Expr::Some(inner) => format!("Some({})", self.render_literal_expr(inner)),
10092            Expr::SeqLiteral(items) => {
10093                let rendered = items
10094                    .iter()
10095                    .map(|item| self.render_literal_expr(item))
10096                    .collect::<Vec<_>>()
10097                    .join(", ");
10098                format!("<<{rendered}>>")
10099            }
10100            Expr::EmptySet => "{}".into(),
10101            Expr::EmptyMap => "<< >>".into(),
10102            // A populated map literal (witness inputs, manifests) as a TLC
10103            // function; never the `None` fallback below.
10104            Expr::MapLiteral(entries) => {
10105                let rendered = entries
10106                    .iter()
10107                    .map(|(key, value)| {
10108                        format!(
10109                            "{} :> {}",
10110                            self.render_literal_expr(key),
10111                            self.render_literal_expr(value)
10112                        )
10113                    })
10114                    .collect::<Vec<_>>()
10115                    .join(" @@ ");
10116                format!("({rendered})")
10117            }
10118            _ => "None".into(),
10119        }
10120    }
10121
10122    fn render_witness_state_formula(
10123        &self,
10124        state: &meerkat_machine_schema::CompositionWitnessState,
10125    ) -> String {
10126        let mut clauses = Vec::new();
10127        if let Some(phase) = &state.phase {
10128            clauses.push(format!(
10129                "{} = {}",
10130                self.phase_var(&state.machine),
10131                tla_string(phase)
10132            ));
10133        }
10134        for field in &state.fields {
10135            clauses.push(format!(
10136                "{} = {}",
10137                self.field_var(&state.machine, &field.field),
10138                self.render_literal_expr(&field.expr)
10139            ));
10140        }
10141        if clauses.is_empty() {
10142            "TRUE".into()
10143        } else {
10144            clauses.join(" /\\ ")
10145        }
10146    }
10147
10148    fn render_witness_transition_formula(
10149        &self,
10150        transition: &meerkat_machine_schema::CompositionWitnessTransition,
10151    ) -> String {
10152        format!(
10153            "\\E packet \\in observed_transitions : /\\ packet.machine = {} /\\ packet.transition = {}",
10154            tla_string(&transition.machine),
10155            tla_string(&transition.transition)
10156        )
10157    }
10158
10159    fn render_witness_transition_order_formula(
10160        &self,
10161        ordering: &meerkat_machine_schema::CompositionWitnessTransitionOrder,
10162    ) -> String {
10163        format!(
10164            "\\E earlier \\in observed_transitions, later \\in observed_transitions : /\\ earlier.machine = {} /\\ earlier.transition = {} /\\ later.machine = {} /\\ later.transition = {} /\\ earlier.step < later.step",
10165            tla_string(&ordering.earlier.machine),
10166            tla_string(&ordering.earlier.transition),
10167            tla_string(&ordering.later.machine),
10168            tla_string(&ordering.later.transition),
10169        )
10170    }
10171
10172    fn route_packet_expr(
10173        &self,
10174        route_name: impl AsRef<str>,
10175        from_machine: impl AsRef<str>,
10176        effect_variant: impl AsRef<str>,
10177        to_machine: impl AsRef<str>,
10178        to_input_variant: impl AsRef<str>,
10179        payload_expr: &str,
10180        effect_id_expr: &str,
10181        source_transition: impl AsRef<str>,
10182    ) -> String {
10183        let to_machine = to_machine.as_ref();
10184        format!(
10185            "[route |-> {}, source_machine |-> {}, effect |-> {}, target_machine |-> {}, target_input |-> {}, payload |-> {}, actor |-> {}, effect_id |-> {}, source_transition |-> {}]",
10186            tla_string(route_name),
10187            tla_string(from_machine),
10188            tla_string(effect_variant),
10189            tla_string(to_machine),
10190            tla_string(to_input_variant),
10191            payload_expr,
10192            tla_string(self.actor(to_machine)),
10193            effect_id_expr,
10194            tla_string(source_transition)
10195        )
10196    }
10197
10198    fn render_machine_transition_action(
10199        &self,
10200        compiler: &mut MachineTlaCompiler<'_>,
10201        instance_id: &str,
10202        transition: &TransitionSchema,
10203        out: &mut String,
10204    ) -> std::result::Result<(), CompositionTlaError> {
10205        let machine = self.machine(instance_id);
10206        let action_name = self.machine_transition_name(instance_id, transition);
10207        let binding_types = compiler.binding_type_map(transition);
10208        let binding_env = transition
10209            .on
10210            .bindings()
10211            .iter()
10212            .map(|binding| {
10213                (
10214                    binding.as_str().to_owned(),
10215                    format!("packet.payload.{}", tla_ident(binding)),
10216                )
10217            })
10218            .collect::<BTreeMap<String, _>>();
10219        let params = transition
10220            .on
10221            .bindings()
10222            .iter()
10223            .map(|binding| format!("arg_{}", tla_ident(binding)))
10224            .collect::<Vec<_>>();
10225
10226        if params.is_empty() {
10227            writeln!(out, "{} ==", action_name);
10228        } else {
10229            pushln!(out, "{}({}) ==", action_name, params.join(", "));
10230        }
10231
10232        let phase_var = self.phase_var(instance_id);
10233        let from_guard = if transition.from.len() == 1 {
10234            format!("{} = {}", phase_var, tla_string(&transition.from[0]))
10235        } else {
10236            transition
10237                .from
10238                .iter()
10239                .map(|phase| format!("{} = {}", phase_var, tla_string(phase)))
10240                .collect::<Vec<_>>()
10241                .join(" \\/ ")
10242        };
10243
10244        pushln!(out, "    /\\ \\E packet \\in SeqElements(pending_inputs) :");
10245        writeln!(
10246            out,
10247            "       /\\ packet.machine = {}",
10248            tla_string(instance_id)
10249        )
10250        .expect("write to string");
10251        writeln!(
10252            out,
10253            "       /\\ packet.variant = {}",
10254            tla_string(transition.on.variant_str())
10255        )
10256        .expect("write to string");
10257        for binding in transition.on.bindings() {
10258            let arg_name = format!("arg_{}", tla_ident(binding));
10259            writeln!(
10260                out,
10261                "       /\\ packet.payload.{} = {}",
10262                tla_ident(binding),
10263                arg_name
10264            )
10265            .expect("write to string");
10266        }
10267        writeln!(
10268            out,
10269            "       /\\ ~HigherPriorityReady({})",
10270            tla_string(self.actor(instance_id))
10271        )
10272        .expect("write to string");
10273        writeln!(out, "       /\\ {}", from_guard);
10274
10275        let field_env = self.machine_field_env(instance_id);
10276        for guard in &transition.guards {
10277            writeln!(
10278                out,
10279                "       /\\ {}",
10280                compiler.render_guard(guard, &field_env, &binding_env, &binding_types)
10281            )
10282            .expect("write to string");
10283        }
10284
10285        let next_env = compiler.compile_updates(
10286            &action_name,
10287            &field_env,
10288            &binding_env,
10289            &binding_types,
10290            &transition.updates,
10291        );
10292        let effect_id_expr = "(model_step_count + 1)".to_string();
10293        let current_phase_symbol = compiler.phase_symbol.clone();
10294        compiler.phase_symbol = Some(tla_string(&transition.to));
10295        let effect_packets = transition
10296            .emit
10297            .iter()
10298            .map(|effect| {
10299                let payload_fields = effect
10300                    .fields
10301                    .iter()
10302                    .map(|(field, expr)| {
10303                        (
10304                            field.as_str().to_owned(),
10305                            compiler.render_expr_with_types(
10306                                expr,
10307                                &next_env,
10308                                &binding_env,
10309                                &binding_types,
10310                            ),
10311                        )
10312                    })
10313                    .collect::<BTreeMap<String, _>>();
10314                (
10315                    effect.variant.as_str().to_owned(),
10316                    format!(
10317                        "[machine |-> {}, variant |-> {}, payload |-> {}, effect_id |-> {}, source_transition |-> {}]",
10318                        tla_string(instance_id),
10319                        tla_string(&effect.variant),
10320                        self.payload_record_expr(&payload_fields),
10321                        effect_id_expr,
10322                        tla_string(&transition.name)
10323                    ),
10324                    payload_fields,
10325                )
10326            })
10327            .collect::<Vec<_>>();
10328        compiler.phase_symbol = current_phase_symbol;
10329
10330        let mut queued_route_packets = Vec::new();
10331        let mut immediate_route_packets = Vec::new();
10332        let mut owner_route_quantifiers = Vec::new();
10333        for (effect_variant, _effect_packet, payload_fields) in &effect_packets {
10334            for route in self.schema.routes.iter().filter(|route| {
10335                route.from_machine.as_str() == instance_id
10336                    && route.effect_variant.as_str() == effect_variant.as_str()
10337            }) {
10338                let (target_payload, route_owner_quantifiers) = self.target_payload_for_route(
10339                    machine,
10340                    effect_variant,
10341                    payload_fields,
10342                    route,
10343                    compiler,
10344                    &next_env,
10345                    &binding_env,
10346                    &binding_types,
10347                );
10348                for quantifier in route_owner_quantifiers {
10349                    if !owner_route_quantifiers.contains(&quantifier) {
10350                        owner_route_quantifiers.push(quantifier);
10351                    }
10352                }
10353                let route_packet = self.route_packet_expr(
10354                    &route.name,
10355                    instance_id,
10356                    effect_variant,
10357                    &route.to.machine,
10358                    &route.to.input_variant,
10359                    &target_payload,
10360                    &effect_id_expr,
10361                    &transition.name,
10362                );
10363                match route.delivery {
10364                    RouteDelivery::Enqueue => {
10365                        queued_route_packets.push((route_packet, target_payload))
10366                    }
10367                    RouteDelivery::Immediate => immediate_route_packets.push((
10368                        route_packet,
10369                        self.input_packet_expr_from_payload_expr(
10370                            &route.to.machine,
10371                            &route.to.input_variant,
10372                            &target_payload,
10373                            "route",
10374                            &route.name,
10375                            instance_id,
10376                            effect_variant,
10377                            &effect_id_expr,
10378                        ),
10379                    )),
10380                }
10381            }
10382        }
10383
10384        writeln!(
10385            out,
10386            "       /\\ {}' = {}",
10387            phase_var,
10388            tla_string(&transition.to)
10389        )
10390        .expect("write to string");
10391        let touched = machine
10392            .state
10393            .fields
10394            .iter()
10395            .filter_map(|field| {
10396                let next = next_env.get(field.name.as_str())?;
10397                if field_env
10398                    .get(field.name.as_str())
10399                    .is_some_and(|current| next != current)
10400                {
10401                    Some((field.name.as_str(), next.as_str()))
10402                } else {
10403                    None
10404                }
10405            })
10406            .collect::<Vec<_>>();
10407        for (field, expr) in &touched {
10408            writeln!(
10409                out,
10410                "       /\\ {}' = {}",
10411                self.field_var(instance_id, field),
10412                expr
10413            )
10414            .expect("write to string");
10415        }
10416
10417        let mut unchanged_machine_vars = Vec::new();
10418        for instance in &self.schema.machines {
10419            if instance.instance_id.as_str() == instance_id {
10420                for field in &machine.state.fields {
10421                    if !touched.iter().any(|(name, _)| *name == field.name.as_str()) {
10422                        unchanged_machine_vars
10423                            .push(self.field_var(instance_id, field.name.as_str()));
10424                    }
10425                }
10426            } else {
10427                unchanged_machine_vars.push(self.phase_var(instance.instance_id.as_str()));
10428                let other_machine = self.machine(instance.instance_id.as_str());
10429                for field in &other_machine.state.fields {
10430                    unchanged_machine_vars
10431                        .push(self.field_var(instance.instance_id.as_str(), field.name.as_str()));
10432                }
10433            }
10434        }
10435
10436        unchanged_machine_vars.push("witness_current_script_input".into());
10437        unchanged_machine_vars.push("witness_remaining_script_inputs".into());
10438
10439        if !unchanged_machine_vars.is_empty() {
10440            self.render_unchanged_vars(out, "       /\\ ", &unchanged_machine_vars);
10441        }
10442
10443        let pending_inputs_next = self.append_if_missing_chain(
10444            format!("SeqRemove(pending_inputs, packet)"),
10445            &immediate_route_packets
10446                .iter()
10447                .map(|(_, input_packet)| input_packet)
10448                .cloned()
10449                .collect::<Vec<_>>(),
10450        );
10451        let pending_routes_next = self.append_if_missing_chain(
10452            "pending_routes".into(),
10453            &queued_route_packets
10454                .iter()
10455                .map(|(route_packet, _)| route_packet)
10456                .cloned()
10457                .collect::<Vec<_>>(),
10458        );
10459        let delivered_routes_next = if immediate_route_packets.is_empty() {
10460            "delivered_routes".into()
10461        } else {
10462            format!(
10463                "delivered_routes \\cup {{ {} }}",
10464                immediate_route_packets
10465                    .iter()
10466                    .map(|(route_packet, _)| route_packet)
10467                    .cloned()
10468                    .collect::<Vec<_>>()
10469                    .join(", ")
10470            )
10471        };
10472        let observed_inputs_next = {
10473            let immediate_inputs = immediate_route_packets
10474                .iter()
10475                .map(|(_, input_packet)| input_packet)
10476                .cloned()
10477                .collect::<Vec<_>>();
10478            self.union_set_items("observed_inputs".into(), &immediate_inputs)
10479        };
10480        let emitted_effects_next = if effect_packets.is_empty() {
10481            "emitted_effects".into()
10482        } else {
10483            format!(
10484                "emitted_effects \\cup {{ {} }}",
10485                effect_packets
10486                    .iter()
10487                    .map(|(_, effect_packet, _)| effect_packet)
10488                    .cloned()
10489                    .collect::<Vec<_>>()
10490                    .join(", ")
10491            )
10492        };
10493        let observed_transitions_next = format!(
10494            "observed_transitions \\cup {{{}}}",
10495            self.transition_packet_expr(instance_id, transition)
10496        );
10497
10498        // Compute obligation set updates: when a transition emits an effect
10499        // that matches a handoff_protocol, add a record to the obligation set
10500        // with the protocol's declared obligation fields from the effect payload.
10501        let mut obligation_updates: BTreeMap<String, String> = BTreeMap::new();
10502        for (effect_variant, _effect_packet, payload_fields) in &effect_packets {
10503            for protocol in &self.schema.handoff_protocols {
10504                if protocol.producer_instance.as_str() == instance_id
10505                    && protocol.effect_variant.as_str() == effect_variant.as_str()
10506                {
10507                    let var = self.obligation_var(protocol);
10508                    let mut record_fields: Vec<String> =
10509                        Vec::with_capacity(protocol.obligation_fields.len() + 1);
10510                    record_fields.push("effect_id |-> (model_step_count + 1)".to_string());
10511                    for field in &protocol.obligation_fields {
10512                        let tla_field = tla_ident(field);
10513                        // Fail closed: an obligation field that is absent from
10514                        // the matching effect's payload used to be papered over
10515                        // with an `"unknown_<field>"` sentinel literal.
10516                        let value =
10517                            payload_fields.get(field.as_str()).cloned().ok_or_else(|| {
10518                                CompositionTlaError::UnknownObligationField {
10519                                    composition: self.schema.name.as_str().to_owned(),
10520                                    protocol: protocol.name.as_str().to_owned(),
10521                                    effect: effect_variant.clone(),
10522                                    field: field.as_str().to_owned(),
10523                                }
10524                            })?;
10525                        record_fields.push(format!("{} |-> {}", tla_field, value));
10526                    }
10527                    let record = if record_fields.is_empty() {
10528                        "\"token\"".to_string()
10529                    } else {
10530                        format!("[{}]", record_fields.join(", "))
10531                    };
10532                    obligation_updates.insert(var.clone(), format!("{} \\cup {{{}}}", var, record));
10533                }
10534            }
10535        }
10536
10537        let route_update_prefix = if owner_route_quantifiers.is_empty() {
10538            "       /\\"
10539        } else {
10540            writeln!(
10541                out,
10542                "       /\\ \\E {} :",
10543                owner_route_quantifiers.join(", ")
10544            )
10545            .expect("write to string");
10546            "           /\\"
10547        };
10548        writeln!(
10549            out,
10550            "{route_update_prefix} pending_inputs' = {pending_inputs_next}"
10551        )
10552        .expect("write to string");
10553        writeln!(
10554            out,
10555            "{route_update_prefix} observed_inputs' = {observed_inputs_next}"
10556        )
10557        .expect("write to string");
10558        writeln!(
10559            out,
10560            "{route_update_prefix} pending_routes' = {pending_routes_next}"
10561        )
10562        .expect("write to string");
10563        writeln!(
10564            out,
10565            "{route_update_prefix} delivered_routes' = {delivered_routes_next}"
10566        )
10567        .expect("write to string");
10568        writeln!(
10569            out,
10570            "{route_update_prefix} emitted_effects' = {emitted_effects_next}"
10571        )
10572        .expect("write to string");
10573        writeln!(
10574            out,
10575            "{route_update_prefix} observed_transitions' = {observed_transitions_next}"
10576        )
10577        .expect("write to string");
10578        // Write obligation variable updates — touched protocols get \cup, untouched get UNCHANGED
10579        let all_obligation_vars = self.obligation_vars();
10580        let mut unchanged_obligation_vars = Vec::new();
10581        for ovar in &all_obligation_vars {
10582            if let Some(next_expr) = obligation_updates.get(ovar) {
10583                writeln!(out, "{route_update_prefix} {}' = {}", ovar, next_expr)
10584                    .expect("write to string");
10585            } else {
10586                unchanged_obligation_vars.push(ovar.clone());
10587            }
10588        }
10589        if !unchanged_obligation_vars.is_empty() {
10590            let unchanged_prefix = format!("{route_update_prefix} ");
10591            self.render_unchanged_vars(out, &unchanged_prefix, &unchanged_obligation_vars);
10592        }
10593        writeln!(
10594            out,
10595            "{route_update_prefix} model_step_count' = model_step_count + 1"
10596        )
10597        .expect("write to string");
10598        Ok(())
10599    }
10600
10601    fn target_payload_for_route(
10602        &self,
10603        source_machine: &MachineSchema,
10604        effect_variant: &str,
10605        effect_payload_fields: &BTreeMap<String, String>,
10606        route: &Route,
10607        compiler: &MachineTlaCompiler<'_>,
10608        next_env: &BTreeMap<String, String>,
10609        binding_env: &BTreeMap<String, String>,
10610        binding_types: &BTreeMap<String, TypeRef>,
10611    ) -> (String, Vec<String>) {
10612        let target_machine = self.machine(route.to.machine.as_str());
10613        let Some(target_variant) = route_target_variant(target_machine, &route.to) else {
10614            return (String::new(), Vec::new());
10615        };
10616        let Ok(source_effect_variant) = source_machine.effects.variant_named(effect_variant) else {
10617            return (String::new(), Vec::new());
10618        };
10619        let mut owner_context_quantifiers = Vec::new();
10620        let bindings = route
10621            .bindings
10622            .iter()
10623            .map(|binding| {
10624                let expr = match &binding.source {
10625                    RouteBindingSource::Field {
10626                        from_field,
10627                        allow_named_alias: _,
10628                    } => effect_payload_fields
10629                        .get(from_field.as_str())
10630                        .cloned()
10631                        .or_else(|| {
10632                            source_effect_variant
10633                                .fields
10634                                .iter()
10635                                .find(|field| field.name == *from_field)
10636                                .map(|_| format!("packet.payload.{}", tla_ident(from_field)))
10637                        })
10638                        .unwrap_or_else(|| "None".to_string()),
10639                    RouteBindingSource::Literal(expr) => {
10640                        compiler.render_expr_with_types(expr, next_env, binding_env, binding_types)
10641                    }
10642                    RouteBindingSource::OwnerProvided => {
10643                        if let Some(target_field) = target_variant
10644                            .fields
10645                            .iter()
10646                            .find(|field| field.name == binding.to_field)
10647                        {
10648                            let var_name = format!(
10649                                "route_owner_ctx_{}_{}",
10650                                tla_ident(&route.name),
10651                                tla_ident(&binding.to_field)
10652                            );
10653                            let domain = self.binding_domain_for_binding(
10654                                route.to.machine.as_str(),
10655                                Some(target_variant.name.as_str()),
10656                                binding.to_field.as_str(),
10657                                &target_field.ty,
10658                            );
10659                            owner_context_quantifiers.push(format!("{var_name} \\in {domain}"));
10660                            var_name
10661                        } else {
10662                            "\"owner_val\"".to_string()
10663                        }
10664                    }
10665                };
10666                (binding.to_field.as_str().to_owned(), expr)
10667            })
10668            .collect::<BTreeMap<String, _>>();
10669        let payload_fields = target_variant
10670            .fields
10671            .iter()
10672            .map(|field| {
10673                let expr = bindings
10674                    .get(field.name.as_str())
10675                    .cloned()
10676                    .unwrap_or_else(|| default_state_init_expr(&field.ty));
10677                (field.name.as_str().to_owned(), expr)
10678            })
10679            .collect::<BTreeMap<String, _>>();
10680        (
10681            self.payload_record_expr(&payload_fields),
10682            owner_context_quantifiers,
10683        )
10684    }
10685
10686    fn append_if_missing_chain(&self, base: String, items: &[String]) -> String {
10687        items.iter().fold(base, |expr, item| {
10688            format!("AppendIfMissing({expr}, {item})")
10689        })
10690    }
10691
10692    fn union_set_items(&self, base: String, items: &[String]) -> String {
10693        if items.is_empty() {
10694            base
10695        } else {
10696            format!("{base} \\cup {{{}}}", items.join(", "))
10697        }
10698    }
10699
10700    fn transition_packet_expr(&self, instance_id: &str, transition: &TransitionSchema) -> String {
10701        format!(
10702            "[machine |-> {}, transition |-> {}, actor |-> {}, step |-> (model_step_count + 1), from_phase |-> {}, to_phase |-> {}]",
10703            tla_string(instance_id),
10704            tla_string(&transition.name),
10705            tla_string(self.actor(instance_id)),
10706            self.phase_var(instance_id),
10707            tla_string(&transition.to)
10708        )
10709    }
10710}
10711
10712#[derive(Clone, Copy)]
10713enum OrderingOperator {
10714    Lt,
10715    Lte,
10716    Gt,
10717    Gte,
10718}
10719
10720struct MachineTlaCompiler<'a> {
10721    schema: &'a MachineSchema,
10722    named_bindings: BTreeMap<String, meerkat_machine_schema::RustTypeAtom>,
10723    helper_defs: Vec<String>,
10724    helper_counter: usize,
10725    helper_prefix: Option<String>,
10726    phase_symbol: Option<String>,
10727    field_env_override: Option<BTreeMap<String, String>>,
10728    unchanged_frames: UnchangedFrameInterner,
10729    /// Set when an ordering comparison renders through `OptionLt` /
10730    /// `OptionLe`; the module then defines them. Shared by every compiler
10731    /// that renders into the same module.
10732    option_order_used: Rc<Cell<bool>>,
10733}
10734
10735impl<'a> MachineTlaCompiler<'a> {
10736    fn new(schema: &'a MachineSchema) -> Self {
10737        Self {
10738            schema,
10739            named_bindings: collect_machine_named_bindings(schema),
10740            helper_defs: Vec::new(),
10741            helper_counter: 0,
10742            helper_prefix: None,
10743            phase_symbol: None,
10744            field_env_override: None,
10745            unchanged_frames: UnchangedFrameInterner::default(),
10746            option_order_used: Rc::default(),
10747        }
10748    }
10749
10750    fn new_with_helper_prefix(schema: &'a MachineSchema, helper_prefix: impl Into<String>) -> Self {
10751        Self {
10752            schema,
10753            named_bindings: collect_machine_named_bindings(schema),
10754            helper_defs: Vec::new(),
10755            helper_counter: 0,
10756            helper_prefix: Some(helper_prefix.into()),
10757            phase_symbol: None,
10758            field_env_override: None,
10759            unchanged_frames: UnchangedFrameInterner::default(),
10760            option_order_used: Rc::default(),
10761        }
10762    }
10763
10764    fn with_option_order_flag(mut self, option_order_used: Rc<Cell<bool>>) -> Self {
10765        self.option_order_used = option_order_used;
10766        self
10767    }
10768
10769    fn with_phase_symbol(mut self, phase_symbol: impl Into<String>) -> Self {
10770        self.phase_symbol = Some(phase_symbol.into());
10771        self
10772    }
10773
10774    fn with_field_env_override(mut self, field_env_override: BTreeMap<String, String>) -> Self {
10775        self.field_env_override = Some(field_env_override);
10776        self
10777    }
10778
10779    fn render(&mut self) -> std::result::Result<String, CompositionTlaError> {
10780        let mut out = String::new();
10781        let constants = collect_binding_domains(self.schema);
10782        let named_samples = collect_machine_named_type_samples(self.schema);
10783        let named_bindings = collect_machine_named_bindings(self.schema);
10784
10785        pushln!(&mut out, "---- MODULE model ----");
10786        pushln!(&mut out, "EXTENDS TLC, Naturals, Sequences, FiniteSets");
10787        pushln!(&mut out);
10788        writeln!(
10789            &mut out,
10790            "\\* Generated semantic machine model for {}.",
10791            self.schema.machine
10792        )
10793        .expect("write to string");
10794        pushln!(&mut out);
10795
10796        let mut model_constants = constants
10797            .iter()
10798            .filter(|(_, ty)| {
10799                !matches!(
10800                    ty,
10801                    TypeRef::Seq(_) | TypeRef::Option(_) | TypeRef::Map(_, _)
10802                )
10803            })
10804            .map(|(name, _)| name)
10805            .cloned()
10806            .collect::<Vec<_>>();
10807        model_constants.extend(
10808            machine_input_sample_constants(self.schema)
10809                .into_iter()
10810                .map(|(constant, _)| constant),
10811        );
10812        model_constants.extend(
10813            machine_input_typed_sample_constants(self.schema)
10814                .into_iter()
10815                .map(|(constant, _, _)| constant),
10816        );
10817        if machine_uses_u64_max(self.schema) {
10818            model_constants.push(TLA_RUST_U64_MAX_CONSTANT.to_owned());
10819        }
10820        if !model_constants.is_empty() {
10821            let constant_list = model_constants.join(", ");
10822            if model_constants
10823                .iter()
10824                .any(|constant| constant == TLA_RUST_U64_MAX_CONSTANT)
10825            {
10826                pushln!(
10827                    &mut out,
10828                    "\\* RustU64Max is the TLA boundary for Expr::U64Max; production generated Rust renders u64::MAX."
10829                );
10830            }
10831            writeln!(&mut out, "CONSTANTS {constant_list}");
10832            pushln!(&mut out);
10833        }
10834
10835        pushln!(&mut out, "None == [tag |-> \"none\", value |-> \"none\"]");
10836        writeln!(&mut out, "Some(v) == [tag |-> \"some\", value |-> v]");
10837        pushln!(&mut out);
10838        let option_order_anchor = out.len();
10839
10840        push_cfg_assignment_operator_definitions(
10841            &mut out,
10842            &constants,
10843            &named_bindings,
10844            &CfgAssignmentOperatorProfile {
10845                suffix: "Ci".to_owned(),
10846                explicit_values: self.schema.tlc_model.as_ref().map(|model| &model.ci),
10847                sample_cardinality: machine_cfg_sample_cardinality(self.schema, false),
10848                domain_overrides: None,
10849                named_samples: &named_samples,
10850                include_string_samples: false,
10851            },
10852        );
10853        push_cfg_assignment_operator_definitions(
10854            &mut out,
10855            &constants,
10856            &named_bindings,
10857            &CfgAssignmentOperatorProfile {
10858                suffix: "Deep".to_owned(),
10859                explicit_values: self.schema.tlc_model.as_ref().map(|model| &model.deep),
10860                sample_cardinality: machine_cfg_sample_cardinality(self.schema, true),
10861                domain_overrides: Some(&self.schema.deep_domain_overrides),
10862                named_samples: &with_guard_binding_string_samples(&named_samples, self.schema),
10863                include_string_samples: !machine_uses_session_id_string_bridge(self.schema),
10864            },
10865        );
10866
10867        for (name, ty) in ordered_composite_domain_definitions(&constants) {
10868            let definition = match ty {
10869                TypeRef::Seq(inner) => render_sequence_domain_definition(inner),
10870                TypeRef::Option(inner) => render_option_domain_definition(inner),
10871                TypeRef::Map(key, value) => render_map_domain_definition(key, value),
10872                _ => continue,
10873            };
10874            writeln!(&mut out, "{} == {}", name, definition).expect("write to string");
10875        }
10876        if constants.values().any(|ty| {
10877            matches!(
10878                ty,
10879                TypeRef::Seq(_) | TypeRef::Option(_) | TypeRef::Map(_, _)
10880            )
10881        }) {
10882            pushln!(&mut out);
10883        }
10884        // What each profile's config assigns a `CiSamples` input field's
10885        // constant: the CI profile the declared values, the Deep profile the
10886        // field type's whole domain (defined above).
10887        let typed_samples = machine_input_typed_sample_constants(self.schema);
10888        for (constant, samples, ty) in &typed_samples {
10889            writeln!(
10890                &mut out,
10891                "{} == {}",
10892                cfg_assignment_operator_name(constant, "Ci"),
10893                render_explicit_values(samples)
10894            )
10895            .expect("write to string");
10896            writeln!(
10897                &mut out,
10898                "{} == {}",
10899                cfg_assignment_operator_name(constant, "Deep"),
10900                self.binding_domain_for_type(ty)
10901            )
10902            .expect("write to string");
10903        }
10904        if !typed_samples.is_empty() {
10905            pushln!(&mut out);
10906        }
10907        writeln!(
10908            &mut out,
10909            "MapLookup(map, key) == IF key \\in DOMAIN map THEN map[key] ELSE None"
10910        )
10911        .expect("write to string");
10912        writeln!(
10913            &mut out,
10914            "MapSet(map, key, value) == [x \\in DOMAIN map \\cup {{key}} |-> IF x = key THEN value ELSE map[x]]"
10915        )
10916        .expect("write to string");
10917        writeln!(
10918            &mut out,
10919            "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]]"
10920        )
10921        .expect("write to string");
10922        writeln!(
10923            &mut out,
10924            "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]]"
10925        )
10926        .expect("write to string");
10927        writeln!(
10928            &mut out,
10929            "MapRemove(map, key) == [x \\in DOMAIN map \\ {{key}} |-> map[x]]"
10930        )
10931        .expect("write to string");
10932        writeln!(
10933            &mut out,
10934            "StartsWith(seq, prefix) == /\\ Len(prefix) <= Len(seq) /\\ SubSeq(seq, 1, Len(prefix)) = prefix"
10935        )
10936        .expect("write to string");
10937        writeln!(
10938            &mut out,
10939            "SeqElements(seq) == {{seq[i] : i \\in 1..Len(seq)}}"
10940        )
10941        .expect("write to string");
10942        writeln!(
10943            &mut out,
10944            "Count(seq, value) == Cardinality({{i \\in DOMAIN seq : seq[i] = value}})"
10945        )
10946        .expect("write to string");
10947        if !self.schema.tlc_representative_inputs.is_empty() {
10948            writeln!(
10949                &mut out,
10950                "{TLC_REPRESENTATIVE_DOMAIN_HELPER}(values) == IF values = {{}} THEN {{}} ELSE {{CHOOSE value \\in values : TRUE}}"
10951            )
10952            .expect("write to string");
10953        }
10954        writeln!(
10955            &mut out,
10956            "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)"
10957        )
10958        .expect("write to string");
10959        writeln!(
10960            &mut out,
10961            "RECURSIVE SeqRemoveAll(_, _)\nSeqRemoveAll(seq, values) == IF Len(values) = 0 THEN seq ELSE SeqRemoveAll(SeqRemove(seq, Head(values)), Tail(values))"
10962        )
10963        .expect("write to string");
10964        pushln!(&mut out);
10965
10966        let variable_list = std::iter::once("phase".to_string())
10967            .chain(std::iter::once("model_step_count".to_string()))
10968            .chain(
10969                self.schema
10970                    .state
10971                    .fields
10972                    .iter()
10973                    .map(|field| field.name.as_str().to_owned()),
10974            )
10975            .collect::<Vec<_>>()
10976            .join(", ");
10977        pushln!(&mut out, "VARIABLES {variable_list}");
10978        pushln!(&mut out);
10979        let vars = std::iter::once("phase".to_string())
10980            .chain(std::iter::once("model_step_count".to_string()))
10981            .chain(
10982                self.schema
10983                    .state
10984                    .fields
10985                    .iter()
10986                    .map(|field| field.name.as_str().to_owned()),
10987            )
10988            .collect::<Vec<_>>();
10989        pushln!(&mut out, "vars == << {} >>", vars.join(", "));
10990        pushln!(&mut out);
10991
10992        for helper in helper_dependency_order(self.schema)? {
10993            self.render_helper(&mut out, helper);
10994        }
10995        if self.schema.machine.as_str() == "MobMachine" {
10996            self.render_mob_machine_native_helpers(&mut out);
10997        }
10998        if self.schema.machine.as_str() == "MeerkatMachine" {
10999            self.render_meerkat_machine_native_helpers(&mut out);
11000        }
11001        if self.schema.machine.as_str() == "RuntimeDeliveryMachine" {
11002            self.render_runtime_delivery_native_helpers(&mut out);
11003        }
11004        if self.schema.machine.as_str() == "SessionDocumentMachine" {
11005            self.render_session_document_native_helpers(&mut out);
11006        }
11007        if !self.schema.helpers.is_empty() || !self.schema.derived.is_empty() {
11008            pushln!(&mut out);
11009        }
11010
11011        pushln!(&mut out, "Init ==");
11012        writeln!(
11013            &mut out,
11014            "    /\\ phase = {}",
11015            tla_string(&self.schema.state.init.phase)
11016        )
11017        .expect("write to string");
11018        pushln!(&mut out, "    /\\ model_step_count = 0");
11019        for field in &self.schema.state.fields {
11020            let init_expr = self
11021                .schema
11022                .state
11023                .init
11024                .fields
11025                .iter()
11026                .find(|item| item.field == field.name)
11027                .map(|item| self.render_expr(&item.expr, &BTreeMap::new(), &BTreeMap::new()))
11028                .unwrap_or_else(|| default_state_init_expr(&field.ty));
11029            pushln!(&mut out, "    /\\ {} = {}", field.name, init_expr);
11030        }
11031        pushln!(&mut out);
11032
11033        let mut rendered_transitions = Vec::new();
11034        for transition in &self.schema.transitions {
11035            let mut rendered = String::new();
11036            self.render_transition(&mut rendered, transition);
11037            rendered_transitions.push(rendered);
11038        }
11039
11040        if !self.schema.state.terminal_phases.is_empty() {
11041            let terminal_guard = if self.schema.state.terminal_phases.len() == 1 {
11042                format!(
11043                    "phase = {}",
11044                    tla_string(&self.schema.state.terminal_phases[0])
11045                )
11046            } else {
11047                self.schema
11048                    .state
11049                    .terminal_phases
11050                    .iter()
11051                    .map(|phase| format!("phase = {}", tla_string(phase)))
11052                    .collect::<Vec<_>>()
11053                    .join(" \\/ ")
11054            };
11055            pushln!(&mut out, "TerminalStutter ==");
11056            pushln!(&mut out, "    /\\ {}", terminal_guard);
11057            pushln!(&mut out, "    /\\ UNCHANGED vars");
11058            pushln!(&mut out);
11059        }
11060
11061        // Fail closed on a frame-name collision: the rendered transitions
11062        // already reference one name for two different frames, so returning the
11063        // module would silently give an action the wrong frame condition.
11064        if let Some(collision) = self.unchanged_frames.collision() {
11065            return Err(CompositionTlaError::MachineUnchangedFrameCollision {
11066                machine: self.schema.machine.as_str().to_owned(),
11067                collision: collision.clone(),
11068            });
11069        }
11070        // Every frame variable is in scope from the VARIABLES declaration
11071        // above, and every reference is in the transition bodies below.
11072        out.push_str(&self.unchanged_frames.definitions_block());
11073
11074        if !self.helper_defs.is_empty() {
11075            for helper in &self.helper_defs {
11076                pushln!(&mut out, "{helper}");
11077                pushln!(&mut out);
11078            }
11079        }
11080
11081        for transition in &rendered_transitions {
11082            pushln!(&mut out, "{transition}");
11083            pushln!(&mut out);
11084        }
11085
11086        pushln!(&mut out, "Next ==");
11087        for transition in &self.schema.transitions {
11088            let call = if transition.on.bindings().is_empty() {
11089                transition.name.as_str().to_owned()
11090            } else {
11091                let binding_types = self.binding_type_map(transition);
11092                let forced_bool_literals =
11093                    transition_forced_bool_literals(transition, &binding_types);
11094                let binding_env = transition
11095                    .on
11096                    .bindings()
11097                    .iter()
11098                    .map(|binding| {
11099                        (
11100                            binding.as_str().to_owned(),
11101                            self.local_binding_name(binding.as_str()),
11102                        )
11103                    })
11104                    .collect::<BTreeMap<_, _>>();
11105                let mut prefix = String::new();
11106                for binding in transition.on.bindings() {
11107                    if forced_bool_literals.contains_key(binding.as_str()) {
11108                        continue;
11109                    }
11110                    let Some(ty) = binding_types.get(binding.as_str()) else {
11111                        return Ok(String::new());
11112                    };
11113                    let domain = self.binding_domain_for_binding(
11114                        trigger_input_variant(transition),
11115                        binding.as_str(),
11116                        ty,
11117                    );
11118                    let domain =
11119                        if transition_uses_tlc_representative_payload(self.schema, transition) {
11120                            tlc_representative_domain(domain)
11121                        } else {
11122                            domain
11123                        };
11124                    let local = binding_env
11125                        .get(binding.as_str())
11126                        .cloned()
11127                        .unwrap_or_else(|| binding.as_str().to_owned());
11128                    prefix.push_str(&format!("\\E {local} \\in {domain} : "));
11129                }
11130                let args = transition
11131                    .on
11132                    .bindings()
11133                    .iter()
11134                    .map(|binding| {
11135                        forced_bool_literals
11136                            .get(binding.as_str())
11137                            .map(|value| tla_bool_literal(*value).to_owned())
11138                            .unwrap_or_else(|| {
11139                                binding_env
11140                                    .get(binding.as_str())
11141                                    .cloned()
11142                                    .unwrap_or_else(|| binding.as_str().to_owned())
11143                            })
11144                    })
11145                    .collect::<Vec<_>>()
11146                    .join(", ");
11147                // Hoist the source-phase guard ahead of the parameter
11148                // quantifiers. The guard is the first conjunct of the action
11149                // body too, so the disjunct is unchanged in meaning, but TLC
11150                // no longer splits it into one action per parameter tuple
11151                // that it must enumerate in every state: states outside the
11152                // source phase reject the whole disjunct at once.
11153                let from_guard = transition
11154                    .from
11155                    .iter()
11156                    .map(|phase| format!("phase = {}", tla_string(phase)))
11157                    .collect::<Vec<_>>()
11158                    .join(" \\/ ");
11159                if prefix.is_empty() || from_guard.is_empty() {
11160                    format!("{prefix}{}({})", transition.name, args)
11161                } else {
11162                    format!("({from_guard}) /\\ {prefix}{}({})", transition.name, args)
11163                }
11164            };
11165            pushln!(&mut out, "    \\/ {}", call);
11166        }
11167        if !self.schema.state.terminal_phases.is_empty() {
11168            pushln!(&mut out, "    \\/ TerminalStutter");
11169        }
11170        pushln!(&mut out);
11171
11172        for invariant in &self.schema.invariants {
11173            writeln!(
11174                &mut out,
11175                "{} == {}",
11176                invariant.name,
11177                self.render_expr(&invariant.expr, &BTreeMap::new(), &BTreeMap::new())
11178            )
11179            .expect("write to string");
11180        }
11181        pushln!(&mut out);
11182
11183        writeln!(
11184            &mut out,
11185            "CiStateConstraint == {}",
11186            render_machine_state_constraint(self.schema, false)
11187        )
11188        .expect("write to string");
11189        writeln!(
11190            &mut out,
11191            "DeepStateConstraint == {}",
11192            render_machine_state_constraint(self.schema, true)
11193        )
11194        .expect("write to string");
11195        pushln!(&mut out);
11196
11197        pushln!(&mut out, "Spec == Init /\\ [][Next]_vars");
11198        pushln!(&mut out);
11199        for invariant in &self.schema.invariants {
11200            pushln!(&mut out, "THEOREM Spec => []{}", invariant.name);
11201        }
11202        pushln!(&mut out);
11203        writeln!(
11204            &mut out,
11205            "============================================================================="
11206        )
11207        .expect("write to string");
11208
11209        if self.option_order_used.get() {
11210            out.insert_str(option_order_anchor, TLA_OPTION_ORDER_DEFINITIONS);
11211        }
11212        Ok(out)
11213    }
11214
11215    fn render_helper(&self, out: &mut String, helper: &HelperSchema) {
11216        let params = helper
11217            .params
11218            .iter()
11219            .map(|field| self.local_binding_name(field.name.as_str()))
11220            .collect::<Vec<_>>()
11221            .join(", ");
11222        let binding_env = helper
11223            .params
11224            .iter()
11225            .map(|field| {
11226                (
11227                    field.name.as_str().to_owned(),
11228                    self.local_binding_name(field.name.as_str()),
11229                )
11230            })
11231            .collect::<BTreeMap<String, _>>();
11232        let field_env = self.field_env_override.clone().unwrap_or_else(|| {
11233            self.schema
11234                .state
11235                .fields
11236                .iter()
11237                .map(|field| {
11238                    (
11239                        field.name.as_str().to_owned(),
11240                        field.name.as_str().to_owned(),
11241                    )
11242                })
11243                .collect::<BTreeMap<String, _>>()
11244        });
11245        let binding_types = helper
11246            .params
11247            .iter()
11248            .map(|field| (field.name.as_str().to_owned(), field.ty.clone()))
11249            .collect::<BTreeMap<String, _>>();
11250        if helper.params.is_empty() {
11251            writeln!(
11252                out,
11253                "{} == {}",
11254                self.scoped_helper_name(&helper.name),
11255                self.render_expr_with_types(&helper.body, &field_env, &binding_env, &binding_types)
11256            )
11257            .expect("write to string");
11258        } else {
11259            writeln!(
11260                out,
11261                "{}({}) == {}",
11262                self.scoped_helper_name(&helper.name),
11263                params,
11264                self.render_expr_with_types(&helper.body, &field_env, &binding_env, &binding_types)
11265            )
11266            .expect("write to string");
11267        }
11268    }
11269
11270    fn render_runtime_delivery_native_helpers(&self, out: &mut String) {
11271        writeln!(
11272            out,
11273            "{}(current, recipient, outcome) ==",
11274            self.scoped_helper_name("runtime_delivery_recipient_outcomes_after_set")
11275        )
11276        .expect("write to string");
11277        pushln!(out, "    MapSet(current, recipient, outcome)");
11278    }
11279
11280    fn render_session_document_native_helpers(&self, out: &mut String) {
11281        writeln!(
11282            out,
11283            "{}(current, slot, value) ==",
11284            self.scoped_helper_name("session_document_instruction_slot_after_set")
11285        )
11286        .expect("write to string");
11287        pushln!(out, "    MapSet(current, slot, value)");
11288        // The body bytes of the Active slots; a slot the bytes map does not
11289        // name counts nothing (the Rust authorities agree).
11290        writeln!(
11291            out,
11292            "{}(slot_effect, slot_bytes) ==",
11293            self.scoped_helper_name("session_document_instruction_active_bytes")
11294        )
11295        .expect("write to string");
11296        pushln!(
11297            out,
11298            "    LET RECURSIVE SessionDocumentInstructionActiveBytesOver(_)"
11299        );
11300        pushln!(
11301            out,
11302            "        SessionDocumentInstructionActiveBytesOver(instruction_slots) =="
11303        );
11304        pushln!(out, "            IF instruction_slots = {{}} THEN 0");
11305        pushln!(
11306            out,
11307            "            ELSE LET instruction_slot == CHOOSE candidate_slot \\in instruction_slots : TRUE"
11308        );
11309        pushln!(
11310            out,
11311            "                 IN (IF slot_effect[instruction_slot] = \"Active\" /\\ instruction_slot \\in DOMAIN slot_bytes"
11312        );
11313        pushln!(
11314            out,
11315            "                     THEN slot_bytes[instruction_slot] ELSE 0)"
11316        );
11317        pushln!(
11318            out,
11319            "                    + SessionDocumentInstructionActiveBytesOver(instruction_slots \\ {{instruction_slot}})"
11320        );
11321        pushln!(
11322            out,
11323            "    IN SessionDocumentInstructionActiveBytesOver(DOMAIN slot_effect)"
11324        );
11325        // The entries of a slot map whose slot is Active: what an
11326        // application puts in effect (the Rust authorities agree).
11327        writeln!(
11328            out,
11329            "{}(slot_effect, slot_values) ==",
11330            self.scoped_helper_name("session_document_instruction_active_slots")
11331        )
11332        .expect("write to string");
11333        pushln!(
11334            out,
11335            "    [instruction_slot \\in {{candidate_slot \\in DOMAIN slot_values :"
11336        );
11337        pushln!(
11338            out,
11339            "            candidate_slot \\in DOMAIN slot_effect /\\ slot_effect[candidate_slot] = \"Active\"}}"
11340        );
11341        pushln!(out, "        |-> slot_values[instruction_slot]]");
11342        // Per activation key, the rows a retirement leaves retired: every
11343        // row but the newest, or the recovered count when that is more; a
11344        // key the retired map does not name counts none (the Rust
11345        // authorities agree).
11346        writeln!(
11347            out,
11348            "{}(activation_rows, activation_retired) ==",
11349            self.scoped_helper_name("session_document_activation_retired_after")
11350        )
11351        .expect("write to string");
11352        pushln!(out, "    [activation_key \\in DOMAIN activation_rows |->");
11353        pushln!(
11354            out,
11355            "        LET retired_count == IF activation_key \\in DOMAIN activation_retired THEN activation_retired[activation_key] ELSE 0"
11356        );
11357        pushln!(
11358            out,
11359            "            superseded_count == IF activation_rows[activation_key] > 0 THEN activation_rows[activation_key] - 1 ELSE 0"
11360        );
11361        pushln!(
11362            out,
11363            "        IN IF retired_count >= superseded_count THEN retired_count ELSE superseded_count]"
11364        );
11365    }
11366
11367    fn render_meerkat_machine_native_helpers(&self, out: &mut String) {
11368        let prefix = |name: &str| self.scoped_helper_name(name);
11369        writeln!(
11370            out,
11371            "{}(current, candidate) ==",
11372            prefix("meerkat_machine_session_id_matches_string")
11373        )
11374        .expect("write to string");
11375        pushln!(out, "    current # None /\\ current.value = candidate");
11376        writeln!(
11377            out,
11378            "{}(endpoints, endpoint_count) ==",
11379            prefix("meerkat_peer_endpoint_set_cardinality_matches")
11380        )
11381        .expect("write to string");
11382        pushln!(out, "    Cardinality(endpoints) = endpoint_count");
11383        writeln!(
11384            out,
11385            "{}(endpoints, peer_id) ==",
11386            prefix("meerkat_peer_endpoint_set_contains_peer_id")
11387        )
11388        .expect("write to string");
11389        pushln!(
11390            out,
11391            "    \\E endpoint \\in endpoints: endpoint.peer_id = peer_id"
11392        );
11393        writeln!(
11394            out,
11395            "{}(endpoint, peer_id) ==",
11396            prefix("meerkat_peer_endpoint_option_peer_id_matches")
11397        )
11398        .expect("write to string");
11399        pushln!(
11400            out,
11401            "    endpoint # None /\\ endpoint.value.peer_id = peer_id"
11402        );
11403        writeln!(
11404            out,
11405            "{}(endpoint, peer_id) ==",
11406            prefix("meerkat_peer_endpoint_peer_id_matches")
11407        )
11408        .expect("write to string");
11409        pushln!(out, "    endpoint.peer_id = peer_id");
11410        writeln!(
11411            out,
11412            "{}(endpoints) ==",
11413            prefix("meerkat_peer_endpoint_set_peer_ids_unique")
11414        )
11415        .expect("write to string");
11416        pushln!(
11417            out,
11418            "    Cardinality(endpoints) = Cardinality({{ endpoint.peer_id : endpoint \\in endpoints }})"
11419        );
11420        writeln!(
11421            out,
11422            "{}(rows, operation_by_authority, operation_id) ==",
11423            prefix("meerkat_machine_live_bridge_authority_rows_without_operation")
11424        )
11425        .expect("write to string");
11426        pushln!(
11427            out,
11428            "    [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]]"
11429        );
11430        writeln!(
11431            out,
11432            "{}(authorities, operation_by_authority, operation_id) ==",
11433            prefix("meerkat_machine_live_bridge_authorities_without_operation")
11434        )
11435        .expect("write to string");
11436        pushln!(
11437            out,
11438            "    {{ authority_id \\in authorities : IF authority_id \\in DOMAIN operation_by_authority THEN operation_by_authority[authority_id] # operation_id ELSE TRUE }}"
11439        );
11440        // The inputs still bound to one run: its batch and its durable joins,
11441        // staged or, in a resumed run, applied by a committed round. The
11442        // parameters are prefixed: TLA+ forbids a parameter named like a
11443        // state variable (`input_phases`).
11444        writeln!(
11445            out,
11446            "{}(arg_run_associations, arg_input_phases, arg_run_id) ==",
11447            prefix("meerkat_machine_run_contributor_count")
11448        )
11449        .expect("write to string");
11450        pushln!(
11451            out,
11452            "    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 }})"
11453        );
11454        // The most contributors one run's commit names. A defined operator,
11455        // not a literal in the guard, so a bounded audit can substitute a
11456        // small bound (`meerkat_machine_run_contributor_limit <- ...`) and
11457        // explore the refused join.
11458        writeln!(
11459            out,
11460            "{} == {}",
11461            prefix("meerkat_machine_run_contributor_limit"),
11462            meerkat_machine_schema::catalog::dsl::meerkat_machine::command_capabilities::RUNTIME_LOOP_BATCH_MAX_INPUTS
11463        )
11464        .expect("write to string");
11465    }
11466
11467    fn render_mob_machine_native_helpers(&self, out: &mut String) {
11468        let prefix = |name: &str| self.scoped_helper_name(name);
11469        let local = |name: &str| self.local_binding_name(name);
11470        // Row #181: compute the next monotone respawn generation for an
11471        // identity. Missing identity starts at generation zero. A retained
11472        // u64::MAX generation has no successor and must never wrap to zero.
11473        writeln!(
11474            out,
11475            "{}(arg_identity_runtime_generations, arg_agent_identity) ==",
11476            prefix("mob_machine_next_respawn_generation")
11477        )
11478        .expect("write to string");
11479        pushln!(
11480            out,
11481            "    IF arg_agent_identity \\notin DOMAIN arg_identity_runtime_generations"
11482        );
11483        pushln!(out, "    THEN Some(0)");
11484        pushln!(
11485            out,
11486            "    ELSE IF arg_identity_runtime_generations[arg_agent_identity] = {TLA_RUST_U64_MAX_CONSTANT}"
11487        );
11488        pushln!(out, "         THEN None");
11489        pushln!(
11490            out,
11491            "         ELSE Some(arg_identity_runtime_generations[arg_agent_identity] + 1)"
11492        );
11493        // The generation a new incarnation mints: one past the larger of the
11494        // retained generation and the recovered high-water, zero for an
11495        // identity in neither map, and no successor past the Rust u64
11496        // ceiling. Recovery replay keeps the operator above, which reads the
11497        // retained map only.
11498        writeln!(
11499            out,
11500            "{}(arg_identity_runtime_generations, arg_identity_generation_highwater, arg_agent_identity) ==",
11501            prefix("mob_machine_next_minted_generation")
11502        )
11503        .expect("write to string");
11504        pushln!(
11505            out,
11506            "    LET retained == IF arg_agent_identity \\in DOMAIN arg_identity_runtime_generations"
11507        );
11508        pushln!(
11509            out,
11510            "                    THEN arg_identity_runtime_generations[arg_agent_identity] ELSE 0"
11511        );
11512        pushln!(
11513            out,
11514            "        highwater == IF arg_agent_identity \\in DOMAIN arg_identity_generation_highwater"
11515        );
11516        pushln!(
11517            out,
11518            "                     THEN arg_identity_generation_highwater[arg_agent_identity] ELSE 0"
11519        );
11520        pushln!(
11521            out,
11522            "        base == IF retained >= highwater THEN retained ELSE highwater"
11523        );
11524        pushln!(
11525            out,
11526            "    IN IF arg_agent_identity \\notin DOMAIN arg_identity_runtime_generations /\\ arg_agent_identity \\notin DOMAIN arg_identity_generation_highwater"
11527        );
11528        pushln!(out, "       THEN Some(0)");
11529        pushln!(
11530            out,
11531            "       ELSE IF base = {TLA_RUST_U64_MAX_CONSTANT} THEN None ELSE Some(base + 1)"
11532        );
11533        // Supervisor epochs use the same non-wrapping u64 successor relation
11534        // in both plain and Option-valued recovered tuples. These operators
11535        // deliberately mention the Rust u64 ceiling so TLC cannot admit
11536        // MAX -> 0 as a successor through unbounded integer arithmetic.
11537        writeln!(
11538            out,
11539            "{}(arg_current, arg_next) ==",
11540            prefix("mob_machine_u64_is_exact_successor")
11541        )
11542        .expect("write to string");
11543        pushln!(out, "    /\\ arg_current # {TLA_RUST_U64_MAX_CONSTANT}");
11544        pushln!(out, "    /\\ arg_next = arg_current + 1");
11545        writeln!(
11546            out,
11547            "{}(arg_current, arg_next) ==",
11548            prefix("mob_machine_optional_u64_is_exact_successor")
11549        )
11550        .expect("write to string");
11551        pushln!(out, "    /\\ arg_current # {TLA_RUST_U64_MAX_CONSTANT}");
11552        pushln!(out, "    /\\ arg_next = Some(arg_current + 1)");
11553        // Remote-turn custody admission is a native MobMachine reducer because
11554        // it enforces aggregate cardinality and correlation-key uniqueness
11555        // across all three custody sets. Keep this operator structurally
11556        // equivalent to the Rust helper in the canonical MobMachine catalog.
11557        writeln!(
11558            out,
11559            "{}(pending, committed, resolved, candidate) ==",
11560            prefix("mob_machine_remote_turn_custody_admits")
11561        )
11562        .expect("write to string");
11563        pushln!(
11564            out,
11565            "    LET same_member_host_count == Cardinality({{ row \\in pending : /\\ row.agent_identity = candidate.agent_identity /\\ row.host_id = candidate.host_id }})"
11566        );
11567        pushln!(
11568            out,
11569            "            + Cardinality({{ row \\in committed : /\\ row.agent_identity = candidate.agent_identity /\\ row.host_id = candidate.host_id }})"
11570        );
11571        pushln!(
11572            out,
11573            "            + Cardinality({{ row \\in resolved : /\\ row.agent_identity = candidate.agent_identity /\\ row.host_id = candidate.host_id }})"
11574        );
11575        pushln!(
11576            out,
11577            "    IN /\\ Cardinality(pending) + Cardinality(committed) + Cardinality(resolved) < 4096"
11578        );
11579        pushln!(out, "       /\\ candidate.dispatch_sequence > 0");
11580        pushln!(out, "       /\\ candidate.input_id # \"\"");
11581        pushln!(out, "       /\\ candidate.run_id # \"\"");
11582        pushln!(out, "       /\\ candidate.step_id # \"\"");
11583        pushln!(out, "       /\\ candidate.host_id # \"\"");
11584        pushln!(out, "       /\\ candidate.member_session_id # \"\"");
11585        for rows in ["pending", "committed", "resolved"] {
11586            pushln!(
11587                out,
11588                "       /\\ \\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)"
11589            );
11590        }
11591        pushln!(out, "       /\\ same_member_host_count < 256");
11592        // Placed completion/kickoff helpers. TLC treats canonical UUID lexical
11593        // shape as an abstract non-empty string property; Rust performs the
11594        // stricter parse-and-roundtrip check at the executable boundary.
11595        writeln!(
11596            out,
11597            "{}(candidate) ==",
11598            prefix("mob_machine_placed_completion_obligation_well_formed")
11599        )
11600        .expect("write to string");
11601        pushln!(out, "    /\\ candidate.agent_identity # \"\"");
11602        pushln!(out, "    /\\ candidate.host_id # \"\"");
11603        pushln!(out, "    /\\ candidate.host_binding_generation > 0");
11604        pushln!(out, "    /\\ candidate.member_session_id # \"\"");
11605        pushln!(out, "    /\\ candidate.dispatch_sequence > 0");
11606        pushln!(out, "    /\\ candidate.input_id # \"\"");
11607        writeln!(
11608            out,
11609            "{}(pending, resolved, candidate) ==",
11610            prefix("mob_machine_placed_completion_custody_admits")
11611        )
11612        .expect("write to string");
11613        pushln!(out, "    LET rows == pending \\cup resolved");
11614        pushln!(
11615            out,
11616            "        same_member_host == Cardinality({{ row \\in rows : /\\ row.agent_identity = candidate.agent_identity /\\ row.host_id = candidate.host_id }})"
11617        );
11618        pushln!(out, "    IN /\\ Cardinality(rows) < 4096");
11619        pushln!(
11620            out,
11621            "       /\\ \\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)"
11622        );
11623        pushln!(out, "       /\\ same_member_host < 256");
11624        writeln!(
11625            out,
11626            "{}(active_run, active_layer, active_members, layer_phases, layer_dispositions) ==",
11627            prefix("mob_machine_adaptive_lifecycle_drained")
11628        )
11629        .expect("write to string");
11630        pushln!(out, "    /\\ active_run = None");
11631        pushln!(out, "    /\\ DOMAIN active_layer = {{}}");
11632        pushln!(
11633            out,
11634            "    /\\ \\A run_id \\in DOMAIN active_members : active_members[run_id] = 0"
11635        );
11636        pushln!(out, "    /\\ \\A layer_id \\in DOMAIN layer_phases :");
11637        pushln!(
11638            out,
11639            "           \\/ layer_phases[layer_id] = \"Validating\""
11640        );
11641        pushln!(
11642            out,
11643            "           \\/ /\\ layer_id \\in DOMAIN layer_dispositions"
11644        );
11645        pushln!(
11646            out,
11647            "              /\\ layer_phases[layer_id] \\in {{\"Completed\", \"SetupFailed\", \"RunFailed\", \"ResultInvalid\", \"Canceled\"}}"
11648        );
11649        writeln!(
11650            out,
11651            "{}(adaptive_run_id, active_layer, active_members, layer_run, layer_phases, layer_dispositions) ==",
11652            prefix("mob_machine_adaptive_run_custody_drained")
11653        )
11654        .expect("write to string");
11655        pushln!(out, "    /\\ adaptive_run_id \\notin DOMAIN active_layer");
11656        pushln!(
11657            out,
11658            "    /\\ (IF adaptive_run_id \\in DOMAIN active_members THEN active_members[adaptive_run_id] ELSE 0) = 0"
11659        );
11660        pushln!(out, "    /\\ \\A layer_id \\in DOMAIN layer_run :");
11661        pushln!(out, "           \\/ layer_run[layer_id] # adaptive_run_id");
11662        pushln!(
11663            out,
11664            "           \\/ /\\ layer_id \\in DOMAIN layer_dispositions"
11665        );
11666        pushln!(out, "              /\\ layer_id \\in DOMAIN layer_phases");
11667        pushln!(
11668            out,
11669            "              /\\ layer_phases[layer_id] \\in {{\"Completed\", \"SetupFailed\", \"RunFailed\", \"ResultInvalid\", \"Canceled\"}}"
11670        );
11671        writeln!(
11672            out,
11673            "{}(started, callback_pending, failed, cancelled, kickoff_errors, identity, outcome_kind, outcome_error, closure_kind) ==",
11674            prefix("mob_machine_finalized_placed_kickoff_recovery_well_formed")
11675        )
11676        .expect("write to string");
11677        pushln!(
11678            out,
11679            "    /\\ Cardinality({{ kickoff_phase \\in {{\"Started\", \"CallbackPending\", \"Failed\", \"Cancelled\"}} :"
11680        );
11681        pushln!(
11682            out,
11683            "           CASE kickoff_phase = \"Started\" -> identity \\in started"
11684        );
11685        pushln!(
11686            out,
11687            "             [] kickoff_phase = \"CallbackPending\" -> identity \\in callback_pending"
11688        );
11689        pushln!(
11690            out,
11691            "             [] kickoff_phase = \"Failed\" -> identity \\in failed"
11692        );
11693        pushln!(
11694            out,
11695            "             [] OTHER -> identity \\in cancelled }}) = 1"
11696        );
11697        pushln!(
11698            out,
11699            "    /\\ CASE outcome_kind = \"Failed\" -> outcome_error # None"
11700        );
11701        pushln!(
11702            out,
11703            "          [] outcome_kind = \"RejectedNoEffect\" -> /\\ outcome_error # None /\\ outcome_error.value # \"\""
11704        );
11705        pushln!(out, "          [] OTHER -> outcome_error = None");
11706        pushln!(
11707            out,
11708            "    /\\ CASE closure_kind = \"Acknowledged\" -> /\\ outcome_kind # \"RejectedNoEffect\" /\\ outcome_kind # \"Disposed\""
11709        );
11710        pushln!(
11711            out,
11712            "          [] closure_kind = \"RejectedNoEffect\" -> outcome_kind = \"RejectedNoEffect\""
11713        );
11714        pushln!(
11715            out,
11716            "          [] OTHER -> outcome_kind # \"RejectedNoEffect\""
11717        );
11718        pushln!(
11719            out,
11720            "    /\\ CASE identity \\in cancelled -> identity \\notin DOMAIN kickoff_errors"
11721        );
11722        pushln!(
11723            out,
11724            "          [] identity \\in started -> /\\ outcome_kind = \"Started\" /\\ identity \\notin DOMAIN kickoff_errors"
11725        );
11726        pushln!(
11727            out,
11728            "          [] identity \\in callback_pending -> /\\ outcome_kind = \"CallbackPending\" /\\ identity \\notin DOMAIN kickoff_errors"
11729        );
11730        pushln!(
11731            out,
11732            "          [] OTHER -> /\\ outcome_kind \\in {{\"Failed\", \"RejectedNoEffect\"}} /\\ identity \\in DOMAIN kickoff_errors /\\ outcome_error = Some(kickoff_errors[identity])"
11733        );
11734        writeln!(
11735            out,
11736            "{}(candidate) ==",
11737            prefix("mob_machine_placed_kickoff_obligation_well_formed")
11738        )
11739        .expect("write to string");
11740        pushln!(out, "    /\\ candidate.agent_identity # \"\"");
11741        pushln!(out, "    /\\ candidate.host_id # \"\"");
11742        pushln!(out, "    /\\ candidate.host_binding_generation > 0");
11743        pushln!(out, "    /\\ candidate.member_session_id # \"\"");
11744        pushln!(out, "    /\\ candidate.input_id # \"\"");
11745        pushln!(out, "    /\\ candidate.objective_id # \"\"");
11746        writeln!(
11747            out,
11748            "{}(pending_kickoffs, resolved_kickoffs, retained_kickoffs, pending_turns, committed_turns, resolved_turns, pending_completions, resolved_completions, candidate) ==",
11749            prefix("mob_machine_placed_kickoff_correlation_available")
11750        )
11751        .expect("write to string");
11752        pushln!(
11753            out,
11754            "    /\\ \\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)"
11755        );
11756        pushln!(
11757            out,
11758            "    /\\ \\A identity \\in DOMAIN retained_kickoffs : retained_kickoffs[identity].agent_identity # candidate.agent_identity"
11759        );
11760        pushln!(
11761            out,
11762            "    /\\ \\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)"
11763        );
11764        pushln!(
11765            out,
11766            "    /\\ \\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)"
11767        );
11768        writeln!(
11769            out,
11770            "{}(pending, resolved, agent_identity) ==",
11771            prefix("mob_machine_placed_kickoff_custody_absent_for_identity")
11772        )
11773        .expect("write to string");
11774        pushln!(
11775            out,
11776            "    \\A row \\in pending \\cup resolved : row.agent_identity # agent_identity"
11777        );
11778        writeln!(
11779            out,
11780            "{}(pending, resolved, host_id) ==",
11781            prefix("mob_machine_placed_kickoff_custody_absent_for_host")
11782        )
11783        .expect("write to string");
11784        pushln!(
11785            out,
11786            "    \\A row \\in pending \\cup resolved : row.host_id # host_id"
11787        );
11788        writeln!(
11789            out,
11790            "{}(pending, resolved, retained, candidate) ==",
11791            prefix("mob_machine_remote_turn_input_id_available_to_kickoff")
11792        )
11793        .expect("write to string");
11794        pushln!(
11795            out,
11796            "    /\\ \\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)"
11797        );
11798        pushln!(
11799            out,
11800            "    /\\ \\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)"
11801        );
11802        // Retirement atomically prunes every local wiring edge incident to
11803        // the retiring identity. This mirrors the catalog-native Rust helper
11804        // and keeps cold replay from resurrecting topology to an absent member.
11805        writeln!(
11806            out,
11807            "{}(arg_wiring_edges, arg_agent_identity) ==",
11808            prefix("mob_machine_wiring_edges_without_identity")
11809        )
11810        .expect("write to string");
11811        pushln!(
11812            out,
11813            "    {{ edge \\in arg_wiring_edges : /\\ edge.a # arg_agent_identity /\\ edge.b # arg_agent_identity }}"
11814        );
11815        // An edge's other end, and the owned edges a removal leaves (every
11816        // owned edge of the removed identity ends, whichever end owns it):
11817        // the catalog-native Rust helpers' mirrors.
11818        writeln!(
11819            out,
11820            "{}(arg_edge, arg_agent_identity) ==",
11821            prefix("mob_machine_wiring_edge_other")
11822        )
11823        .expect("write to string");
11824        pushln!(
11825            out,
11826            "    IF arg_edge.a = arg_agent_identity THEN arg_edge.b ELSE arg_edge.a"
11827        );
11828        writeln!(
11829            out,
11830            "{}(arg_identity_edge_owners, arg_agent_identity) ==",
11831            prefix("mob_machine_owned_edges_without_identity")
11832        )
11833        .expect("write to string");
11834        pushln!(
11835            out,
11836            "    [edge \\in {{ e \\in DOMAIN arg_identity_edge_owners : /\\ e.a # arg_agent_identity /\\ e.b # arg_agent_identity }} |-> arg_identity_edge_owners[edge]]"
11837        );
11838        writeln!(
11839            out,
11840            "{}(arg_external_peer_edges, arg_agent_identity) ==",
11841            prefix("mob_machine_external_peer_edges_without_identity")
11842        )
11843        .expect("write to string");
11844        pushln!(
11845            out,
11846            "    {{ edge \\in arg_external_peer_edges : edge.local # arg_agent_identity }}"
11847        );
11848        writeln!(
11849            out,
11850            "{}(arg_external_peer_edges_by_key, arg_agent_identity) ==",
11851            prefix("mob_machine_external_peer_edges_by_key_without_identity")
11852        )
11853        .expect("write to string");
11854        pushln!(
11855            out,
11856            "    [key \\in {{ key \\in DOMAIN arg_external_peer_edges_by_key : key.local # arg_agent_identity }} |-> arg_external_peer_edges_by_key[key]]"
11857        );
11858        // The next sessions of the pending FreshSession rotations, which a
11859        // destroy's admission abandons. A SameSession rotation names its
11860        // member's own session, which the destroy's retirement of that member
11861        // disposes of. Mirror of the catalog-native Rust helper.
11862        writeln!(
11863            out,
11864            "{}(arg_member_rotation_session_ids, arg_member_rotation_targets) ==",
11865            prefix("mob_machine_fresh_rotation_sessions")
11866        )
11867        .expect("write to string");
11868        pushln!(
11869            out,
11870            "    [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]]"
11871        );
11872        // Row #351: reconcile-membership spawn/retire set helpers. The DSL
11873        // ReconcileMembership effect emits calls to these, but they had no TLA+
11874        // operator definitions, so TLC reported "Unknown operator" for
11875        // MobMachine (and any composition embedding it). Mirror of the Rust
11876        // helpers in `catalog::dsl::mob_machine`: spawn = desired identities not
11877        // yet bound to a runtime; retire = currently-bound identities that are
11878        // no longer desired, gated on `retire_stale` (empty set otherwise).
11879        // `identity_to_runtime` is the bound-identity function (DOMAIN = the
11880        // currently-bound identities); `desired` is the target identity set.
11881        // Both range over workers only: an identity entry (DOMAIN of
11882        // `identity_entry_origins`) is never spawned or retired by them, and
11883        // neither is a reserved name (`identity_entry_tombstones`, never
11884        // seated, is never spawned; `identity_entry_unreadable` is neither
11885        // spawned nor retired).
11886        writeln!(
11887            out,
11888            "{}(arg_identity_to_runtime, arg_identity_entry_origins, arg_identity_entry_tombstones, arg_identity_entry_unreadable, arg_desired) ==",
11889            prefix("mob_machine_members_to_spawn")
11890        )
11891        .expect("write to string");
11892        pushln!(
11893            out,
11894            "    {{ 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 }}"
11895        );
11896        writeln!(
11897            out,
11898            "{}(arg_identity_to_runtime, arg_identity_entry_origins, arg_identity_entry_unreadable, arg_desired, arg_retire_stale) ==",
11899            prefix("mob_machine_members_to_retire")
11900        )
11901        .expect("write to string");
11902        pushln!(out, "    IF arg_retire_stale");
11903        pushln!(
11904            out,
11905            "    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 }}"
11906        );
11907        pushln!(out, "    ELSE {{}}");
11908        // Placed-carrier cleanup is identity-exclusive and carries the exact
11909        // durable operation tuple. Both operators are native Rust helpers in
11910        // the catalog, so every standalone/composition TLA namespace must
11911        // define their semantic twins explicitly.
11912        writeln!(
11913            out,
11914            "{}(arg_obligations, arg_agent_identity) ==",
11915            prefix("mob_machine_placed_cleanup_absent_for_identity")
11916        )
11917        .expect("write to string");
11918        pushln!(
11919            out,
11920            "    \\A obligation \\in arg_obligations : obligation.agent_identity # arg_agent_identity"
11921        );
11922        writeln!(
11923            out,
11924            "{}(arg_agent_identity, arg_spawn_id, arg_generation, arg_fence_token, arg_provision_operation_id, arg_operation_owner_session_id, arg_expected_phase) ==",
11925            prefix("mob_machine_placed_cleanup_obligation")
11926        )
11927        .expect("write to string");
11928        pushln!(
11929            out,
11930            "    [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]"
11931        );
11932        // A placed carrier is live only at the exact currently bound host
11933        // generation. Keep every partial-map read behind a TLA IF so sampled
11934        // malformed/partial states evaluate to FALSE instead of indexing an
11935        // absent function key.
11936        writeln!(
11937            out,
11938            "{}(arg_member_placement, arg_current_binding_generations, arg_host_bind_phase, arg_host_binding_generations, arg_agent_identity) ==",
11939            prefix("mob_machine_placed_carrier_binding_active")
11940        )
11941        .expect("write to string");
11942        pushln!(
11943            out,
11944            "    IF arg_agent_identity \\notin DOMAIN arg_member_placement"
11945        );
11946        pushln!(out, "    THEN FALSE");
11947        pushln!(
11948            out,
11949            "    ELSE LET host == arg_member_placement[arg_agent_identity]"
11950        );
11951        pushln!(
11952            out,
11953            "         IN IF host \\notin DOMAIN arg_host_bind_phase"
11954        );
11955        pushln!(out, "            THEN FALSE");
11956        pushln!(
11957            out,
11958            "            ELSE IF arg_host_bind_phase[host] # \"Bound\""
11959        );
11960        pushln!(out, "                 THEN FALSE");
11961        pushln!(
11962            out,
11963            "                 ELSE IF arg_agent_identity \\notin DOMAIN arg_current_binding_generations"
11964        );
11965        pushln!(out, "                      THEN FALSE");
11966        pushln!(
11967            out,
11968            "                      ELSE LET generation == arg_current_binding_generations[arg_agent_identity]"
11969        );
11970        pushln!(out, "                           IN /\\ generation > 0");
11971        pushln!(
11972            out,
11973            "                              /\\ host \\in DOMAIN arg_host_binding_generations"
11974        );
11975        pushln!(
11976            out,
11977            "                              /\\ arg_host_binding_generations[host] = generation"
11978        );
11979        writeln!(
11980            out,
11981            "{}(arg_host_id, arg_binding_generation) ==",
11982            prefix("mob_machine_host_binding_generation_tombstone")
11983        )
11984        .expect("write to string");
11985        pushln!(
11986            out,
11987            "    [host_id |-> arg_host_id, binding_generation |-> arg_binding_generation]"
11988        );
11989        // Cleanup after a revoke is authorized only when the exact retained
11990        // carrier generation has a durable revocation tombstone and that host
11991        // is no longer Bound.
11992        writeln!(
11993            out,
11994            "{}(arg_member_placement, arg_current_binding_generations, arg_host_bind_phase, arg_confirmed_revocations, arg_agent_identity) ==",
11995            prefix("mob_machine_placed_carrier_binding_confirmed_revoked")
11996        )
11997        .expect("write to string");
11998        pushln!(
11999            out,
12000            "    IF arg_agent_identity \\notin DOMAIN arg_member_placement"
12001        );
12002        pushln!(out, "    THEN FALSE");
12003        pushln!(
12004            out,
12005            "    ELSE LET host == arg_member_placement[arg_agent_identity]"
12006        );
12007        pushln!(
12008            out,
12009            "         IN IF arg_agent_identity \\notin DOMAIN arg_current_binding_generations"
12010        );
12011        pushln!(out, "            THEN FALSE");
12012        pushln!(
12013            out,
12014            "            ELSE LET generation == arg_current_binding_generations[arg_agent_identity]"
12015        );
12016        pushln!(out, "                 IN /\\ generation > 0");
12017        pushln!(
12018            out,
12019            "                    /\\ (IF host \\in DOMAIN arg_host_bind_phase THEN arg_host_bind_phase[host] # \"Bound\" ELSE TRUE)"
12020        );
12021        pushln!(
12022            out,
12023            "                    /\\ [host_id |-> host, binding_generation |-> generation] \\in arg_confirmed_revocations"
12024        );
12025        // Mob-coordination temporal predicates (work-intent / resource-claim
12026        // expiry). The DSL emits calls to these guards but they had no TLA+
12027        // definitions, so TLC reported "Unknown operator" for MobMachine (and
12028        // for any composition embedding it). The expires-at argument is the
12029        // stored `Option<u64>` (`Some(ms)`/`None`) and `now_ms` is a raw value;
12030        // `e # None /\ e.value <= now_ms` short-circuits when there is no expiry.
12031        // Resource-claim status arrives as the raw status string.
12032        writeln!(
12033            out,
12034            "{}(expires_at_ms, now_ms) ==",
12035            prefix("mob_coordination_expired_at")
12036        )
12037        .expect("write to string");
12038        pushln!(out, "    /\\ expires_at_ms # None");
12039        pushln!(out, "    /\\ expires_at_ms.value <= now_ms");
12040        writeln!(
12041            out,
12042            "{}(expires_at_ms, now_ms) == ~{}(expires_at_ms, now_ms)",
12043            prefix("mob_coordination_work_intent_unexpired"),
12044            prefix("mob_coordination_expired_at")
12045        )
12046        .expect("write to string");
12047        writeln!(
12048            out,
12049            "{}(expires_at_ms, now_ms) == ~{}(expires_at_ms, now_ms)",
12050            prefix("mob_coordination_resource_claim_unexpired"),
12051            prefix("mob_coordination_expired_at")
12052        )
12053        .expect("write to string");
12054        writeln!(
12055            out,
12056            "{}(status, expires_at_ms, now_ms) ==",
12057            prefix("mob_coordination_resource_claim_active_at")
12058        )
12059        .expect("write to string");
12060        pushln!(out, "    /\\ status = \"Active\"");
12061        writeln!(
12062            out,
12063            "    /\\ ~{}(expires_at_ms, now_ms)",
12064            prefix("mob_coordination_expired_at")
12065        )
12066        .expect("write to string");
12067        writeln!(
12068            out,
12069            "{}(status, expires_at_ms, now_ms) == ~{}(status, expires_at_ms, now_ms)",
12070            prefix("mob_coordination_resource_claim_inactive_at"),
12071            prefix("mob_coordination_resource_claim_active_at")
12072        )
12073        .expect("write to string");
12074        writeln!(
12075            out,
12076            "{}(edges_by_key, edge) ==",
12077            prefix("mob_machine_external_peer_edge_has_matching_key")
12078        )
12079        .expect("write to string");
12080        pushln!(
12081            out,
12082            "    LET key == [local |-> edge.local, name |-> edge.endpoint.name]"
12083        );
12084        pushln!(out, "    IN /\\ key \\in DOMAIN edges_by_key");
12085        pushln!(out, "       /\\ edges_by_key[key] = edge");
12086        writeln!(
12087            out,
12088            "{}(edge) == edge.local",
12089            prefix("mob_machine_external_peer_edge_local")
12090        )
12091        .expect("write to string");
12092        writeln!(
12093            out,
12094            "{}(edge) == edge.endpoint.peer_id",
12095            prefix("mob_machine_external_peer_edge_peer_id")
12096        )
12097        .expect("write to string");
12098        writeln!(
12099            out,
12100            "{}(key, edge) ==",
12101            prefix("mob_machine_external_peer_key_matches_edge")
12102        )
12103        .expect("write to string");
12104        pushln!(out, "    /\\ key.local = edge.local");
12105        pushln!(out, "    /\\ key.name = edge.endpoint.name");
12106        writeln!(
12107            out,
12108            "{}(key, agent_identity) == key.local = agent_identity",
12109            prefix("mob_machine_external_peer_key_matches_local")
12110        )
12111        .expect("write to string");
12112        writeln!(
12113            out,
12114            "{}(edges, agent_identity) ==",
12115            prefix("mob_machine_external_peer_identity_absent")
12116        )
12117        .expect("write to string");
12118        pushln!(
12119            out,
12120            "    \\A edge \\in edges : edge.endpoint.name /= agent_identity"
12121        );
12122        writeln!(
12123            out,
12124            "{}({}, agent_identity) ==",
12125            prefix("mob_machine_identity_has_session_binding"),
12126            local("member_session_bindings")
12127        )
12128        .expect("write to string");
12129        pushln!(
12130            out,
12131            "    /\\ agent_identity \\in DOMAIN {}",
12132            local("member_session_bindings")
12133        );
12134        pushln!(
12135            out,
12136            "    /\\ {}[agent_identity] /= \"\"",
12137            local("member_session_bindings")
12138        );
12139        writeln!(
12140            out,
12141            "{}({}, {}, {}, expected_runtime_ids) ==",
12142            prefix("mob_machine_session_bound_live_runtime_ids_match"),
12143            local("identity_to_runtime"),
12144            local("member_session_bindings"),
12145            local("live_runtime_ids")
12146        )
12147        .expect("write to string");
12148        pushln!(
12149            out,
12150            "    LET eligible_ids == {{ candidate \\in DOMAIN {} : {}[candidate] /= \"\" /\\ candidate \\in DOMAIN {} /\\ {}[candidate] \\in {} }}",
12151            local("member_session_bindings"),
12152            local("member_session_bindings"),
12153            local("identity_to_runtime"),
12154            local("identity_to_runtime"),
12155            local("live_runtime_ids")
12156        );
12157        pushln!(
12158            out,
12159            "    IN expected_runtime_ids = {{ {}[id] : id \\in eligible_ids }}",
12160            local("identity_to_runtime")
12161        );
12162        writeln!(
12163            out,
12164            "{}(endpoint) == endpoint.peer_id",
12165            prefix("mob_machine_member_peer_endpoint_peer_id")
12166        )
12167        .expect("write to string");
12168        writeln!(
12169            out,
12170            "{}(host_id, peer_id) == host_id = peer_id",
12171            prefix("mob_machine_host_id_matches_peer_id")
12172        )
12173        .expect("write to string");
12174        writeln!(
12175            out,
12176            "{}(current_endpoints, prior_endpoints, agent_identity, candidate_endpoint) ==",
12177            prefix("mob_machine_member_peer_id_available_for_identity")
12178        )
12179        .expect("write to string");
12180        pushln!(
12181            out,
12182            "    /\\ \\A other_identity \\in DOMAIN current_endpoints : other_identity = agent_identity \\/ current_endpoints[other_identity].peer_id /= candidate_endpoint.peer_id"
12183        );
12184        pushln!(
12185            out,
12186            "    /\\ \\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"
12187        );
12188        // The two peer id invariants' predicates. The Rust natives read each
12189        // endpoint once; the model states the property pairwise, as the
12190        // invariants read before they called a native.
12191        writeln!(
12192            out,
12193            "{}(current_endpoints, prior_endpoints) ==",
12194            prefix("mob_machine_member_peer_id_ownership_is_global")
12195        )
12196        .expect("write to string");
12197        pushln!(
12198            out,
12199            "    /\\ \\A agent_identity \\in DOMAIN current_endpoints : {}(current_endpoints, prior_endpoints, agent_identity, current_endpoints[agent_identity])",
12200            prefix("mob_machine_member_peer_id_available_for_identity")
12201        );
12202        pushln!(
12203            out,
12204            "    /\\ \\A agent_identity \\in DOMAIN prior_endpoints : \\A prior_endpoint \\in prior_endpoints[agent_identity] : {}(current_endpoints, prior_endpoints, agent_identity, prior_endpoint)",
12205            prefix("mob_machine_member_peer_id_available_for_identity")
12206        );
12207        writeln!(
12208            out,
12209            "{}(current_endpoints) ==",
12210            prefix("mob_machine_live_member_peer_ids_are_unique")
12211        )
12212        .expect("write to string");
12213        pushln!(
12214            out,
12215            "    \\A agent_identity \\in DOMAIN current_endpoints : \\A other_identity \\in DOMAIN current_endpoints : agent_identity = other_identity \\/ current_endpoints[agent_identity].peer_id /= current_endpoints[other_identity].peer_id"
12216        );
12217        writeln!(
12218            out,
12219            "{}(edges, agent_identity) ==",
12220            prefix("mob_machine_member_has_no_external_peer_edges")
12221        )
12222        .expect("write to string");
12223        pushln!(
12224            out,
12225            "    \\A edge \\in edges : edge.local /= agent_identity"
12226        );
12227        writeln!(
12228            out,
12229            "{}(all_prior_endpoints, agent_identity, current_endpoint, next_endpoint) ==",
12230            prefix("mob_machine_member_prior_peer_endpoints_after_migration")
12231        )
12232        .expect("write to string");
12233        pushln!(
12234            out,
12235            "    LET prior == IF agent_identity \\in DOMAIN all_prior_endpoints THEN all_prior_endpoints[agent_identity] ELSE {{}}"
12236        );
12237        pushln!(
12238            out,
12239            "        retained == {{ endpoint \\in (prior \\cup {{current_endpoint}}) : endpoint.peer_id /= next_endpoint.peer_id }}"
12240        );
12241        pushln!(out, "    IN IF retained = {{}}");
12242        pushln!(
12243            out,
12244            "       THEN [id \\in (DOMAIN all_prior_endpoints \\ {{agent_identity}}) |-> all_prior_endpoints[id]]"
12245        );
12246        pushln!(
12247            out,
12248            "       ELSE [id \\in (DOMAIN all_prior_endpoints \\cup {{agent_identity}}) |-> IF id = agent_identity THEN retained ELSE all_prior_endpoints[id]]"
12249        );
12250        writeln!(
12251            out,
12252            "{}(endpoint_identity, migrated_identity, retained_peer_endpoint, current_peer_ids) ==",
12253            prefix("mob_machine_member_endpoint_migration_cleanup_peer_id")
12254        )
12255        .expect("write to string");
12256        pushln!(
12257            out,
12258            "    IF endpoint_identity = migrated_identity THEN retained_peer_endpoint.peer_id ELSE current_peer_ids[endpoint_identity]"
12259        );
12260        writeln!(
12261            out,
12262            "{}(edge) == edge.a",
12263            prefix("mob_machine_wiring_edge_a")
12264        )
12265        .expect("write to string");
12266        writeln!(
12267            out,
12268            "{}(edge) == edge.b",
12269            prefix("mob_machine_wiring_edge_b")
12270        )
12271        .expect("write to string");
12272        writeln!(
12273            out,
12274            "{}(edge, agent_identity) == edge.a = agent_identity \\/ edge.b = agent_identity",
12275            prefix("mob_machine_wiring_edge_contains_identity")
12276        )
12277        .expect("write to string");
12278        writeln!(
12279            out,
12280            "{}({}, {}, agent_identity) ==",
12281            prefix("mob_machine_member_peer_overlay_complete"),
12282            local("wiring_edges"),
12283            local("member_peer_endpoints")
12284        )
12285        .expect("write to string");
12286        pushln!(
12287            out,
12288            "    \\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",
12289            local("wiring_edges"),
12290            local("member_peer_endpoints"),
12291            local("member_peer_endpoints")
12292        );
12293        writeln!(
12294            out,
12295            "{}({}, {}, {}, agent_identity) ==",
12296            prefix("mob_machine_member_peer_overlay"),
12297            local("wiring_edges"),
12298            local("member_peer_endpoints"),
12299            local("external_peer_edges")
12300        )
12301        .expect("write to string");
12302        pushln!(
12303            out,
12304            "    LET outgoing_edges == {{ edge \\in {} : edge.a = agent_identity /\\ edge.b \\in DOMAIN {} }}",
12305            local("wiring_edges"),
12306            local("member_peer_endpoints")
12307        );
12308        pushln!(
12309            out,
12310            "        incoming_edges == {{ edge \\in {} : edge.b = agent_identity /\\ edge.a \\in DOMAIN {} }}",
12311            local("wiring_edges"),
12312            local("member_peer_endpoints")
12313        );
12314        pushln!(
12315            out,
12316            "        local_external_edges == {{ edge \\in {} : edge.local = agent_identity }}",
12317            local("external_peer_edges")
12318        );
12319        pushln!(
12320            out,
12321            "    IN {{ {}[edge.b] : edge \\in outgoing_edges }}",
12322            local("member_peer_endpoints")
12323        );
12324        pushln!(
12325            out,
12326            "       \\cup {{ {}[edge.a] : edge \\in incoming_edges }}",
12327            local("member_peer_endpoints")
12328        );
12329        pushln!(
12330            out,
12331            "       \\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 }}"
12332        );
12333        writeln!(
12334            out,
12335            "{}({}, a_identity, b_identity) == \\E edge \\in {}: (edge.a = a_identity /\\ edge.b = b_identity) \\/ (edge.a = b_identity /\\ edge.b = a_identity)",
12336            prefix("mob_machine_wiring_contains_pair"),
12337            local("wiring_edges"),
12338            local("wiring_edges")
12339        )
12340        .expect("write to string");
12341        writeln!(
12342            out,
12343            "{}({}, {}, agent_identity, excluded_identity) ==",
12344            prefix("mob_machine_member_peer_overlay_without_identity_complete"),
12345            local("wiring_edges"),
12346            local("member_peer_endpoints")
12347        )
12348        .expect("write to string");
12349        pushln!(
12350            out,
12351            "    \\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",
12352            local("wiring_edges"),
12353            local("member_peer_endpoints"),
12354            local("member_peer_endpoints")
12355        );
12356        writeln!(
12357            out,
12358            "{}({}, {}, {}, agent_identity, excluded_identity) ==",
12359            prefix("mob_machine_member_peer_overlay_without_identity"),
12360            local("wiring_edges"),
12361            local("member_peer_endpoints"),
12362            local("external_peer_edges")
12363        )
12364        .expect("write to string");
12365        pushln!(
12366            out,
12367            "    LET outgoing_edges == {{ edge \\in {} : edge.a = agent_identity /\\ edge.b # excluded_identity /\\ edge.b \\in DOMAIN {} }}",
12368            local("wiring_edges"),
12369            local("member_peer_endpoints")
12370        );
12371        pushln!(
12372            out,
12373            "        incoming_edges == {{ edge \\in {} : edge.b = agent_identity /\\ edge.a # excluded_identity /\\ edge.a \\in DOMAIN {} }}",
12374            local("wiring_edges"),
12375            local("member_peer_endpoints")
12376        );
12377        pushln!(
12378            out,
12379            "        local_external_edges == {{ edge \\in {} : edge.local = agent_identity }}",
12380            local("external_peer_edges")
12381        );
12382        pushln!(
12383            out,
12384            "    IN {{ {}[edge.b] : edge \\in outgoing_edges }}",
12385            local("member_peer_endpoints")
12386        );
12387        pushln!(
12388            out,
12389            "       \\cup {{ {}[edge.a] : edge \\in incoming_edges }}",
12390            local("member_peer_endpoints")
12391        );
12392        pushln!(
12393            out,
12394            "       \\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 }}"
12395        );
12396        writeln!(
12397            out,
12398            "{}({}, {}, {}, agent_identity, excluded_identity) ==",
12399            prefix("mob_machine_member_peer_overlay_without_identity_peer_ids_unique"),
12400            local("wiring_edges"),
12401            local("member_peer_endpoints"),
12402            local("external_peer_edges")
12403        )
12404        .expect("write to string");
12405        writeln!(
12406            out,
12407            "    LET overlay == {}({}, {}, {}, agent_identity, excluded_identity) IN Cardinality(overlay) = Cardinality({{endpoint.peer_id : endpoint \\in overlay}})",
12408            prefix("mob_machine_member_peer_overlay_without_identity"),
12409            local("wiring_edges"),
12410            local("member_peer_endpoints"),
12411            local("external_peer_edges")
12412        )
12413        .expect("write to string");
12414        writeln!(
12415            out,
12416            "{}({}, {}, {}, agent_identity) ==",
12417            prefix("mob_machine_member_peer_overlay_peer_ids_unique"),
12418            local("wiring_edges"),
12419            local("member_peer_endpoints"),
12420            local("external_peer_edges")
12421        )
12422        .expect("write to string");
12423        writeln!(
12424            out,
12425            "    LET overlay == {}({}, {}, {}, agent_identity) IN Cardinality(overlay) = Cardinality({{endpoint.peer_id : endpoint \\in overlay}})",
12426            prefix("mob_machine_member_peer_overlay"),
12427            local("wiring_edges"),
12428            local("member_peer_endpoints"),
12429            local("external_peer_edges")
12430        )
12431        .expect("write to string");
12432        writeln!(
12433            out,
12434            "{}(edge, a_identity, b_identity) ==",
12435            prefix("mob_machine_wiring_edge_matches_members")
12436        )
12437        .expect("write to string");
12438        pushln!(out, "    /\\ edge.a = a_identity");
12439        pushln!(out, "    /\\ edge.b = b_identity");
12440        writeln!(
12441            out,
12442            "{}(all_statuses, run_id, step_id, status) ==",
12443            prefix("mob_machine_run_step_status_after_set")
12444        )
12445        .expect("write to string");
12446        pushln!(
12447            out,
12448            "    LET current == IF run_id \\in DOMAIN all_statuses THEN all_statuses[run_id] ELSE [x \\in {{}} |-> None]"
12449        );
12450        pushln!(
12451            out,
12452            "    IN MapSet(all_statuses, run_id, MapSet(current, step_id, Some(status)))"
12453        );
12454        writeln!(
12455            out,
12456            "{}(all_statuses, run_id) ==",
12457            prefix("mob_machine_run_step_status_after_cancel_unfinished")
12458        )
12459        .expect("write to string");
12460        pushln!(
12461            out,
12462            "    LET current == IF run_id \\in DOMAIN all_statuses THEN all_statuses[run_id] ELSE [x \\in {{}} |-> None]"
12463        );
12464        pushln!(
12465            out,
12466            "        folded == [step_id \\in DOMAIN current |-> IF current[step_id] = None \\/ current[step_id] = Some(\"Dispatched\") THEN Some(\"Canceled\") ELSE current[step_id]]"
12467        );
12468        pushln!(out, "    IN MapSet(all_statuses, run_id, folded)");
12469        writeln!(
12470            out,
12471            "{}(all_values, run_id, step_id, value) ==",
12472            prefix("mob_machine_run_step_bool_after_set")
12473        )
12474        .expect("write to string");
12475        pushln!(
12476            out,
12477            "    LET current == IF run_id \\in DOMAIN all_values THEN all_values[run_id] ELSE [x \\in {{}} |-> FALSE]"
12478        );
12479        pushln!(
12480            out,
12481            "    IN MapSet(all_values, run_id, MapSet(current, step_id, value))"
12482        );
12483        writeln!(
12484            out,
12485            "{}(all_results, run_id, step_id, result) ==",
12486            prefix("mob_machine_run_step_condition_result_after_set")
12487        )
12488        .expect("write to string");
12489        pushln!(
12490            out,
12491            "    LET current == IF run_id \\in DOMAIN all_results THEN all_results[run_id] ELSE [x \\in {{}} |-> None]"
12492        );
12493        pushln!(
12494            out,
12495            "    IN MapSet(all_results, run_id, MapSet(current, step_id, Some(result)))"
12496        );
12497        writeln!(
12498            out,
12499            "{}(all_counts, run_id, step_id, value) ==",
12500            prefix("mob_machine_run_step_u64_after_set")
12501        )
12502        .expect("write to string");
12503        pushln!(
12504            out,
12505            "    LET current == IF run_id \\in DOMAIN all_counts THEN all_counts[run_id] ELSE [x \\in {{}} |-> 0]"
12506        );
12507        pushln!(
12508            out,
12509            "    IN MapSet(all_counts, run_id, MapSet(current, step_id, value))"
12510        );
12511        writeln!(
12512            out,
12513            "{}(all_counts, run_id, step_id, delta) ==",
12514            prefix("mob_machine_run_step_u64_after_increment")
12515        )
12516        .expect("write to string");
12517        pushln!(
12518            out,
12519            "    LET current == IF run_id \\in DOMAIN all_counts THEN all_counts[run_id] ELSE [x \\in {{}} |-> 0]"
12520        );
12521        pushln!(
12522            out,
12523            "        current_value == IF step_id \\in DOMAIN current THEN current[step_id] ELSE 0"
12524        );
12525        pushln!(
12526            out,
12527            "    IN MapSet(all_counts, run_id, MapSet(current, step_id, current_value + delta))"
12528        );
12529        writeln!(
12530            out,
12531            "{}(all_counts, run_id, retry_key, delta) ==",
12532            prefix("mob_machine_run_retry_count_after_increment")
12533        )
12534        .expect("write to string");
12535        pushln!(
12536            out,
12537            "    LET current == IF run_id \\in DOMAIN all_counts THEN all_counts[run_id] ELSE [x \\in {{}} |-> 0]"
12538        );
12539        pushln!(
12540            out,
12541            "        current_value == IF retry_key \\in DOMAIN current THEN current[retry_key] ELSE 0"
12542        );
12543        pushln!(
12544            out,
12545            "    IN MapSet(all_counts, run_id, MapSet(current, retry_key, current_value + delta))"
12546        );
12547        writeln!(
12548            out,
12549            "{}(all_values, frame_id, node_id, value) ==",
12550            prefix("mob_machine_frame_node_bool_after_set")
12551        )
12552        .expect("write to string");
12553        pushln!(
12554            out,
12555            "    LET current == IF frame_id \\in DOMAIN all_values THEN all_values[frame_id] ELSE [x \\in {{}} |-> FALSE]"
12556        );
12557        pushln!(
12558            out,
12559            "    IN MapSet(all_values, frame_id, MapSet(current, node_id, value))"
12560        );
12561        writeln!(
12562            out,
12563            "{}(status) == status \\in {{\"Completed\", \"Failed\", \"Skipped\", \"Canceled\"}}",
12564            prefix("mob_machine_node_terminal")
12565        )
12566        .expect("write to string");
12567        writeln!(
12568            out,
12569            "{}(status) ==",
12570            prefix("mob_machine_step_status_from_frame_node_status")
12571        )
12572        .expect("write to string");
12573        pushln!(out, "    IF status = \"Completed\" THEN \"Completed\"");
12574        pushln!(out, "    ELSE IF status = \"Skipped\" THEN \"Skipped\"");
12575        pushln!(out, "    ELSE IF status = \"Failed\" THEN \"Failed\"");
12576        pushln!(out, "    ELSE IF status = \"Canceled\" THEN \"Canceled\"");
12577        pushln!(out, "    ELSE \"Dispatched\"");
12578        writeln!(
12579            out,
12580            "{}(all_statuses, frame_branches, ordered_nodes_by_frame, frame_id, node_id) ==",
12581            prefix("mob_machine_frame_node_status_after_admit")
12582        )
12583        .expect("write to string");
12584        pushln!(
12585            out,
12586            "    LET current == IF frame_id \\in DOMAIN all_statuses THEN all_statuses[frame_id] ELSE [x \\in {{}} |-> None]"
12587        );
12588        pushln!(
12589            out,
12590            "        branches == IF frame_id \\in DOMAIN frame_branches THEN frame_branches[frame_id] ELSE [x \\in {{}} |-> None]"
12591        );
12592        pushln!(
12593            out,
12594            "        admitted_branch == IF node_id \\in DOMAIN branches THEN branches[node_id] ELSE None"
12595        );
12596        pushln!(
12597            out,
12598            "        after_branch_reservation == [candidate \\in DOMAIN current |->"
12599        );
12600        pushln!(out, "            IF admitted_branch # None");
12601        pushln!(out, "                /\\ candidate # node_id");
12602        pushln!(out, "                /\\ candidate \\in DOMAIN branches");
12603        pushln!(
12604            out,
12605            "                /\\ branches[candidate] = admitted_branch"
12606        );
12607        pushln!(out, "                /\\ current[candidate] = \"Ready\"");
12608        pushln!(out, "            THEN \"Pending\" ELSE current[candidate]]");
12609        pushln!(
12610            out,
12611            "        after_admit == MapSet(after_branch_reservation, node_id, \"Running\")"
12612        );
12613        pushln!(out, "    IN MapSet(all_statuses, frame_id, after_admit)");
12614        writeln!(
12615            out,
12616            "{}(all_ready_queues, all_statuses, ordered_nodes_by_frame, frame_id) ==",
12617            prefix("mob_machine_frame_ready_queue_after_terminal")
12618        )
12619        .expect("write to string");
12620        pushln!(
12621            out,
12622            "    LET statuses == IF frame_id \\in DOMAIN all_statuses THEN all_statuses[frame_id] ELSE [x \\in {{}} |-> None]"
12623        );
12624        pushln!(
12625            out,
12626            "        ordered == IF frame_id \\in DOMAIN ordered_nodes_by_frame THEN ordered_nodes_by_frame[frame_id] ELSE <<>>"
12627        );
12628        pushln!(
12629            out,
12630            "    IN MapSet(all_ready_queues, frame_id, SelectSeq(ordered, LAMBDA candidate: candidate \\in DOMAIN statuses /\\ statuses[candidate] = \"Ready\"))"
12631        );
12632        writeln!(
12633            out,
12634            "{}(all_ready_queues, all_statuses, ordered_nodes_by_frame, frame_id) ==",
12635            prefix("mob_machine_frame_ready_queue_after_admit")
12636        )
12637        .expect("write to string");
12638        writeln!(
12639            out,
12640            "    {}(all_ready_queues, all_statuses, ordered_nodes_by_frame, frame_id)",
12641            prefix("mob_machine_frame_ready_queue_after_terminal")
12642        )
12643        .expect("write to string");
12644        writeln!(
12645            out,
12646            "{}(current, branches, node_id, terminal_status) ==",
12647            prefix("mob_machine_frame_node_status_after_terminal_branch")
12648        )
12649        .expect("write to string");
12650        pushln!(
12651            out,
12652            "    LET after_terminal == MapSet(current, node_id, terminal_status)"
12653        );
12654        pushln!(out, "    IN [candidate \\in DOMAIN after_terminal |->");
12655        pushln!(
12656            out,
12657            "        IF terminal_status = \"Completed\" /\\ candidate # node_id"
12658        );
12659        pushln!(
12660            out,
12661            "            /\\ candidate \\in DOMAIN branches /\\ node_id \\in DOMAIN branches"
12662        );
12663        pushln!(out, "            /\\ branches[node_id] # None");
12664        pushln!(
12665            out,
12666            "            /\\ branches[candidate] = branches[node_id]"
12667        );
12668        writeln!(
12669            out,
12670            "            /\\ ~{}(after_terminal[candidate])",
12671            prefix("mob_machine_node_terminal")
12672        )
12673        .expect("write to string");
12674        pushln!(
12675            out,
12676            "            /\\ after_terminal[candidate] # \"Running\""
12677        );
12678        pushln!(
12679            out,
12680            "        THEN \"Skipped\" ELSE after_terminal[candidate]]"
12681        );
12682        writeln!(
12683            out,
12684            "{}(after_branch, dependencies, dependency_modes) ==",
12685            prefix("mob_machine_frame_node_status_after_terminal_dependencies")
12686        )
12687        .expect("write to string");
12688        pushln!(out, "    [candidate \\in DOMAIN after_branch |->");
12689        pushln!(
12690            out,
12691            "        IF after_branch[candidate] # \"Pending\" THEN after_branch[candidate]"
12692        );
12693        pushln!(
12694            out,
12695            "        ELSE LET deps == IF candidate \\in DOMAIN dependencies THEN dependencies[candidate] ELSE <<>>"
12696        );
12697        pushln!(
12698            out,
12699            "                 mode == IF candidate \\in DOMAIN dependency_modes THEN dependency_modes[candidate] ELSE \"All\""
12700        );
12701        pushln!(out, "                 failed == Len(deps) # 0");
12702        pushln!(
12703            out,
12704            "                     /\\ ((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\"}})"
12705        );
12706        pushln!(
12707            out,
12708            "                         \\/ (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\"}}))"
12709        );
12710        pushln!(out, "                 satisfied == Len(deps) = 0");
12711        pushln!(
12712            out,
12713            "                     \\/ (mode = \"All\" /\\ \\A dep_index \\in DOMAIN deps: LET dep == deps[dep_index] IN dep \\in DOMAIN after_branch /\\ after_branch[dep] = \"Completed\")"
12714        );
12715        pushln!(
12716            out,
12717            "                     \\/ (mode = \"Any\" /\\ \\E dep_index \\in DOMAIN deps: LET dep == deps[dep_index] IN dep \\in DOMAIN after_branch /\\ after_branch[dep] = \"Completed\")"
12718        );
12719        pushln!(
12720            out,
12721            "             IN IF failed THEN \"Skipped\" ELSE IF satisfied THEN \"Ready\" ELSE after_branch[candidate]]"
12722        );
12723        writeln!(
12724            out,
12725            "{}(all_statuses, frame_branches, ordered_nodes_by_frame, dependencies_by_frame, dependency_modes_by_frame, frame_id, node_id, terminal_status) ==",
12726            prefix("mob_machine_frame_node_status_after_terminal")
12727        )
12728        .expect("write to string");
12729        pushln!(
12730            out,
12731            "    LET current == IF frame_id \\in DOMAIN all_statuses THEN all_statuses[frame_id] ELSE [x \\in {{}} |-> None]"
12732        );
12733        pushln!(
12734            out,
12735            "        branches == IF frame_id \\in DOMAIN frame_branches THEN frame_branches[frame_id] ELSE [x \\in {{}} |-> None]"
12736        );
12737        pushln!(
12738            out,
12739            "        dependencies == IF frame_id \\in DOMAIN dependencies_by_frame THEN dependencies_by_frame[frame_id] ELSE [x \\in {{}} |-> <<>>]"
12740        );
12741        pushln!(
12742            out,
12743            "        dependency_modes == IF frame_id \\in DOMAIN dependency_modes_by_frame THEN dependency_modes_by_frame[frame_id] ELSE [x \\in {{}} |-> \"All\"]"
12744        );
12745        writeln!(
12746            out,
12747            "        after_branch == {}(current, branches, node_id, terminal_status)",
12748            prefix("mob_machine_frame_node_status_after_terminal_branch")
12749        )
12750        .expect("write to string");
12751        writeln!(
12752            out,
12753            "        after_dependencies == {}(after_branch, dependencies, dependency_modes)",
12754            prefix("mob_machine_frame_node_status_after_terminal_dependencies")
12755        )
12756        .expect("write to string");
12757        pushln!(
12758            out,
12759            "    IN MapSet(all_statuses, frame_id, after_dependencies)"
12760        );
12761        // Operator instructions: the snapshot natives below are defined over
12762        // the session document's slot-set natives (the body bytes of a slot
12763        // set's Active slots), rendered for this machine too.
12764        self.render_session_document_native_helpers(out);
12765        // The widest member snapshot the records allow: the shared records
12766        // (every slot that is not member-targeted) plus the most one name
12767        // holds of its own, alone or together with what another name's
12768        // records pass to that name's forks (any name may be seated as a
12769        // fork of another). A slot is member-targeted while its kind is
12770        // Member or MemberAndForks and the member map names it (the Rust
12771        // authorities agree).
12772        writeln!(
12773            out,
12774            "{}(target_kind, target_member) ==",
12775            prefix("mob_machine_instruction_widest_snapshot_slots")
12776        )
12777        .expect("write to string");
12778        pushln!(
12779            out,
12780            "    LET member_slots == {{candidate_slot \\in DOMAIN target_kind : target_kind[candidate_slot] \\in {{\"Member\", \"MemberAndForks\"}} /\\ candidate_slot \\in DOMAIN target_member}}"
12781        );
12782        pushln!(
12783            out,
12784            "        instruction_fork_slots == {{candidate_slot \\in member_slots : target_kind[candidate_slot] = \"MemberAndForks\"}}"
12785        );
12786        pushln!(
12787            out,
12788            "        instruction_member_names == {{target_member[named_slot] : named_slot \\in member_slots}}"
12789        );
12790        pushln!(
12791            out,
12792            "        InstructionOwnOf(named_member) == Cardinality({{own_slot \\in member_slots : target_member[own_slot] = named_member}})"
12793        );
12794        pushln!(
12795            out,
12796            "        InstructionForForksOf(named_member) == Cardinality({{own_slot \\in instruction_fork_slots : target_member[own_slot] = named_member}})"
12797        );
12798        pushln!(
12799            out,
12800            "        instruction_snapshots == {{InstructionOwnOf(named_member) : named_member \\in instruction_member_names}} \\cup {{InstructionOwnOf(name_pair[1]) + InstructionForForksOf(name_pair[2]) : name_pair \\in {{candidate_pair \\in instruction_member_names \\X instruction_member_names : candidate_pair[1] # candidate_pair[2]}}}}"
12801        );
12802        pushln!(
12803            out,
12804            "        widest_own == IF instruction_snapshots = {{}} THEN 0 ELSE CHOOSE snapshot_size \\in instruction_snapshots : \\A other_size \\in instruction_snapshots : snapshot_size >= other_size"
12805        );
12806        pushln!(
12807            out,
12808            "    IN Cardinality(DOMAIN target_kind \\ member_slots) + widest_own"
12809        );
12810        // The same snapshot's Active body bytes; a slot the bytes map does
12811        // not name counts nothing.
12812        writeln!(
12813            out,
12814            "{}(slot_effect, slot_bytes, target_kind, target_member) ==",
12815            prefix("mob_machine_instruction_widest_snapshot_active_bytes")
12816        )
12817        .expect("write to string");
12818        pushln!(
12819            out,
12820            "    LET member_slots == {{candidate_slot \\in DOMAIN slot_effect : candidate_slot \\in DOMAIN target_kind /\\ target_kind[candidate_slot] \\in {{\"Member\", \"MemberAndForks\"}} /\\ candidate_slot \\in DOMAIN target_member}}"
12821        );
12822        pushln!(
12823            out,
12824            "        instruction_fork_slots == {{candidate_slot \\in member_slots : target_kind[candidate_slot] = \"MemberAndForks\"}}"
12825        );
12826        pushln!(
12827            out,
12828            "        instruction_member_names == {{target_member[named_slot] : named_slot \\in member_slots}}"
12829        );
12830        writeln!(
12831            out,
12832            "        ActiveBytesOf(instruction_slots) == {}([instruction_slot \\in instruction_slots |-> slot_effect[instruction_slot]], slot_bytes)",
12833            prefix("session_document_instruction_active_bytes")
12834        )
12835        .expect("write to string");
12836        pushln!(
12837            out,
12838            "        InstructionOwnOf(named_member) == ActiveBytesOf({{own_slot \\in member_slots : target_member[own_slot] = named_member}})"
12839        );
12840        pushln!(
12841            out,
12842            "        InstructionForForksOf(named_member) == ActiveBytesOf({{own_slot \\in instruction_fork_slots : target_member[own_slot] = named_member}})"
12843        );
12844        pushln!(
12845            out,
12846            "        instruction_snapshots == {{InstructionOwnOf(named_member) : named_member \\in instruction_member_names}} \\cup {{InstructionOwnOf(name_pair[1]) + InstructionForForksOf(name_pair[2]) : name_pair \\in {{candidate_pair \\in instruction_member_names \\X instruction_member_names : candidate_pair[1] # candidate_pair[2]}}}}"
12847        );
12848        pushln!(
12849            out,
12850            "        widest_own == IF instruction_snapshots = {{}} THEN 0 ELSE CHOOSE snapshot_size \\in instruction_snapshots : \\A other_size \\in instruction_snapshots : snapshot_size >= other_size"
12851        );
12852        pushln!(
12853            out,
12854            "    IN ActiveBytesOf(DOMAIN slot_effect \\ member_slots) + widest_own"
12855        );
12856        // The records of the widest member snapshot once a write is applied:
12857        // the widest snapshot of the record maps the write leaves, where the
12858        // slot takes the write's kind and names the write's member or no
12859        // member (the Rust authorities agree, without building those maps).
12860        writeln!(
12861            out,
12862            "{}(target_kind, target_member, slot, kind, member) ==",
12863            prefix("mob_machine_instruction_write_snapshot_slots")
12864        )
12865        .expect("write to string");
12866        pushln!(out, "    LET kind_after == MapSet(target_kind, slot, kind)");
12867        pushln!(
12868            out,
12869            "        member_after == IF member = None THEN [other_slot \\in DOMAIN target_member \\ {{slot}} |-> target_member[other_slot]] ELSE MapSet(target_member, slot, member.value)"
12870        );
12871        writeln!(
12872            out,
12873            "    IN {}(kind_after, member_after)",
12874            prefix("mob_machine_instruction_widest_snapshot_slots")
12875        )
12876        .expect("write to string");
12877        // The same snapshot's Active body bytes, with the written slot
12878        // Active at its body bytes.
12879        writeln!(
12880            out,
12881            "{}(slot_effect, slot_bytes, target_kind, target_member, slot, body_bytes, kind, member) ==",
12882            prefix("mob_machine_instruction_write_snapshot_active_bytes")
12883        )
12884        .expect("write to string");
12885        pushln!(
12886            out,
12887            "    LET effect_after == MapSet(slot_effect, slot, \"Active\")"
12888        );
12889        pushln!(
12890            out,
12891            "        bytes_after == MapSet(slot_bytes, slot, body_bytes)"
12892        );
12893        pushln!(out, "        kind_after == MapSet(target_kind, slot, kind)");
12894        pushln!(
12895            out,
12896            "        member_after == IF member = None THEN [other_slot \\in DOMAIN target_member \\ {{slot}} |-> target_member[other_slot]] ELSE MapSet(target_member, slot, member.value)"
12897        );
12898        writeln!(
12899            out,
12900            "    IN {}(effect_after, bytes_after, kind_after, member_after)",
12901            prefix("mob_machine_instruction_widest_snapshot_active_bytes")
12902        )
12903        .expect("write to string");
12904    }
12905
12906    fn render_transition(&mut self, out: &mut String, transition: &TransitionSchema) {
12907        let binding_types = self.binding_type_map(transition);
12908        let binding_env = transition
12909            .on
12910            .bindings()
12911            .iter()
12912            .map(|binding| {
12913                (
12914                    binding.as_str().to_owned(),
12915                    self.local_binding_name(binding.as_str()),
12916                )
12917            })
12918            .collect::<BTreeMap<String, _>>();
12919        let params = transition
12920            .on
12921            .bindings()
12922            .iter()
12923            .map(|binding| {
12924                binding_env
12925                    .get(binding.as_str())
12926                    .cloned()
12927                    .unwrap_or_else(|| binding.as_str().to_owned())
12928            })
12929            .collect::<Vec<_>>()
12930            .join(", ");
12931        if params.is_empty() {
12932            writeln!(out, "{} ==", transition.name);
12933        } else {
12934            pushln!(out, "{}({}) ==", transition.name, params);
12935        }
12936
12937        let from_guard = if transition.from.len() == 1 {
12938            format!("phase = {}", tla_string(&transition.from[0]))
12939        } else {
12940            transition
12941                .from
12942                .iter()
12943                .map(|phase| format!("phase = {}", tla_string(phase)))
12944                .collect::<Vec<_>>()
12945                .join(" \\/ ")
12946        };
12947        pushln!(out, "    /\\ {}", from_guard);
12948
12949        let mut env = self
12950            .schema
12951            .state
12952            .fields
12953            .iter()
12954            .map(|field| {
12955                (
12956                    field.name.as_str().to_owned(),
12957                    field.name.as_str().to_owned(),
12958                )
12959            })
12960            .collect::<BTreeMap<String, _>>();
12961
12962        for guard in &transition.guards {
12963            writeln!(
12964                out,
12965                "    /\\ {}",
12966                self.render_guard(guard, &env, &binding_env, &binding_types)
12967            )
12968            .expect("write to string");
12969        }
12970
12971        env = self.compile_updates(
12972            transition.name.as_str(),
12973            &env,
12974            &binding_env,
12975            &binding_types,
12976            &transition.updates,
12977        );
12978
12979        pushln!(out, "    /\\ phase' = {}", tla_string(&transition.to));
12980        pushln!(out, "    /\\ model_step_count' = model_step_count + 1");
12981        let touched = self
12982            .schema
12983            .state
12984            .fields
12985            .iter()
12986            .filter_map(|field| {
12987                let next = env.get(field.name.as_str())?;
12988                if next != field.name.as_str() {
12989                    Some((field.name.as_str(), next.as_str()))
12990                } else {
12991                    None
12992                }
12993            })
12994            .collect::<Vec<_>>();
12995
12996        for (field, expr) in &touched {
12997            pushln!(out, "    /\\ {}' = {}", field, expr);
12998        }
12999
13000        let unchanged = self
13001            .schema
13002            .state
13003            .fields
13004            .iter()
13005            .filter(|field| !touched.iter().any(|(name, _)| *name == field.name.as_str()))
13006            .map(|field| field.name.as_str().to_owned())
13007            .collect::<Vec<_>>();
13008        if !unchanged.is_empty() {
13009            // Machine frames are never chunked: the split policy is a
13010            // composition-scale TLC mitigation, and applying it here would
13011            // change the emitted formula for wide machines.
13012            let name = self
13013                .unchanged_frames
13014                .intern(unchanged_frame_body(&unchanged, None));
13015            pushln!(out, "    /\\ {name}");
13016        }
13017    }
13018
13019    fn render_guard(
13020        &self,
13021        guard: &Guard,
13022        env: &BTreeMap<String, String>,
13023        binding_env: &BTreeMap<String, String>,
13024        binding_types: &BTreeMap<String, TypeRef>,
13025    ) -> String {
13026        self.render_expr_with_types(&guard.expr, env, binding_env, binding_types)
13027    }
13028
13029    fn binding_type_map(&self, transition: &TransitionSchema) -> BTreeMap<String, TypeRef> {
13030        let mut map = BTreeMap::new();
13031        if let Some(variant) = transition_trigger_variant(self.schema, transition) {
13032            for binding in transition.on.bindings() {
13033                if let Some(field) = variant.fields.iter().find(|field| field.name == *binding) {
13034                    map.insert(binding.as_str().to_owned(), field.ty.clone());
13035                }
13036            }
13037        }
13038        map
13039    }
13040
13041    fn local_binding_name(&self, name: impl AsRef<str>) -> String {
13042        let name = name.as_ref();
13043        let candidate = tla_ident(name);
13044        if candidate == "phase"
13045            || self
13046                .schema
13047                .state
13048                .fields
13049                .iter()
13050                .any(|field| field.name.as_str() == name)
13051        {
13052            format!("arg_{candidate}")
13053        } else {
13054            candidate
13055        }
13056    }
13057
13058    fn binding_domain_for_type(&self, ty: &TypeRef) -> String {
13059        match ty {
13060            TypeRef::Bool => "BOOLEAN".into(),
13061            TypeRef::U32 | TypeRef::U64 => "0..2".into(),
13062            TypeRef::String => "StringValues".into(),
13063            TypeRef::Named(_)
13064            | TypeRef::Enum(_)
13065            | TypeRef::Seq(_)
13066            | TypeRef::Set(_)
13067            | TypeRef::Option(_)
13068            | TypeRef::Map(_, _) => domain_constant_name(ty),
13069        }
13070    }
13071
13072    /// Payload domain for one bound field of `input`: the declared input
13073    /// field domain if the schema has one, otherwise the type's default.
13074    fn binding_domain_for_binding(
13075        &self,
13076        input: Option<&str>,
13077        binding: &str,
13078        ty: &TypeRef,
13079    ) -> String {
13080        let declared = input.and_then(|input| {
13081            self.schema
13082                .input_field_domain(input, binding)
13083                .map(|domain| (input, domain))
13084        });
13085        match declared {
13086            Some((_, meerkat_machine_schema::InputFieldDomainKind::StateField(state_field))) => {
13087                format!("{{{}}}", state_field.as_str())
13088            }
13089            Some((_, meerkat_machine_schema::InputFieldDomainKind::AdditionalValues(values))) => {
13090                additional_values_domain(&self.binding_domain_for_type(ty), values)
13091            }
13092            // A model constant that each profile's config assigns: the CI
13093            // profile the declared values, the Deep profile those and `0..2`
13094            // for `CiValues`, the field type's whole domain for `CiSamples`.
13095            Some((
13096                input,
13097                meerkat_machine_schema::InputFieldDomainKind::CiValues(_)
13098                | meerkat_machine_schema::InputFieldDomainKind::CiSamples(_),
13099            )) => input_samples_constant_name(input, binding),
13100            None => self.binding_domain_for_type(ty),
13101        }
13102    }
13103
13104    fn compile_updates(
13105        &mut self,
13106        transition_name: &str,
13107        env: &BTreeMap<String, String>,
13108        binding_env: &BTreeMap<String, String>,
13109        binding_types: &BTreeMap<String, TypeRef>,
13110        updates: &[Update],
13111    ) -> BTreeMap<String, String> {
13112        let mut current = env.clone();
13113        for update in updates {
13114            self.apply_update(
13115                transition_name,
13116                &mut current,
13117                binding_env,
13118                binding_types,
13119                update,
13120            );
13121        }
13122        current
13123    }
13124
13125    fn apply_update(
13126        &mut self,
13127        transition_name: &str,
13128        env: &mut BTreeMap<String, String>,
13129        binding_env: &BTreeMap<String, String>,
13130        binding_types: &BTreeMap<String, TypeRef>,
13131        update: &Update,
13132    ) {
13133        match update {
13134            Update::Assign { field, expr } => {
13135                let value = self.render_expr_with_types(expr, env, binding_env, binding_types);
13136                env.insert(field.as_str().to_owned(), value);
13137            }
13138            Update::Increment { field, amount } => {
13139                let current = env
13140                    .get(field.as_str())
13141                    .cloned()
13142                    .unwrap_or_else(|| field.as_str().to_owned());
13143                env.insert(field.as_str().to_owned(), format!("({current}) + {amount}"));
13144            }
13145            Update::Decrement { field, amount } => {
13146                let current = env
13147                    .get(field.as_str())
13148                    .cloned()
13149                    .unwrap_or_else(|| field.as_str().to_owned());
13150                env.insert(field.as_str().to_owned(), format!("({current}) - {amount}"));
13151            }
13152            Update::MapInsert { field, key, value } => {
13153                let current = env
13154                    .get(field.as_str())
13155                    .cloned()
13156                    .unwrap_or_else(|| field.as_str().to_owned());
13157                let key_expr = self.render_expr_with_types(key, env, binding_env, binding_types);
13158                let value_expr =
13159                    self.render_expr_with_types(value, env, binding_env, binding_types);
13160                env.insert(
13161                    field.as_str().to_owned(),
13162                    format!("MapSet({current}, {key_expr}, {value_expr})"),
13163                );
13164            }
13165            Update::MapRemove { field, key } => {
13166                let current = env
13167                    .get(field.as_str())
13168                    .cloned()
13169                    .unwrap_or_else(|| field.as_str().to_owned());
13170                let key_expr = self.render_expr_with_types(key, env, binding_env, binding_types);
13171                env.insert(
13172                    field.as_str().to_owned(),
13173                    format!("MapRemove({current}, {key_expr})"),
13174                );
13175            }
13176            Update::MapIncrement { field, key, amount } => {
13177                let current = env
13178                    .get(field.as_str())
13179                    .cloned()
13180                    .unwrap_or_else(|| field.as_str().to_owned());
13181                let key_expr = self.render_expr_with_types(key, env, binding_env, binding_types);
13182                env.insert(
13183                    field.as_str().to_owned(),
13184                    format!("MapIncrement({current}, {key_expr}, {amount})"),
13185                );
13186            }
13187            Update::MapDecrement { field, key, amount } => {
13188                let current = env
13189                    .get(field.as_str())
13190                    .cloned()
13191                    .unwrap_or_else(|| field.as_str().to_owned());
13192                let key_expr = self.render_expr_with_types(key, env, binding_env, binding_types);
13193                env.insert(
13194                    field.as_str().to_owned(),
13195                    format!("MapDecrement({current}, {key_expr}, {amount})"),
13196                );
13197            }
13198            Update::SetInsert { field, value } => {
13199                // The field's pending value may be an unparenthesized
13200                // conditional (`IF c THEN a ELSE b`); spliced bare as the left
13201                // operand, the ELSE branch would capture the set operator.
13202                let current = env
13203                    .get(field.as_str())
13204                    .map(|value| tla_delimited(value))
13205                    .unwrap_or_else(|| field.as_str().to_owned());
13206                let value_expr =
13207                    self.render_expr_with_types(value, env, binding_env, binding_types);
13208                env.insert(
13209                    field.as_str().to_owned(),
13210                    format!("({current} \\cup {{{value_expr}}})"),
13211                );
13212            }
13213            Update::SetRemove { field, value } => {
13214                // The field's pending value may be an unparenthesized
13215                // conditional (`IF c THEN a ELSE b`); spliced bare as the left
13216                // operand, the ELSE branch would capture the set operator.
13217                let current = env
13218                    .get(field.as_str())
13219                    .map(|value| tla_delimited(value))
13220                    .unwrap_or_else(|| field.as_str().to_owned());
13221                let value_expr =
13222                    self.render_expr_with_types(value, env, binding_env, binding_types);
13223                env.insert(
13224                    field.as_str().to_owned(),
13225                    format!("({current} \\ {{{value_expr}}})"),
13226                );
13227            }
13228            Update::SeqAppend { field, value } => {
13229                let current = env
13230                    .get(field.as_str())
13231                    .cloned()
13232                    .unwrap_or_else(|| field.as_str().to_owned());
13233                let value_expr =
13234                    self.render_expr_with_types(value, env, binding_env, binding_types);
13235                env.insert(
13236                    field.as_str().to_owned(),
13237                    format!("Append({current}, {value_expr})"),
13238                );
13239            }
13240            Update::SeqPrepend { field, values } => {
13241                let current = env
13242                    .get(field.as_str())
13243                    .cloned()
13244                    .unwrap_or_else(|| field.as_str().to_owned());
13245                let value_expr =
13246                    self.render_expr_with_types(values, env, binding_env, binding_types);
13247                env.insert(
13248                    field.as_str().to_owned(),
13249                    format!("({value_expr} \\o {current})"),
13250                );
13251            }
13252            Update::SeqPopFront { field } => {
13253                let current = env
13254                    .get(field.as_str())
13255                    .cloned()
13256                    .unwrap_or_else(|| field.as_str().to_owned());
13257                env.insert(field.as_str().to_owned(), format!("Tail({current})"));
13258            }
13259            Update::SeqRemoveValue { field, value } => {
13260                let current = env
13261                    .get(field.as_str())
13262                    .cloned()
13263                    .unwrap_or_else(|| field.as_str().to_owned());
13264                let value_expr =
13265                    self.render_expr_with_types(value, env, binding_env, binding_types);
13266                env.insert(
13267                    field.as_str().to_owned(),
13268                    format!("SeqRemove({current}, {value_expr})"),
13269                );
13270            }
13271            Update::SeqRemoveAll { field, values } => {
13272                let current = env
13273                    .get(field.as_str())
13274                    .cloned()
13275                    .unwrap_or_else(|| field.as_str().to_owned());
13276                let value_expr =
13277                    self.render_expr_with_types(values, env, binding_env, binding_types);
13278                env.insert(
13279                    field.as_str().to_owned(),
13280                    format!("SeqRemoveAll({current}, {value_expr})"),
13281                );
13282            }
13283            Update::Conditional {
13284                condition,
13285                then_updates,
13286                else_updates,
13287            } => {
13288                let base = env.clone();
13289                let mut then_env = base.clone();
13290                for update in then_updates {
13291                    self.apply_update(
13292                        transition_name,
13293                        &mut then_env,
13294                        binding_env,
13295                        binding_types,
13296                        update,
13297                    );
13298                }
13299                let mut else_env = base.clone();
13300                for update in else_updates {
13301                    self.apply_update(
13302                        transition_name,
13303                        &mut else_env,
13304                        binding_env,
13305                        binding_types,
13306                        update,
13307                    );
13308                }
13309                let condition_expr =
13310                    self.render_expr_with_types(condition, &base, binding_env, binding_types);
13311                let touched = union_touched_fields(&base, &then_env, &else_env);
13312                for field in touched {
13313                    let then_expr = then_env
13314                        .get(&field)
13315                        .cloned()
13316                        .unwrap_or_else(|| field.clone());
13317                    let else_expr = else_env
13318                        .get(&field)
13319                        .cloned()
13320                        .unwrap_or_else(|| field.clone());
13321                    env.insert(
13322                        field.clone(),
13323                        format!("IF {condition_expr} THEN {then_expr} ELSE {else_expr}"),
13324                    );
13325                }
13326            }
13327            Update::ForEach {
13328                binding,
13329                over,
13330                updates,
13331            } => {
13332                let helper_index = self.helper_counter;
13333                self.helper_counter += 1;
13334                let over_expr = self.render_expr_with_types(over, env, binding_env, binding_types);
13335                let touched = collect_update_fields(updates);
13336                // Every touched field's fold reads the other fields as they
13337                // were BEFORE the loop: the loop below writes each fold back
13338                // into `env` as it goes, so reading `env` there would hand a
13339                // later field the earlier field's post-loop value (all of its
13340                // iterations already applied), not the value an iteration
13341                // reads in the sequential kernel.
13342                let base_env = env.clone();
13343                let referenced_bindings = collect_update_bindings(updates)
13344                    .into_iter()
13345                    .filter(|item| item != binding)
13346                    .collect::<BTreeSet<_>>();
13347                let referenced_fields = collect_update_fields_exprs(updates)
13348                    .into_iter()
13349                    .filter(|field| {
13350                        touched.contains(field) || base_env.get(field.as_str()) != Some(field)
13351                    })
13352                    .collect::<BTreeSet<_>>();
13353
13354                for field in touched {
13355                    let current = base_env
13356                        .get(&field)
13357                        .cloned()
13358                        .unwrap_or_else(|| field.clone());
13359                    let helper_name = format!(
13360                        "{}_ForEach{}_{}",
13361                        tla_ident(transition_name),
13362                        helper_index,
13363                        tla_ident(&field)
13364                    );
13365                    let collection_kind = infer_collection_kind(over, self.schema, binding_types);
13366
13367                    let mut param_defs = Vec::new();
13368                    let mut call_args = vec![current.clone(), over_expr.clone()];
13369                    let mut helper_binding_env = binding_env.clone();
13370                    helper_binding_env.insert(binding.clone(), binding.clone());
13371                    let mut helper_field_env = self
13372                        .schema
13373                        .state
13374                        .fields
13375                        .iter()
13376                        .map(|item| (item.name.as_str().to_owned(), item.name.as_str().to_owned()))
13377                        .collect::<BTreeMap<String, _>>();
13378                    helper_field_env.insert(field.clone(), "acc".into());
13379
13380                    for outer_binding in &referenced_bindings {
13381                        let param = format!("outer_{}", tla_ident(outer_binding));
13382                        param_defs.push(param.clone());
13383                        call_args.push(
13384                            binding_env
13385                                .get(outer_binding)
13386                                .cloned()
13387                                .unwrap_or_else(|| outer_binding.clone()),
13388                        );
13389                        helper_binding_env.insert(outer_binding.clone(), param);
13390                    }
13391
13392                    for ref_field in &referenced_fields {
13393                        if *ref_field == field {
13394                            continue;
13395                        }
13396                        let current_expr = base_env
13397                            .get(ref_field)
13398                            .cloned()
13399                            .unwrap_or_else(|| ref_field.clone());
13400                        if current_expr != *ref_field {
13401                            let param = format!("captured_{}", tla_ident(ref_field));
13402                            param_defs.push(param.clone());
13403                            call_args.push(current_expr);
13404                            helper_field_env.insert(ref_field.clone(), param);
13405                        }
13406                    }
13407
13408                    let body_expr = self.compile_for_each_field_body(
13409                        &field,
13410                        &helper_field_env,
13411                        &helper_binding_env,
13412                        binding_types,
13413                        updates,
13414                    );
13415
13416                    let helper_def = match collection_kind {
13417                        CollectionKind::Sequence => render_sequence_foreach_helper(
13418                            &helper_name,
13419                            binding,
13420                            &param_defs,
13421                            &body_expr,
13422                        ),
13423                        CollectionKind::Set => render_set_foreach_helper(
13424                            &helper_name,
13425                            binding,
13426                            &param_defs,
13427                            &body_expr,
13428                        ),
13429                    };
13430                    self.helper_defs.push(helper_def);
13431                    env.insert(
13432                        field.clone(),
13433                        format!("{}({})", helper_name, call_args.join(", ")),
13434                    );
13435                }
13436            }
13437        }
13438    }
13439
13440    fn compile_for_each_field_body(
13441        &mut self,
13442        target_field: &str,
13443        env: &BTreeMap<String, String>,
13444        binding_env: &BTreeMap<String, String>,
13445        binding_types: &BTreeMap<String, TypeRef>,
13446        updates: &[Update],
13447    ) -> String {
13448        let mut current = env.clone();
13449        for update in updates {
13450            self.apply_update_for_target(
13451                target_field,
13452                &mut current,
13453                binding_env,
13454                binding_types,
13455                update,
13456            );
13457        }
13458        current
13459            .get(target_field)
13460            .cloned()
13461            .unwrap_or_else(|| target_field.to_owned())
13462    }
13463
13464    fn apply_update_for_target(
13465        &mut self,
13466        target_field: &str,
13467        env: &mut BTreeMap<String, String>,
13468        binding_env: &BTreeMap<String, String>,
13469        binding_types: &BTreeMap<String, TypeRef>,
13470        update: &Update,
13471    ) {
13472        match update {
13473            Update::Conditional {
13474                condition,
13475                then_updates,
13476                else_updates,
13477            } => {
13478                let base = env.clone();
13479                let mut then_env = base.clone();
13480                for update in then_updates {
13481                    self.apply_update_for_target(
13482                        target_field,
13483                        &mut then_env,
13484                        binding_env,
13485                        binding_types,
13486                        update,
13487                    );
13488                }
13489                let mut else_env = base.clone();
13490                for update in else_updates {
13491                    self.apply_update_for_target(
13492                        target_field,
13493                        &mut else_env,
13494                        binding_env,
13495                        binding_types,
13496                        update,
13497                    );
13498                }
13499                let base_expr = base
13500                    .get(target_field)
13501                    .cloned()
13502                    .unwrap_or_else(|| target_field.to_owned());
13503                let then_expr = then_env
13504                    .get(target_field)
13505                    .cloned()
13506                    .unwrap_or_else(|| base_expr.clone());
13507                let else_expr = else_env
13508                    .get(target_field)
13509                    .cloned()
13510                    .unwrap_or_else(|| base_expr.clone());
13511                if then_expr != base_expr || else_expr != base_expr {
13512                    let condition_expr =
13513                        self.render_expr_with_types(condition, &base, binding_env, binding_types);
13514                    env.insert(
13515                        target_field.to_owned(),
13516                        format!("IF {condition_expr} THEN {then_expr} ELSE {else_expr}"),
13517                    );
13518                }
13519            }
13520            Update::ForEach {
13521                binding,
13522                over,
13523                updates,
13524            } => {
13525                let helper_index = self.helper_counter;
13526                self.helper_counter += 1;
13527                let over_expr = self.render_expr_with_types(over, env, binding_env, binding_types);
13528                let helper_name = format!(
13529                    "{}_NestedForEach{}_{}",
13530                    tla_ident(target_field),
13531                    helper_index,
13532                    tla_ident(binding)
13533                );
13534                let collection_kind = infer_collection_kind(over, self.schema, binding_types);
13535                let mut nested_binding_env = binding_env.clone();
13536                nested_binding_env.insert(binding.clone(), binding.clone());
13537                let mut nested_env = env.clone();
13538                nested_env.insert(target_field.to_owned(), "acc".into());
13539                let body_expr = self.compile_for_each_field_body(
13540                    target_field,
13541                    &nested_env,
13542                    &nested_binding_env,
13543                    binding_types,
13544                    updates,
13545                );
13546                let helper_def = match collection_kind {
13547                    CollectionKind::Sequence => {
13548                        render_sequence_foreach_helper(&helper_name, binding, &[], &body_expr)
13549                    }
13550                    CollectionKind::Set => {
13551                        render_set_foreach_helper(&helper_name, binding, &[], &body_expr)
13552                    }
13553                };
13554                self.helper_defs.push(helper_def);
13555                let current = env
13556                    .get(target_field)
13557                    .cloned()
13558                    .unwrap_or_else(|| target_field.to_owned());
13559                env.insert(
13560                    target_field.to_owned(),
13561                    format!("{}({}, {})", helper_name, current, over_expr),
13562                );
13563            }
13564            _ => {
13565                let before = env
13566                    .get(target_field)
13567                    .cloned()
13568                    .unwrap_or_else(|| target_field.to_owned());
13569                self.apply_update(
13570                    &format!("Target{}", target_field),
13571                    env,
13572                    binding_env,
13573                    binding_types,
13574                    update,
13575                );
13576                let after = env
13577                    .get(target_field)
13578                    .cloned()
13579                    .unwrap_or_else(|| target_field.to_owned());
13580                if after == before {
13581                    env.insert(target_field.to_owned(), before);
13582                }
13583            }
13584        }
13585    }
13586
13587    fn render_expr(
13588        &self,
13589        expr: &Expr,
13590        env: &BTreeMap<String, String>,
13591        binding_env: &BTreeMap<String, String>,
13592    ) -> String {
13593        self.render_expr_with_types(expr, env, binding_env, &BTreeMap::new())
13594    }
13595
13596    fn scoped_helper_name(&self, helper: &str) -> String {
13597        match &self.helper_prefix {
13598            Some(prefix) => format!("{prefix}{}", tla_ident(helper)),
13599            None => helper.to_owned(),
13600        }
13601    }
13602
13603    fn render_expr_with_types(
13604        &self,
13605        expr: &Expr,
13606        env: &BTreeMap<String, String>,
13607        binding_env: &BTreeMap<String, String>,
13608        binding_types: &BTreeMap<String, TypeRef>,
13609    ) -> String {
13610        match expr {
13611            Expr::Bool(value) => {
13612                if *value {
13613                    "TRUE".into()
13614                } else {
13615                    "FALSE".into()
13616                }
13617            }
13618            Expr::U64(value) => value.to_string(),
13619            Expr::U64Max => TLA_RUST_U64_MAX_CONSTANT.to_owned(),
13620            Expr::String(value) => tla_string(value),
13621            Expr::NamedVariant { enum_name, variant } => render_named_variant_value(
13622                enum_name.as_str(),
13623                variant.as_str(),
13624                &self.named_bindings,
13625            ),
13626            Expr::FieldAccess { base, field } => format!(
13627                "{}.{}",
13628                self.render_expr_with_types(base, env, binding_env, binding_types),
13629                tla_ident(field.as_str())
13630            ),
13631            Expr::EnumVariantIs { value, variant, .. } => format!(
13632                "({}.tag = {})",
13633                self.render_expr_with_types(value, env, binding_env, binding_types),
13634                tla_string(variant.as_str())
13635            ),
13636            Expr::EnumStringSetPayload {
13637                value,
13638                variant,
13639                field,
13640                ..
13641            } => {
13642                let rendered = self.render_expr_with_types(value, env, binding_env, binding_types);
13643                let tag = tla_string(variant.as_str());
13644                let field = tla_ident(field.as_str());
13645                format!("(IF {rendered}.tag = {tag} THEN {rendered}.{field} ELSE {{}})")
13646            }
13647            Expr::EmptySet => "{}".into(),
13648            Expr::EmptyMap => "[x \\in {} |-> None]".into(),
13649            Expr::SeqLiteral(items) => format!(
13650                "<<{}>>",
13651                items
13652                    .iter()
13653                    .map(|item| self.render_expr_with_types(item, env, binding_env, binding_types))
13654                    .collect::<Vec<_>>()
13655                    .join(", ")
13656            ),
13657            Expr::CurrentPhase => self.phase_symbol.clone().unwrap_or_else(|| "phase".into()),
13658            Expr::Phase(value) => tla_string(value),
13659            // A field already assigned earlier in the same update block reads
13660            // its pending value, which may be an unparenthesized compound
13661            // (a conditional update renders `IF c THEN a ELSE b`). Spliced bare
13662            // into a larger expression, TLA+ precedence would capture the
13663            // surrounding operator: `IF c THEN a ELSE b = x` parses as
13664            // `IF c THEN a ELSE (b = x)`. Delimit every substituted value.
13665            Expr::Field(name) => match env.get(name.as_str()) {
13666                Some(value) if value != name.as_str() => tla_delimited(value),
13667                Some(value) => value.clone(),
13668                None => name.as_str().to_owned(),
13669            },
13670            Expr::Binding(name) => binding_env
13671                .get(name)
13672                .cloned()
13673                .unwrap_or_else(|| name.clone()),
13674            Expr::Variant(name) => tla_string(name),
13675            Expr::None => "None".into(),
13676            Expr::IfElse {
13677                condition,
13678                then_expr,
13679                else_expr,
13680            } => format!(
13681                "(IF {} THEN {} ELSE {})",
13682                self.render_expr_with_types(condition, env, binding_env, binding_types),
13683                self.render_expr_with_types(then_expr, env, binding_env, binding_types),
13684                self.render_expr_with_types(else_expr, env, binding_env, binding_types)
13685            ),
13686            Expr::Not(inner) => format!(
13687                "~({})",
13688                self.render_expr_with_types(inner, env, binding_env, binding_types)
13689            ),
13690            Expr::And(items) => join_exprs(
13691                &items
13692                    .iter()
13693                    .map(|item| self.render_expr_with_types(item, env, binding_env, binding_types))
13694                    .collect::<Vec<_>>(),
13695                " /\\ ",
13696            ),
13697            Expr::Or(items) => render_or_short_circuit(
13698                &items
13699                    .iter()
13700                    .map(|item| self.render_expr_with_types(item, env, binding_env, binding_types))
13701                    .collect::<Vec<_>>(),
13702            ),
13703            Expr::Eq(left, right) => format!(
13704                "({} = {})",
13705                self.render_expr_with_types(left, env, binding_env, binding_types),
13706                self.render_expr_with_types(right, env, binding_env, binding_types)
13707            ),
13708            Expr::Neq(left, right) => format!(
13709                "({} # {})",
13710                self.render_expr_with_types(left, env, binding_env, binding_types),
13711                self.render_expr_with_types(right, env, binding_env, binding_types)
13712            ),
13713            Expr::Add(left, right) => format!(
13714                "({} + {})",
13715                self.render_expr_with_types(left, env, binding_env, binding_types),
13716                self.render_expr_with_types(right, env, binding_env, binding_types)
13717            ),
13718            Expr::Sub(left, right) => format!(
13719                "({} - {})",
13720                self.render_expr_with_types(left, env, binding_env, binding_types),
13721                self.render_expr_with_types(right, env, binding_env, binding_types)
13722            ),
13723            Expr::Gt(left, right) => self.render_ordering(
13724                OrderingOperator::Gt,
13725                left,
13726                right,
13727                env,
13728                binding_env,
13729                binding_types,
13730            ),
13731            Expr::Gte(left, right) => self.render_ordering(
13732                OrderingOperator::Gte,
13733                left,
13734                right,
13735                env,
13736                binding_env,
13737                binding_types,
13738            ),
13739            Expr::Lt(left, right) => self.render_ordering(
13740                OrderingOperator::Lt,
13741                left,
13742                right,
13743                env,
13744                binding_env,
13745                binding_types,
13746            ),
13747            Expr::Lte(left, right) => self.render_ordering(
13748                OrderingOperator::Lte,
13749                left,
13750                right,
13751                env,
13752                binding_env,
13753                binding_types,
13754            ),
13755            Expr::Contains { collection, value } => format!(
13756                "({} \\in {})",
13757                self.render_expr_with_types(value, env, binding_env, binding_types),
13758                self.render_collection_domain(collection, env, binding_env, binding_types)
13759            ),
13760            Expr::MapContainsKey { map, key } => format!(
13761                "({} \\in DOMAIN {})",
13762                self.render_expr_with_types(key, env, binding_env, binding_types),
13763                self.render_expr_with_types(map, env, binding_env, binding_types)
13764            ),
13765            Expr::SeqStartsWith { seq, prefix } => format!(
13766                "StartsWith({}, {})",
13767                self.render_expr_with_types(seq, env, binding_env, binding_types),
13768                self.render_expr_with_types(prefix, env, binding_env, binding_types)
13769            ),
13770            Expr::SeqElements(inner) => format!(
13771                "SeqElements({})",
13772                self.render_expr_with_types(inner, env, binding_env, binding_types)
13773            ),
13774            Expr::Len(inner) => {
13775                // The kernel counts the entries of a sequence, set or map
13776                // alike; TLA+ `Len` is defined only on sequences.
13777                let rendered = self.render_expr_with_types(inner, env, binding_env, binding_types);
13778                match self.infer_expr_type_for_render(inner, binding_types) {
13779                    Some(TypeRef::Map(_, _)) => format!("Cardinality(DOMAIN {rendered})"),
13780                    Some(ty) if self.type_renders_as_set(&ty) => {
13781                        format!("Cardinality({rendered})")
13782                    }
13783                    _ => format!("Len({rendered})"),
13784                }
13785            }
13786            Expr::Count { collection, value } => format!(
13787                "Count({}, {})",
13788                self.render_expr_with_types(collection, env, binding_env, binding_types),
13789                self.render_expr_with_types(value, env, binding_env, binding_types)
13790            ),
13791            Expr::Head(inner) => format!(
13792                "Head({})",
13793                self.render_expr_with_types(inner, env, binding_env, binding_types)
13794            ),
13795            Expr::MapKeys(inner) => format!(
13796                "DOMAIN {}",
13797                self.render_expr_with_types(inner, env, binding_env, binding_types)
13798            ),
13799            Expr::MapGet { map, key } => format!(
13800                "{}",
13801                if self.is_scalar_value_projection(map, key, binding_types) {
13802                    self.render_expr_with_types(map, env, binding_env, binding_types)
13803                } else {
13804                    format!(
13805                        "(IF {} \\in DOMAIN {} THEN {}[{}] ELSE {})",
13806                        self.render_expr_with_types(key, env, binding_env, binding_types),
13807                        self.render_expr_with_types(map, env, binding_env, binding_types),
13808                        self.render_expr_with_types(map, env, binding_env, binding_types),
13809                        self.render_expr_with_types(key, env, binding_env, binding_types),
13810                        self.map_absent_value_expr(map, binding_types)
13811                    )
13812                }
13813            ),
13814            // A populated map literal as a TLC function: `k1 :> v1 @@ k2 :> v2`
13815            // (the TLC module every generated model extends).
13816            Expr::MapLiteral(entries) => format!(
13817                "({})",
13818                entries
13819                    .iter()
13820                    .map(|(key, value)| format!(
13821                        "{} :> {}",
13822                        self.render_expr_with_types(key, env, binding_env, binding_types),
13823                        self.render_expr_with_types(value, env, binding_env, binding_types)
13824                    ))
13825                    .collect::<Vec<_>>()
13826                    .join(" @@ ")
13827            ),
13828            // Strict read: plain function application, so TLC reports an
13829            // error if a reachable state reads a key outside DOMAIN (#1811).
13830            Expr::MapValue { map, key } => format!(
13831                "({})[{}]",
13832                self.render_expr_with_types(map, env, binding_env, binding_types),
13833                self.render_expr_with_types(key, env, binding_env, binding_types)
13834            ),
13835            Expr::Some(inner) => format!(
13836                "Some({})",
13837                self.render_expr_with_types(inner, env, binding_env, binding_types)
13838            ),
13839            Expr::Call { helper, args } => format!(
13840                "{}",
13841                if args.is_empty() {
13842                    self.scoped_helper_name(helper)
13843                } else {
13844                    format!(
13845                        "{}({})",
13846                        self.scoped_helper_name(helper),
13847                        args.iter()
13848                            .map(|arg| self.render_expr_with_types(
13849                                arg,
13850                                env,
13851                                binding_env,
13852                                binding_types
13853                            ))
13854                            .collect::<Vec<_>>()
13855                            .join(", ")
13856                    )
13857                }
13858            ),
13859            Expr::Quantified {
13860                quantifier,
13861                binding,
13862                over,
13863                body,
13864            } => {
13865                let keyword = match quantifier {
13866                    Quantifier::Any => "\\E",
13867                    Quantifier::All => "\\A",
13868                };
13869                let mut nested_bindings = binding_env.clone();
13870                nested_bindings.insert(binding.clone(), binding.clone());
13871                let mut nested_binding_types = binding_types.clone();
13872                if let Some(item_ty) = self.collection_item_type(over, binding_types) {
13873                    nested_binding_types.insert(binding.clone(), item_ty);
13874                }
13875                format!(
13876                    "({} {} \\in {} : {})",
13877                    keyword,
13878                    binding,
13879                    self.render_collection_domain(over, env, binding_env, binding_types),
13880                    self.render_expr_with_types(body, env, &nested_bindings, &nested_binding_types)
13881                )
13882            }
13883        }
13884    }
13885
13886    /// `left op right` for an ordering comparison. With an `Option` operand
13887    /// it takes Rust's order through `OptionLt` / `OptionLe` (see
13888    /// [`TLA_OPTION_ORDER_DEFINITIONS`]); otherwise the TLA+ operator.
13889    fn render_ordering(
13890        &self,
13891        operator: OrderingOperator,
13892        left: &Expr,
13893        right: &Expr,
13894        env: &BTreeMap<String, String>,
13895        binding_env: &BTreeMap<String, String>,
13896        binding_types: &BTreeMap<String, TypeRef>,
13897    ) -> String {
13898        let left_tla = self.render_expr_with_types(left, env, binding_env, binding_types);
13899        let right_tla = self.render_expr_with_types(right, env, binding_env, binding_types);
13900        if !self.is_option_operand(left, binding_types)
13901            && !self.is_option_operand(right, binding_types)
13902        {
13903            let symbol = match operator {
13904                OrderingOperator::Lt => "<",
13905                OrderingOperator::Lte => "<=",
13906                OrderingOperator::Gt => ">",
13907                OrderingOperator::Gte => ">=",
13908            };
13909            return format!("({left_tla} {symbol} {right_tla})");
13910        }
13911        self.option_order_used.set(true);
13912        match operator {
13913            OrderingOperator::Lt => format!("OptionLt({left_tla}, {right_tla})"),
13914            OrderingOperator::Lte => format!("OptionLe({left_tla}, {right_tla})"),
13915            OrderingOperator::Gt => format!("OptionLt({right_tla}, {left_tla})"),
13916            OrderingOperator::Gte => format!("OptionLe({right_tla}, {left_tla})"),
13917        }
13918    }
13919
13920    /// Whether `expr` is an `Option` value: a `None` / `Some` literal, or an
13921    /// operand whose type is `Option<_>` (a field, a trigger binding or helper
13922    /// parameter, a helper call, a map read, the `get_copied` / `get_cloned`
13923    /// lowering).
13924    fn is_option_operand(&self, expr: &Expr, binding_types: &BTreeMap<String, TypeRef>) -> bool {
13925        matches!(expr, Expr::None | Expr::Some(_))
13926            || matches!(
13927                self.infer_expr_type_for_render(expr, binding_types),
13928                Some(TypeRef::Option(_))
13929            )
13930    }
13931
13932    fn infer_expr_type_for_render(
13933        &self,
13934        expr: &Expr,
13935        binding_types: &BTreeMap<String, TypeRef>,
13936    ) -> Option<TypeRef> {
13937        // A projection into a structural record (`restrictions.lifetime.unresolved`)
13938        // takes the declared type of the record field, so `.len()` on a
13939        // field-presence set reached through one renders as `Cardinality`.
13940        if let Expr::FieldAccess { base, field } = expr {
13941            let TypeRef::Named(record) = self.infer_expr_type_for_render(base, binding_types)?
13942            else {
13943                return None;
13944            };
13945            let meerkat_machine_schema::RustTypeAtom::TypePathStruct { fields, .. } =
13946                self.named_bindings.get(record.as_str())?
13947            else {
13948                return None;
13949            };
13950            return match &fields
13951                .iter()
13952                .find(|candidate| candidate.name == *field)?
13953                .atom
13954            {
13955                meerkat_machine_schema::TypePathStructFieldAtom::String => Some(TypeRef::String),
13956                meerkat_machine_schema::TypePathStructFieldAtom::Named(name) => {
13957                    Some(TypeRef::Named(name.clone()))
13958                }
13959                meerkat_machine_schema::TypePathStructFieldAtom::OptionalNamed(name) => {
13960                    Some(TypeRef::Option(Box::new(TypeRef::Named(name.clone()))))
13961                }
13962            };
13963        }
13964        let field_types = self
13965            .schema
13966            .state
13967            .fields
13968            .iter()
13969            .map(|field| (field.name.as_str().to_owned(), field.ty.clone()))
13970            .collect::<BTreeMap<String, _>>();
13971        let helper_returns = self
13972            .schema
13973            .helpers
13974            .iter()
13975            .chain(self.schema.derived.iter())
13976            .map(|helper| (helper.name.clone(), helper.returns.clone()))
13977            .collect::<BTreeMap<String, _>>();
13978        infer_expr_type(expr, &field_types, &helper_returns, binding_types)
13979    }
13980
13981    fn type_renders_as_set(&self, ty: &TypeRef) -> bool {
13982        match ty {
13983            TypeRef::Set(_) => true,
13984            TypeRef::Named(name) => matches!(
13985                self.named_bindings.get(name.as_str()),
13986                Some(meerkat_machine_schema::RustTypeAtom::TypePathFieldPresenceSet { .. })
13987            ),
13988            TypeRef::Enum(name) => matches!(
13989                self.named_bindings.get(name.as_str()),
13990                Some(meerkat_machine_schema::RustTypeAtom::TypePathFieldPresenceSet { .. })
13991            ),
13992            _ => false,
13993        }
13994    }
13995
13996    fn render_collection_domain(
13997        &self,
13998        over: &Expr,
13999        env: &BTreeMap<String, String>,
14000        binding_env: &BTreeMap<String, String>,
14001        binding_types: &BTreeMap<String, TypeRef>,
14002    ) -> String {
14003        let rendered = self.render_expr_with_types(over, env, binding_env, binding_types);
14004        match self.collection_item_type(over, binding_types) {
14005            Some(_) if self.is_sequence_expr(over, binding_types) => {
14006                format!("SeqElements({rendered})")
14007            }
14008            _ => rendered,
14009        }
14010    }
14011
14012    fn collection_item_type(
14013        &self,
14014        expr: &Expr,
14015        binding_types: &BTreeMap<String, TypeRef>,
14016    ) -> Option<TypeRef> {
14017        match expr {
14018            Expr::Field(name) => self
14019                .schema
14020                .state
14021                .fields
14022                .iter()
14023                .find(|field| field.name == *name)
14024                .and_then(|field| match &field.ty {
14025                    TypeRef::Seq(inner) | TypeRef::Set(inner) => Some((**inner).clone()),
14026                    _ => None,
14027                }),
14028            Expr::Binding(name) => binding_types.get(name).and_then(|ty| match ty {
14029                TypeRef::Seq(inner) | TypeRef::Set(inner) => Some((**inner).clone()),
14030                _ => None,
14031            }),
14032            Expr::EnumStringSetPayload { .. } => Some(TypeRef::String),
14033            Expr::SeqLiteral(items) => {
14034                if let Some(first) = items.first() {
14035                    self.scalar_expr_type(first, binding_types)
14036                } else {
14037                    Some(TypeRef::String)
14038                }
14039            }
14040            Expr::MapKeys(_) | Expr::EmptySet => Some(TypeRef::String),
14041            _ => None,
14042        }
14043    }
14044
14045    fn scalar_expr_type(
14046        &self,
14047        expr: &Expr,
14048        binding_types: &BTreeMap<String, TypeRef>,
14049    ) -> Option<TypeRef> {
14050        match expr {
14051            Expr::Bool(_) => Some(TypeRef::Bool),
14052            Expr::U64(_) | Expr::U64Max => Some(TypeRef::U64),
14053            Expr::String(_) | Expr::Phase(_) | Expr::Variant(_) => Some(TypeRef::String),
14054            Expr::NamedVariant { enum_name, .. } => Some(TypeRef::Enum(enum_name.clone())),
14055            Expr::FieldAccess { .. } => None,
14056            Expr::EnumVariantIs { .. } => Some(TypeRef::Bool),
14057            Expr::EnumStringSetPayload { .. } => Some(TypeRef::Set(Box::new(TypeRef::String))),
14058            Expr::MapGet { map, .. } | Expr::MapValue { map, .. } => {
14059                self.map_value_type(map, binding_types)
14060            }
14061            Expr::Field(name) => self
14062                .schema
14063                .state
14064                .fields
14065                .iter()
14066                .find(|field| field.name == *name)
14067                .map(|field| &field.ty)
14068                .cloned(),
14069            Expr::Binding(name) => binding_types.get(name).cloned(),
14070            _ => None,
14071        }
14072    }
14073
14074    fn is_scalar_value_projection(
14075        &self,
14076        map: &Expr,
14077        key: &Expr,
14078        binding_types: &BTreeMap<String, TypeRef>,
14079    ) -> bool {
14080        matches!(key, Expr::String(value) if value == "value")
14081            && matches!(
14082                self.scalar_expr_type(map, binding_types),
14083                Some(
14084                    TypeRef::Bool
14085                        | TypeRef::U32
14086                        | TypeRef::U64
14087                        | TypeRef::String
14088                        | TypeRef::Enum(_)
14089                        | TypeRef::Named(_)
14090                )
14091            )
14092    }
14093
14094    fn map_value_type(
14095        &self,
14096        expr: &Expr,
14097        binding_types: &BTreeMap<String, TypeRef>,
14098    ) -> Option<TypeRef> {
14099        match expr {
14100            Expr::Field(name) => self
14101                .schema
14102                .state
14103                .fields
14104                .iter()
14105                .find(|field| field.name == *name)
14106                .and_then(|field| match &field.ty {
14107                    TypeRef::Map(_, value) => Some((**value).clone()),
14108                    _ => None,
14109                }),
14110            Expr::Binding(name) => binding_types.get(name).and_then(|ty| match ty {
14111                TypeRef::Map(_, value) => Some((**value).clone()),
14112                _ => None,
14113            }),
14114            _ => None,
14115        }
14116    }
14117
14118    fn map_absent_value_expr(
14119        &self,
14120        expr: &Expr,
14121        binding_types: &BTreeMap<String, TypeRef>,
14122    ) -> String {
14123        self.map_value_type(expr, binding_types)
14124            .map(|ty| default_absent_map_value_expr(&ty))
14125            .unwrap_or_else(|| "None".into())
14126    }
14127
14128    fn is_sequence_expr(&self, expr: &Expr, binding_types: &BTreeMap<String, TypeRef>) -> bool {
14129        match expr {
14130            Expr::Field(name) => self
14131                .schema
14132                .state
14133                .fields
14134                .iter()
14135                .find(|field| field.name == *name)
14136                .is_some_and(|field| matches!(field.ty, TypeRef::Seq(_))),
14137            Expr::Binding(name) => binding_types
14138                .get(name)
14139                .is_some_and(|ty| matches!(ty, TypeRef::Seq(_))),
14140            Expr::SeqLiteral(_) => true,
14141            _ => false,
14142        }
14143    }
14144}
14145
14146#[derive(Copy, Clone)]
14147enum CollectionKind {
14148    Sequence,
14149    Set,
14150}
14151
14152fn infer_collection_kind(
14153    expr: &Expr,
14154    schema: &MachineSchema,
14155    binding_types: &BTreeMap<String, TypeRef>,
14156) -> CollectionKind {
14157    match expr {
14158        Expr::Field(name) => schema
14159            .state
14160            .fields
14161            .iter()
14162            .find(|field| field.name == *name)
14163            .map(|field| match field.ty {
14164                TypeRef::Set(_) => CollectionKind::Set,
14165                _ => CollectionKind::Sequence,
14166            })
14167            .unwrap_or(CollectionKind::Sequence),
14168        Expr::Binding(name) => binding_types
14169            .get(name)
14170            .map(|ty| match ty {
14171                TypeRef::Set(_) => CollectionKind::Set,
14172                _ => CollectionKind::Sequence,
14173            })
14174            .unwrap_or(CollectionKind::Sequence),
14175        Expr::MapKeys(_) | Expr::EmptySet | Expr::EnumStringSetPayload { .. } => {
14176            CollectionKind::Set
14177        }
14178        _ => CollectionKind::Sequence,
14179    }
14180}
14181
14182fn render_sequence_foreach_helper(
14183    name: &str,
14184    binding: &str,
14185    extra_params: &[String],
14186    body_expr: &str,
14187) -> String {
14188    let mut params = vec!["acc".to_owned(), "items".to_owned()];
14189    params.extend(extra_params.iter().cloned());
14190    let params_str = params.join(", ");
14191    let recurse_args = std::iter::once("next_acc".to_owned())
14192        .chain(std::iter::once("Tail(items)".to_owned()))
14193        .chain(extra_params.iter().cloned())
14194        .collect::<Vec<_>>()
14195        .join(", ");
14196    let recursive_args = std::iter::repeat_n("_", params.len())
14197        .collect::<Vec<_>>()
14198        .join(", ");
14199
14200    format!(
14201        "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})"
14202    )
14203}
14204
14205fn render_set_foreach_helper(
14206    name: &str,
14207    binding: &str,
14208    extra_params: &[String],
14209    body_expr: &str,
14210) -> String {
14211    let mut params = vec!["acc".to_owned(), "remaining".to_owned()];
14212    params.extend(extra_params.iter().cloned());
14213    let params_str = params.join(", ");
14214    let recurse_args = std::iter::once("next_acc".to_owned())
14215        .chain(std::iter::once("remaining \\ {item}".to_owned()))
14216        .chain(extra_params.iter().cloned())
14217        .collect::<Vec<_>>()
14218        .join(", ");
14219    let recursive_args = std::iter::repeat_n("_", params.len())
14220        .collect::<Vec<_>>()
14221        .join(", ");
14222
14223    format!(
14224        "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})"
14225    )
14226}
14227
14228fn collect_update_fields(updates: &[Update]) -> BTreeSet<String> {
14229    let mut fields = BTreeSet::new();
14230    for update in updates {
14231        match update {
14232            Update::Assign { field, .. }
14233            | Update::Increment { field, .. }
14234            | Update::Decrement { field, .. }
14235            | Update::MapInsert { field, .. }
14236            | Update::MapIncrement { field, .. }
14237            | Update::MapDecrement { field, .. }
14238            | Update::MapRemove { field, .. }
14239            | Update::SetInsert { field, .. }
14240            | Update::SetRemove { field, .. }
14241            | Update::SeqAppend { field, .. }
14242            | Update::SeqPrepend { field, .. }
14243            | Update::SeqPopFront { field }
14244            | Update::SeqRemoveValue { field, .. }
14245            | Update::SeqRemoveAll { field, .. } => {
14246                fields.insert(field.as_str().to_owned());
14247            }
14248            Update::Conditional {
14249                then_updates,
14250                else_updates,
14251                ..
14252            } => {
14253                fields.extend(collect_update_fields(then_updates));
14254                fields.extend(collect_update_fields(else_updates));
14255            }
14256            Update::ForEach { updates, .. } => {
14257                fields.extend(collect_update_fields(updates));
14258            }
14259        }
14260    }
14261    fields
14262}
14263
14264fn collect_update_bindings(updates: &[Update]) -> BTreeSet<String> {
14265    let mut bindings = BTreeSet::new();
14266    for update in updates {
14267        match update {
14268            Update::Assign { expr, .. } => collect_expr_bindings(expr, &mut bindings),
14269            Update::MapInsert { key, value, .. } => {
14270                collect_expr_bindings(key, &mut bindings);
14271                collect_expr_bindings(value, &mut bindings);
14272            }
14273            Update::MapRemove { key, .. } => {
14274                collect_expr_bindings(key, &mut bindings);
14275            }
14276            Update::MapIncrement { key, .. } | Update::MapDecrement { key, .. } => {
14277                collect_expr_bindings(key, &mut bindings);
14278            }
14279            Update::SetInsert { value, .. }
14280            | Update::SetRemove { value, .. }
14281            | Update::SeqAppend { value, .. }
14282            | Update::SeqRemoveValue { value, .. }
14283            | Update::SeqPrepend { values: value, .. }
14284            | Update::SeqRemoveAll { values: value, .. } => {
14285                collect_expr_bindings(value, &mut bindings);
14286            }
14287            Update::Conditional {
14288                condition,
14289                then_updates,
14290                else_updates,
14291            } => {
14292                collect_expr_bindings(condition, &mut bindings);
14293                bindings.extend(collect_update_bindings(then_updates));
14294                bindings.extend(collect_update_bindings(else_updates));
14295            }
14296            Update::ForEach {
14297                binding,
14298                over,
14299                updates,
14300            } => {
14301                bindings.insert(binding.clone());
14302                collect_expr_bindings(over, &mut bindings);
14303                bindings.extend(collect_update_bindings(updates));
14304            }
14305            Update::Increment { .. } | Update::Decrement { .. } | Update::SeqPopFront { .. } => {}
14306        }
14307    }
14308    bindings
14309}
14310
14311fn collect_update_fields_exprs(updates: &[Update]) -> BTreeSet<String> {
14312    let mut fields = BTreeSet::new();
14313    for update in updates {
14314        match update {
14315            Update::Assign { expr, .. } => collect_expr_fields(expr, &mut fields),
14316            Update::MapInsert { key, value, .. } => {
14317                collect_expr_fields(key, &mut fields);
14318                collect_expr_fields(value, &mut fields);
14319            }
14320            Update::MapRemove { key, .. } => {
14321                collect_expr_fields(key, &mut fields);
14322            }
14323            Update::MapIncrement { key, .. } | Update::MapDecrement { key, .. } => {
14324                collect_expr_fields(key, &mut fields);
14325            }
14326            Update::SetInsert { value, .. }
14327            | Update::SetRemove { value, .. }
14328            | Update::SeqAppend { value, .. }
14329            | Update::SeqRemoveValue { value, .. }
14330            | Update::SeqPrepend { values: value, .. }
14331            | Update::SeqRemoveAll { values: value, .. } => {
14332                collect_expr_fields(value, &mut fields);
14333            }
14334            Update::Conditional {
14335                condition,
14336                then_updates,
14337                else_updates,
14338            } => {
14339                collect_expr_fields(condition, &mut fields);
14340                fields.extend(collect_update_fields_exprs(then_updates));
14341                fields.extend(collect_update_fields_exprs(else_updates));
14342            }
14343            Update::ForEach { over, updates, .. } => {
14344                collect_expr_fields(over, &mut fields);
14345                fields.extend(collect_update_fields_exprs(updates));
14346            }
14347            Update::Increment { .. } | Update::Decrement { .. } | Update::SeqPopFront { .. } => {}
14348        }
14349    }
14350    fields
14351}
14352
14353fn collect_expr_bindings(expr: &Expr, bindings: &mut BTreeSet<String>) {
14354    match expr {
14355        Expr::Binding(name) => {
14356            bindings.insert(name.clone());
14357        }
14358        Expr::SeqLiteral(items) | Expr::And(items) | Expr::Or(items) => {
14359            for item in items {
14360                collect_expr_bindings(item, bindings);
14361            }
14362        }
14363        Expr::IfElse {
14364            condition,
14365            then_expr,
14366            else_expr,
14367        } => {
14368            collect_expr_bindings(condition, bindings);
14369            collect_expr_bindings(then_expr, bindings);
14370            collect_expr_bindings(else_expr, bindings);
14371        }
14372        Expr::Not(inner)
14373        | Expr::SeqElements(inner)
14374        | Expr::Len(inner)
14375        | Expr::Head(inner)
14376        | Expr::MapKeys(inner)
14377        | Expr::Some(inner)
14378        | Expr::FieldAccess { base: inner, .. }
14379        | Expr::EnumVariantIs { value: inner, .. }
14380        | Expr::EnumStringSetPayload { value: inner, .. } => collect_expr_bindings(inner, bindings),
14381        Expr::Eq(left, right)
14382        | Expr::Neq(left, right)
14383        | Expr::Add(left, right)
14384        | Expr::Sub(left, right)
14385        | Expr::Gt(left, right)
14386        | Expr::Gte(left, right)
14387        | Expr::Lt(left, right)
14388        | Expr::Lte(left, right) => {
14389            collect_expr_bindings(left, bindings);
14390            collect_expr_bindings(right, bindings);
14391        }
14392        Expr::Contains { collection, value } => {
14393            collect_expr_bindings(collection, bindings);
14394            collect_expr_bindings(value, bindings);
14395        }
14396        Expr::Count { collection, value } => {
14397            collect_expr_bindings(collection, bindings);
14398            collect_expr_bindings(value, bindings);
14399        }
14400        Expr::MapContainsKey { map, key } => {
14401            collect_expr_bindings(map, bindings);
14402            collect_expr_bindings(key, bindings);
14403        }
14404        Expr::SeqStartsWith { seq, prefix } => {
14405            collect_expr_bindings(seq, bindings);
14406            collect_expr_bindings(prefix, bindings);
14407        }
14408        Expr::MapGet { map, key } | Expr::MapValue { map, key } => {
14409            collect_expr_bindings(map, bindings);
14410            collect_expr_bindings(key, bindings);
14411        }
14412        Expr::MapLiteral(entries) => {
14413            for (key, value) in entries {
14414                collect_expr_bindings(key, bindings);
14415                collect_expr_bindings(value, bindings);
14416            }
14417        }
14418        Expr::Call { args, .. } => {
14419            for arg in args {
14420                collect_expr_bindings(arg, bindings);
14421            }
14422        }
14423        Expr::Quantified {
14424            binding,
14425            over,
14426            body,
14427            ..
14428        } => {
14429            bindings.insert(binding.clone());
14430            collect_expr_bindings(over, bindings);
14431            collect_expr_bindings(body, bindings);
14432        }
14433        Expr::Bool(_)
14434        | Expr::U64(_)
14435        | Expr::U64Max
14436        | Expr::String(_)
14437        | Expr::NamedVariant { .. }
14438        | Expr::EmptySet
14439        | Expr::EmptyMap
14440        | Expr::CurrentPhase
14441        | Expr::Phase(_)
14442        | Expr::Field(_)
14443        | Expr::Variant(_)
14444        | Expr::None => {}
14445    }
14446}
14447
14448fn collect_expr_fields(expr: &Expr, fields: &mut BTreeSet<String>) {
14449    match expr {
14450        Expr::Field(name) => {
14451            fields.insert(name.as_str().to_owned());
14452        }
14453        Expr::SeqLiteral(items) | Expr::And(items) | Expr::Or(items) => {
14454            for item in items {
14455                collect_expr_fields(item, fields);
14456            }
14457        }
14458        Expr::IfElse {
14459            condition,
14460            then_expr,
14461            else_expr,
14462        } => {
14463            collect_expr_fields(condition, fields);
14464            collect_expr_fields(then_expr, fields);
14465            collect_expr_fields(else_expr, fields);
14466        }
14467        Expr::Not(inner)
14468        | Expr::SeqElements(inner)
14469        | Expr::Len(inner)
14470        | Expr::Head(inner)
14471        | Expr::MapKeys(inner)
14472        | Expr::Some(inner)
14473        | Expr::FieldAccess { base: inner, .. }
14474        | Expr::EnumVariantIs { value: inner, .. }
14475        | Expr::EnumStringSetPayload { value: inner, .. } => collect_expr_fields(inner, fields),
14476        Expr::Eq(left, right)
14477        | Expr::Neq(left, right)
14478        | Expr::Add(left, right)
14479        | Expr::Sub(left, right)
14480        | Expr::Gt(left, right)
14481        | Expr::Gte(left, right)
14482        | Expr::Lt(left, right)
14483        | Expr::Lte(left, right) => {
14484            collect_expr_fields(left, fields);
14485            collect_expr_fields(right, fields);
14486        }
14487        Expr::Contains { collection, value } => {
14488            collect_expr_fields(collection, fields);
14489            collect_expr_fields(value, fields);
14490        }
14491        Expr::Count { collection, value } => {
14492            collect_expr_fields(collection, fields);
14493            collect_expr_fields(value, fields);
14494        }
14495        Expr::MapContainsKey { map, key } => {
14496            collect_expr_fields(map, fields);
14497            collect_expr_fields(key, fields);
14498        }
14499        Expr::SeqStartsWith { seq, prefix } => {
14500            collect_expr_fields(seq, fields);
14501            collect_expr_fields(prefix, fields);
14502        }
14503        Expr::MapGet { map, key } | Expr::MapValue { map, key } => {
14504            collect_expr_fields(map, fields);
14505            collect_expr_fields(key, fields);
14506        }
14507        Expr::MapLiteral(entries) => {
14508            for (key, value) in entries {
14509                collect_expr_fields(key, fields);
14510                collect_expr_fields(value, fields);
14511            }
14512        }
14513        Expr::Call { args, .. } => {
14514            for arg in args {
14515                collect_expr_fields(arg, fields);
14516            }
14517        }
14518        Expr::Quantified { over, body, .. } => {
14519            collect_expr_fields(over, fields);
14520            collect_expr_fields(body, fields);
14521        }
14522        Expr::Bool(_)
14523        | Expr::U64(_)
14524        | Expr::U64Max
14525        | Expr::String(_)
14526        | Expr::NamedVariant { .. }
14527        | Expr::EmptySet
14528        | Expr::EmptyMap
14529        | Expr::CurrentPhase
14530        | Expr::Phase(_)
14531        | Expr::Binding(_)
14532        | Expr::Variant(_)
14533        | Expr::None => {}
14534    }
14535}
14536
14537fn union_touched_fields(
14538    base: &BTreeMap<String, String>,
14539    then_env: &BTreeMap<String, String>,
14540    else_env: &BTreeMap<String, String>,
14541) -> BTreeSet<String> {
14542    base.keys()
14543        .filter(|field| {
14544            then_env.get(*field) != base.get(*field) || else_env.get(*field) != base.get(*field)
14545        })
14546        .cloned()
14547        .collect()
14548}
14549
14550fn join_exprs(items: &[String], separator: &str) -> String {
14551    if items.is_empty() {
14552        return "TRUE".into();
14553    }
14554    if items.len() == 1 {
14555        items[0].clone()
14556    } else {
14557        format!("({})", items.join(separator))
14558    }
14559}
14560
14561/// Render a boolean disjunction as a short-circuiting `IF a THEN TRUE ELSE …`
14562/// chain instead of `a \/ b`.
14563///
14564/// TLC expands an action-level `\/` into a tableau and evaluates *every*
14565/// disjunct independently to enumerate successor states. That breaks the
14566/// idiomatic optional guard `opt = None \/ opt.value > now`: the second
14567/// disjunct's `opt.value > now` is evaluated even when `opt = None`
14568/// (`None` still has a `"value"` field equal to the string `"none"`), so TLC
14569/// raises `first argument of > should be an integer, but instead it is "none"`.
14570/// `IF a THEN TRUE ELSE b` is boolean-equivalent to `a \/ b` but is evaluated
14571/// as a single function: the `ELSE` branch is only evaluated when `a` is false,
14572/// matching the short-circuit that `/\` already gives conjunctive guards. State
14573/// space and enabledness are unchanged. Empty/single disjunctions preserve the
14574/// prior `join_exprs` behavior.
14575fn render_or_short_circuit(items: &[String]) -> String {
14576    match items {
14577        [] => "TRUE".into(),
14578        [single] => single.clone(),
14579        [first, rest @ ..] => {
14580            format!(
14581                "(IF {first} THEN TRUE ELSE {})",
14582                render_or_short_circuit(rest)
14583            )
14584        }
14585    }
14586}
14587
14588fn default_state_init_expr(ty: &TypeRef) -> String {
14589    match ty {
14590        TypeRef::Bool => "FALSE".into(),
14591        TypeRef::U32 | TypeRef::U64 => "0".into(),
14592        TypeRef::String => tla_string(""),
14593        TypeRef::Named(name) => tla_string(format!("{}_default", tla_ident(name).to_lowercase())),
14594        TypeRef::Enum(name) => tla_string(format!("{}_default", tla_ident(name).to_lowercase())),
14595        TypeRef::Option(_) => "None".into(),
14596        TypeRef::Set(_) => "{}".into(),
14597        TypeRef::Seq(_) => "<<>>".into(),
14598        TypeRef::Map(_, _) => "[x \\in {} |-> None]".into(),
14599    }
14600}
14601
14602fn default_absent_map_value_expr(ty: &TypeRef) -> String {
14603    match ty {
14604        TypeRef::Bool => "FALSE".into(),
14605        TypeRef::U32 | TypeRef::U64 => "0".into(),
14606        TypeRef::String | TypeRef::Named(_) | TypeRef::Enum(_) => tla_string("None"),
14607        TypeRef::Option(_) => "None".into(),
14608        TypeRef::Set(_) => "{}".into(),
14609        TypeRef::Seq(_) => "<<>>".into(),
14610        TypeRef::Map(_, _) => "[x \\in {} |-> None]".into(),
14611    }
14612}
14613
14614fn render_type_ref(ty: &TypeRef) -> String {
14615    match ty {
14616        TypeRef::Bool => "Bool".into(),
14617        TypeRef::U32 => "u32".into(),
14618        TypeRef::U64 => "u64".into(),
14619        TypeRef::String => "String".into(),
14620        TypeRef::Named(name) => name.as_str().to_owned(),
14621        TypeRef::Enum(name) => name.as_str().to_owned(),
14622        TypeRef::Option(inner) => format!("Option<{}>", render_type_ref(inner)),
14623        TypeRef::Set(inner) => format!("Set<{}>", render_type_ref(inner)),
14624        TypeRef::Seq(inner) => format!("Seq<{}>", render_type_ref(inner)),
14625        TypeRef::Map(key, value) => {
14626            format!("Map<{}, {}>", render_type_ref(key), render_type_ref(value))
14627        }
14628    }
14629}
14630
14631fn render_route_delivery(route: &meerkat_machine_schema::Route) -> &'static str {
14632    match route.delivery {
14633        RouteDelivery::Immediate => "Immediate",
14634        RouteDelivery::Enqueue => "Enqueue",
14635    }
14636}
14637
14638fn render_scheduler_rule(rule: &SchedulerRule) -> String {
14639    match rule {
14640        SchedulerRule::PreemptWhenReady { higher, lower } => {
14641            format!("PreemptWhenReady({higher}, {lower})")
14642        }
14643    }
14644}
14645
14646fn render_scheduler_rule_tuple(rule: &SchedulerRule) -> String {
14647    match rule {
14648        SchedulerRule::PreemptWhenReady { higher, lower } => {
14649            format!(
14650                "<<{}, {}, {}>>",
14651                tla_string("PreemptWhenReady"),
14652                tla_string(higher),
14653                tla_string(lower)
14654            )
14655        }
14656    }
14657}
14658
14659fn render_scheduler_trigger_formula(rule: &SchedulerRule) -> String {
14660    match rule {
14661        SchedulerRule::PreemptWhenReady { higher, lower } => format!(
14662            "/\\ {} \\in PendingActors /\\ {} \\in PendingActors",
14663            tla_string(higher),
14664            tla_string(lower)
14665        ),
14666    }
14667}
14668
14669fn render_composition_invariant_formula(
14670    schema: &CompositionSchema,
14671    kind: &CompositionInvariantKind,
14672) -> String {
14673    match kind {
14674        CompositionInvariantKind::RoutePresent {
14675            from_machine,
14676            effect_variant,
14677            to_machine,
14678            input_variant,
14679        } => format!(
14680            "\\E route_name \\in RouteNames : /\\ RouteSource(route_name) = {} /\\ RouteEffect(route_name) = {} /\\ RouteTargetMachine(route_name) = {} /\\ RouteTargetInput(route_name) = {}",
14681            tla_string(from_machine),
14682            tla_string(effect_variant),
14683            tla_string(to_machine),
14684            tla_string(input_variant)
14685        ),
14686        CompositionInvariantKind::ObservedInputOriginatesFromEffect {
14687            to_machine,
14688            input_variant,
14689            from_machine,
14690            effect_variant,
14691        } => format!(
14692            "\\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))",
14693            tla_string(to_machine),
14694            tla_string(input_variant),
14695            tla_string(from_machine),
14696            tla_string(effect_variant),
14697            tla_string(from_machine),
14698            tla_string(effect_variant),
14699            tla_string(from_machine),
14700            tla_string(effect_variant),
14701            tla_string(to_machine),
14702            tla_string(input_variant)
14703        ),
14704        CompositionInvariantKind::ObservedRouteInputOriginatesFromEffect {
14705            route_name,
14706            to_machine,
14707            input_variant,
14708            from_machine,
14709            effect_variant,
14710        } => format!(
14711            "\\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))",
14712            tla_string(to_machine),
14713            tla_string(input_variant),
14714            tla_string(route_name),
14715            tla_string(from_machine),
14716            tla_string(effect_variant),
14717            tla_string(from_machine),
14718            tla_string(effect_variant),
14719            tla_string(route_name),
14720            tla_string(from_machine),
14721            tla_string(effect_variant),
14722            tla_string(to_machine),
14723            tla_string(input_variant)
14724        ),
14725        CompositionInvariantKind::ActorPriorityPresent { higher, lower } => format!(
14726            "<<{}, {}>> \\in ActorPriorities",
14727            tla_string(higher),
14728            tla_string(lower)
14729        ),
14730        CompositionInvariantKind::SchedulerRulePresent { rule } => {
14731            format!("{} \\in SchedulerRules", render_scheduler_rule_tuple(rule))
14732        }
14733        CompositionInvariantKind::OutcomeHandled {
14734            from_machine,
14735            effect_variant,
14736            required_targets,
14737        } => {
14738            let required = required_targets
14739                .iter()
14740                .enumerate()
14741                .map(|(idx, target)| {
14742                    let binding = format!("route_packet_{idx}");
14743                    let input_binding = format!("input_packet_{idx}");
14744                    format!(
14745                        "\\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",
14746                        tla_string(from_machine),
14747                        tla_string(effect_variant),
14748                        tla_string(&target.machine),
14749                        tla_string(&target.input_variant)
14750                        ,
14751                        tla_string(&target.machine),
14752                        tla_string(&target.input_variant),
14753                        tla_string(from_machine),
14754                        tla_string(effect_variant)
14755                    )
14756                })
14757                .collect::<Vec<_>>()
14758                .join(" /\\ ");
14759            let fallback = schema
14760                .routes
14761                .iter()
14762                .filter(|route| {
14763                    route.from_machine == *from_machine && route.effect_variant == *effect_variant
14764                })
14765                .count();
14766            if fallback == 0 {
14767                "FALSE".into()
14768            } else {
14769                format!(
14770                    "\\A effect_packet \\in emitted_effects : ((effect_packet.machine = {} /\\ effect_packet.variant = {}) => ({}))",
14771                    tla_string(from_machine),
14772                    tla_string(effect_variant),
14773                    required
14774                )
14775            }
14776        }
14777        CompositionInvariantKind::HandoffProtocolCovered { .. } => {
14778            // Structural invariant — validated at schema level, always TRUE in TLA+.
14779            "TRUE".into()
14780        }
14781    }
14782}
14783
14784fn render_composition_state_constraint(
14785    schema: &CompositionSchema,
14786    limits: &CompositionStateLimits,
14787    compiler: &CompositionTlaCompiler<'_>,
14788) -> String {
14789    let limits = effective_composition_state_limits(limits, None);
14790    let mut clauses = vec![
14791        format!("model_step_count <= {}", limits.step_limit),
14792        format!("Len(pending_inputs) <= {}", limits.pending_input_limit),
14793        format!(
14794            "Cardinality(observed_inputs) <= {}",
14795            limits.pending_input_limit + limits.delivered_route_limit + 2
14796        ),
14797        format!("Len(pending_routes) <= {}", limits.pending_route_limit),
14798        format!(
14799            "Cardinality(delivered_routes) <= {}",
14800            limits.delivered_route_limit
14801        ),
14802        format!(
14803            "Cardinality(emitted_effects) <= {}",
14804            limits.emitted_effect_limit
14805        ),
14806        format!("Cardinality(observed_transitions) <= {}", limits.step_limit),
14807    ];
14808
14809    for instance in &schema.machines {
14810        let machine = compiler.machine(instance.instance_id.as_str());
14811        for field in &machine.state.fields {
14812            let field_var = compiler.field_var(instance.instance_id.as_str(), field.name.as_str());
14813            match &field.ty {
14814                TypeRef::Seq(_) => {
14815                    clauses.push(format!("Len({field_var}) <= {}", limits.seq_limit))
14816                }
14817                TypeRef::Set(_) => {
14818                    clauses.push(format!("Cardinality({field_var}) <= {}", limits.set_limit))
14819                }
14820                TypeRef::Map(_, _) => clauses.push(format!(
14821                    "Cardinality(DOMAIN {field_var}) <= {}",
14822                    limits.map_limit
14823                )),
14824                _ => {}
14825            }
14826        }
14827    }
14828
14829    format!("/\\ {}", clauses.join(" /\\ "))
14830}
14831
14832fn effective_composition_state_limits(
14833    limits: &CompositionStateLimits,
14834    witness: Option<&CompositionWitness>,
14835) -> CompositionStateLimits {
14836    let mut effective = limits.clone();
14837    if let Some(witness) = witness {
14838        let minimum_step_limit =
14839            (witness.preload_inputs.len() + witness.expected_transitions.len()) as u32;
14840        effective.step_limit = effective.step_limit.max(minimum_step_limit);
14841        effective.delivered_route_limit = effective
14842            .delivered_route_limit
14843            .max(witness.expected_routes.len() as u32);
14844        effective.emitted_effect_limit = effective
14845            .emitted_effect_limit
14846            .max(witness.expected_transitions.len() as u32);
14847        effective.pending_input_limit = effective.pending_input_limit.max(1);
14848    }
14849    effective
14850}
14851
14852fn composition_deep_state_limits(schema: &CompositionSchema) -> CompositionStateLimits {
14853    let mut deep = CompositionStateLimits::deep_defaults();
14854    if let Some(ci) = &schema.ci_limits {
14855        deep.step_limit = deep.step_limit.max(ci.step_limit);
14856        deep.pending_input_limit = deep.pending_input_limit.max(ci.pending_input_limit);
14857        deep.pending_route_limit = deep.pending_route_limit.max(ci.pending_route_limit);
14858        deep.delivered_route_limit = deep.delivered_route_limit.max(ci.delivered_route_limit);
14859        deep.emitted_effect_limit = deep.emitted_effect_limit.max(ci.emitted_effect_limit);
14860        deep.seq_limit = deep.seq_limit.max(ci.seq_limit);
14861        deep.set_limit = deep.set_limit.max(ci.set_limit);
14862        deep.map_limit = deep.map_limit.max(ci.map_limit);
14863    }
14864    deep
14865}
14866
14867fn render_machine_state_constraint(schema: &MachineSchema, deep: bool) -> String {
14868    let step_limit = if deep {
14869        8
14870    } else {
14871        schema.ci_step_limit.unwrap_or(6) as usize
14872    };
14873    let seq_limit = if deep { 2 } else { 1 };
14874    let set_limit = if deep { 2 } else { 1 };
14875    let map_limit = if deep { 2 } else { 1 };
14876    let (step_limit, seq_limit, set_limit, map_limit) =
14877        if !deep && let Some(model) = &schema.tlc_model {
14878            let limits = &model.ci_limits;
14879            (
14880                limits.step_limit as usize,
14881                limits.seq_limit as usize,
14882                limits.set_limit as usize,
14883                limits.map_limit as usize,
14884            )
14885        } else {
14886            (step_limit, seq_limit, set_limit, map_limit)
14887        };
14888    let mut clauses = vec![format!("model_step_count <= {step_limit}")];
14889
14890    for field in &schema.state.fields {
14891        match &field.ty {
14892            TypeRef::Seq(_) => {
14893                clauses.push(format!("Len({}) <= {seq_limit}", tla_ident(&field.name)))
14894            }
14895            TypeRef::Set(_) => clauses.push(format!(
14896                "Cardinality({}) <= {set_limit}",
14897                tla_ident(&field.name)
14898            )),
14899            TypeRef::Map(_, _) => clauses.push(format!(
14900                "Cardinality(DOMAIN {}) <= {map_limit}",
14901                tla_ident(&field.name)
14902            )),
14903            _ => {}
14904        }
14905    }
14906
14907    if clauses.is_empty() {
14908        "TRUE".into()
14909    } else {
14910        format!("/\\ {}", clauses.join(" /\\ "))
14911    }
14912}
14913
14914/// Default arm for a generated composition `CASE` operator.
14915///
14916/// Route-component lookups (`RouteSource`, `RouteEffect`, …) are validated
14917/// up-front by [`CompositionTlaCompiler::validate_routes`], so the historical
14918/// `OTHER -> "unknown_*"` arm is provably unreachable for any real route name.
14919/// Emitting that sentinel was a silent catch-all that could launder an
14920/// undeclared route component into a passing model. Such lookups now use
14921/// [`CaseDefault::FailClosed`]: the `OTHER` arm is dropped entirely so an
14922/// unmatched route name surfaces as a TLC error instead of a fabricated value,
14923/// and the renderer fails closed at codegen time if a route component cannot
14924/// be resolved.
14925///
14926/// Genuinely closed enumerations (`RouteTargetKind`, `RouteDeliveryKind`) keep
14927/// a total literal fallback via [`CaseDefault::ClosedEnum`]; every input maps
14928/// to a finite, exhaustive enum, so the literal is a sound total default rather
14929/// than a sentinel standing in for an undeclared component.
14930enum CaseDefault {
14931    /// Total literal fallback over a closed enumeration domain.
14932    ClosedEnum(String),
14933    /// Fail-closed route-component lookup: no `OTHER` sentinel is emitted.
14934    ///
14935    /// `require_mapping` is `true` for operators whose domain must be
14936    /// non-empty for a well-formed composition (e.g. `ActorOfMachine`, which
14937    /// maps over declared machine instances): an empty mapping is then a hard
14938    /// codegen error. It is `false` for operators keyed on routes, since a
14939    /// protocol-only composition legitimately declares zero routes — the
14940    /// operator is structurally defined but never evaluated.
14941    FailClosed {
14942        component: &'static str,
14943        require_mapping: bool,
14944    },
14945}
14946
14947fn render_composition_case_fn(
14948    out: &mut String,
14949    composition: &str,
14950    fn_name: &str,
14951    param: &str,
14952    mappings: Vec<(&str, String)>,
14953    default: CaseDefault,
14954) -> std::result::Result<(), CompositionTlaError> {
14955    writeln!(out, "{fn_name}({param}) ==");
14956    if mappings.is_empty() {
14957        // No keys to map. For a closed-enum operator the literal fallback is
14958        // the operator body. For a fail-closed route-component operator the
14959        // composition declares no routes, so the operator is structurally
14960        // defined but unreachable; emitting the bare error label as a string
14961        // makes any accidental evaluation explode in TLC rather than yield a
14962        // plausible-looking value.
14963        let body = match &default {
14964            CaseDefault::ClosedEnum(expr) => expr.clone(),
14965            CaseDefault::FailClosed {
14966                component,
14967                require_mapping,
14968            } => {
14969                if *require_mapping {
14970                    return Err(CompositionTlaError::UnknownRouteComponent {
14971                        composition: composition.to_owned(),
14972                        component,
14973                    });
14974                }
14975                tla_string(format!("unresolved_{component}"))
14976            }
14977        };
14978        pushln!(out, "    {}", body);
14979        pushln!(out);
14980        return Ok(());
14981    }
14982
14983    let mut first = true;
14984    for (key, value) in mappings {
14985        if first {
14986            pushln!(out, "    CASE {} = {} -> {}", param, tla_string(key), value);
14987            first = false;
14988        } else {
14989            writeln!(out, "      [] {} = {} -> {}", param, tla_string(key), value);
14990        }
14991    }
14992    match default {
14993        CaseDefault::ClosedEnum(expr) => {
14994            writeln!(out, "      [] OTHER -> {}", expr);
14995        }
14996        CaseDefault::FailClosed { .. } => {
14997            // validate_routes() guarantees the CASE arms cover every declared
14998            // route, so an OTHER arm here would be a silent catch-all over an
14999            // undeclared route component. Drop it: an unmatched route name now
15000            // becomes a TLC evaluation error (fail closed) instead of a
15001            // fabricated sentinel.
15002        }
15003    }
15004    pushln!(out);
15005    Ok(())
15006}
15007
15008fn tla_ident(value: impl AsRef<str>) -> String {
15009    value
15010        .as_ref()
15011        .chars()
15012        .map(|ch| if ch.is_ascii_alphanumeric() { ch } else { '_' })
15013        .collect()
15014}
15015
15016fn tla_string(value: impl AsRef<str>) -> String {
15017    format!("\"{}\"", value.as_ref().replace('"', "\\\""))
15018}
15019
15020/// Wrap a rendered TLA+ expression in parentheses unless it is already an
15021/// atom (an identifier, field path, number or string, optionally applied with balanced
15022/// `(...)`/`[...]` suffixes, or one parenthesized group), so it can be spliced
15023/// as an operand without TLA+ operator precedence reaching into it.
15024fn tla_delimited(expr: &str) -> String {
15025    if tla_is_atom(expr) {
15026        expr.to_owned()
15027    } else {
15028        format!("({expr})")
15029    }
15030}
15031
15032fn tla_is_atom(expr: &str) -> bool {
15033    let bytes = expr.as_bytes();
15034    let mut index = 0;
15035    match bytes.first() {
15036        Some(b'(') => {}
15037        Some(b'"') => {
15038            index = 1;
15039            while index < bytes.len() && bytes[index] != b'"' {
15040                index += 1;
15041            }
15042            if index >= bytes.len() {
15043                return false;
15044            }
15045            index += 1;
15046        }
15047        Some(byte) if byte.is_ascii_alphanumeric() || *byte == b'_' => {
15048            // Identifiers and record field paths (`packet.payload.run_id`):
15049            // field access binds tighter than every operator.
15050            while index < bytes.len()
15051                && (bytes[index].is_ascii_alphanumeric()
15052                    || bytes[index] == b'_'
15053                    || bytes[index] == b'.')
15054            {
15055                index += 1;
15056            }
15057        }
15058        _ => return false,
15059    }
15060    // Zero or more balanced `(...)` / `[...]` groups, with nothing between.
15061    while index < bytes.len() {
15062        let (open, close) = match bytes[index] {
15063            b'(' => (b'(', b')'),
15064            b'[' => (b'[', b']'),
15065            _ => return false,
15066        };
15067        let mut depth = 0usize;
15068        let mut in_string = false;
15069        let mut end = None;
15070        for (offset, byte) in bytes[index..].iter().enumerate() {
15071            match *byte {
15072                b'"' => in_string = !in_string,
15073                b if b == open && !in_string => depth += 1,
15074                b if b == close && !in_string => {
15075                    depth -= 1;
15076                    if depth == 0 {
15077                        end = Some(index + offset);
15078                        break;
15079                    }
15080                }
15081                _ => {}
15082            }
15083        }
15084        match end {
15085            Some(end) => index = end + 1,
15086            None => return false,
15087        }
15088    }
15089    true
15090}
15091
15092/// The input variant a transition is triggered by, if it is input-triggered.
15093fn trigger_input_variant(transition: &TransitionSchema) -> Option<&str> {
15094    match &transition.on {
15095        TriggerMatch::Input { variant, .. } => Some(variant.as_str()),
15096        _ => None,
15097    }
15098}
15099
15100/// The default unsigned domain extended with declared additional values.
15101fn additional_values_domain(default: &str, values: &BTreeSet<u64>) -> String {
15102    let values = values
15103        .iter()
15104        .map(u64::to_string)
15105        .collect::<Vec<_>>()
15106        .join(", ");
15107    format!("({default} \\cup {{{values}}})")
15108}
15109
15110/// The model constant that a `CiValues` or `CiSamples` input field ranges
15111/// over in the generated model; each profile's config assigns it.
15112fn input_samples_constant_name(input: &str, field: &str) -> String {
15113    format!("InputSamples_{}_{}", tla_ident(input), tla_ident(field))
15114}
15115
15116/// The samples a `CiValues` input field keeps outside the CI profile (the
15117/// Deep profile and every composition): the declared values together with the
15118/// default unsigned domain (`0..2`).
15119fn broad_input_samples(ci_values: &BTreeSet<u64>) -> BTreeSet<u64> {
15120    (0..=2).chain(ci_values.iter().copied()).collect()
15121}
15122
15123fn render_u64_set(values: &BTreeSet<u64>) -> String {
15124    let values = values
15125        .iter()
15126        .map(u64::to_string)
15127        .collect::<Vec<_>>()
15128        .join(", ");
15129    format!("{{{values}}}")
15130}
15131
15132/// Every `CiValues` input field of a machine, in declaration order: the model
15133/// constant the field ranges over and the values the CI profile assigns it.
15134fn machine_input_sample_constants(schema: &MachineSchema) -> Vec<(String, &BTreeSet<u64>)> {
15135    schema
15136        .input_field_domains
15137        .iter()
15138        .filter_map(|declaration| match &declaration.domain {
15139            meerkat_machine_schema::InputFieldDomainKind::CiValues(values) => Some((
15140                input_samples_constant_name(declaration.input.as_str(), declaration.field.as_str()),
15141                values,
15142            )),
15143            meerkat_machine_schema::InputFieldDomainKind::AdditionalValues(_)
15144            | meerkat_machine_schema::InputFieldDomainKind::StateField(_)
15145            | meerkat_machine_schema::InputFieldDomainKind::CiSamples(_) => None,
15146        })
15147        .collect()
15148}
15149
15150/// Every `CiSamples` input field of a machine, in declaration order: the
15151/// model constant the field ranges over, the values the CI profile assigns
15152/// it, and the field's type, whose whole domain the Deep profile assigns it.
15153/// The schema's validation resolves every declared field.
15154fn machine_input_typed_sample_constants(
15155    schema: &MachineSchema,
15156) -> Vec<(String, &[meerkat_machine_schema::TlcValue], TypeRef)> {
15157    schema
15158        .input_field_domains
15159        .iter()
15160        .filter_map(|declaration| match &declaration.domain {
15161            meerkat_machine_schema::InputFieldDomainKind::CiSamples(samples) => {
15162                let field = schema
15163                    .inputs
15164                    .variant_named(declaration.input.as_str())
15165                    .ok()?
15166                    .fields
15167                    .iter()
15168                    .find(|field| field.name == declaration.field)?;
15169                Some((
15170                    input_samples_constant_name(
15171                        declaration.input.as_str(),
15172                        declaration.field.as_str(),
15173                    ),
15174                    samples.as_slice(),
15175                    field.ty.clone(),
15176                ))
15177            }
15178            meerkat_machine_schema::InputFieldDomainKind::AdditionalValues(_)
15179            | meerkat_machine_schema::InputFieldDomainKind::StateField(_)
15180            | meerkat_machine_schema::InputFieldDomainKind::CiValues(_) => None,
15181        })
15182        .collect()
15183}