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_enum_markdown(&mut out, "Signals", &schema.signals);
989    render_enum_markdown(&mut out, "Effects", &schema.effects);
990
991    if !schema.helpers.is_empty() {
992        pushln!(&mut out, "## Helpers");
993        for helper in &schema.helpers {
994            writeln!(
995                &mut out,
996                "- `{}`({}) -> `{}`",
997                helper.name,
998                render_field_list(&helper.params),
999                render_type_ref(&helper.returns)
1000            )
1001            .expect("write to string");
1002        }
1003        pushln!(&mut out);
1004    }
1005
1006    if !schema.derived.is_empty() {
1007        pushln!(&mut out, "## Derived");
1008        for derived in &schema.derived {
1009            writeln!(
1010                &mut out,
1011                "- `{}`({}) -> `{}`",
1012                derived.name,
1013                render_field_list(&derived.params),
1014                render_type_ref(&derived.returns)
1015            )
1016            .expect("write to string");
1017        }
1018        pushln!(&mut out);
1019    }
1020
1021    if !schema.command_plans.is_empty() {
1022        pushln!(&mut out, "## Command Plans");
1023        let transitions_by_name = schema
1024            .transitions
1025            .iter()
1026            .map(|transition| (transition.name.as_str(), transition))
1027            .collect::<BTreeMap<_, _>>();
1028        for plan in &schema.command_plans {
1029            pushln!(&mut out, "### `{}`", plan.name);
1030            pushln!(&mut out, "- Authority: `{}`", plan.authority_type);
1031            if !plan.source_inputs.is_empty() {
1032                writeln!(
1033                    &mut out,
1034                    "- Source Inputs: {}",
1035                    plan.source_inputs
1036                        .iter()
1037                        .map(|input| format!("`{input}`"))
1038                        .collect::<Vec<_>>()
1039                        .join(", ")
1040                )
1041                .expect("write to string");
1042            }
1043            if !plan.source_signals.is_empty() {
1044                writeln!(
1045                    &mut out,
1046                    "- Source Signals: {}",
1047                    plan.source_signals
1048                        .iter()
1049                        .map(|signal| format!("`{signal}`"))
1050                        .collect::<Vec<_>>()
1051                        .join(", ")
1052                )
1053                .expect("write to string");
1054            }
1055            if !plan.transitions.is_empty() {
1056                writeln!(
1057                    &mut out,
1058                    "- Transitions: {}",
1059                    plan.transitions
1060                        .iter()
1061                        .map(|transition| format!("`{transition}`"))
1062                        .collect::<Vec<_>>()
1063                        .join(", ")
1064                )
1065                .expect("write to string");
1066                pushln!(&mut out, "- Guard Expansion:");
1067                for transition_id in &plan.transitions {
1068                    if let Some(transition) = transitions_by_name.get(transition_id.as_str()) {
1069                        let guards = if transition.guards.is_empty() {
1070                            "`<none>`".to_owned()
1071                        } else {
1072                            transition
1073                                .guards
1074                                .iter()
1075                                .map(|guard| format!("`{}`", guard.name))
1076                                .collect::<Vec<_>>()
1077                                .join(", ")
1078                        };
1079                        pushln!(&mut out, "  - `{transition_id}`: {guards}");
1080                    }
1081                }
1082            }
1083            if !plan.effects.is_empty() {
1084                writeln!(
1085                    &mut out,
1086                    "- Command Effects: {}",
1087                    plan.effects
1088                        .iter()
1089                        .map(|effect| format!("`{effect}`"))
1090                        .collect::<Vec<_>>()
1091                        .join(", ")
1092                )
1093                .expect("write to string");
1094            }
1095            if !plan.effect_closures.is_empty() {
1096                pushln!(&mut out, "- Effect Closure:");
1097                for closure in &plan.effect_closures {
1098                    writeln!(
1099                        &mut out,
1100                        "  - `{}` via `{}` ({}) states: {}",
1101                        closure.effect,
1102                        closure.authority_type,
1103                        closure.closure_policy,
1104                        closure
1105                            .lifecycle
1106                            .iter()
1107                            .map(|state| format!("`{state}`"))
1108                            .collect::<Vec<_>>()
1109                            .join(", ")
1110                    )
1111                    .expect("write to string");
1112                }
1113            }
1114            let emitted_effects = plan
1115                .transitions
1116                .iter()
1117                .filter_map(|transition_id| transitions_by_name.get(transition_id.as_str()))
1118                .flat_map(|transition| transition.emit.iter().map(|effect| &effect.variant))
1119                .collect::<BTreeSet<_>>();
1120            if !emitted_effects.is_empty() {
1121                writeln!(
1122                    &mut out,
1123                    "- Emitted By Transitions: {}",
1124                    emitted_effects
1125                        .iter()
1126                        .map(|effect| format!("`{effect}`"))
1127                        .collect::<Vec<_>>()
1128                        .join(", ")
1129                )
1130                .expect("write to string");
1131            }
1132            pushln!(&mut out);
1133        }
1134    }
1135
1136    pushln!(&mut out, "## Invariants");
1137    for invariant in &schema.invariants {
1138        pushln!(&mut out, "- `{}`", invariant.name);
1139    }
1140    pushln!(&mut out);
1141
1142    pushln!(&mut out, "## Transitions");
1143    for transition in &schema.transitions {
1144        pushln!(&mut out, "### `{}`", transition.name);
1145        writeln!(
1146            &mut out,
1147            "- From: {}",
1148            transition
1149                .from
1150                .iter()
1151                .map(|item| format!("`{item}`"))
1152                .collect::<Vec<_>>()
1153                .join(", ")
1154        )
1155        .expect("write to string");
1156        writeln!(
1157            &mut out,
1158            "- On: `{}`({})",
1159            transition.on.variant_str(),
1160            transition
1161                .on
1162                .bindings()
1163                .iter()
1164                .map(meerkat_machine_schema::identity::FieldId::as_str)
1165                .collect::<Vec<_>>()
1166                .join(", ")
1167        )
1168        .expect("write to string");
1169        if !transition.guards.is_empty() {
1170            pushln!(&mut out, "- Guards:");
1171            for guard in &transition.guards {
1172                pushln!(&mut out, "  - `{}`", guard.name);
1173            }
1174        }
1175        if !transition.emit.is_empty() {
1176            writeln!(
1177                &mut out,
1178                "- Emits: {}",
1179                transition
1180                    .emit
1181                    .iter()
1182                    .map(|effect| format!("`{}`", effect.variant))
1183                    .collect::<Vec<_>>()
1184                    .join(", ")
1185            )
1186            .expect("write to string");
1187        }
1188        pushln!(&mut out, "- To: `{}`", transition.to);
1189        pushln!(&mut out);
1190    }
1191
1192    pushln!(&mut out, "## Coverage");
1193    pushln!(&mut out, "### Code Anchors");
1194    for anchor in &coverage.code_anchors {
1195        pushln!(
1196            &mut out,
1197            "{}",
1198            render_contract_coverage_anchor_bullet(anchor)
1199        );
1200    }
1201    pushln!(&mut out);
1202    pushln!(&mut out, "### Scenarios");
1203    for scenario in &coverage.scenarios {
1204        pushln!(&mut out, "- `{}` — {}", scenario.id, scenario.summary);
1205    }
1206
1207    out
1208}
1209
1210pub fn render_composition_contract_markdown(
1211    schema: &CompositionSchema,
1212    coverage: &CompositionCoverageManifest,
1213) -> String {
1214    let mut out = String::new();
1215
1216    pushln!(&mut out, "# {}", schema.name);
1217    pushln!(&mut out);
1218    writeln!(
1219        &mut out,
1220        "_Generated from the Rust composition catalog. Do not edit by hand._"
1221    )
1222    .expect("write to string");
1223    pushln!(&mut out);
1224
1225    pushln!(&mut out, "## Machines");
1226    for machine in &schema.machines {
1227        writeln!(
1228            &mut out,
1229            "- `{}`: `{}` @ actor `{}`",
1230            machine.instance_id, machine.machine_name, machine.actor
1231        )
1232        .expect("write to string");
1233    }
1234    pushln!(&mut out);
1235
1236    pushln!(&mut out, "## Routes");
1237    for route in &schema.routes {
1238        writeln!(
1239            &mut out,
1240            "- `{}`: `{}`.`{}` -> `{}`.`{}` [{}]",
1241            route.name,
1242            route.from_machine,
1243            route.effect_variant,
1244            route.to.machine,
1245            route.to.input_variant,
1246            render_route_delivery(route)
1247        )
1248        .expect("write to string");
1249    }
1250    pushln!(&mut out);
1251
1252    pushln!(&mut out, "## Target Selectors");
1253    if schema.route_target_selectors.is_empty() {
1254        pushln!(&mut out, "- `(none)`");
1255    } else {
1256        for selector in &schema.route_target_selectors {
1257            pushln!(
1258                &mut out,
1259                "- `{}` selects `{}` from `{:?}`",
1260                selector.route_name,
1261                selector.selector_field,
1262                selector.source
1263            );
1264        }
1265    }
1266    pushln!(&mut out);
1267
1268    pushln!(&mut out, "## Driver");
1269    if let Some(driver) = &schema.driver {
1270        pushln!(
1271            &mut out,
1272            "- `{}` (`{}` in `{}`)",
1273            driver.name,
1274            driver.rust.driver_type,
1275            driver.rust.module_path
1276        );
1277        if !driver.watched_effects.is_empty() {
1278            pushln!(&mut out, "  - watches:");
1279            for watched in &driver.watched_effects {
1280                pushln!(
1281                    &mut out,
1282                    "    - `{}::{}`",
1283                    watched.producer_instance,
1284                    watched.effect_variant
1285                );
1286            }
1287        }
1288        if !driver.dispatch_routes.is_empty() {
1289            pushln!(&mut out, "  - dispatches:");
1290            for dispatch in &driver.dispatch_routes {
1291                pushln!(
1292                    &mut out,
1293                    "    - `{}` → `{}::{}` ({:?})",
1294                    dispatch.name,
1295                    dispatch.target_instance,
1296                    dispatch.input_variant,
1297                    dispatch.target_kind
1298                );
1299            }
1300        }
1301        if !driver.refusal_closures.is_empty() {
1302            pushln!(&mut out, "  - consumer-refusal closures:");
1303            for closure in &driver.refusal_closures {
1304                pushln!(
1305                    &mut out,
1306                    "    - `{}` refusal → `{}::{}`",
1307                    closure.dispatch_route,
1308                    closure.feedback_instance,
1309                    closure.feedback_input
1310                );
1311            }
1312        }
1313    } else {
1314        pushln!(&mut out, "- `(none)`");
1315    }
1316    pushln!(&mut out);
1317
1318    pushln!(&mut out, "## Transaction Plans");
1319    if schema.transaction_plans.is_empty() {
1320        pushln!(&mut out, "- `(none)`");
1321    } else {
1322        for plan in &schema.transaction_plans {
1323            pushln!(
1324                &mut out,
1325                "- `{}` via `{}` / `{}` — {}",
1326                plan.name,
1327                plan.trigger,
1328                plan.store_primitive,
1329                plan.description
1330            );
1331        }
1332    }
1333    pushln!(&mut out);
1334
1335    pushln!(&mut out, "## Scheduler Rules");
1336    if schema.scheduler_rules.is_empty() {
1337        pushln!(&mut out, "- `(none)`");
1338    } else {
1339        for rule in &schema.scheduler_rules {
1340            pushln!(&mut out, "- `{}`", render_scheduler_rule(rule));
1341        }
1342    }
1343    pushln!(&mut out);
1344
1345    let structural_invariants = schema
1346        .invariants
1347        .iter()
1348        .filter(|invariant| invariant.kind.is_structural())
1349        .collect::<Vec<_>>();
1350    let behavioral_invariants = schema
1351        .invariants
1352        .iter()
1353        .filter(|invariant| invariant.kind.is_behavioral())
1354        .collect::<Vec<_>>();
1355
1356    pushln!(&mut out, "## Structural Requirements");
1357    if structural_invariants.is_empty() {
1358        pushln!(&mut out, "- `(none)`");
1359    } else {
1360        for invariant in &structural_invariants {
1361            pushln!(&mut out, "- `{}` — {}", invariant.name, invariant.statement);
1362        }
1363    }
1364    pushln!(&mut out);
1365
1366    writeln!(&mut out, "## Behavioral Invariants");
1367    if behavioral_invariants.is_empty() {
1368        pushln!(&mut out, "- `(none)`");
1369    } else {
1370        for invariant in &behavioral_invariants {
1371            pushln!(&mut out, "- `{}` — {}", invariant.name, invariant.statement);
1372        }
1373    }
1374    pushln!(&mut out);
1375
1376    writeln!(&mut out, "## Coverage");
1377    pushln!(&mut out, "### Code Anchors");
1378    for anchor in &coverage.code_anchors {
1379        pushln!(
1380            &mut out,
1381            "{}",
1382            render_contract_coverage_anchor_bullet(anchor)
1383        );
1384    }
1385    pushln!(&mut out);
1386    pushln!(&mut out, "### Scenarios");
1387    for scenario in &coverage.scenarios {
1388        pushln!(&mut out, "- `{}` — {}", scenario.id, scenario.summary);
1389    }
1390
1391    out
1392}
1393
1394pub fn render_machine_ci_cfg(
1395    schema: &MachineSchema,
1396    deep: bool,
1397) -> Result<String, CompositionTlaError> {
1398    if schema.tlc_model.is_some() {
1399        validate_machine_model(schema)?;
1400    }
1401    let mut out = String::new();
1402    let domains = collect_binding_domains(schema);
1403    let named_samples = collect_machine_named_type_samples(schema);
1404    let deep_named_samples = with_guard_binding_string_samples(&named_samples, schema);
1405    // The native SessionId/String bridge deliberately substitutes its sample
1406    // into a fixed-size Deep string pool; keep that bound for bridge machines.
1407    let deep_guard_string_samples = deep && !machine_uses_session_id_string_bridge(schema);
1408    let named_bindings = collect_machine_named_bindings(schema);
1409    let sample_cardinality = machine_cfg_sample_cardinality(schema, deep);
1410    let operator_suffix = if deep { "Deep" } else { "Ci" };
1411    let uses_u64_max = machine_uses_u64_max(schema);
1412    let session_id_cardinality = if deep {
1413        schema
1414            .deep_domain_overrides
1415            .get("SessionIdValues")
1416            .copied()
1417            .unwrap_or(sample_cardinality)
1418    } else {
1419        sample_cardinality
1420    };
1421    let session_id_string_bridge_sample = session_id_string_bridge_sample(
1422        deep && machine_uses_session_id_string_bridge(schema),
1423        &domains,
1424        session_id_cardinality,
1425        &named_samples,
1426        &named_bindings,
1427    );
1428    let input_samples = machine_input_sample_constants(schema);
1429
1430    pushln!(&mut out, "SPECIFICATION Spec");
1431    if !domains.is_empty() || uses_u64_max || !input_samples.is_empty() {
1432        pushln!(&mut out, "CONSTANTS");
1433        if uses_u64_max {
1434            push_u64_max_cfg_assignment(&mut out);
1435        }
1436        for (name, ty) in domains {
1437            if matches!(
1438                ty,
1439                TypeRef::Seq(_) | TypeRef::Option(_) | TypeRef::Map(_, _)
1440            ) {
1441                continue;
1442            }
1443            if machine_explicit_values(schema, deep, &ty).is_some()
1444                || cfg_assignment_requires_model_operator(&ty, &named_bindings)
1445            {
1446                writeln!(
1447                    &mut out,
1448                    "  {} <- {}",
1449                    name,
1450                    cfg_assignment_operator_name(&name, operator_suffix),
1451                )
1452                .expect("write to string");
1453            } else {
1454                // Deep-profile per-domain override (machine analog of the
1455                // composition path): absent keys use the profile default.
1456                let domain_cardinality = if deep {
1457                    schema
1458                        .deep_domain_overrides
1459                        .get(name.as_str())
1460                        .copied()
1461                        .unwrap_or(sample_cardinality)
1462                } else {
1463                    sample_cardinality
1464                };
1465                writeln!(
1466                    &mut out,
1467                    "  {} = {}",
1468                    name,
1469                    render_cfg_domain_assignment(
1470                        &ty,
1471                        domain_cardinality,
1472                        if deep_guard_string_samples {
1473                            &deep_named_samples
1474                        } else {
1475                            &named_samples
1476                        },
1477                        &named_bindings,
1478                        deep_guard_string_samples,
1479                        session_id_string_bridge_sample.as_deref(),
1480                    )
1481                )
1482                .expect("write to string");
1483            }
1484        }
1485        // A `CiValues` input field: the CI profile explores exactly its
1486        // declared values, the Deep profile those and the default `0..2`.
1487        for (constant, ci_values) in &input_samples {
1488            let values: BTreeSet<u64> = if deep {
1489                broad_input_samples(ci_values)
1490            } else {
1491                ci_values.iter().copied().collect()
1492            };
1493            writeln!(&mut out, "  {} = {}", constant, render_u64_set(&values))
1494                .expect("write to string");
1495        }
1496    }
1497    if !schema.invariants.is_empty() {
1498        pushln!(&mut out, "INVARIANTS");
1499        for invariant in &schema.invariants {
1500            pushln!(&mut out, "  {}", invariant.name);
1501        }
1502    }
1503    pushln!(&mut out, "CONSTRAINTS");
1504    writeln!(
1505        &mut out,
1506        "  {}",
1507        if deep {
1508            "DeepStateConstraint"
1509        } else {
1510            "CiStateConstraint"
1511        }
1512    )
1513    .expect("write to string");
1514
1515    Ok(out)
1516}
1517
1518pub fn render_composition_ci_cfg(schema: &CompositionSchema, deep: bool) -> String {
1519    render_composition_ci_cfg_from_catalog(schema, deep, &canonical_machine_schemas())
1520}
1521
1522/// [`render_composition_ci_cfg`] against an explicitly supplied machine
1523/// catalog, for compositions whose machines live outside Meerkat's catalog.
1524pub fn render_composition_ci_cfg_with_catalog(
1525    schema: &CompositionSchema,
1526    deep: bool,
1527    machine_catalog: &[MachineSchema],
1528) -> std::result::Result<String, CompositionTlaError> {
1529    validate_supplied_catalog(schema, machine_catalog)?;
1530    Ok(render_composition_ci_cfg_from_catalog(
1531        schema,
1532        deep,
1533        machine_catalog,
1534    ))
1535}
1536
1537fn render_composition_ci_cfg_from_catalog(
1538    schema: &CompositionSchema,
1539    deep: bool,
1540    machine_catalog: &[MachineSchema],
1541) -> String {
1542    let mut out = String::new();
1543    let machine_by_name = machine_catalog
1544        .iter()
1545        .map(|machine| (machine.machine.as_str(), machine))
1546        .collect::<BTreeMap<_, _>>();
1547    let machine_by_instance = schema
1548        .machines
1549        .iter()
1550        .filter_map(|instance| {
1551            machine_by_name
1552                .get(instance.machine_name.as_str())
1553                .copied()
1554                .map(|machine| (instance.instance_id.as_str(), machine))
1555        })
1556        .collect::<BTreeMap<_, _>>();
1557    let domains = collect_composition_binding_domains(schema, &machine_by_instance);
1558    let named_samples = collect_composition_named_type_samples(schema, &machine_by_instance);
1559    let named_bindings = collect_composition_named_bindings(machine_by_instance.values().copied());
1560    let operator_suffix = if deep { "Deep" } else { "Ci" };
1561    let mut instance_invariants = Vec::new();
1562    let mut obligation_invariants = Vec::new();
1563    let uses_u64_max = composition_uses_u64_max(schema, &machine_by_instance);
1564    let session_id_cardinality = if deep {
1565        schema
1566            .deep_domain_overrides
1567            .get("SessionIdValues")
1568            .copied()
1569            .unwrap_or(schema.deep_domain_cardinality)
1570    } else {
1571        default_sample_cardinality(false)
1572    };
1573    let session_id_string_bridge_sample = session_id_string_bridge_sample(
1574        deep && composition_uses_session_id_string_bridge(&machine_by_instance),
1575        &domains,
1576        session_id_cardinality,
1577        &named_samples,
1578        &named_bindings,
1579    );
1580
1581    for instance in &schema.machines {
1582        let Some(machine) = machine_by_instance
1583            .get(instance.instance_id.as_str())
1584            .copied()
1585        else {
1586            continue;
1587        };
1588        for invariant in &machine.invariants {
1589            instance_invariants.push(format!(
1590                "{}_{}",
1591                tla_ident(&instance.instance_id),
1592                tla_ident(&invariant.name)
1593            ));
1594        }
1595    }
1596    for protocol in &schema.handoff_protocols {
1597        let suffix = format!(
1598            "{}_{}",
1599            tla_ident(&protocol.producer_instance),
1600            tla_ident(&protocol.name)
1601        );
1602        if machine_by_instance
1603            .get(protocol.producer_instance.as_str())
1604            .is_some_and(|machine| terminal_closure_required(protocol, machine))
1605        {
1606            obligation_invariants.push(format!("NoOpenObligationsOnTerminal_{suffix}"));
1607        }
1608    }
1609    if schema
1610        .handoff_protocols
1611        .iter()
1612        .any(|protocol| !protocol.allowed_feedback_inputs.is_empty())
1613    {
1614        obligation_invariants.push("OwnerFeedbackHasProtocolProvenance".to_string());
1615    }
1616    pushln!(&mut out, "SPECIFICATION Spec");
1617    if !domains.is_empty() || uses_u64_max {
1618        pushln!(&mut out, "CONSTANTS");
1619        if uses_u64_max {
1620            push_u64_max_cfg_assignment(&mut out);
1621        }
1622        for (name, ty) in domains {
1623            if matches!(
1624                ty,
1625                TypeRef::Seq(_) | TypeRef::Option(_) | TypeRef::Map(_, _)
1626            ) {
1627                continue;
1628            }
1629            let cardinality = if deep {
1630                schema
1631                    .deep_domain_overrides
1632                    .get(name.as_str())
1633                    .copied()
1634                    .unwrap_or(schema.deep_domain_cardinality)
1635            } else {
1636                default_sample_cardinality(false)
1637            };
1638            if cfg_assignment_requires_model_operator(&ty, &named_bindings) {
1639                writeln!(
1640                    &mut out,
1641                    "  {} <- {}",
1642                    name,
1643                    cfg_assignment_operator_name(&name, operator_suffix),
1644                )
1645                .expect("write to string");
1646            } else {
1647                writeln!(
1648                    &mut out,
1649                    "  {} = {}",
1650                    name,
1651                    render_cfg_domain_assignment(
1652                        &ty,
1653                        cardinality,
1654                        &named_samples,
1655                        &named_bindings,
1656                        false,
1657                        session_id_string_bridge_sample.as_deref(),
1658                    )
1659                )
1660                .expect("write to string");
1661            }
1662        }
1663    }
1664    let behavioral_invariants = schema
1665        .invariants
1666        .iter()
1667        .filter(|invariant| invariant.kind.is_behavioral())
1668        .collect::<Vec<_>>();
1669    // Structural requirements (route/scheduler/priority presence, etc.) are
1670    // static, cheap-to-check predicates over the generated topology. They were
1671    // previously only validated in the Deep witness lane; emit them into the
1672    // standard INVARIANTS block unconditionally so the default (Ci) verify
1673    // profile fails closed on a missing structural requirement instead of
1674    // deferring the check to a Deep-only run.
1675    let structural_invariants = schema
1676        .invariants
1677        .iter()
1678        .filter(|invariant| invariant.kind.is_structural())
1679        .collect::<Vec<_>>();
1680    if !behavioral_invariants.is_empty()
1681        || !structural_invariants.is_empty()
1682        || !instance_invariants.is_empty()
1683        || !obligation_invariants.is_empty()
1684        || deep
1685    {
1686        pushln!(&mut out, "INVARIANTS");
1687        for invariant in behavioral_invariants {
1688            pushln!(&mut out, "  {}", invariant.name);
1689        }
1690        for invariant in structural_invariants {
1691            pushln!(&mut out, "  {}", invariant.name);
1692        }
1693        for invariant_name in instance_invariants {
1694            pushln!(&mut out, "  {}", invariant_name);
1695        }
1696        for invariant_name in obligation_invariants {
1697            pushln!(&mut out, "  {}", invariant_name);
1698        }
1699        if deep {
1700            pushln!(&mut out, "  CoverageInstrumentation");
1701        }
1702    }
1703    pushln!(&mut out, "CONSTRAINTS");
1704    writeln!(
1705        &mut out,
1706        "  {}",
1707        if deep {
1708            "DeepStateConstraint"
1709        } else {
1710            "CiStateConstraint"
1711        }
1712    )
1713    .expect("write to string");
1714
1715    out
1716}
1717
1718pub fn render_composition_witness_cfg(
1719    schema: &CompositionSchema,
1720    witness: &CompositionWitness,
1721) -> String {
1722    render_composition_witness_cfg_from_catalog(schema, witness, &canonical_machine_schemas())
1723}
1724
1725/// [`render_composition_witness_cfg`] against an explicitly supplied machine
1726/// catalog, for compositions whose machines live outside Meerkat's catalog.
1727pub fn render_composition_witness_cfg_with_catalog(
1728    schema: &CompositionSchema,
1729    witness: &CompositionWitness,
1730    machine_catalog: &[MachineSchema],
1731) -> std::result::Result<String, CompositionTlaError> {
1732    validate_supplied_catalog(schema, machine_catalog)?;
1733    Ok(render_composition_witness_cfg_from_catalog(
1734        schema,
1735        witness,
1736        machine_catalog,
1737    ))
1738}
1739
1740fn render_composition_witness_cfg_from_catalog(
1741    schema: &CompositionSchema,
1742    witness: &CompositionWitness,
1743    machine_catalog: &[MachineSchema],
1744) -> String {
1745    let mut out = String::new();
1746    let machine_by_name = machine_catalog
1747        .iter()
1748        .map(|machine| (machine.machine.as_str(), machine))
1749        .collect::<BTreeMap<_, _>>();
1750    let machine_by_instance = schema
1751        .machines
1752        .iter()
1753        .filter_map(|instance| {
1754            machine_by_name
1755                .get(instance.machine_name.as_str())
1756                .copied()
1757                .map(|machine| (instance.instance_id.as_str(), machine))
1758        })
1759        .collect::<BTreeMap<_, _>>();
1760    let domains = collect_composition_binding_domains(schema, &machine_by_instance);
1761    let named_samples =
1762        collect_composition_witness_named_type_samples(schema, witness, &machine_by_instance);
1763    let named_bindings = collect_composition_named_bindings(machine_by_instance.values().copied());
1764    let witness_sample_cardinality = schema
1765        .witness_domain_cardinality
1766        .max(max_named_sample_cardinality(&named_samples));
1767    let operator_suffix = witness_cfg_operator_suffix(witness);
1768    let mut instance_invariants = Vec::new();
1769    let mut obligation_invariants = Vec::new();
1770    let uses_u64_max = composition_uses_u64_max(schema, &machine_by_instance);
1771
1772    for instance in &schema.machines {
1773        let Some(machine) = machine_by_instance
1774            .get(instance.instance_id.as_str())
1775            .copied()
1776        else {
1777            continue;
1778        };
1779        for invariant in &machine.invariants {
1780            instance_invariants.push(format!(
1781                "{}_{}",
1782                tla_ident(&instance.instance_id),
1783                tla_ident(&invariant.name)
1784            ));
1785        }
1786    }
1787    for protocol in &schema.handoff_protocols {
1788        let suffix = format!(
1789            "{}_{}",
1790            tla_ident(&protocol.producer_instance),
1791            tla_ident(&protocol.name)
1792        );
1793        if machine_by_instance
1794            .get(protocol.producer_instance.as_str())
1795            .is_some_and(|machine| terminal_closure_required(protocol, machine))
1796        {
1797            obligation_invariants.push(format!("NoOpenObligationsOnTerminal_{suffix}"));
1798        }
1799    }
1800    if schema
1801        .handoff_protocols
1802        .iter()
1803        .any(|protocol| !protocol.allowed_feedback_inputs.is_empty())
1804    {
1805        obligation_invariants.push("OwnerFeedbackHasProtocolProvenance".to_string());
1806    }
1807
1808    writeln!(
1809        &mut out,
1810        "SPECIFICATION {}",
1811        composition_witness_spec_name(&witness.name)
1812    )
1813    .expect("write to string");
1814    if !domains.is_empty() || uses_u64_max {
1815        pushln!(&mut out, "CONSTANTS");
1816        if uses_u64_max {
1817            push_u64_max_cfg_assignment(&mut out);
1818        }
1819        for (name, ty) in domains {
1820            if matches!(
1821                ty,
1822                TypeRef::Seq(_) | TypeRef::Option(_) | TypeRef::Map(_, _)
1823            ) {
1824                continue;
1825            }
1826            if cfg_assignment_requires_model_operator(&ty, &named_bindings) {
1827                writeln!(
1828                    &mut out,
1829                    "  {} <- {}",
1830                    name,
1831                    cfg_assignment_operator_name(&name, &operator_suffix),
1832                )
1833                .expect("write to string");
1834            } else {
1835                writeln!(
1836                    &mut out,
1837                    "  {} = {}",
1838                    name,
1839                    render_default_domain_assignment(
1840                        &ty,
1841                        witness_sample_cardinality,
1842                        &named_samples,
1843                        &named_bindings,
1844                        true,
1845                    )
1846                )
1847                .expect("write to string");
1848            }
1849        }
1850    }
1851    let witness_properties = witness
1852        .expected_routes
1853        .iter()
1854        .map(|route| composition_witness_route_property_name(&witness.name, route))
1855        .chain(
1856            witness
1857                .expected_scheduler_rules
1858                .iter()
1859                .map(|rule| composition_witness_scheduler_property_name(&witness.name, rule)),
1860        )
1861        .chain(
1862            witness
1863                .expected_states
1864                .iter()
1865                .enumerate()
1866                .map(|(idx, _)| composition_witness_state_property_name(&witness.name, idx)),
1867        )
1868        .chain(witness.expected_transitions.iter().map(|transition| {
1869            composition_witness_transition_property_name(
1870                &witness.name,
1871                &transition.machine,
1872                &transition.transition,
1873            )
1874        }))
1875        .chain(
1876            witness
1877                .expected_transition_order
1878                .iter()
1879                .enumerate()
1880                .map(|(idx, _)| {
1881                    composition_witness_transition_order_property_name(&witness.name, idx)
1882                }),
1883        )
1884        .collect::<Vec<_>>();
1885    let explicit_witness = CompositionTlaCompiler::witness_has_explicit_progress(witness);
1886    if !schema.invariants.is_empty()
1887        || !instance_invariants.is_empty()
1888        || !obligation_invariants.is_empty()
1889        || (explicit_witness && !witness_properties.is_empty())
1890    {
1891        pushln!(&mut out, "INVARIANTS");
1892        for invariant in &schema.invariants {
1893            pushln!(&mut out, "  {}", invariant.name);
1894        }
1895        for invariant_name in instance_invariants {
1896            pushln!(&mut out, "  {}", invariant_name);
1897        }
1898        for invariant_name in obligation_invariants {
1899            pushln!(&mut out, "  {}", invariant_name);
1900        }
1901        pushln!(&mut out, "  CoverageInstrumentation");
1902        if explicit_witness {
1903            for property in &witness_properties {
1904                pushln!(&mut out, "  {property}");
1905            }
1906        }
1907    }
1908    if !explicit_witness && !witness_properties.is_empty() {
1909        pushln!(&mut out, "PROPERTIES");
1910        for property in witness_properties {
1911            pushln!(&mut out, "  {property}");
1912        }
1913    }
1914    if explicit_witness {
1915        pushln!(&mut out, "ACTION_CONSTRAINTS");
1916        pushln!(
1917            &mut out,
1918            "  {}",
1919            composition_witness_action_constraint_name(&witness.name)
1920        );
1921    }
1922    pushln!(&mut out, "CONSTRAINTS");
1923    writeln!(
1924        &mut out,
1925        "  {}",
1926        composition_witness_state_constraint_name(&witness.name)
1927    )
1928    .expect("write to string");
1929
1930    out
1931}
1932
1933pub fn composition_route_observed_operator_name(route_name: impl AsRef<str>) -> String {
1934    format!("RouteObserved_{}", tla_ident(route_name))
1935}
1936
1937pub fn composition_route_coverage_operator_name(route_name: impl AsRef<str>) -> String {
1938    format!("RouteCoverage_{}", tla_ident(route_name))
1939}
1940
1941pub fn composition_scheduler_triggered_operator_name(rule: &SchedulerRule) -> String {
1942    match rule {
1943        SchedulerRule::PreemptWhenReady { higher, lower } => format!(
1944            "SchedulerTriggered_PreemptWhenReady_{}_{}",
1945            tla_ident(higher),
1946            tla_ident(lower)
1947        ),
1948    }
1949}
1950
1951pub fn composition_scheduler_coverage_operator_name(rule: &SchedulerRule) -> String {
1952    match rule {
1953        SchedulerRule::PreemptWhenReady { higher, lower } => format!(
1954            "SchedulerCoverage_PreemptWhenReady_{}_{}",
1955            tla_ident(higher),
1956            tla_ident(lower)
1957        ),
1958    }
1959}
1960
1961fn max_named_sample_cardinality(named_samples: &BTreeMap<String, BTreeSet<String>>) -> usize {
1962    named_samples.values().map(BTreeSet::len).max().unwrap_or(1)
1963}
1964
1965struct CfgAssignmentOperatorProfile<'a> {
1966    suffix: String,
1967    explicit_values: Option<&'a meerkat_machine_schema::MachineTlcProfile>,
1968    sample_cardinality: usize,
1969    domain_overrides: Option<&'a BTreeMap<String, usize>>,
1970    named_samples: &'a BTreeMap<String, BTreeSet<String>>,
1971    include_string_samples: bool,
1972}
1973
1974fn cfg_assignment_operator_name(domain_name: &str, suffix: impl AsRef<str>) -> String {
1975    format!("{}{}", tla_ident(domain_name), tla_ident(suffix))
1976}
1977
1978fn push_u64_max_cfg_assignment(out: &mut String) {
1979    pushln!(
1980        out,
1981        "  \\* Rust u64::MAX, supplied as a finite TLC model-checking value."
1982    );
1983    writeln!(
1984        out,
1985        "  {} = {}",
1986        TLA_RUST_U64_MAX_CONSTANT, TLC_SAFE_RUST_U64_MAX_VALUE
1987    )
1988    .expect("write to string");
1989}
1990
1991fn witness_cfg_operator_suffix(witness: &CompositionWitness) -> String {
1992    format!("Witness{}", tla_ident(&witness.name))
1993}
1994
1995fn profile_sample_cardinality(
1996    profile: &CfgAssignmentOperatorProfile<'_>,
1997    domain_name: &str,
1998) -> usize {
1999    profile
2000        .domain_overrides
2001        .and_then(|overrides| overrides.get(domain_name).copied())
2002        .unwrap_or(profile.sample_cardinality)
2003}
2004
2005fn profile_sample_cardinality_for_domain(
2006    profile: &CfgAssignmentOperatorProfile<'_>,
2007    domain_name: &str,
2008    ty: &TypeRef,
2009    named_bindings: &BTreeMap<String, meerkat_machine_schema::RustTypeAtom>,
2010) -> usize {
2011    let sample_cardinality = profile_sample_cardinality(profile, domain_name);
2012    if profile.suffix == "Ci" && cfg_assignment_requires_model_operator(ty, named_bindings) {
2013        return 0;
2014    }
2015
2016    sample_cardinality
2017}
2018
2019fn machine_cfg_sample_cardinality(schema: &MachineSchema, deep: bool) -> usize {
2020    if !deep && schema.ci_step_limit == Some(1) {
2021        0
2022    } else {
2023        default_sample_cardinality(deep)
2024    }
2025}
2026
2027fn session_id_string_bridge_sample(
2028    enabled: bool,
2029    domains: &BTreeMap<String, TypeRef>,
2030    session_id_cardinality: usize,
2031    named_samples: &BTreeMap<String, BTreeSet<String>>,
2032    named_bindings: &BTreeMap<String, meerkat_machine_schema::RustTypeAtom>,
2033) -> Option<String> {
2034    if !enabled {
2035        return None;
2036    }
2037
2038    assert!(
2039        matches!(
2040            domains.get("SessionIdValues"),
2041            Some(TypeRef::Named(name)) if name.as_str() == "SessionId"
2042        ) && matches!(domains.get("StringValues"), Some(TypeRef::String)),
2043        "the SessionId/String native bridge requires both model domains"
2044    );
2045
2046    let sample = sample_values_for_named_type(
2047        "SessionId",
2048        session_id_cardinality.max(1),
2049        named_samples,
2050        named_bindings,
2051    )
2052    .into_iter()
2053    .next();
2054    assert!(
2055        sample.is_some(),
2056        "the SessionId/String native bridge requires a SessionId sample"
2057    );
2058    sample
2059}
2060
2061fn render_cfg_domain_assignment(
2062    ty: &TypeRef,
2063    sample_cardinality: usize,
2064    named_samples: &BTreeMap<String, BTreeSet<String>>,
2065    named_bindings: &BTreeMap<String, meerkat_machine_schema::RustTypeAtom>,
2066    include_string_samples: bool,
2067    session_id_string_bridge_sample: Option<&str>,
2068) -> String {
2069    let bridge_applies_to_session_id = matches!(
2070        ty,
2071        TypeRef::Named(name) if name.as_str() == "SessionId"
2072    );
2073    let effective_cardinality = if session_id_string_bridge_sample.is_some()
2074        && (matches!(ty, TypeRef::String) || bridge_applies_to_session_id)
2075    {
2076        sample_cardinality.max(1)
2077    } else {
2078        sample_cardinality
2079    };
2080
2081    if let (TypeRef::String, Some(bridge_sample)) = (ty, session_id_string_bridge_sample) {
2082        let mut samples =
2083            collected_string_samples(effective_cardinality, named_samples, include_string_samples)
2084                .into_iter()
2085                .map(|sample| tla_string(&sample))
2086                .collect::<Vec<_>>();
2087        let baseline_sample_count = samples.len();
2088        samples.retain(|sample| sample != bridge_sample);
2089        samples.insert(0, bridge_sample.to_owned());
2090        // Deep transition coverage makes the equality branch a non-vacuity
2091        // gate. Substitute the shared SessionId value into StringValues rather
2092        // than growing the renderer's actual baseline pool (which can be
2093        // smaller than a configured cardinality) and multiplying the explored
2094        // state space.
2095        if !include_string_samples {
2096            samples.truncate(baseline_sample_count);
2097        }
2098        return format!("{{{}}}", samples.join(", "));
2099    }
2100
2101    render_default_domain_assignment(
2102        ty,
2103        effective_cardinality,
2104        named_samples,
2105        named_bindings,
2106        include_string_samples,
2107    )
2108}
2109
2110fn push_cfg_assignment_operator_definitions(
2111    out: &mut String,
2112    domains: &BTreeMap<String, TypeRef>,
2113    named_bindings: &BTreeMap<String, meerkat_machine_schema::RustTypeAtom>,
2114    profile: &CfgAssignmentOperatorProfile<'_>,
2115) -> bool {
2116    let mut wrote = false;
2117    for (name, ty) in domains {
2118        let explicit = profile
2119            .explicit_values
2120            .and_then(|values| profile_explicit_values(values, ty));
2121        if cfg_domain_is_skipped_in_cfg(ty)
2122            || (explicit.is_none() && !cfg_assignment_requires_model_operator(ty, named_bindings))
2123        {
2124            continue;
2125        }
2126        let sample_cardinality =
2127            profile_sample_cardinality_for_domain(profile, name, ty, named_bindings);
2128        let assignment = explicit.map(render_explicit_values).unwrap_or_else(|| {
2129            render_default_domain_assignment(
2130                ty,
2131                sample_cardinality,
2132                profile.named_samples,
2133                named_bindings,
2134                profile.include_string_samples,
2135            )
2136        });
2137        writeln!(
2138            out,
2139            "{} == {}",
2140            cfg_assignment_operator_name(name, &profile.suffix),
2141            assignment
2142        )
2143        .expect("write to string");
2144        wrote = true;
2145    }
2146    if wrote {
2147        pushln!(out);
2148    }
2149    wrote
2150}
2151
2152fn validate_machine_model(schema: &MachineSchema) -> Result<(), CompositionTlaError> {
2153    let invalid = |reason| CompositionTlaError::InvalidTlcModel {
2154        machine: schema.machine.to_string(),
2155        reason,
2156    };
2157    schema
2158        .validate()
2159        .map_err(|error| invalid(error.to_string()))?;
2160    if let Some(model) = &schema.tlc_model {
2161        let domains = collect_binding_domains(schema);
2162        for profile in [&model.ci, &model.deep] {
2163            for name in profile.named_values.keys() {
2164                if !domains.values().any(|ty| match ty {
2165                    TypeRef::Named(id) => id == name,
2166                    TypeRef::Enum(id) => id.as_str() == name.as_str(),
2167                    _ => false,
2168                }) {
2169                    return Err(invalid(format!(
2170                        "explicit sample type {name} has no standalone model domain"
2171                    )));
2172                }
2173            }
2174        }
2175    }
2176    Ok(())
2177}
2178
2179fn profile_explicit_values<'a>(
2180    profile: &'a meerkat_machine_schema::MachineTlcProfile,
2181    ty: &TypeRef,
2182) -> Option<&'a [meerkat_machine_schema::TlcValue]> {
2183    let name = match ty {
2184        TypeRef::Named(name) => name.as_str(),
2185        TypeRef::Enum(name) => name.as_str(),
2186        _ => return None,
2187    };
2188    profile
2189        .named_values
2190        .iter()
2191        .find(|(id, _)| id.as_str() == name)
2192        .map(|(_, values)| values.as_slice())
2193}
2194
2195fn machine_explicit_values<'a>(
2196    schema: &'a MachineSchema,
2197    deep: bool,
2198    ty: &TypeRef,
2199) -> Option<&'a [meerkat_machine_schema::TlcValue]> {
2200    let model = schema.tlc_model.as_ref()?;
2201    profile_explicit_values(if deep { &model.deep } else { &model.ci }, ty)
2202}
2203
2204fn render_explicit_values(values: &[meerkat_machine_schema::TlcValue]) -> String {
2205    format!(
2206        "{{{}}}",
2207        values
2208            .iter()
2209            .map(render_explicit_value)
2210            .collect::<Vec<_>>()
2211            .join(", ")
2212    )
2213}
2214
2215fn render_explicit_value(value: &meerkat_machine_schema::TlcValue) -> String {
2216    use meerkat_machine_schema::TlcValue;
2217    match value {
2218        TlcValue::Bool(value) => if *value { "TRUE" } else { "FALSE" }.into(),
2219        TlcValue::U64(value) if *value == u64::MAX => TLA_RUST_U64_MAX_CONSTANT.to_owned(),
2220        TlcValue::U64(value) => value.to_string(),
2221        TlcValue::String(value) => tla_string(value),
2222        TlcValue::None => "None".into(),
2223        TlcValue::Some(value) => format!("Some({})", render_explicit_value(value)),
2224        TlcValue::Set(values) => render_explicit_values(values),
2225        TlcValue::Record(fields) => format!(
2226            "[{}]",
2227            fields
2228                .iter()
2229                .map(|(field, value)| format!(
2230                    "{} |-> {}",
2231                    tla_ident(field.as_str()),
2232                    render_explicit_value(value)
2233                ))
2234                .collect::<Vec<_>>()
2235                .join(", ")
2236        ),
2237    }
2238}
2239
2240fn cfg_domain_is_skipped_in_cfg(ty: &TypeRef) -> bool {
2241    matches!(
2242        ty,
2243        TypeRef::Seq(_) | TypeRef::Option(_) | TypeRef::Map(_, _)
2244    )
2245}
2246
2247fn cfg_assignment_requires_model_operator(
2248    ty: &TypeRef,
2249    named_bindings: &BTreeMap<String, meerkat_machine_schema::RustTypeAtom>,
2250) -> bool {
2251    match ty {
2252        TypeRef::Named(name) => {
2253            require_named_binding(named_bindings, name.as_str()).renders_cfg_hostile_record()
2254        }
2255        TypeRef::Enum(name) => {
2256            require_named_binding(named_bindings, name.as_str()).renders_cfg_hostile_record()
2257        }
2258        TypeRef::Set(inner) | TypeRef::Seq(inner) => {
2259            cfg_assignment_requires_model_operator(inner, named_bindings)
2260        }
2261        TypeRef::Option(_) | TypeRef::Map(_, _) => true,
2262        TypeRef::Bool | TypeRef::U32 | TypeRef::U64 | TypeRef::String => false,
2263    }
2264}
2265
2266trait CfgRecordRendering {
2267    fn renders_cfg_hostile_record(&self) -> bool;
2268}
2269
2270impl CfgRecordRendering for meerkat_machine_schema::RustTypeAtom {
2271    fn renders_cfg_hostile_record(&self) -> bool {
2272        match self {
2273            meerkat_machine_schema::RustTypeAtom::TypePathStruct { .. } => true,
2274            meerkat_machine_schema::RustTypeAtom::TypePathEnum {
2275                structural_variants,
2276                ..
2277            } => !structural_variants.is_empty(),
2278            _ => false,
2279        }
2280    }
2281}
2282
2283pub fn composition_witness_cfg_name(name: impl AsRef<str>) -> String {
2284    format!("witness-{}.cfg", tla_ident(name.as_ref()))
2285}
2286
2287fn composition_witness_route_property_name(
2288    witness: impl AsRef<str>,
2289    route_name: impl AsRef<str>,
2290) -> String {
2291    format!(
2292        "WitnessRouteObserved_{}_{}",
2293        tla_ident(witness.as_ref()),
2294        tla_ident(route_name)
2295    )
2296}
2297
2298fn composition_witness_scheduler_property_name(
2299    witness: impl AsRef<str>,
2300    rule: &SchedulerRule,
2301) -> String {
2302    format!(
2303        "WitnessSchedulerTriggered_{}_{}",
2304        tla_ident(witness.as_ref()),
2305        tla_ident(witness_scheduler_rule_label(rule))
2306    )
2307}
2308
2309fn composition_witness_state_property_name(witness: impl AsRef<str>, index: usize) -> String {
2310    format!(
2311        "WitnessStateObserved_{}_{}",
2312        tla_ident(witness.as_ref()),
2313        index + 1
2314    )
2315}
2316
2317fn composition_witness_transition_property_name(
2318    witness: impl AsRef<str>,
2319    machine: impl AsRef<str>,
2320    transition: impl AsRef<str>,
2321) -> String {
2322    format!(
2323        "WitnessTransitionObserved_{}_{}_{}",
2324        tla_ident(witness.as_ref()),
2325        tla_ident(machine),
2326        tla_ident(transition)
2327    )
2328}
2329
2330fn composition_witness_transition_order_property_name(
2331    witness: impl AsRef<str>,
2332    index: usize,
2333) -> String {
2334    format!(
2335        "WitnessTransitionOrder_{}_{}",
2336        tla_ident(witness.as_ref()),
2337        index + 1
2338    )
2339}
2340
2341fn witness_scheduler_rule_label(rule: &SchedulerRule) -> String {
2342    match rule {
2343        SchedulerRule::PreemptWhenReady { higher, lower } => {
2344            format!("PreemptWhenReady_{}_{}", higher, lower)
2345        }
2346    }
2347}
2348
2349fn composition_witness_init_name(name: impl AsRef<str>) -> String {
2350    format!("WitnessInit_{}", tla_ident(name.as_ref()))
2351}
2352
2353fn composition_witness_next_name(name: impl AsRef<str>) -> String {
2354    format!("WitnessNext_{}", tla_ident(name.as_ref()))
2355}
2356
2357fn composition_witness_spec_name(name: impl AsRef<str>) -> String {
2358    format!("WitnessSpec_{}", tla_ident(name.as_ref()))
2359}
2360
2361fn composition_witness_fairness_name(name: impl AsRef<str>, index: usize) -> String {
2362    format!("WitnessFairness_{}_{}", tla_ident(name.as_ref()), index + 1)
2363}
2364
2365fn composition_witness_completion_name(name: impl AsRef<str>) -> String {
2366    format!("WitnessScriptComplete_{}", tla_ident(name.as_ref()))
2367}
2368
2369fn composition_witness_action_constraint_name(name: impl AsRef<str>) -> String {
2370    format!("WitnessNoPrematureStutter_{}", tla_ident(name.as_ref()))
2371}
2372
2373fn composition_witness_state_constraint_name(name: impl AsRef<str>) -> String {
2374    format!("WitnessStateConstraint_{}", tla_ident(name.as_ref()))
2375}
2376
2377pub fn render_composition_semantic_model(
2378    schema: &CompositionSchema,
2379) -> std::result::Result<String, CompositionTlaError> {
2380    render_composition_semantic_model_from_catalog(schema, &canonical_machine_schemas())
2381}
2382
2383/// [`render_composition_semantic_model`] against an explicitly supplied
2384/// machine catalog, for compositions whose machines live outside Meerkat's
2385/// catalog.
2386pub fn render_composition_semantic_model_with_catalog(
2387    schema: &CompositionSchema,
2388    machine_catalog: &[MachineSchema],
2389) -> std::result::Result<String, CompositionTlaError> {
2390    validate_supplied_catalog(schema, machine_catalog)?;
2391    render_composition_semantic_model_from_catalog(schema, machine_catalog)
2392}
2393
2394fn render_composition_semantic_model_from_catalog(
2395    schema: &CompositionSchema,
2396    machine_catalog: &[MachineSchema],
2397) -> std::result::Result<String, CompositionTlaError> {
2398    // Fail closed: compiler construction (unknown machine schema, empty
2399    // catalog) and rendering (unresolved route component, helper-call cycle,
2400    // absent obligation field) used to be swallowed into `String::new()`,
2401    // producing a broken-but-passing model. Propagate the typed error so
2402    // `machine-generate` / `machine-check-drift` fail on malformed input.
2403    let compiler = CompositionTlaCompiler::new(schema, machine_catalog)
2404        .map_err(CompositionTlaError::Compile)?;
2405    compiler.render()
2406}
2407
2408/// Renders the generated per-composition Rust module (Track-B wave-b V2).
2409///
2410/// The emitted module is the typed seam between the composition's route
2411/// schema and the runtime composition dispatcher. It declares:
2412///
2413/// * generated producer/effect/input/signal/field identity facts,
2414/// * `TypedRoutedInput` / `TypedRoutedSignal` descriptors carrying typed
2415///   route targets and `(FieldId, FieldId)` binding pairs,
2416/// * a `route_to_input(instance, effect_variant) -> Option<TypedRoutedInput>`
2417///   fact resolver for input-kind routes, and
2418/// * a `route_to_signal(instance, effect_variant) -> Option<TypedRoutedSignal>`
2419///   fact resolver for signal-kind routes.
2420///
2421/// Returns `None` when the composition declares no driver descriptor; the
2422/// driver descriptor continues to carry the Rust emission path for xtask
2423/// consumers.
2424pub fn render_composition_driver(schema: &CompositionSchema) -> Option<String> {
2425    render_composition_driver_from_catalog(schema, &canonical_machine_schemas())
2426}
2427
2428/// [`render_composition_driver`] against an explicitly supplied machine
2429/// catalog, for compositions whose machines live outside Meerkat's catalog.
2430pub fn render_composition_driver_with_catalog(
2431    schema: &CompositionSchema,
2432    machine_catalog: &[MachineSchema],
2433) -> std::result::Result<Option<String>, CompositionTlaError> {
2434    validate_supplied_catalog(schema, machine_catalog)?;
2435    Ok(render_composition_driver_from_catalog(
2436        schema,
2437        machine_catalog,
2438    ))
2439}
2440
2441fn render_composition_driver_from_catalog(
2442    schema: &CompositionSchema,
2443    machine_catalog: &[MachineSchema],
2444) -> Option<String> {
2445    let driver = schema.driver.as_ref()?;
2446
2447    let machine_by_name = machine_catalog
2448        .iter()
2449        .map(|machine| (machine.machine.as_str(), machine))
2450        .collect::<BTreeMap<_, _>>();
2451
2452    let mut producers: Vec<(&str, &MachineSchema)> = Vec::new();
2453    let mut seen: BTreeSet<&str> = BTreeSet::new();
2454    for instance in &schema.machines {
2455        if !seen.insert(instance.instance_id.as_str()) {
2456            continue;
2457        }
2458        let Some(machine) = machine_by_name.get(instance.machine_name.as_str()).copied() else {
2459            continue;
2460        };
2461        producers.push((instance.instance_id.as_str(), machine));
2462    }
2463
2464    let composition_name = schema.name.as_str();
2465    let mut effect_variants_by_producer: BTreeMap<&str, BTreeSet<&str>> = BTreeMap::new();
2466    let mut input_variants: BTreeSet<&str> = BTreeSet::new();
2467    let mut signal_variants: BTreeSet<&str> = BTreeSet::new();
2468    let mut fields: BTreeSet<&str> = BTreeSet::new();
2469
2470    for route in &schema.routes {
2471        effect_variants_by_producer
2472            .entry(route.from_machine.as_str())
2473            .or_default()
2474            .insert(route.effect_variant.as_str());
2475
2476        match route.to.kind {
2477            RouteTargetKind::Input => {
2478                input_variants.insert(route.to.input_variant.as_str());
2479            }
2480            RouteTargetKind::Signal => {
2481                signal_variants.insert(route.to.input_variant.as_str());
2482            }
2483        }
2484
2485        for binding in &route.bindings {
2486            fields.insert(binding.to_field.as_str());
2487            if let RouteBindingSource::Field { from_field, .. } = &binding.source {
2488                fields.insert(from_field.as_str());
2489            }
2490        }
2491    }
2492    for closure in &driver.refusal_closures {
2493        input_variants.insert(closure.feedback_input.as_str());
2494        for binding in &closure.field_bindings {
2495            fields.insert(binding.input_field.as_str());
2496            if let DriverRefusalFieldSource::EffectField(source_field) = &binding.source {
2497                fields.insert(source_field.as_str());
2498            }
2499        }
2500    }
2501
2502    let mut out = String::new();
2503    pushln!(
2504        &mut out,
2505        "// @generated — composition module for `{composition_name}`"
2506    );
2507    pushln!(
2508        &mut out,
2509        "// DO NOT EDIT. Emitted by meerkat_machine_codegen::render_composition_driver."
2510    );
2511    pushln!(
2512        &mut out,
2513        "// Source of truth: catalog::compositions::{composition_name}"
2514    );
2515    pushln!(
2516        &mut out,
2517        "// Driver: `{}` (rust path: `{}`).",
2518        driver.name,
2519        driver.rust.module_path
2520    );
2521    pushln!(&mut out, "#![allow(clippy::expect_used)]");
2522    out.push('\n');
2523
2524    pushln!(
2525        &mut out,
2526        "use meerkat_machine_schema::identity::{{CompositionId, EffectVariantId, FieldId, InputVariantId, MachineId, MachineInstanceId, RouteId, SignalVariantId}};"
2527    );
2528    for import in &driver.rust.required_imports {
2529        pushln!(&mut out, "{import}");
2530    }
2531    out.push('\n');
2532
2533    pushln!(
2534        &mut out,
2535        "/// Typed route descriptor resolved from generated composition facts."
2536    );
2537    pushln!(&mut out, "///");
2538    pushln!(
2539        &mut out,
2540        "/// `bindings` lists producer-field → consumer-field pairs in the"
2541    );
2542    pushln!(&mut out, "/// order declared by the composition schema.");
2543    pushln!(&mut out, "#[derive(Debug, Clone, PartialEq, Eq)]");
2544    pushln!(&mut out, "pub struct TypedRoutedInput {{");
2545    pushln!(&mut out, "    pub route_id: RouteId,");
2546    pushln!(&mut out, "    pub instance_id: MachineInstanceId,");
2547    pushln!(&mut out, "    pub variant: InputVariantId,");
2548    pushln!(&mut out, "    pub bindings: Vec<(FieldId, FieldId)>,");
2549    pushln!(&mut out, "}}");
2550    out.push('\n');
2551
2552    pushln!(
2553        &mut out,
2554        "/// Typed signal-route descriptor resolved from generated composition facts."
2555    );
2556    pushln!(&mut out, "///");
2557    pushln!(
2558        &mut out,
2559        "/// `bindings` lists producer-field → consumer-field pairs in the"
2560    );
2561    pushln!(&mut out, "/// order declared by the composition schema.");
2562    pushln!(&mut out, "#[derive(Debug, Clone, PartialEq, Eq)]");
2563    pushln!(&mut out, "pub struct TypedRoutedSignal {{");
2564    pushln!(&mut out, "    pub route_id: RouteId,");
2565    pushln!(&mut out, "    pub instance_id: MachineInstanceId,");
2566    pushln!(&mut out, "    pub variant: SignalVariantId,");
2567    pushln!(&mut out, "    pub bindings: Vec<(FieldId, FieldId)>,");
2568    pushln!(&mut out, "}}");
2569    out.push('\n');
2570
2571    pushln!(
2572        &mut out,
2573        "/// Generated source for one consumer-refusal feedback field."
2574    );
2575    pushln!(&mut out, "#[derive(Debug, Clone, PartialEq, Eq)]");
2576    pushln!(&mut out, "pub enum GeneratedRefusalFieldSource {{");
2577    pushln!(&mut out, "    EffectField(FieldId),");
2578    pushln!(&mut out, "    ConsumerErrorCode,");
2579    pushln!(&mut out, "    ConsumerErrorMessage,");
2580    pushln!(&mut out, "}}");
2581    out.push('\n');
2582
2583    pushln!(
2584        &mut out,
2585        "/// Generated feedback closure for a consumer-refused dispatch."
2586    );
2587    pushln!(&mut out, "#[derive(Debug, Clone, PartialEq, Eq)]");
2588    pushln!(&mut out, "pub struct TypedDispatchRefusalClosure {{");
2589    pushln!(&mut out, "    pub route_id: RouteId,");
2590    pushln!(&mut out, "    pub producer_instance: MachineInstanceId,");
2591    pushln!(&mut out, "    pub effect_variant: EffectVariantId,");
2592    pushln!(&mut out, "    pub feedback_instance: MachineInstanceId,");
2593    pushln!(&mut out, "    pub feedback_input: InputVariantId,");
2594    pushln!(
2595        &mut out,
2596        "    pub field_bindings: Vec<(GeneratedRefusalFieldSource, FieldId)>,"
2597    );
2598    pushln!(&mut out, "}}");
2599    out.push('\n');
2600
2601    pushln!(
2602        &mut out,
2603        "/// Generated producer identity declared by this composition."
2604    );
2605    pushln!(&mut out, "#[derive(Debug, Clone, PartialEq, Eq)]");
2606    pushln!(&mut out, "pub struct ProducerFacts {{");
2607    pushln!(&mut out, "    pub instance_id: MachineInstanceId,");
2608    pushln!(&mut out, "    pub machine: MachineId,");
2609    pushln!(&mut out, "}}");
2610    out.push('\n');
2611
2612    pushln!(&mut out, "/// Composition id for this generated fact set.");
2613    pushln!(&mut out, "pub fn composition_id() -> CompositionId {{");
2614    pushln!(
2615        &mut out,
2616        "    CompositionId::parse(\"{composition_name}\").expect(\"composition slug\")"
2617    );
2618    pushln!(&mut out, "}}");
2619    out.push('\n');
2620
2621    pushln!(&mut out, "/// Generated producer instance facts.");
2622    pushln!(&mut out, "pub mod producers {{");
2623    pushln!(&mut out, "    use super::*;");
2624    for (instance_id, machine) in &producers {
2625        let fn_name = to_snake_case_local(instance_id);
2626        let machine_name = machine.machine.as_str();
2627        pushln!(&mut out);
2628        pushln!(&mut out, "    pub fn {fn_name}() -> ProducerFacts {{");
2629        pushln!(&mut out, "        ProducerFacts {{");
2630        pushln!(
2631            &mut out,
2632            "            instance_id: {fn_name}_instance_id(),"
2633        );
2634        pushln!(&mut out, "            machine: {fn_name}_machine_id(),");
2635        pushln!(&mut out, "        }}");
2636        pushln!(&mut out, "    }}");
2637        pushln!(&mut out);
2638        pushln!(
2639            &mut out,
2640            "    pub fn {fn_name}_instance_id() -> MachineInstanceId {{"
2641        );
2642        pushln!(
2643            &mut out,
2644            "        MachineInstanceId::parse(\"{instance_id}\").expect(\"producer instance slug\")"
2645        );
2646        pushln!(&mut out, "    }}");
2647        pushln!(&mut out);
2648        pushln!(
2649            &mut out,
2650            "    pub fn {fn_name}_machine_id() -> MachineId {{"
2651        );
2652        pushln!(
2653            &mut out,
2654            "        MachineId::parse(\"{machine_name}\").expect(\"producer machine slug\")"
2655        );
2656        pushln!(&mut out, "    }}");
2657    }
2658    pushln!(&mut out, "}}");
2659    out.push('\n');
2660
2661    pushln!(&mut out, "/// Generated producer-side effect variant ids.");
2662    pushln!(&mut out, "pub mod effects {{");
2663    for (instance_id, _) in &producers {
2664        let producer_mod = to_snake_case_local(instance_id);
2665        pushln!(&mut out);
2666        pushln!(&mut out, "    pub mod {producer_mod} {{");
2667        pushln!(&mut out, "        use super::super::*;");
2668        if let Some(effect_variants) = effect_variants_by_producer.get(instance_id) {
2669            for effect_variant in effect_variants {
2670                let fn_name = to_snake_case_local(effect_variant);
2671                pushln!(&mut out);
2672                pushln!(&mut out, "        pub fn {fn_name}() -> EffectVariantId {{");
2673                pushln!(
2674                    &mut out,
2675                    "            EffectVariantId::parse(\"{effect_variant}\").expect(\"effect variant slug\")"
2676                );
2677                pushln!(&mut out, "        }}");
2678            }
2679        }
2680        pushln!(&mut out, "    }}");
2681    }
2682    pushln!(&mut out, "}}");
2683    out.push('\n');
2684
2685    pushln!(&mut out, "/// Generated consumer input variant ids.");
2686    pushln!(&mut out, "pub mod inputs {{");
2687    pushln!(&mut out, "    use super::*;");
2688    for input_variant in &input_variants {
2689        let fn_name = to_snake_case_local(input_variant);
2690        pushln!(&mut out);
2691        pushln!(&mut out, "    pub fn {fn_name}() -> InputVariantId {{");
2692        pushln!(
2693            &mut out,
2694            "        InputVariantId::parse(\"{input_variant}\").expect(\"input variant slug\")"
2695        );
2696        pushln!(&mut out, "    }}");
2697    }
2698    pushln!(&mut out, "}}");
2699    out.push('\n');
2700
2701    pushln!(&mut out, "/// Generated consumer signal variant ids.");
2702    pushln!(&mut out, "pub mod signals {{");
2703    pushln!(&mut out, "    use super::*;");
2704    for signal_variant in &signal_variants {
2705        let fn_name = to_snake_case_local(signal_variant);
2706        pushln!(&mut out);
2707        pushln!(&mut out, "    pub fn {fn_name}() -> SignalVariantId {{");
2708        pushln!(
2709            &mut out,
2710            "        SignalVariantId::parse(\"{signal_variant}\").expect(\"signal variant slug\")"
2711        );
2712        pushln!(&mut out, "    }}");
2713    }
2714    pushln!(&mut out, "}}");
2715    out.push('\n');
2716
2717    pushln!(
2718        &mut out,
2719        "/// Generated field ids referenced by route bindings."
2720    );
2721    pushln!(&mut out, "pub mod fields {{");
2722    pushln!(&mut out, "    use super::*;");
2723    for field in &fields {
2724        let fn_name = to_snake_case_local(field);
2725        pushln!(&mut out);
2726        pushln!(&mut out, "    pub fn {fn_name}() -> FieldId {{");
2727        pushln!(
2728            &mut out,
2729            "        FieldId::parse(\"{field}\").expect(\"field slug\")"
2730        );
2731        pushln!(&mut out, "    }}");
2732    }
2733    pushln!(&mut out, "}}");
2734    out.push('\n');
2735
2736    for route in schema
2737        .routes
2738        .iter()
2739        .filter(|route| route.to.kind == RouteTargetKind::Input)
2740    {
2741        let route_fn = format!("route_{}", to_snake_case_local(route.name.as_str()));
2742        let target_machine = route.to.machine.as_str();
2743        let target_variant = route.to.input_variant.as_str();
2744        pushln!(
2745            &mut out,
2746            "/// Generated facts for input route `{}`.",
2747            route.name.as_str()
2748        );
2749        pushln!(&mut out, "pub fn {route_fn}() -> TypedRoutedInput {{");
2750        pushln!(&mut out, "    TypedRoutedInput {{");
2751        pushln!(
2752            &mut out,
2753            "        route_id: RouteId::parse(\"{}\").expect(\"route slug\"),",
2754            route.name.as_str()
2755        );
2756        pushln!(
2757            &mut out,
2758            "        instance_id: MachineInstanceId::parse(\"{target_machine}\").expect(\"composition instance slug\"),"
2759        );
2760        pushln!(
2761            &mut out,
2762            "        variant: InputVariantId::parse(\"{target_variant}\").expect(\"composition input slug\"),"
2763        );
2764        if route.bindings.is_empty() {
2765            pushln!(&mut out, "        bindings: Vec::new(),");
2766        } else {
2767            pushln!(&mut out, "        bindings: vec![");
2768            for binding in &route.bindings {
2769                let from_field = match &binding.source {
2770                    RouteBindingSource::Field { from_field, .. } => from_field.as_str(),
2771                    RouteBindingSource::Literal(_) | RouteBindingSource::OwnerProvided => {
2772                        continue;
2773                    }
2774                };
2775                let to_field = binding.to_field.as_str();
2776                pushln!(
2777                    &mut out,
2778                    "            (FieldId::parse(\"{from_field}\").expect(\"route producer field slug\"), FieldId::parse(\"{to_field}\").expect(\"route consumer field slug\")),"
2779                );
2780            }
2781            pushln!(&mut out, "        ],");
2782        }
2783        pushln!(&mut out, "    }}");
2784        pushln!(&mut out, "}}");
2785        out.push('\n');
2786    }
2787
2788    for closure in &driver.refusal_closures {
2789        let route = schema
2790            .routes
2791            .iter()
2792            .find(|route| route.name == closure.dispatch_route)?;
2793        let closure_fn = format!(
2794            "refusal_closure_{}",
2795            to_snake_case_local(closure.dispatch_route.as_str())
2796        );
2797        pushln!(
2798            &mut out,
2799            "/// Generated consumer-refusal closure for route `{}`.",
2800            closure.dispatch_route
2801        );
2802        pushln!(
2803            &mut out,
2804            "pub fn {closure_fn}() -> TypedDispatchRefusalClosure {{"
2805        );
2806        pushln!(&mut out, "    TypedDispatchRefusalClosure {{");
2807        pushln!(
2808            &mut out,
2809            "        route_id: RouteId::parse(\"{}\").expect(\"route slug\"),",
2810            closure.dispatch_route
2811        );
2812        pushln!(
2813            &mut out,
2814            "        producer_instance: MachineInstanceId::parse(\"{}\").expect(\"producer instance slug\"),",
2815            route.from_machine
2816        );
2817        pushln!(
2818            &mut out,
2819            "        effect_variant: EffectVariantId::parse(\"{}\").expect(\"effect variant slug\"),",
2820            route.effect_variant
2821        );
2822        pushln!(
2823            &mut out,
2824            "        feedback_instance: MachineInstanceId::parse(\"{}\").expect(\"feedback instance slug\"),",
2825            closure.feedback_instance
2826        );
2827        pushln!(
2828            &mut out,
2829            "        feedback_input: InputVariantId::parse(\"{}\").expect(\"feedback input slug\"),",
2830            closure.feedback_input
2831        );
2832        pushln!(&mut out, "        field_bindings: vec![");
2833        for binding in &closure.field_bindings {
2834            let source = match &binding.source {
2835                DriverRefusalFieldSource::EffectField(field) => format!(
2836                    "GeneratedRefusalFieldSource::EffectField(FieldId::parse(\"{}\").expect(\"effect field slug\"))",
2837                    field
2838                ),
2839                DriverRefusalFieldSource::ConsumerErrorCode => {
2840                    "GeneratedRefusalFieldSource::ConsumerErrorCode".to_owned()
2841                }
2842                DriverRefusalFieldSource::ConsumerErrorMessage => {
2843                    "GeneratedRefusalFieldSource::ConsumerErrorMessage".to_owned()
2844                }
2845            };
2846            pushln!(
2847                &mut out,
2848                "            ({source}, FieldId::parse(\"{}\").expect(\"feedback field slug\")),",
2849                binding.input_field
2850            );
2851        }
2852        pushln!(&mut out, "        ],");
2853        pushln!(&mut out, "    }}");
2854        pushln!(&mut out, "}}");
2855        out.push('\n');
2856    }
2857
2858    pushln!(
2859        &mut out,
2860        "/// Resolve a generated route to its consumer-refusal feedback closure."
2861    );
2862    pushln!(
2863        &mut out,
2864        "pub fn refusal_closure_for_route(route_id: &RouteId) -> Option<TypedDispatchRefusalClosure> {{"
2865    );
2866    for closure in &driver.refusal_closures {
2867        let closure_fn = format!(
2868            "refusal_closure_{}",
2869            to_snake_case_local(closure.dispatch_route.as_str())
2870        );
2871        pushln!(
2872            &mut out,
2873            "    if route_id == &RouteId::parse(\"{}\").expect(\"route slug\") {{",
2874            closure.dispatch_route
2875        );
2876        pushln!(&mut out, "        return Some({closure_fn}());");
2877        pushln!(&mut out, "    }}");
2878    }
2879    pushln!(&mut out, "    None");
2880    pushln!(&mut out, "}}");
2881    out.push('\n');
2882
2883    for route in schema
2884        .routes
2885        .iter()
2886        .filter(|route| route.to.kind == RouteTargetKind::Signal)
2887    {
2888        let route_fn = format!("route_{}", to_snake_case_local(route.name.as_str()));
2889        let target_machine = route.to.machine.as_str();
2890        let target_variant = route.to.input_variant.as_str();
2891        pushln!(
2892            &mut out,
2893            "/// Generated facts for signal route `{}`.",
2894            route.name.as_str()
2895        );
2896        pushln!(&mut out, "pub fn {route_fn}() -> TypedRoutedSignal {{");
2897        pushln!(&mut out, "    TypedRoutedSignal {{");
2898        pushln!(
2899            &mut out,
2900            "        route_id: RouteId::parse(\"{}\").expect(\"route slug\"),",
2901            route.name.as_str()
2902        );
2903        pushln!(
2904            &mut out,
2905            "        instance_id: MachineInstanceId::parse(\"{target_machine}\").expect(\"composition instance slug\"),"
2906        );
2907        pushln!(
2908            &mut out,
2909            "        variant: SignalVariantId::parse(\"{target_variant}\").expect(\"composition signal slug\"),"
2910        );
2911        if route.bindings.is_empty() {
2912            pushln!(&mut out, "        bindings: Vec::new(),");
2913        } else {
2914            pushln!(&mut out, "        bindings: vec![");
2915            for binding in &route.bindings {
2916                let from_field = match &binding.source {
2917                    RouteBindingSource::Field { from_field, .. } => from_field.as_str(),
2918                    RouteBindingSource::Literal(_) | RouteBindingSource::OwnerProvided => {
2919                        continue;
2920                    }
2921                };
2922                let to_field = binding.to_field.as_str();
2923                pushln!(
2924                    &mut out,
2925                    "            (FieldId::parse(\"{from_field}\").expect(\"route producer field slug\"), FieldId::parse(\"{to_field}\").expect(\"route consumer field slug\")),"
2926                );
2927            }
2928            pushln!(&mut out, "        ],");
2929        }
2930        pushln!(&mut out, "    }}");
2931        pushln!(&mut out, "}}");
2932        out.push('\n');
2933    }
2934
2935    pushln!(
2936        &mut out,
2937        "/// Resolve a producer `(instance, effect_variant)` to generated input-route facts."
2938    );
2939    pushln!(&mut out, "pub fn route_to_input(");
2940    pushln!(&mut out, "    producer_instance: &MachineInstanceId,");
2941    pushln!(&mut out, "    effect_variant: &EffectVariantId,");
2942    pushln!(&mut out, ") -> Option<TypedRoutedInput> {{");
2943    for route in schema
2944        .routes
2945        .iter()
2946        .filter(|route| route.to.kind == RouteTargetKind::Input)
2947    {
2948        let producer_mod = to_snake_case_local(route.from_machine.as_str());
2949        let effect_fn = to_snake_case_local(route.effect_variant.as_str());
2950        let route_fn = format!("route_{}", to_snake_case_local(route.name.as_str()));
2951        pushln!(
2952            &mut out,
2953            "    if producer_instance == &producers::{producer_mod}_instance_id() && effect_variant == &effects::{producer_mod}::{effect_fn}() {{"
2954        );
2955        pushln!(&mut out, "        return Some({route_fn}());");
2956        pushln!(&mut out, "    }}");
2957    }
2958    pushln!(&mut out, "    None");
2959    pushln!(&mut out, "}}");
2960    out.push('\n');
2961
2962    pushln!(
2963        &mut out,
2964        "/// Resolve a producer `(instance, effect_variant)` to generated signal-route facts."
2965    );
2966    pushln!(&mut out, "pub fn route_to_signal(");
2967    pushln!(&mut out, "    producer_instance: &MachineInstanceId,");
2968    pushln!(&mut out, "    effect_variant: &EffectVariantId,");
2969    pushln!(&mut out, ") -> Option<TypedRoutedSignal> {{");
2970    for route in schema
2971        .routes
2972        .iter()
2973        .filter(|route| route.to.kind == RouteTargetKind::Signal)
2974    {
2975        let producer_mod = to_snake_case_local(route.from_machine.as_str());
2976        let effect_fn = to_snake_case_local(route.effect_variant.as_str());
2977        let route_fn = format!("route_{}", to_snake_case_local(route.name.as_str()));
2978        pushln!(
2979            &mut out,
2980            "    if producer_instance == &producers::{producer_mod}_instance_id() && effect_variant == &effects::{producer_mod}::{effect_fn}() {{"
2981        );
2982        pushln!(&mut out, "        return Some({route_fn}());");
2983        pushln!(&mut out, "    }}");
2984    }
2985    pushln!(&mut out, "    None");
2986    pushln!(&mut out, "}}");
2987    out.push('\n');
2988
2989    let driver_type = driver.rust.driver_type.as_ref();
2990    let store_plan_type = driver.rust.store_plan_type.as_ref();
2991    let work_type = driver.rust.work_type.as_ref();
2992    let decision_type = driver.rust.decision_type.as_ref();
2993
2994    pushln!(
2995        &mut out,
2996        "/// Generated route target selected by `{driver_type}`."
2997    );
2998    pushln!(&mut out, "#[derive(Debug, Clone, PartialEq, Eq)]");
2999    pushln!(&mut out, "pub enum GeneratedRouteTarget {{");
3000    pushln!(&mut out, "    Input(TypedRoutedInput),");
3001    pushln!(&mut out, "    Signal(TypedRoutedSignal),");
3002    pushln!(&mut out, "}}");
3003    out.push('\n');
3004
3005    pushln!(
3006        &mut out,
3007        "/// Generated store plan emitted by `{driver_type}`."
3008    );
3009    pushln!(&mut out, "#[derive(Debug, Clone, PartialEq, Eq)]");
3010    pushln!(&mut out, "pub struct {store_plan_type} {{");
3011    pushln!(&mut out, "    pub target: GeneratedRouteTarget,");
3012    pushln!(&mut out, "}}");
3013    pushln!(&mut out);
3014    pushln!(&mut out, "impl {store_plan_type} {{");
3015    pushln!(
3016        &mut out,
3017        "    pub fn input(route: TypedRoutedInput) -> Self {{"
3018    );
3019    pushln!(
3020        &mut out,
3021        "        Self {{ target: GeneratedRouteTarget::Input(route) }}"
3022    );
3023    pushln!(&mut out, "    }}");
3024    pushln!(&mut out);
3025    pushln!(
3026        &mut out,
3027        "    pub fn signal(route: TypedRoutedSignal) -> Self {{"
3028    );
3029    pushln!(
3030        &mut out,
3031        "        Self {{ target: GeneratedRouteTarget::Signal(route) }}"
3032    );
3033    pushln!(&mut out, "    }}");
3034    pushln!(&mut out);
3035    pushln!(&mut out, "    pub fn route_id(&self) -> &RouteId {{");
3036    pushln!(&mut out, "        match &self.target {{");
3037    pushln!(
3038        &mut out,
3039        "            GeneratedRouteTarget::Input(route) => &route.route_id,"
3040    );
3041    pushln!(
3042        &mut out,
3043        "            GeneratedRouteTarget::Signal(route) => &route.route_id,"
3044    );
3045    pushln!(&mut out, "        }}");
3046    pushln!(&mut out, "    }}");
3047    pushln!(&mut out, "}}");
3048    out.push('\n');
3049
3050    pushln!(
3051        &mut out,
3052        "/// Generated work packet consumed by `{driver_type}`."
3053    );
3054    pushln!(&mut out, "#[derive(Debug, Clone, PartialEq, Eq)]");
3055    pushln!(&mut out, "pub struct {work_type} {{");
3056    pushln!(&mut out, "    pub producer_instance: MachineInstanceId,");
3057    pushln!(&mut out, "    pub effect_variant: EffectVariantId,");
3058    pushln!(&mut out, "}}");
3059    pushln!(&mut out);
3060    pushln!(&mut out, "impl {work_type} {{");
3061    pushln!(
3062        &mut out,
3063        "    pub fn new(producer_instance: MachineInstanceId, effect_variant: EffectVariantId) -> Self {{"
3064    );
3065    pushln!(
3066        &mut out,
3067        "        Self {{ producer_instance, effect_variant }}"
3068    );
3069    pushln!(&mut out, "    }}");
3070    pushln!(&mut out, "}}");
3071    out.push('\n');
3072
3073    pushln!(
3074        &mut out,
3075        "/// Generated routing decision emitted by `{driver_type}`."
3076    );
3077    pushln!(&mut out, "#[derive(Debug, Clone, PartialEq, Eq)]");
3078    pushln!(&mut out, "pub enum {decision_type} {{");
3079    pushln!(&mut out, "    DispatchInput(TypedRoutedInput),");
3080    pushln!(&mut out, "    DispatchSignal(TypedRoutedSignal),");
3081    pushln!(&mut out, "    NoRoute,");
3082    pushln!(&mut out, "}}");
3083    out.push('\n');
3084
3085    pushln!(
3086        &mut out,
3087        "/// Generated composition driver constrained by the catalog driver descriptor."
3088    );
3089    pushln!(&mut out, "#[derive(Debug, Clone, Copy, PartialEq, Eq)]");
3090    pushln!(&mut out, "pub struct {driver_type};");
3091    pushln!(&mut out);
3092    pushln!(&mut out, "impl {driver_type} {{");
3093    pushln!(
3094        &mut out,
3095        "    pub fn decide(work: &{work_type}) -> {decision_type} {{"
3096    );
3097    pushln!(
3098        &mut out,
3099        "        if let Some(route) = route_to_input(&work.producer_instance, &work.effect_variant) {{"
3100    );
3101    pushln!(
3102        &mut out,
3103        "            return {decision_type}::DispatchInput(route);"
3104    );
3105    pushln!(&mut out, "        }}");
3106    pushln!(
3107        &mut out,
3108        "        if let Some(route) = route_to_signal(&work.producer_instance, &work.effect_variant) {{"
3109    );
3110    pushln!(
3111        &mut out,
3112        "            return {decision_type}::DispatchSignal(route);"
3113    );
3114    pushln!(&mut out, "        }}");
3115    pushln!(&mut out, "        {decision_type}::NoRoute");
3116    pushln!(&mut out, "    }}");
3117    pushln!(&mut out);
3118    pushln!(
3119        &mut out,
3120        "    pub fn store_plan(decision: {decision_type}) -> Option<{store_plan_type}> {{"
3121    );
3122    pushln!(&mut out, "        match decision {{");
3123    pushln!(
3124        &mut out,
3125        "            {decision_type}::DispatchInput(route) => Some({store_plan_type}::input(route)),"
3126    );
3127    pushln!(
3128        &mut out,
3129        "            {decision_type}::DispatchSignal(route) => Some({store_plan_type}::signal(route)),"
3130    );
3131    pushln!(&mut out, "            {decision_type}::NoRoute => None,");
3132    pushln!(&mut out, "        }}");
3133    pushln!(&mut out, "    }}");
3134    pushln!(&mut out, "}}");
3135
3136    Some(out)
3137}
3138
3139fn to_snake_case_local(value: &str) -> String {
3140    let mut out = String::new();
3141    let mut previous_is_sep = true;
3142    for ch in value.chars() {
3143        if ch == '_' || ch == '-' || ch == ' ' {
3144            if !previous_is_sep {
3145                out.push('_');
3146                previous_is_sep = true;
3147            }
3148            continue;
3149        }
3150        if ch.is_ascii_uppercase() {
3151            if !out.is_empty() && !previous_is_sep {
3152                out.push('_');
3153            }
3154            out.push(ch.to_ascii_lowercase());
3155            previous_is_sep = false;
3156        } else {
3157            out.push(ch.to_ascii_lowercase());
3158            previous_is_sep = false;
3159        }
3160    }
3161    out.trim_matches('_').to_owned()
3162}
3163
3164pub fn render_machine_semantic_model(
3165    schema: &MachineSchema,
3166) -> std::result::Result<String, CompositionTlaError> {
3167    check_canonical_named_bindings(schema)?;
3168    if schema.tlc_model.is_some() {
3169        validate_machine_model(schema)?;
3170    }
3171    let mut compiler = MachineTlaCompiler::new(schema);
3172    compiler.render()
3173}
3174
3175fn render_state_markdown(out: &mut String, schema: &MachineSchema) {
3176    pushln!(out, "## State");
3177    writeln!(
3178        out,
3179        "- Phase enum: `{}`",
3180        schema
3181            .state
3182            .phase
3183            .variants
3184            .iter()
3185            .map(|variant| variant.name.as_str())
3186            .collect::<Vec<_>>()
3187            .join(" | ")
3188    )
3189    .expect("write to string");
3190    for field in &schema.state.fields {
3191        pushln!(out, "- `{}`: `{}`", field.name, render_type_ref(&field.ty));
3192    }
3193    pushln!(out);
3194}
3195
3196fn render_enum_markdown(out: &mut String, label: &str, schema: &EnumSchema) {
3197    writeln!(out, "## {label}");
3198    for variant in &schema.variants {
3199        if variant.fields.is_empty() {
3200            pushln!(out, "- `{}`", variant.name);
3201        } else {
3202            writeln!(
3203                out,
3204                "- `{}`({})",
3205                variant.name,
3206                render_field_list(&variant.fields)
3207            )
3208            .expect("write to string");
3209        }
3210    }
3211    pushln!(out);
3212}
3213
3214/// Render a labelled subset of an input enum's variants, keeping only those whose
3215/// name satisfies `keep`. Used to split the public command surface from the
3216/// runtime-internal inputs in the generated machine contract.
3217fn render_input_subset(
3218    out: &mut String,
3219    label: &str,
3220    schema: &EnumSchema,
3221    keep: impl Fn(&str) -> bool,
3222) {
3223    writeln!(out, "## {label}");
3224    for variant in schema
3225        .variants
3226        .iter()
3227        .filter(|variant| keep(variant.name.as_str()))
3228    {
3229        if variant.fields.is_empty() {
3230            pushln!(out, "- `{}`", variant.name);
3231        } else {
3232            writeln!(
3233                out,
3234                "- `{}`({})",
3235                variant.name,
3236                render_field_list(&variant.fields)
3237            )
3238            .expect("write to string");
3239        }
3240    }
3241    pushln!(out);
3242}
3243
3244fn render_field_list(fields: &[meerkat_machine_schema::FieldSchema]) -> String {
3245    fields
3246        .iter()
3247        .map(|field| format!("{}: {}", field.name, render_type_ref(&field.ty)))
3248        .collect::<Vec<_>>()
3249        .join(", ")
3250}
3251
3252fn collect_binding_domains(schema: &MachineSchema) -> BTreeMap<String, TypeRef> {
3253    let mut domains = BTreeMap::new();
3254
3255    for field in &schema.state.fields {
3256        collect_type_domains(&field.ty, &mut domains);
3257    }
3258
3259    for transition in &schema.transitions {
3260        if let Some(variant) = transition_trigger_variant(schema, transition) {
3261            for binding in transition.on.bindings() {
3262                if let Some(field) = variant.fields.iter().find(|field| field.name == *binding) {
3263                    collect_type_domains(&field.ty, &mut domains);
3264                }
3265            }
3266        }
3267    }
3268
3269    for variant in &schema.effects.variants {
3270        for field in &variant.fields {
3271            collect_type_domains(&field.ty, &mut domains);
3272        }
3273    }
3274
3275    domains
3276}
3277
3278fn collect_composition_binding_domains(
3279    schema: &CompositionSchema,
3280    machine_by_instance: &BTreeMap<&str, &MachineSchema>,
3281) -> BTreeMap<String, TypeRef> {
3282    let mut domains = BTreeMap::new();
3283
3284    for machine in machine_by_instance.values() {
3285        for (name, ty) in collect_binding_domains(machine) {
3286            domains.entry(name).or_insert(ty);
3287        }
3288    }
3289
3290    for entry_input in &schema.entry_inputs {
3291        let Some(machine) = machine_by_instance
3292            .get(entry_input.machine.as_str())
3293            .copied()
3294        else {
3295            continue;
3296        };
3297        let Ok(variant) = machine.inputs.variant_named(&entry_input.input_variant) else {
3298            continue;
3299        };
3300        for field in &variant.fields {
3301            collect_type_domains(&field.ty, &mut domains);
3302        }
3303    }
3304
3305    domains
3306}
3307
3308fn collect_type_domains(ty: &TypeRef, domains: &mut BTreeMap<String, TypeRef>) {
3309    let name = domain_constant_name(ty);
3310    domains.entry(name).or_insert_with(|| ty.clone());
3311    match ty {
3312        TypeRef::Option(inner) | TypeRef::Seq(inner) | TypeRef::Set(inner) => {
3313            collect_type_domains(inner, domains);
3314        }
3315        TypeRef::Map(key, value) => {
3316            collect_type_domains(key, domains);
3317            collect_type_domains(value, domains);
3318        }
3319        TypeRef::Bool
3320        | TypeRef::U32
3321        | TypeRef::U64
3322        | TypeRef::String
3323        | TypeRef::Named(_)
3324        | TypeRef::Enum(_) => {}
3325    }
3326}
3327
3328/// Named samples for a machine Deep profile: every named bucket unchanged, but
3329/// the generic `String` bucket holds only the string literals a transition
3330/// guard requires an input binding to equal (`delivery_id == "terminal"`,
3331/// `claim_id == ""`). Without them a transition guarded on such a literal is
3332/// unreachable under the generic `"alpha"`/`"beta"` samples and Deep coverage
3333/// reports it as zero-hit. Literals from updates, effects or init (messages,
3334/// error codes) are deliberately not added, so unrelated machines keep their
3335/// sample domains.
3336fn with_guard_binding_string_samples(
3337    named_samples: &BTreeMap<String, BTreeSet<String>>,
3338    schema: &MachineSchema,
3339) -> BTreeMap<String, BTreeSet<String>> {
3340    let mut samples = named_samples.clone();
3341    let literals = collect_guard_binding_string_literals(schema);
3342    if literals.is_empty() {
3343        samples.remove("String");
3344    } else {
3345        samples.insert("String".to_owned(), literals);
3346    }
3347    samples
3348}
3349
3350fn collect_guard_binding_string_literals(schema: &MachineSchema) -> BTreeSet<String> {
3351    let mut literals = BTreeSet::new();
3352    for transition in &schema.transitions {
3353        let string_bindings = transition_trigger_variant(schema, transition)
3354            .map(|variant| {
3355                variant
3356                    .fields
3357                    .iter()
3358                    .filter(|field| {
3359                        matches!(field.ty, TypeRef::String)
3360                            && transition
3361                                .on
3362                                .bindings()
3363                                .iter()
3364                                .any(|binding| binding == &field.name)
3365                    })
3366                    .map(|field| field.name.as_str().to_owned())
3367                    .collect::<BTreeSet<_>>()
3368            })
3369            .unwrap_or_default();
3370        if string_bindings.is_empty() {
3371            continue;
3372        }
3373        for guard in &transition.guards {
3374            collect_binding_literal_comparisons(&guard.expr, &string_bindings, &mut literals);
3375        }
3376    }
3377    literals
3378}
3379
3380fn collect_binding_literal_comparisons(
3381    expr: &Expr,
3382    string_bindings: &BTreeSet<String>,
3383    literals: &mut BTreeSet<String>,
3384) {
3385    match expr {
3386        // Only equality makes a guard unreachable without its literal. An
3387        // inequality such as `attempt_id != ""` is already satisfied by the
3388        // generic samples, so its literal would only add rejection-path states.
3389        Expr::Eq(left, right) => {
3390            match (left.as_ref(), right.as_ref()) {
3391                (Expr::Binding(binding), Expr::String(literal))
3392                | (Expr::String(literal), Expr::Binding(binding))
3393                    if string_bindings.contains(binding) =>
3394                {
3395                    literals.insert(literal.clone());
3396                }
3397                _ => {}
3398            }
3399            collect_binding_literal_comparisons(left, string_bindings, literals);
3400            collect_binding_literal_comparisons(right, string_bindings, literals);
3401        }
3402        Expr::Neq(left, right) => {
3403            collect_binding_literal_comparisons(left, string_bindings, literals);
3404            collect_binding_literal_comparisons(right, string_bindings, literals);
3405        }
3406        Expr::Not(inner) => collect_binding_literal_comparisons(inner, string_bindings, literals),
3407        Expr::And(items) | Expr::Or(items) => {
3408            for item in items {
3409                collect_binding_literal_comparisons(item, string_bindings, literals);
3410            }
3411        }
3412        Expr::IfElse {
3413            condition,
3414            then_expr,
3415            else_expr,
3416        } => {
3417            for item in [condition, then_expr, else_expr] {
3418                collect_binding_literal_comparisons(item, string_bindings, literals);
3419            }
3420        }
3421        _ => {}
3422    }
3423}
3424
3425fn collect_machine_named_type_samples(
3426    schema: &MachineSchema,
3427) -> BTreeMap<String, BTreeSet<String>> {
3428    let field_types = schema
3429        .state
3430        .fields
3431        .iter()
3432        .map(|field| (field.name.as_str().to_owned(), field.ty.clone()))
3433        .collect::<BTreeMap<String, _>>();
3434    let helper_returns = schema
3435        .helpers
3436        .iter()
3437        .chain(schema.derived.iter())
3438        .map(|helper| (helper.name.clone(), helper.returns.clone()))
3439        .collect::<BTreeMap<String, _>>();
3440    let mut samples = BTreeMap::new();
3441
3442    for init in &schema.state.init.fields {
3443        if let Some(field_ty) = field_types.get(init.field.as_str()) {
3444            collect_named_literals_from_expr(
3445                &mut samples,
3446                &init.expr,
3447                Some(field_ty),
3448                &field_types,
3449                &helper_returns,
3450                &BTreeMap::new(),
3451            );
3452        }
3453    }
3454
3455    for helper in schema.helpers.iter().chain(schema.derived.iter()) {
3456        let bindings = helper
3457            .params
3458            .iter()
3459            .map(|field| (field.name.as_str().to_owned(), field.ty.clone()))
3460            .collect::<BTreeMap<String, _>>();
3461        collect_named_literals_from_expr(
3462            &mut samples,
3463            &helper.body,
3464            Some(&helper.returns),
3465            &field_types,
3466            &helper_returns,
3467            &bindings,
3468        );
3469    }
3470
3471    for invariant in &schema.invariants {
3472        collect_named_literals_from_expr(
3473            &mut samples,
3474            &invariant.expr,
3475            None,
3476            &field_types,
3477            &helper_returns,
3478            &BTreeMap::new(),
3479        );
3480    }
3481
3482    for transition in &schema.transitions {
3483        let binding_types = transition_trigger_variant(schema, transition)
3484            .map(|variant| {
3485                variant
3486                    .fields
3487                    .iter()
3488                    .filter(|field| {
3489                        transition
3490                            .on
3491                            .bindings()
3492                            .iter()
3493                            .any(|binding| binding == &field.name)
3494                    })
3495                    .map(|field| (field.name.as_str().to_owned(), field.ty.clone()))
3496                    .collect::<BTreeMap<_, _>>()
3497            })
3498            .unwrap_or_default();
3499
3500        for guard in &transition.guards {
3501            collect_named_literals_from_expr(
3502                &mut samples,
3503                &guard.expr,
3504                None,
3505                &field_types,
3506                &helper_returns,
3507                &binding_types,
3508            );
3509        }
3510        for update in &transition.updates {
3511            collect_named_literals_from_update(
3512                &mut samples,
3513                update,
3514                &field_types,
3515                &helper_returns,
3516                &binding_types,
3517            );
3518        }
3519        for effect in &transition.emit {
3520            let Ok(effect_variant) = schema.effects.variant_named(effect.variant.as_str()) else {
3521                continue;
3522            };
3523            for field in &effect_variant.fields {
3524                if let Some(expr) = effect.fields.get(&field.name) {
3525                    collect_named_literals_from_expr(
3526                        &mut samples,
3527                        expr,
3528                        Some(&field.ty),
3529                        &field_types,
3530                        &helper_returns,
3531                        &binding_types,
3532                    );
3533                }
3534            }
3535        }
3536    }
3537
3538    samples
3539}
3540
3541fn collect_composition_named_type_samples(
3542    schema: &CompositionSchema,
3543    machine_by_instance: &BTreeMap<&str, &MachineSchema>,
3544) -> BTreeMap<String, BTreeSet<String>> {
3545    let mut samples = BTreeMap::new();
3546    for machine in machine_by_instance.values() {
3547        merge_named_type_samples(&mut samples, collect_machine_named_type_samples(machine));
3548    }
3549
3550    for entry_input in &schema.entry_inputs {
3551        let Some(machine) = machine_by_instance
3552            .get(entry_input.machine.as_str())
3553            .copied()
3554        else {
3555            continue;
3556        };
3557        merge_named_type_samples(&mut samples, collect_machine_named_type_samples(machine));
3558    }
3559
3560    for route in &schema.routes {
3561        let Some(source_machine) = machine_by_instance
3562            .get(route.from_machine.as_str())
3563            .copied()
3564        else {
3565            continue;
3566        };
3567        let Ok(source_variant) = source_machine.effects.variant_named(&route.effect_variant) else {
3568            continue;
3569        };
3570        let source_field_types = source_variant
3571            .fields
3572            .iter()
3573            .map(|field| (field.name.as_str().to_owned(), field.ty.clone()))
3574            .collect::<BTreeMap<String, _>>();
3575        let Some(target_machine) = machine_by_instance.get(route.to.machine.as_str()).copied()
3576        else {
3577            continue;
3578        };
3579        let Some(target_variant) = route_target_variant(target_machine, &route.to) else {
3580            continue;
3581        };
3582        let field_types = target_variant
3583            .fields
3584            .iter()
3585            .map(|field| (field.name.as_str().to_owned(), field.ty.clone()))
3586            .collect::<BTreeMap<String, _>>();
3587
3588        for binding in &route.bindings {
3589            if let RouteBindingSource::Literal(expr) = &binding.source
3590                && let Some(field_ty) = field_types.get(binding.to_field.as_str())
3591            {
3592                collect_named_literals_from_expr(
3593                    &mut samples,
3594                    expr,
3595                    Some(field_ty),
3596                    &field_types,
3597                    &BTreeMap::new(),
3598                    &BTreeMap::new(),
3599                );
3600            }
3601            if let RouteBindingSource::Field { from_field, .. } = &binding.source
3602                && let (Some(source_ty), Some(target_ty)) = (
3603                    source_field_types.get(from_field.as_str()),
3604                    field_types.get(binding.to_field.as_str()),
3605                )
3606            {
3607                propagate_named_samples_between_types(&mut samples, source_ty, target_ty);
3608            }
3609        }
3610    }
3611
3612    for witness in &schema.witnesses {
3613        for preload in &witness.preload_inputs {
3614            let Some(machine) = machine_by_instance.get(preload.machine.as_str()).copied() else {
3615                continue;
3616            };
3617            let Ok(variant) = machine
3618                .inputs
3619                .variant_named(&preload.input_variant)
3620                .or_else(|_| machine.signals.variant_named(&preload.input_variant))
3621            else {
3622                continue;
3623            };
3624            let field_types = variant
3625                .fields
3626                .iter()
3627                .map(|field| (field.name.as_str().to_owned(), field.ty.clone()))
3628                .collect::<BTreeMap<String, _>>();
3629
3630            for field in &preload.fields {
3631                if let Some(field_ty) = field_types.get(field.field.as_str()) {
3632                    collect_named_literals_from_expr(
3633                        &mut samples,
3634                        &field.expr,
3635                        Some(field_ty),
3636                        &field_types,
3637                        &BTreeMap::new(),
3638                        &BTreeMap::new(),
3639                    );
3640                }
3641            }
3642        }
3643    }
3644
3645    samples
3646}
3647
3648fn collect_composition_witness_named_type_samples(
3649    schema: &CompositionSchema,
3650    witness: &CompositionWitness,
3651    machine_by_instance: &BTreeMap<&str, &MachineSchema>,
3652) -> BTreeMap<String, BTreeSet<String>> {
3653    let mut samples = BTreeMap::new();
3654
3655    for preload in &witness.preload_inputs {
3656        let Some(machine) = machine_by_instance.get(preload.machine.as_str()).copied() else {
3657            continue;
3658        };
3659        let Ok(variant) = machine
3660            .inputs
3661            .variant_named(&preload.input_variant)
3662            .or_else(|_| machine.signals.variant_named(&preload.input_variant))
3663        else {
3664            continue;
3665        };
3666        let field_types = variant
3667            .fields
3668            .iter()
3669            .map(|field| (field.name.as_str().to_owned(), field.ty.clone()))
3670            .collect::<BTreeMap<String, _>>();
3671
3672        for field in &preload.fields {
3673            if let Some(field_ty) = field_types.get(field.field.as_str()) {
3674                collect_named_literals_from_expr(
3675                    &mut samples,
3676                    &field.expr,
3677                    Some(field_ty),
3678                    &field_types,
3679                    &BTreeMap::new(),
3680                    &BTreeMap::new(),
3681                );
3682            }
3683        }
3684    }
3685
3686    let witness_routes = schema
3687        .routes
3688        .iter()
3689        .filter(|route| {
3690            witness
3691                .expected_routes
3692                .iter()
3693                .any(|name| name == &route.name)
3694        })
3695        .collect::<Vec<_>>();
3696    collect_route_binding_named_type_samples_to_fixpoint(
3697        &mut samples,
3698        &witness_routes,
3699        machine_by_instance,
3700    );
3701
3702    samples
3703}
3704
3705fn merge_named_type_samples(
3706    target: &mut BTreeMap<String, BTreeSet<String>>,
3707    source: BTreeMap<String, BTreeSet<String>>,
3708) {
3709    for (name, values) in source {
3710        target.entry(name).or_default().extend(values);
3711    }
3712}
3713
3714fn collect_route_binding_named_type_samples_to_fixpoint(
3715    samples: &mut BTreeMap<String, BTreeSet<String>>,
3716    routes: &[&Route],
3717    machine_by_instance: &BTreeMap<&str, &MachineSchema>,
3718) {
3719    loop {
3720        let mut changed = false;
3721        for route in routes {
3722            changed |=
3723                collect_route_binding_named_type_samples(samples, route, machine_by_instance);
3724        }
3725        if !changed {
3726            break;
3727        }
3728    }
3729}
3730
3731fn collect_route_binding_named_type_samples(
3732    samples: &mut BTreeMap<String, BTreeSet<String>>,
3733    route: &Route,
3734    machine_by_instance: &BTreeMap<&str, &MachineSchema>,
3735) -> bool {
3736    let Some(source_machine) = machine_by_instance
3737        .get(route.from_machine.as_str())
3738        .copied()
3739    else {
3740        return false;
3741    };
3742    let Ok(source_variant) = source_machine.effects.variant_named(&route.effect_variant) else {
3743        return false;
3744    };
3745    let source_field_types = source_variant
3746        .fields
3747        .iter()
3748        .map(|field| (field.name.as_str().to_owned(), field.ty.clone()))
3749        .collect::<BTreeMap<String, _>>();
3750    let Some(target_machine) = machine_by_instance.get(route.to.machine.as_str()).copied() else {
3751        return false;
3752    };
3753    let Some(target_variant) = route_target_variant(target_machine, &route.to) else {
3754        return false;
3755    };
3756    let target_field_types = target_variant
3757        .fields
3758        .iter()
3759        .map(|field| (field.name.as_str().to_owned(), field.ty.clone()))
3760        .collect::<BTreeMap<String, _>>();
3761
3762    let mut changed = false;
3763    for binding in &route.bindings {
3764        if let RouteBindingSource::Literal(expr) = &binding.source
3765            && let Some(field_ty) = target_field_types.get(binding.to_field.as_str())
3766        {
3767            let before = samples.clone();
3768            collect_named_literals_from_expr(
3769                samples,
3770                expr,
3771                Some(field_ty),
3772                &target_field_types,
3773                &BTreeMap::new(),
3774                &BTreeMap::new(),
3775            );
3776            changed |= *samples != before;
3777        }
3778        if let RouteBindingSource::Field { from_field, .. } = &binding.source
3779            && let (Some(source_ty), Some(target_ty)) = (
3780                source_field_types.get(from_field.as_str()),
3781                target_field_types.get(binding.to_field.as_str()),
3782            )
3783        {
3784            changed |= propagate_named_samples_between_types(samples, source_ty, target_ty);
3785        }
3786    }
3787
3788    changed
3789}
3790
3791fn propagate_named_samples_between_types(
3792    samples: &mut BTreeMap<String, BTreeSet<String>>,
3793    source_ty: &TypeRef,
3794    target_ty: &TypeRef,
3795) -> bool {
3796    match (source_ty, target_ty) {
3797        (TypeRef::Option(source_inner), TypeRef::Option(target_inner))
3798        | (TypeRef::Seq(source_inner), TypeRef::Seq(target_inner))
3799        | (TypeRef::Set(source_inner), TypeRef::Set(target_inner)) => {
3800            propagate_named_samples_between_types(samples, source_inner, target_inner)
3801        }
3802        _ => {
3803            let (Some(source_bucket), Some(target_bucket)) =
3804                (type_sample_bucket(source_ty), type_sample_bucket(target_ty))
3805            else {
3806                return false;
3807            };
3808            if let Some(source_samples) = samples.get(&source_bucket).cloned() {
3809                let target_samples = samples.entry(target_bucket).or_default();
3810                let before = target_samples.len();
3811                target_samples.extend(source_samples);
3812                target_samples.len() != before
3813            } else {
3814                false
3815            }
3816        }
3817    }
3818}
3819
3820fn collect_named_literals_from_update(
3821    samples: &mut BTreeMap<String, BTreeSet<String>>,
3822    update: &Update,
3823    field_types: &BTreeMap<String, TypeRef>,
3824    helper_returns: &BTreeMap<String, TypeRef>,
3825    binding_types: &BTreeMap<String, TypeRef>,
3826) {
3827    match update {
3828        Update::Assign { field, expr } => {
3829            collect_named_literals_from_expr(
3830                samples,
3831                expr,
3832                field_types.get(field.as_str()),
3833                field_types,
3834                helper_returns,
3835                binding_types,
3836            );
3837        }
3838        Update::MapInsert { field, key, value } => {
3839            if let Some(TypeRef::Map(key_ty, value_ty)) = field_types.get(field.as_str()) {
3840                collect_named_literals_from_expr(
3841                    samples,
3842                    key,
3843                    Some(key_ty),
3844                    field_types,
3845                    helper_returns,
3846                    binding_types,
3847                );
3848                collect_named_literals_from_expr(
3849                    samples,
3850                    value,
3851                    Some(value_ty),
3852                    field_types,
3853                    helper_returns,
3854                    binding_types,
3855                );
3856            }
3857        }
3858        Update::MapRemove { field, key } => {
3859            if let Some(TypeRef::Map(key_ty, _)) = field_types.get(field.as_str()) {
3860                collect_named_literals_from_expr(
3861                    samples,
3862                    key,
3863                    Some(key_ty),
3864                    field_types,
3865                    helper_returns,
3866                    binding_types,
3867                );
3868            }
3869        }
3870        Update::MapIncrement { field, key, .. } | Update::MapDecrement { field, key, .. } => {
3871            if let Some(TypeRef::Map(key_ty, _)) = field_types.get(field.as_str()) {
3872                collect_named_literals_from_expr(
3873                    samples,
3874                    key,
3875                    Some(key_ty),
3876                    field_types,
3877                    helper_returns,
3878                    binding_types,
3879                );
3880            }
3881        }
3882        Update::SetInsert { field, value } | Update::SetRemove { field, value } => {
3883            if let Some(TypeRef::Set(inner_ty)) = field_types.get(field.as_str()) {
3884                collect_named_literals_from_expr(
3885                    samples,
3886                    value,
3887                    Some(inner_ty),
3888                    field_types,
3889                    helper_returns,
3890                    binding_types,
3891                );
3892            }
3893        }
3894        Update::SeqAppend { field, value } | Update::SeqRemoveValue { field, value } => {
3895            if let Some(TypeRef::Seq(inner_ty)) = field_types.get(field.as_str()) {
3896                collect_named_literals_from_expr(
3897                    samples,
3898                    value,
3899                    Some(inner_ty),
3900                    field_types,
3901                    helper_returns,
3902                    binding_types,
3903                );
3904            }
3905        }
3906        Update::SeqPrepend { field, values } | Update::SeqRemoveAll { field, values } => {
3907            if let Some(field_ty) = field_types.get(field.as_str()) {
3908                collect_named_literals_from_expr(
3909                    samples,
3910                    values,
3911                    Some(field_ty),
3912                    field_types,
3913                    helper_returns,
3914                    binding_types,
3915                );
3916            }
3917        }
3918        Update::Conditional {
3919            condition,
3920            then_updates,
3921            else_updates,
3922        } => {
3923            collect_named_literals_from_expr(
3924                samples,
3925                condition,
3926                None,
3927                field_types,
3928                helper_returns,
3929                binding_types,
3930            );
3931            for nested in then_updates {
3932                collect_named_literals_from_update(
3933                    samples,
3934                    nested,
3935                    field_types,
3936                    helper_returns,
3937                    binding_types,
3938                );
3939            }
3940            for nested in else_updates {
3941                collect_named_literals_from_update(
3942                    samples,
3943                    nested,
3944                    field_types,
3945                    helper_returns,
3946                    binding_types,
3947                );
3948            }
3949        }
3950        Update::ForEach {
3951            binding,
3952            over,
3953            updates,
3954        } => {
3955            collect_named_literals_from_expr(
3956                samples,
3957                over,
3958                None,
3959                field_types,
3960                helper_returns,
3961                binding_types,
3962            );
3963            let mut nested_bindings = binding_types.clone();
3964            if let Some(over_ty) = infer_expr_type(over, field_types, helper_returns, binding_types)
3965            {
3966                match over_ty {
3967                    TypeRef::Seq(inner_ty) | TypeRef::Set(inner_ty) => {
3968                        nested_bindings.insert(binding.clone(), (*inner_ty).clone());
3969                    }
3970                    TypeRef::Map(key_ty, _) => {
3971                        nested_bindings.insert(binding.clone(), (*key_ty).clone());
3972                    }
3973                    _ => {}
3974                }
3975            }
3976            for nested in updates {
3977                collect_named_literals_from_update(
3978                    samples,
3979                    nested,
3980                    field_types,
3981                    helper_returns,
3982                    &nested_bindings,
3983                );
3984            }
3985        }
3986        Update::Increment { .. } | Update::Decrement { .. } | Update::SeqPopFront { .. } => {}
3987    }
3988}
3989
3990fn collect_named_literals_from_expr(
3991    samples: &mut BTreeMap<String, BTreeSet<String>>,
3992    expr: &Expr,
3993    expected_ty: Option<&TypeRef>,
3994    field_types: &BTreeMap<String, TypeRef>,
3995    helper_returns: &BTreeMap<String, TypeRef>,
3996    binding_types: &BTreeMap<String, TypeRef>,
3997) {
3998    if let Expr::String(value) = expr
3999        && let Some(bucket) = expected_ty.and_then(type_sample_bucket)
4000    {
4001        samples.entry(bucket).or_default().insert(value.clone());
4002    }
4003
4004    if let (Expr::NamedVariant { variant, .. }, Some(expected_ty)) = (expr, expected_ty)
4005        && let Some(bucket) = type_sample_bucket(expected_ty)
4006    {
4007        samples
4008            .entry(bucket)
4009            .or_default()
4010            .insert(variant.as_str().to_owned());
4011    }
4012
4013    match expr {
4014        Expr::Eq(left, right) | Expr::Neq(left, right) => {
4015            let left_ty = infer_expr_type(left, field_types, helper_returns, binding_types);
4016            let right_ty = infer_expr_type(right, field_types, helper_returns, binding_types);
4017            if let (Some(left_ty), Expr::String(value)) = (&left_ty, right.as_ref())
4018                && let Some(bucket) = type_sample_bucket(left_ty)
4019            {
4020                samples.entry(bucket).or_default().insert(value.clone());
4021            }
4022            if let (Some(right_ty), Expr::String(value)) = (&right_ty, left.as_ref())
4023                && let Some(bucket) = type_sample_bucket(right_ty)
4024            {
4025                samples.entry(bucket).or_default().insert(value.clone());
4026            }
4027            if let (Some(left_ty), Expr::NamedVariant { variant, .. }) = (&left_ty, right.as_ref())
4028                && let Some(bucket) = type_sample_bucket(left_ty)
4029            {
4030                samples
4031                    .entry(bucket)
4032                    .or_default()
4033                    .insert(variant.as_str().to_owned());
4034            }
4035            if let (Some(right_ty), Expr::NamedVariant { variant, .. }) = (&right_ty, left.as_ref())
4036                && let Some(bucket) = type_sample_bucket(right_ty)
4037            {
4038                samples
4039                    .entry(bucket)
4040                    .or_default()
4041                    .insert(variant.as_str().to_owned());
4042            }
4043            collect_named_literals_from_expr(
4044                samples,
4045                left,
4046                left_ty.as_ref(),
4047                field_types,
4048                helper_returns,
4049                binding_types,
4050            );
4051            collect_named_literals_from_expr(
4052                samples,
4053                right,
4054                right_ty.as_ref(),
4055                field_types,
4056                helper_returns,
4057                binding_types,
4058            );
4059        }
4060        Expr::IfElse {
4061            condition,
4062            then_expr,
4063            else_expr,
4064        } => {
4065            collect_named_literals_from_expr(
4066                samples,
4067                condition,
4068                Some(&TypeRef::Bool),
4069                field_types,
4070                helper_returns,
4071                binding_types,
4072            );
4073            collect_named_literals_from_expr(
4074                samples,
4075                then_expr,
4076                expected_ty,
4077                field_types,
4078                helper_returns,
4079                binding_types,
4080            );
4081            collect_named_literals_from_expr(
4082                samples,
4083                else_expr,
4084                expected_ty,
4085                field_types,
4086                helper_returns,
4087                binding_types,
4088            );
4089        }
4090        Expr::Not(inner)
4091        | Expr::SeqElements(inner)
4092        | Expr::Len(inner)
4093        | Expr::Head(inner)
4094        | Expr::MapKeys(inner)
4095        | Expr::Some(inner)
4096        | Expr::FieldAccess { base: inner, .. }
4097        | Expr::EnumVariantIs { value: inner, .. }
4098        | Expr::EnumStringSetPayload { value: inner, .. } => {
4099            let nested_ty = infer_expr_type(inner, field_types, helper_returns, binding_types);
4100            collect_named_literals_from_expr(
4101                samples,
4102                inner,
4103                nested_ty.as_ref(),
4104                field_types,
4105                helper_returns,
4106                binding_types,
4107            );
4108        }
4109        Expr::And(items) | Expr::Or(items) => {
4110            for item in items {
4111                collect_named_literals_from_expr(
4112                    samples,
4113                    item,
4114                    None,
4115                    field_types,
4116                    helper_returns,
4117                    binding_types,
4118                );
4119            }
4120        }
4121        Expr::SeqLiteral(items) => {
4122            let item_expected_ty = match expected_ty {
4123                Some(TypeRef::Seq(inner)) => Some(inner.as_ref()),
4124                _ => None,
4125            };
4126            for item in items {
4127                collect_named_literals_from_expr(
4128                    samples,
4129                    item,
4130                    item_expected_ty,
4131                    field_types,
4132                    helper_returns,
4133                    binding_types,
4134                );
4135            }
4136        }
4137        Expr::Add(left, right)
4138        | Expr::Sub(left, right)
4139        | Expr::Gt(left, right)
4140        | Expr::Gte(left, right)
4141        | Expr::Lt(left, right)
4142        | Expr::Lte(left, right) => {
4143            collect_named_literals_from_expr(
4144                samples,
4145                left,
4146                infer_expr_type(left, field_types, helper_returns, binding_types).as_ref(),
4147                field_types,
4148                helper_returns,
4149                binding_types,
4150            );
4151            collect_named_literals_from_expr(
4152                samples,
4153                right,
4154                infer_expr_type(right, field_types, helper_returns, binding_types).as_ref(),
4155                field_types,
4156                helper_returns,
4157                binding_types,
4158            );
4159        }
4160        Expr::Contains { collection, value } => {
4161            let collection_ty =
4162                infer_expr_type(collection, field_types, helper_returns, binding_types);
4163            let value_ty = match collection_ty {
4164                Some(TypeRef::Set(inner_ty) | TypeRef::Seq(inner_ty)) => Some(*inner_ty),
4165                Some(TypeRef::Map(key_ty, _)) => Some(*key_ty),
4166                _ => None,
4167            };
4168            collect_named_literals_from_expr(
4169                samples,
4170                collection,
4171                None,
4172                field_types,
4173                helper_returns,
4174                binding_types,
4175            );
4176            collect_named_literals_from_expr(
4177                samples,
4178                value,
4179                value_ty.as_ref(),
4180                field_types,
4181                helper_returns,
4182                binding_types,
4183            );
4184        }
4185        Expr::Count { collection, value } => {
4186            let collection_ty =
4187                infer_expr_type(collection, field_types, helper_returns, binding_types);
4188            let value_ty = match collection_ty {
4189                Some(TypeRef::Set(inner_ty) | TypeRef::Seq(inner_ty)) => Some(*inner_ty),
4190                Some(TypeRef::Map(key_ty, _)) => Some(*key_ty),
4191                _ => None,
4192            };
4193            collect_named_literals_from_expr(
4194                samples,
4195                collection,
4196                None,
4197                field_types,
4198                helper_returns,
4199                binding_types,
4200            );
4201            collect_named_literals_from_expr(
4202                samples,
4203                value,
4204                value_ty.as_ref(),
4205                field_types,
4206                helper_returns,
4207                binding_types,
4208            );
4209        }
4210        Expr::MapContainsKey { map, key } => {
4211            let map_ty = infer_expr_type(map, field_types, helper_returns, binding_types);
4212            let key_ty = match map_ty {
4213                Some(TypeRef::Map(key_ty, _)) => Some(*key_ty),
4214                _ => None,
4215            };
4216            collect_named_literals_from_expr(
4217                samples,
4218                map,
4219                None,
4220                field_types,
4221                helper_returns,
4222                binding_types,
4223            );
4224            collect_named_literals_from_expr(
4225                samples,
4226                key,
4227                key_ty.as_ref(),
4228                field_types,
4229                helper_returns,
4230                binding_types,
4231            );
4232        }
4233        Expr::SeqStartsWith { seq, prefix } => {
4234            let seq_ty = infer_expr_type(seq, field_types, helper_returns, binding_types);
4235            collect_named_literals_from_expr(
4236                samples,
4237                seq,
4238                seq_ty.as_ref(),
4239                field_types,
4240                helper_returns,
4241                binding_types,
4242            );
4243            collect_named_literals_from_expr(
4244                samples,
4245                prefix,
4246                seq_ty.as_ref(),
4247                field_types,
4248                helper_returns,
4249                binding_types,
4250            );
4251        }
4252        Expr::MapGet { map, key } | Expr::MapValue { map, key } => {
4253            let map_ty = infer_expr_type(map, field_types, helper_returns, binding_types);
4254            let key_ty = match map_ty {
4255                Some(TypeRef::Map(key_ty, _)) => Some(*key_ty),
4256                _ => None,
4257            };
4258            collect_named_literals_from_expr(
4259                samples,
4260                map,
4261                None,
4262                field_types,
4263                helper_returns,
4264                binding_types,
4265            );
4266            collect_named_literals_from_expr(
4267                samples,
4268                key,
4269                key_ty.as_ref(),
4270                field_types,
4271                helper_returns,
4272                binding_types,
4273            );
4274        }
4275        Expr::MapLiteral(entries) => {
4276            let (key_ty, value_ty) = match expected_ty {
4277                Some(TypeRef::Map(key_ty, value_ty)) => {
4278                    (Some(key_ty.as_ref()), Some(value_ty.as_ref()))
4279                }
4280                _ => (None, None),
4281            };
4282            for (key, value) in entries {
4283                collect_named_literals_from_expr(
4284                    samples,
4285                    key,
4286                    key_ty,
4287                    field_types,
4288                    helper_returns,
4289                    binding_types,
4290                );
4291                collect_named_literals_from_expr(
4292                    samples,
4293                    value,
4294                    value_ty,
4295                    field_types,
4296                    helper_returns,
4297                    binding_types,
4298                );
4299            }
4300        }
4301        Expr::Call { helper: _, args } => {
4302            for arg in args {
4303                collect_named_literals_from_expr(
4304                    samples,
4305                    arg,
4306                    infer_expr_type(arg, field_types, helper_returns, binding_types).as_ref(),
4307                    field_types,
4308                    helper_returns,
4309                    binding_types,
4310                );
4311            }
4312        }
4313        Expr::Quantified {
4314            binding,
4315            over,
4316            body,
4317            ..
4318        } => {
4319            collect_named_literals_from_expr(
4320                samples,
4321                over,
4322                None,
4323                field_types,
4324                helper_returns,
4325                binding_types,
4326            );
4327            // Thread the quantifier binding's element type into the body so
4328            // literals compared against the binding land in the element's
4329            // named sample domain (e.g. `exists(name in <Set<ToolName>>,
4330            // name == "view_image")` buckets the literal under `ToolName`).
4331            let element_ty = infer_expr_type(over, field_types, helper_returns, binding_types)
4332                .and_then(|ty| match ty {
4333                    TypeRef::Set(inner) | TypeRef::Seq(inner) => Some(*inner),
4334                    _ => None,
4335                });
4336            let mut body_binding_types = binding_types.clone();
4337            if let Some(element_ty) = element_ty {
4338                body_binding_types.insert(binding.clone(), element_ty);
4339            }
4340            collect_named_literals_from_expr(
4341                samples,
4342                body,
4343                Some(&TypeRef::Bool),
4344                field_types,
4345                helper_returns,
4346                &body_binding_types,
4347            );
4348        }
4349        Expr::Bool(_)
4350        | Expr::U64(_)
4351        | Expr::U64Max
4352        | Expr::String(_)
4353        | Expr::NamedVariant { .. }
4354        | Expr::EmptySet
4355        | Expr::EmptyMap
4356        | Expr::CurrentPhase
4357        | Expr::Phase(_)
4358        | Expr::Field(_)
4359        | Expr::Binding(_)
4360        | Expr::Variant(_)
4361        | Expr::None => {}
4362    }
4363}
4364
4365fn infer_expr_type(
4366    expr: &Expr,
4367    field_types: &BTreeMap<String, TypeRef>,
4368    helper_returns: &BTreeMap<String, TypeRef>,
4369    binding_types: &BTreeMap<String, TypeRef>,
4370) -> Option<TypeRef> {
4371    match expr {
4372        Expr::Bool(_) => Some(TypeRef::Bool),
4373        Expr::U64(_) | Expr::U64Max => Some(TypeRef::U64),
4374        Expr::String(_) | Expr::CurrentPhase | Expr::Phase(_) | Expr::Variant(_) => {
4375            Some(TypeRef::String)
4376        }
4377        Expr::NamedVariant { enum_name, .. } => Some(TypeRef::Enum(enum_name.clone())),
4378        Expr::FieldAccess { .. } => None,
4379        Expr::EnumVariantIs { .. } => Some(TypeRef::Bool),
4380        Expr::EnumStringSetPayload { .. } => Some(TypeRef::Set(Box::new(TypeRef::String))),
4381        Expr::Field(name) => field_types.get(name.as_str()).cloned(),
4382        Expr::Binding(name) => binding_types.get(name).cloned(),
4383        Expr::None => None,
4384        Expr::IfElse {
4385            then_expr,
4386            else_expr,
4387            ..
4388        } => {
4389            let then_ty = infer_expr_type(then_expr, field_types, helper_returns, binding_types);
4390            let else_ty = infer_expr_type(else_expr, field_types, helper_returns, binding_types);
4391            if then_ty == else_ty {
4392                then_ty
4393            } else {
4394                then_ty.or(else_ty)
4395            }
4396        }
4397        Expr::Not(_)
4398        | Expr::And(_)
4399        | Expr::Or(_)
4400        | Expr::Eq(_, _)
4401        | Expr::Neq(_, _)
4402        | Expr::Gt(_, _)
4403        | Expr::Gte(_, _)
4404        | Expr::Lt(_, _)
4405        | Expr::Lte(_, _)
4406        | Expr::Contains { .. }
4407        | Expr::MapContainsKey { .. }
4408        | Expr::SeqStartsWith { .. }
4409        | Expr::Quantified { .. } => Some(TypeRef::Bool),
4410        Expr::Add(_, _) | Expr::Sub(_, _) | Expr::Len(_) | Expr::Count { .. } => Some(TypeRef::U64),
4411        Expr::SeqElements(inner) => {
4412            match infer_expr_type(inner, field_types, helper_returns, binding_types) {
4413                Some(TypeRef::Seq(inner_ty)) => Some(TypeRef::Set(inner_ty)),
4414                _ => None,
4415            }
4416        }
4417        Expr::Head(inner) => {
4418            match infer_expr_type(inner, field_types, helper_returns, binding_types) {
4419                Some(TypeRef::Seq(inner_ty)) => Some(*inner_ty),
4420                _ => None,
4421            }
4422        }
4423        Expr::MapKeys(inner) => {
4424            match infer_expr_type(inner, field_types, helper_returns, binding_types) {
4425                Some(TypeRef::Map(key_ty, _)) => Some(TypeRef::Set(key_ty)),
4426                _ => None,
4427            }
4428        }
4429        Expr::MapGet { map, .. } | Expr::MapValue { map, .. } => {
4430            match infer_expr_type(map, field_types, helper_returns, binding_types) {
4431                Some(TypeRef::Map(_, value_ty)) => Some(*value_ty),
4432                _ => None,
4433            }
4434        }
4435        Expr::MapLiteral(entries) => entries.first().and_then(|(key, value)| {
4436            let key_ty = infer_expr_type(key, field_types, helper_returns, binding_types)?;
4437            let value_ty = infer_expr_type(value, field_types, helper_returns, binding_types)?;
4438            Some(TypeRef::Map(Box::new(key_ty), Box::new(value_ty)))
4439        }),
4440        Expr::Some(inner) => infer_expr_type(inner, field_types, helper_returns, binding_types)
4441            .map(|inner_ty| TypeRef::Option(Box::new(inner_ty))),
4442        Expr::Call { helper, .. } if helper == "mob_machine_step_status_from_frame_node_status" => {
4443            meerkat_machine_schema::identity::EnumTypeId::parse("StepRunStatus")
4444                .ok()
4445                .map(TypeRef::Enum)
4446        }
4447        Expr::Call { helper, args } if helper == "session_document_instruction_slot_after_set" => {
4448            args.first().and_then(|current| {
4449                infer_expr_type(current, field_types, helper_returns, binding_types)
4450            })
4451        }
4452        Expr::Call { helper, .. } if helper == "session_document_instruction_active_bytes" => {
4453            Some(TypeRef::U64)
4454        }
4455        // The Active entries of a slot map: the type of the map it filters.
4456        Expr::Call { helper, args } if helper == "session_document_instruction_active_slots" => {
4457            args.get(1).and_then(|values| {
4458                infer_expr_type(values, field_types, helper_returns, binding_types)
4459            })
4460        }
4461        // The retired count per activation key: the type of the row counts.
4462        Expr::Call { helper, args } if helper == "session_document_activation_retired_after" => {
4463            args.first()
4464                .and_then(|rows| infer_expr_type(rows, field_types, helper_returns, binding_types))
4465        }
4466        Expr::Call { helper, .. } if helper == "runtime_delivery_recipient_outcomes_after_set" => {
4467            Some(TypeRef::Map(
4468                Box::new(TypeRef::String),
4469                Box::new(TypeRef::Enum(
4470                    meerkat_machine_schema::identity::EnumTypeId::parse("DeliveryRecipientOutcome")
4471                        .ok()?,
4472                )),
4473            ))
4474        }
4475        Expr::Call { helper, .. } if helper == "mob_machine_run_step_status_after_set" => {
4476            Some(TypeRef::Map(
4477                Box::new(TypeRef::Named(
4478                    meerkat_machine_schema::identity::NamedTypeId::parse("RunId").ok()?,
4479                )),
4480                Box::new(TypeRef::Map(
4481                    Box::new(TypeRef::Named(
4482                        meerkat_machine_schema::identity::NamedTypeId::parse("StepId").ok()?,
4483                    )),
4484                    Box::new(TypeRef::Option(Box::new(TypeRef::Enum(
4485                        meerkat_machine_schema::identity::EnumTypeId::parse("StepRunStatus")
4486                            .ok()?,
4487                    )))),
4488                )),
4489            ))
4490        }
4491        Expr::Call { helper, .. }
4492            if helper == "mob_machine_run_step_status_after_cancel_unfinished" =>
4493        {
4494            Some(TypeRef::Map(
4495                Box::new(TypeRef::Named(
4496                    meerkat_machine_schema::identity::NamedTypeId::parse("RunId").ok()?,
4497                )),
4498                Box::new(TypeRef::Map(
4499                    Box::new(TypeRef::Named(
4500                        meerkat_machine_schema::identity::NamedTypeId::parse("StepId").ok()?,
4501                    )),
4502                    Box::new(TypeRef::Option(Box::new(TypeRef::Enum(
4503                        meerkat_machine_schema::identity::EnumTypeId::parse("StepRunStatus")
4504                            .ok()?,
4505                    )))),
4506                )),
4507            ))
4508        }
4509        Expr::Call { helper, .. } if helper == "mob_machine_run_step_bool_after_set" => {
4510            Some(TypeRef::Map(
4511                Box::new(TypeRef::Named(
4512                    meerkat_machine_schema::identity::NamedTypeId::parse("RunId").ok()?,
4513                )),
4514                Box::new(TypeRef::Map(
4515                    Box::new(TypeRef::Named(
4516                        meerkat_machine_schema::identity::NamedTypeId::parse("StepId").ok()?,
4517                    )),
4518                    Box::new(TypeRef::Bool),
4519                )),
4520            ))
4521        }
4522        Expr::Call { helper, .. }
4523            if helper == "mob_machine_run_step_condition_result_after_set" =>
4524        {
4525            Some(TypeRef::Map(
4526                Box::new(TypeRef::Named(
4527                    meerkat_machine_schema::identity::NamedTypeId::parse("RunId").ok()?,
4528                )),
4529                Box::new(TypeRef::Map(
4530                    Box::new(TypeRef::Named(
4531                        meerkat_machine_schema::identity::NamedTypeId::parse("StepId").ok()?,
4532                    )),
4533                    Box::new(TypeRef::Option(Box::new(TypeRef::Bool))),
4534                )),
4535            ))
4536        }
4537        Expr::Call { helper, .. }
4538            if helper == "mob_machine_run_step_u64_after_set"
4539                || helper == "mob_machine_run_step_u64_after_increment" =>
4540        {
4541            Some(TypeRef::Map(
4542                Box::new(TypeRef::Named(
4543                    meerkat_machine_schema::identity::NamedTypeId::parse("RunId").ok()?,
4544                )),
4545                Box::new(TypeRef::Map(
4546                    Box::new(TypeRef::Named(
4547                        meerkat_machine_schema::identity::NamedTypeId::parse("StepId").ok()?,
4548                    )),
4549                    Box::new(TypeRef::U64),
4550                )),
4551            ))
4552        }
4553        Expr::Call { helper, .. } if helper == "mob_machine_run_retry_count_after_increment" => {
4554            Some(TypeRef::Map(
4555                Box::new(TypeRef::Named(
4556                    meerkat_machine_schema::identity::NamedTypeId::parse("RunId").ok()?,
4557                )),
4558                Box::new(TypeRef::Map(
4559                    Box::new(TypeRef::String),
4560                    Box::new(TypeRef::U64),
4561                )),
4562            ))
4563        }
4564        Expr::Call { helper, .. } if helper == "mob_machine_frame_node_bool_after_set" => {
4565            Some(TypeRef::Map(
4566                Box::new(TypeRef::Named(
4567                    meerkat_machine_schema::identity::NamedTypeId::parse("FrameId").ok()?,
4568                )),
4569                Box::new(TypeRef::Map(
4570                    Box::new(TypeRef::Named(
4571                        meerkat_machine_schema::identity::NamedTypeId::parse("FlowNodeId").ok()?,
4572                    )),
4573                    Box::new(TypeRef::Bool),
4574                )),
4575            ))
4576        }
4577        Expr::Call { helper, .. } => helper_returns.get(helper).cloned(),
4578        Expr::SeqLiteral(items) => items.first().and_then(|item| {
4579            infer_expr_type(item, field_types, helper_returns, binding_types)
4580                .map(|inner_ty| TypeRef::Seq(Box::new(inner_ty)))
4581        }),
4582        Expr::EmptySet => None,
4583        Expr::EmptyMap => None,
4584    }
4585}
4586
4587fn default_sample_cardinality(deep: bool) -> usize {
4588    if deep { 2 } else { 1 }
4589}
4590
4591fn type_sample_bucket(ty: &TypeRef) -> Option<String> {
4592    match ty {
4593        TypeRef::String => Some("String".into()),
4594        TypeRef::Named(name) => Some(name.as_str().to_owned()),
4595        TypeRef::Enum(name) => Some(name.as_str().to_owned()),
4596        _ => None,
4597    }
4598}
4599
4600fn collected_sample_literals(
4601    bucket: &str,
4602    sample_cardinality: usize,
4603    named_samples: &BTreeMap<String, BTreeSet<String>>,
4604) -> Option<Vec<String>> {
4605    let samples = named_samples.get(bucket)?;
4606    let limit = sample_cardinality.max(1);
4607    let rendered = samples
4608        .iter()
4609        .take(limit)
4610        .map(tla_string)
4611        .collect::<Vec<_>>();
4612    (!rendered.is_empty()).then_some(rendered)
4613}
4614
4615fn generic_string_samples(sample_cardinality: usize) -> Vec<String> {
4616    if sample_cardinality > 1 {
4617        vec!["alpha".into(), "beta".into()]
4618    } else {
4619        vec!["alpha".into()]
4620    }
4621}
4622
4623fn collected_string_samples(
4624    sample_cardinality: usize,
4625    named_samples: &BTreeMap<String, BTreeSet<String>>,
4626    include_named_samples: bool,
4627) -> Vec<String> {
4628    let mut values = generic_string_samples(sample_cardinality);
4629    if include_named_samples && let Some(samples) = named_samples.get("String") {
4630        for sample in samples {
4631            if !values.iter().any(|existing| existing == sample) {
4632                values.push(sample.clone());
4633            }
4634        }
4635    }
4636    values
4637}
4638
4639fn render_default_domain_assignment(
4640    ty: &TypeRef,
4641    sample_cardinality: usize,
4642    named_samples: &BTreeMap<String, BTreeSet<String>>,
4643    named_bindings: &BTreeMap<String, meerkat_machine_schema::RustTypeAtom>,
4644    include_string_samples: bool,
4645) -> String {
4646    match ty {
4647        TypeRef::Bool => "{TRUE, FALSE}".into(),
4648        TypeRef::U32 | TypeRef::U64 => {
4649            if sample_cardinality > 1 {
4650                "{0, 1, 2}".into()
4651            } else {
4652                // CI uses {1} to avoid state explosion from zero-as-unlimited
4653                // semantics in scheduler guards (Or(max==0, count<max)).
4654                // Counter fields that start at 0 get it via Init, not NatValues.
4655                // Deep uses {0, 1} to cover the full range.
4656                "{1}".into()
4657            }
4658        }
4659        TypeRef::String if sample_cardinality == 0 => "{}".into(),
4660        TypeRef::String => format!(
4661            "{{{}}}",
4662            collected_string_samples(sample_cardinality, named_samples, include_string_samples)
4663                .into_iter()
4664                .map(|sample| tla_string(&sample))
4665                .collect::<Vec<_>>()
4666                .join(", ")
4667        ),
4668        TypeRef::Named(name) => render_named_type_domain_assignment(
4669            name.as_str(),
4670            sample_cardinality,
4671            named_samples,
4672            named_bindings,
4673        ),
4674        TypeRef::Enum(name) => render_enum_type_domain_assignment(
4675            name.as_str(),
4676            sample_cardinality,
4677            named_samples,
4678            named_bindings,
4679        ),
4680        TypeRef::Seq(inner) => {
4681            let samples = sample_values(
4682                inner,
4683                sample_cardinality,
4684                named_samples,
4685                named_bindings,
4686                include_string_samples,
4687            );
4688            if samples.len() >= 2 {
4689                format!(
4690                    "{{<<>>, <<{}>>, <<{}, {}>>}}",
4691                    samples[0], samples[0], samples[1]
4692                )
4693            } else if let Some(sample) = samples.first() {
4694                format!("{{<<>>, <<{}>>}}", sample)
4695            } else {
4696                "{<<>>}".into()
4697            }
4698        }
4699        TypeRef::Set(inner) => {
4700            let samples = sample_values(
4701                inner,
4702                sample_cardinality,
4703                named_samples,
4704                named_bindings,
4705                include_string_samples,
4706            );
4707            if samples.len() >= 2 {
4708                format!(
4709                    "{{{{}}, {{{}}}, {{{}, {}}}}}",
4710                    samples[0], samples[0], samples[1]
4711                )
4712            } else if let Some(sample) = samples.first() {
4713                format!("{{{{}}, {{{}}}}}", sample)
4714            } else {
4715                "{{}}".into()
4716            }
4717        }
4718        TypeRef::Option(inner) => {
4719            let samples = sample_values(
4720                inner,
4721                sample_cardinality,
4722                named_samples,
4723                named_bindings,
4724                include_string_samples,
4725            )
4726            .into_iter()
4727            .map(|sample| format!("[tag |-> {}, value |-> {}]", tla_string("some"), sample))
4728            .collect::<Vec<_>>();
4729            if samples.is_empty() {
4730                format!(
4731                    "{{[tag |-> {}, value |-> {}]}}",
4732                    tla_string("none"),
4733                    tla_string("none")
4734                )
4735            } else {
4736                format!(
4737                    "{{[tag |-> {}, value |-> {}], {}}}",
4738                    tla_string("none"),
4739                    tla_string("none"),
4740                    samples.join(", ")
4741                )
4742            }
4743        }
4744        TypeRef::Map(_, _) => "{}".into(),
4745    }
4746}
4747
4748fn render_named_type_domain_assignment(
4749    name: impl AsRef<str>,
4750    sample_cardinality: usize,
4751    named_samples: &BTreeMap<String, BTreeSet<String>>,
4752    named_bindings: &BTreeMap<String, meerkat_machine_schema::RustTypeAtom>,
4753) -> String {
4754    use meerkat_machine_schema::RustTypeAtom;
4755
4756    let name = name.as_ref();
4757    if name == "OperationSource" {
4758        return format!(
4759            "{{{}}}",
4760            operation_source_samples(sample_cardinality).join(", ")
4761        );
4762    }
4763    match require_named_binding(named_bindings, name) {
4764        RustTypeAtom::U64 | RustTypeAtom::U32 | RustTypeAtom::U16 | RustTypeAtom::U8 => {
4765            if sample_cardinality > 1 {
4766                "{1, 2}".into()
4767            } else {
4768                "{1}".into()
4769            }
4770        }
4771        RustTypeAtom::Bool => "{TRUE, FALSE}".into(),
4772        RustTypeAtom::StringEnum { variants } => {
4773            format!(
4774                "{{{}}}",
4775                string_enum_variant_samples(name, variants).join(", ")
4776            )
4777        }
4778        RustTypeAtom::TypePathEnum {
4779            unit_variants,
4780            structural_variants,
4781            ..
4782        } => format!(
4783            "{{{}}}",
4784            type_path_enum_variant_samples(
4785                unit_variants,
4786                structural_variants,
4787                sample_cardinality,
4788                named_samples,
4789                named_bindings,
4790            )
4791            .join(", ")
4792        ),
4793        RustTypeAtom::TypePathFieldPresenceSet { fields, .. } => format!(
4794            "{{{}}}",
4795            field_presence_set_samples(fields, sample_cardinality).join(", ")
4796        ),
4797        RustTypeAtom::TypePathStruct { fields, .. } => format!(
4798            "{{{}}}",
4799            type_path_struct_samples(fields, sample_cardinality, named_samples, named_bindings)
4800                .join(", ")
4801        ),
4802        RustTypeAtom::String | RustTypeAtom::TypePath(_) => {
4803            if sample_cardinality == 0 {
4804                return "{}".into();
4805            }
4806
4807            if let Some(rendered) =
4808                collected_sample_literals(name, sample_cardinality, named_samples)
4809            {
4810                return format!("{{{}}}", rendered.join(", "));
4811            }
4812
4813            let values = (1..=sample_cardinality.max(1))
4814                .map(|idx| tla_string(format!("{}_{}", tla_ident(name).to_lowercase(), idx)))
4815                .collect::<Vec<_>>()
4816                .join(", ");
4817            format!("{{{values}}}")
4818        }
4819    }
4820}
4821
4822#[allow(clippy::panic)]
4823fn render_enum_type_domain_assignment(
4824    name: impl AsRef<str>,
4825    sample_cardinality: usize,
4826    named_samples: &BTreeMap<String, BTreeSet<String>>,
4827    named_bindings: &BTreeMap<String, meerkat_machine_schema::RustTypeAtom>,
4828) -> String {
4829    use meerkat_machine_schema::RustTypeAtom;
4830
4831    let name = name.as_ref();
4832    match require_named_binding(named_bindings, name) {
4833        RustTypeAtom::StringEnum { variants } => {
4834            format!(
4835                "{{{}}}",
4836                string_enum_variant_samples(name, variants).join(", ")
4837            )
4838        }
4839        RustTypeAtom::TypePathEnum {
4840            unit_variants,
4841            structural_variants,
4842            ..
4843        } => format!(
4844            "{{{}}}",
4845            type_path_enum_variant_samples(
4846                unit_variants,
4847                structural_variants,
4848                sample_cardinality,
4849                named_samples,
4850                named_bindings,
4851            )
4852            .join(", ")
4853        ),
4854        other => {
4855            panic!(
4856                "generated enum domain `{name}` requires StringEnum or TypePathEnum binding, found {other:?}"
4857            );
4858        }
4859    }
4860}
4861
4862fn sample_values(
4863    ty: &TypeRef,
4864    sample_cardinality: usize,
4865    named_samples: &BTreeMap<String, BTreeSet<String>>,
4866    named_bindings: &BTreeMap<String, meerkat_machine_schema::RustTypeAtom>,
4867    include_string_samples: bool,
4868) -> Vec<String> {
4869    match ty {
4870        TypeRef::Bool => vec!["TRUE".into(), "FALSE".into()],
4871        TypeRef::U32 | TypeRef::U64 => {
4872            if sample_cardinality > 1 {
4873                vec!["1".into(), "2".into()]
4874            } else {
4875                vec!["1".into()]
4876            }
4877        }
4878        TypeRef::String if sample_cardinality == 0 => Vec::new(),
4879        TypeRef::String => {
4880            collected_string_samples(sample_cardinality, named_samples, include_string_samples)
4881                .into_iter()
4882                .map(|sample| tla_string(&sample))
4883                .collect()
4884        }
4885        TypeRef::Named(name) if named_type_uses_nat_domain(named_bindings, name.as_str()) => {
4886            if sample_cardinality > 1 {
4887                vec!["1".into(), "2".into()]
4888            } else {
4889                vec!["1".into()]
4890            }
4891        }
4892        TypeRef::Named(name) => {
4893            let name = name.as_str();
4894            sample_values_for_named_type(name, sample_cardinality, named_samples, named_bindings)
4895        }
4896        TypeRef::Enum(name) => {
4897            let name = name.as_str();
4898            sample_values_for_enum_type(name, sample_cardinality, named_samples, named_bindings)
4899        }
4900        TypeRef::Option(inner) => {
4901            let mut values = vec![format!(
4902                "[tag |-> {}, value |-> {}]",
4903                tla_string("none"),
4904                tla_string("none")
4905            )];
4906            values.extend(
4907                sample_values(
4908                    inner,
4909                    sample_cardinality,
4910                    named_samples,
4911                    named_bindings,
4912                    include_string_samples,
4913                )
4914                .into_iter()
4915                .map(|sample| format!("[tag |-> {}, value |-> {}]", tla_string("some"), sample)),
4916            );
4917            values
4918        }
4919        TypeRef::Seq(inner) => sample_values(
4920            inner,
4921            sample_cardinality,
4922            named_samples,
4923            named_bindings,
4924            include_string_samples,
4925        ),
4926        TypeRef::Set(inner) => sample_values(
4927            inner,
4928            sample_cardinality,
4929            named_samples,
4930            named_bindings,
4931            include_string_samples,
4932        ),
4933        TypeRef::Map(_, _) => vec![],
4934    }
4935}
4936
4937fn sample_values_for_named_type(
4938    name: &str,
4939    sample_cardinality: usize,
4940    named_samples: &BTreeMap<String, BTreeSet<String>>,
4941    bindings: &BTreeMap<String, meerkat_machine_schema::RustTypeAtom>,
4942) -> Vec<String> {
4943    use meerkat_machine_schema::RustTypeAtom;
4944
4945    if name == "OperationSource" {
4946        return operation_source_samples(sample_cardinality);
4947    }
4948    match require_named_binding(bindings, name) {
4949        RustTypeAtom::U64 | RustTypeAtom::U32 | RustTypeAtom::U16 | RustTypeAtom::U8 => {
4950            if sample_cardinality > 1 {
4951                vec!["1".into(), "2".into()]
4952            } else {
4953                vec!["1".into()]
4954            }
4955        }
4956        RustTypeAtom::Bool => vec!["TRUE".into(), "FALSE".into()],
4957        RustTypeAtom::StringEnum { variants } => string_enum_variant_samples(name, variants),
4958        RustTypeAtom::TypePathEnum {
4959            unit_variants,
4960            structural_variants,
4961            ..
4962        } => type_path_enum_variant_samples(
4963            unit_variants,
4964            structural_variants,
4965            sample_cardinality,
4966            named_samples,
4967            bindings,
4968        ),
4969        RustTypeAtom::TypePathFieldPresenceSet { fields, .. } => {
4970            field_presence_set_samples(fields, sample_cardinality)
4971        }
4972        RustTypeAtom::TypePathStruct { fields, .. } => {
4973            type_path_struct_samples(fields, sample_cardinality, named_samples, bindings)
4974        }
4975        RustTypeAtom::String | RustTypeAtom::TypePath(_) => {
4976            if sample_cardinality == 0 {
4977                return Vec::new();
4978            }
4979            if let Some(samples) = named_samples.get(name) {
4980                let limit = sample_cardinality.max(1);
4981                let rendered = samples
4982                    .iter()
4983                    .take(limit)
4984                    .map(tla_string)
4985                    .collect::<Vec<_>>();
4986                if !rendered.is_empty() {
4987                    return rendered;
4988                }
4989            }
4990            (1..=sample_cardinality.max(1))
4991                .map(|idx| tla_string(format!("{}_{}", tla_ident(name).to_lowercase(), idx)))
4992                .collect()
4993        }
4994    }
4995}
4996
4997#[allow(clippy::panic)]
4998fn sample_values_for_enum_type(
4999    name: &str,
5000    sample_cardinality: usize,
5001    named_samples: &BTreeMap<String, BTreeSet<String>>,
5002    bindings: &BTreeMap<String, meerkat_machine_schema::RustTypeAtom>,
5003) -> Vec<String> {
5004    use meerkat_machine_schema::RustTypeAtom;
5005
5006    match require_named_binding(bindings, name) {
5007        RustTypeAtom::StringEnum { variants } => string_enum_variant_samples(name, variants),
5008        RustTypeAtom::TypePathEnum {
5009            unit_variants,
5010            structural_variants,
5011            ..
5012        } => type_path_enum_variant_samples(
5013            unit_variants,
5014            structural_variants,
5015            sample_cardinality,
5016            named_samples,
5017            bindings,
5018        ),
5019        other => {
5020            panic!(
5021                "generated enum domain `{name}` requires StringEnum or TypePathEnum binding, found {other:?}"
5022            );
5023        }
5024    }
5025}
5026
5027#[allow(clippy::panic)]
5028fn require_named_binding<'a>(
5029    bindings: &'a BTreeMap<String, meerkat_machine_schema::RustTypeAtom>,
5030    name: &str,
5031) -> &'a meerkat_machine_schema::RustTypeAtom {
5032    bindings
5033        .get(name)
5034        .unwrap_or_else(|| panic!("missing NamedTypeBinding for generated domain `{name}`"))
5035}
5036
5037fn string_enum_variant_samples(
5038    name: &str,
5039    variants: &[meerkat_machine_schema::identity::EnumVariantId],
5040) -> Vec<String> {
5041    variants
5042        .iter()
5043        .map(|variant| tla_string(string_enum_wire_label(name, variant.as_str())))
5044        .collect()
5045}
5046
5047fn render_named_variant_value(
5048    enum_name: &str,
5049    variant: &str,
5050    named_bindings: &BTreeMap<String, meerkat_machine_schema::RustTypeAtom>,
5051) -> String {
5052    let label = tla_string(string_enum_wire_label(enum_name, variant));
5053    if named_bindings
5054        .get(enum_name)
5055        .is_some_and(CfgRecordRendering::renders_cfg_hostile_record)
5056    {
5057        format!("[tag |-> {label}]")
5058    } else {
5059        label
5060    }
5061}
5062
5063fn type_path_enum_variant_samples(
5064    unit_variants: &[meerkat_machine_schema::identity::EnumVariantId],
5065    structural_variants: &[TypePathEnumStructuralVariant],
5066    sample_cardinality: usize,
5067    named_samples: &BTreeMap<String, BTreeSet<String>>,
5068    named_bindings: &BTreeMap<String, meerkat_machine_schema::RustTypeAtom>,
5069) -> Vec<String> {
5070    let unit_variants_are_records = !structural_variants.is_empty();
5071    let mut samples = unit_variants
5072        .iter()
5073        .map(|variant| {
5074            let tag = tla_string(variant.as_str());
5075            if unit_variants_are_records {
5076                format!("[tag |-> {tag}]")
5077            } else {
5078                tag
5079            }
5080        })
5081        .collect::<Vec<_>>();
5082    if sample_cardinality > 0 {
5083        samples.extend(structural_variants.iter().flat_map(|variant| {
5084            render_type_path_enum_structural_samples(
5085                variant,
5086                sample_cardinality,
5087                named_samples,
5088                named_bindings,
5089            )
5090        }));
5091    }
5092    samples
5093}
5094
5095fn field_presence_set_samples(
5096    fields: &[meerkat_machine_schema::identity::FieldId],
5097    sample_cardinality: usize,
5098) -> Vec<String> {
5099    if sample_cardinality == 0 {
5100        return Vec::new();
5101    }
5102    let limit = sample_cardinality.max(1);
5103    let rendered_fields = fields
5104        .iter()
5105        .map(|field| tla_string(field.as_str()))
5106        .collect::<Vec<_>>();
5107    let mut samples = rendered_fields
5108        .iter()
5109        .take(limit)
5110        .map(|field| format!("{{{field}}}"))
5111        .collect::<Vec<_>>();
5112    if limit > rendered_fields.len() && rendered_fields.len() >= 2 {
5113        samples.push(format!("{{{}}}", rendered_fields.join(", ")));
5114    }
5115    samples
5116}
5117
5118fn operation_source_samples(sample_cardinality: usize) -> Vec<String> {
5119    let mut samples = vec![
5120        format!(
5121            "[kind |-> {}, session_id |-> Some({}), peer_id |-> None, address |-> None]",
5122            tla_string("SessionChild"),
5123            tla_string("sessionid_1")
5124        ),
5125        format!(
5126            "[kind |-> {}, session_id |-> None, peer_id |-> Some({}), address |-> Some({})]",
5127            tla_string("BackendPeer"),
5128            tla_string("peerid_1"),
5129            tla_string("peeraddress_1")
5130        ),
5131    ];
5132    if sample_cardinality > 2 {
5133        samples.push(format!(
5134            "[kind |-> {}, session_id |-> Some({}), peer_id |-> None, address |-> None]",
5135            tla_string("SessionChild"),
5136            tla_string("sessionid_2")
5137        ));
5138    }
5139    samples
5140}
5141
5142fn type_path_struct_samples(
5143    fields: &[TypePathStructField],
5144    sample_cardinality: usize,
5145    named_samples: &BTreeMap<String, BTreeSet<String>>,
5146    bindings: &BTreeMap<String, meerkat_machine_schema::RustTypeAtom>,
5147) -> Vec<String> {
5148    if sample_cardinality == 0 {
5149        return Vec::new();
5150    }
5151    if fields.is_empty() {
5152        return vec!["[]".to_owned()];
5153    }
5154
5155    let limit = sample_cardinality.max(1);
5156    let mut field_values = Vec::new();
5157    for field in fields {
5158        let values =
5159            type_path_struct_field_samples(field, sample_cardinality, named_samples, bindings);
5160        if values.is_empty() {
5161            return Vec::new();
5162        }
5163        field_values.push((field.name.as_str().to_owned(), values));
5164    }
5165
5166    (0..limit)
5167        .map(|idx| {
5168            let fields = field_values
5169                .iter()
5170                .map(|(name, values)| {
5171                    let value = &values[idx % values.len()];
5172                    format!("{name} |-> {value}")
5173                })
5174                .collect::<Vec<_>>();
5175            format!("[{}]", fields.join(", "))
5176        })
5177        .collect()
5178}
5179
5180fn type_path_struct_field_samples(
5181    field: &TypePathStructField,
5182    sample_cardinality: usize,
5183    named_samples: &BTreeMap<String, BTreeSet<String>>,
5184    bindings: &BTreeMap<String, meerkat_machine_schema::RustTypeAtom>,
5185) -> Vec<String> {
5186    match &field.atom {
5187        TypePathStructFieldAtom::String => {
5188            if sample_cardinality == 0 {
5189                Vec::new()
5190            } else {
5191                generic_string_samples(sample_cardinality)
5192                    .into_iter()
5193                    .map(tla_string)
5194                    .collect()
5195            }
5196        }
5197        TypePathStructFieldAtom::Named(name) => {
5198            sample_values_for_named_type(name.as_str(), sample_cardinality, named_samples, bindings)
5199        }
5200        TypePathStructFieldAtom::OptionalNamed(name) => {
5201            let mut values = vec!["None".to_owned()];
5202            values.extend(
5203                sample_values_for_named_type(
5204                    name.as_str(),
5205                    sample_cardinality,
5206                    named_samples,
5207                    bindings,
5208                )
5209                .into_iter()
5210                .map(|value| format!("Some({value})")),
5211            );
5212            values
5213        }
5214    }
5215}
5216
5217fn render_type_path_enum_structural_samples(
5218    variant: &TypePathEnumStructuralVariant,
5219    sample_cardinality: usize,
5220    named_samples: &BTreeMap<String, BTreeSet<String>>,
5221    named_bindings: &BTreeMap<String, meerkat_machine_schema::RustTypeAtom>,
5222) -> Vec<String> {
5223    let mut samples = vec![vec![format!(
5224        "tag |-> {}",
5225        tla_string(variant.variant.as_str())
5226    )]];
5227    for field in &variant.fields {
5228        let values = match &field.atom {
5229            TypePathEnumPayloadAtom::StringSet => string_set_payload_samples(sample_cardinality),
5230            TypePathEnumPayloadAtom::NamedSet(type_name) => named_set_payload_samples(
5231                type_name.as_str(),
5232                sample_cardinality,
5233                named_samples,
5234                named_bindings,
5235            ),
5236            TypePathEnumPayloadAtom::String => {
5237                if sample_cardinality == 0 {
5238                    Vec::new()
5239                } else {
5240                    generic_string_samples(sample_cardinality)
5241                        .into_iter()
5242                        .map(tla_string)
5243                        .collect()
5244                }
5245            }
5246            TypePathEnumPayloadAtom::OptionalString => {
5247                let mut values = vec![format!(
5248                    "[tag |-> {}, value |-> {}]",
5249                    tla_string("none"),
5250                    tla_string("none")
5251                )];
5252                if sample_cardinality > 0 {
5253                    values.extend(generic_string_samples(sample_cardinality).into_iter().map(
5254                        |sample| {
5255                            format!(
5256                                "[tag |-> {}, value |-> {}]",
5257                                tla_string("some"),
5258                                tla_string(&sample)
5259                            )
5260                        },
5261                    ));
5262                }
5263                values
5264            }
5265            TypePathEnumPayloadAtom::Named(type_name) => sample_values_for_named_type(
5266                type_name.as_str(),
5267                sample_cardinality,
5268                named_samples,
5269                named_bindings,
5270            ),
5271        };
5272        let mut next_samples = Vec::new();
5273        for sample in &samples {
5274            for value in &values {
5275                let mut next = sample.clone();
5276                next.push(format!("{} |-> {value}", field.name));
5277                next_samples.push(next);
5278            }
5279        }
5280        samples = next_samples;
5281    }
5282    samples
5283        .into_iter()
5284        .map(|fields| format!("[{}]", fields.join(", ")))
5285        .collect()
5286}
5287
5288/// TLA sample sets for a structural enum payload carrying a finite set of
5289/// values from a named value domain. Mirrors [`string_set_payload_samples`]
5290/// shape (empty / one-member / two-member sets) over the named domain's
5291/// sample pool so payload sets stay aligned with catalog key domains.
5292fn named_set_payload_samples(
5293    type_name: &str,
5294    sample_cardinality: usize,
5295    named_samples: &BTreeMap<String, BTreeSet<String>>,
5296    named_bindings: &BTreeMap<String, meerkat_machine_schema::RustTypeAtom>,
5297) -> Vec<String> {
5298    let mut values = if sample_cardinality == 0 {
5299        Vec::new()
5300    } else {
5301        sample_values_for_named_type(type_name, sample_cardinality, named_samples, named_bindings)
5302    };
5303    // Pad the payload element pool with synthetic domain members up to the
5304    // requested cardinality so the deep model still covers differing
5305    // same-variant multi-member payloads when the collected named-sample
5306    // pool is smaller than the cardinality.
5307    let mut synthetic_idx = 0usize;
5308    while sample_cardinality > 0 && values.len() < sample_cardinality {
5309        synthetic_idx += 1;
5310        let synthetic = tla_string(format!(
5311            "{}_{synthetic_idx}",
5312            tla_ident(type_name).to_lowercase()
5313        ));
5314        if !values.contains(&synthetic) {
5315            values.push(synthetic);
5316        }
5317    }
5318    let mut samples = vec!["{}".to_owned()];
5319    if let Some(first) = values.first() {
5320        samples.push(format!("{{{first}}}"));
5321    }
5322    if values.len() >= 2 {
5323        samples.push(format!("{{{}, {}}}", values[0], values[1]));
5324    }
5325    samples
5326}
5327
5328fn string_set_payload_samples(sample_cardinality: usize) -> Vec<String> {
5329    let values = if sample_cardinality == 0 {
5330        Vec::new()
5331    } else {
5332        generic_string_samples(sample_cardinality)
5333            .into_iter()
5334            .map(tla_string)
5335            .collect::<Vec<_>>()
5336    };
5337    let mut samples = vec!["{}".to_owned()];
5338    if let Some(first) = values.first() {
5339        samples.push(format!("{{{first}}}"));
5340    }
5341    if values.len() >= 2 {
5342        samples.push(format!("{{{}, {}}}", values[0], values[1]));
5343    }
5344    samples
5345}
5346
5347fn string_enum_wire_label(name: &str, variant: &str) -> String {
5348    if name == meerkat_core::turn_execution_authority::ContentShape::SCHEMA_TYPE_NAME
5349        && let Some(shape) =
5350            meerkat_core::turn_execution_authority::ContentShape::from_schema_variant(variant)
5351    {
5352        return shape.as_str().to_owned();
5353    }
5354
5355    variant.to_owned()
5356}
5357
5358/// Consult the schema's named-type binding table to decide whether a
5359/// named type's TLA domain is `Nat` (numeric) rather than string-like.
5360///
5361/// A named type resolves to a `Nat` TLA domain when its Rust atom lowers
5362/// to an unsigned integer width — the TLA projection mirrors the Rust
5363/// atom. Schemas reach codegen only after validation, so every
5364/// referenced named type has a binding; an unbound name here is a
5365/// codegen invariant violation.
5366fn named_type_uses_nat_domain(
5367    bindings: &BTreeMap<String, meerkat_machine_schema::RustTypeAtom>,
5368    name: &str,
5369) -> bool {
5370    use meerkat_machine_schema::RustTypeAtom;
5371    matches!(
5372        bindings.get(name),
5373        Some(RustTypeAtom::U64 | RustTypeAtom::U32 | RustTypeAtom::U16 | RustTypeAtom::U8)
5374    )
5375}
5376
5377/// Collect the `NamedTypeId → RustTypeAtom` map for a single machine.
5378fn collect_machine_named_bindings(
5379    schema: &MachineSchema,
5380) -> BTreeMap<String, meerkat_machine_schema::RustTypeAtom> {
5381    assert_machine_named_bindings_match_canonical(schema);
5382    schema
5383        .named_types
5384        .iter()
5385        .map(|binding| (binding.name.as_str().to_owned(), binding.rust.clone()))
5386        .collect()
5387}
5388
5389/// A machine that shares a canonical machine's id must bind every canonical
5390/// struct named type, and bind each shared named type with the canonical
5391/// generated domain shape.
5392fn check_canonical_named_bindings(schema: &MachineSchema) -> Result<(), CompositionTlaError> {
5393    let Some(canonical) = canonical_machine_schemas()
5394        .into_iter()
5395        .find(|canonical| canonical.machine == schema.machine)
5396    else {
5397        return Ok(());
5398    };
5399    let mismatch = |named_type: &str, reason| CompositionTlaError::CanonicalNamedTypeMismatch {
5400        machine: schema.machine.as_str().to_owned(),
5401        named_type: named_type.to_owned(),
5402        reason,
5403    };
5404    for canonical_binding in canonical.named_types.iter().filter(|binding| {
5405        matches!(
5406            binding.rust,
5407            meerkat_machine_schema::RustTypeAtom::TypePathStruct { .. }
5408        )
5409    }) {
5410        if !schema
5411            .named_types
5412            .iter()
5413            .any(|binding| binding.name == canonical_binding.name)
5414        {
5415            return Err(mismatch(
5416                canonical_binding.name.as_str(),
5417                CanonicalNamedTypeMismatchKind::MissingStructBinding,
5418            ));
5419        }
5420    }
5421    for binding in &schema.named_types {
5422        let Some(canonical_binding) = canonical
5423            .named_types
5424            .iter()
5425            .find(|candidate| candidate.name == binding.name)
5426        else {
5427            continue;
5428        };
5429        if !canonical_binding
5430            .rust
5431            .has_same_composition_domain_shape(&binding.rust)
5432        {
5433            return Err(mismatch(
5434                binding.name.as_str(),
5435                CanonicalNamedTypeMismatchKind::DomainShape,
5436            ));
5437        }
5438    }
5439    Ok(())
5440}
5441
5442/// Internal invariant for the infallible renderers, whose callers pass
5443/// canonical machines; the public fallible entry points check first.
5444fn assert_machine_named_bindings_match_canonical(schema: &MachineSchema) {
5445    if let Err(CompositionTlaError::CanonicalNamedTypeMismatch {
5446        machine,
5447        named_type,
5448        reason,
5449    }) = check_canonical_named_bindings(schema)
5450    {
5451        assert!(
5452            reason != CanonicalNamedTypeMismatchKind::MissingStructBinding,
5453            "generated machine `{machine}` missing canonical named-type `{named_type}` binding"
5454        );
5455        assert!(
5456            reason != CanonicalNamedTypeMismatchKind::DomainShape,
5457            "generated machine `{machine}` named-type `{named_type}` binding must match canonical domain shape"
5458        );
5459    }
5460}
5461
5462/// Validate a caller-supplied machine catalog before rendering a composition
5463/// against it: every machine validates, ids are unique, no machine shadows a
5464/// canonical Meerkat machine with a different schema, the composition's
5465/// machines agree on shared named types, and the composition validates
5466/// against the catalog. The render paths behind this never panic on a
5467/// supplied catalog.
5468fn validate_supplied_catalog(
5469    schema: &CompositionSchema,
5470    machine_catalog: &[MachineSchema],
5471) -> Result<(), CompositionTlaError> {
5472    let canonical = canonical_machine_schemas();
5473    let mut seen = BTreeSet::new();
5474    for machine in machine_catalog {
5475        machine
5476            .validate()
5477            .map_err(|error| CompositionTlaError::InvalidSuppliedMachine {
5478                machine: machine.machine.as_str().to_owned(),
5479                error: error.to_string(),
5480            })?;
5481        if !seen.insert(machine.machine.as_str()) {
5482            return Err(CompositionTlaError::DuplicateSuppliedMachine {
5483                machine: machine.machine.as_str().to_owned(),
5484            });
5485        }
5486        if canonical
5487            .iter()
5488            .any(|candidate| candidate.machine == machine.machine && candidate != machine)
5489        {
5490            return Err(CompositionTlaError::ShadowsCanonicalMachine {
5491                machine: machine.machine.as_str().to_owned(),
5492            });
5493        }
5494    }
5495    let mut merged: BTreeMap<&str, &meerkat_machine_schema::RustTypeAtom> = BTreeMap::new();
5496    for instance in &schema.machines {
5497        let Some(machine) = machine_catalog
5498            .iter()
5499            .find(|machine| machine.machine.as_str() == instance.machine_name.as_str())
5500        else {
5501            continue;
5502        };
5503        for binding in &machine.named_types {
5504            match merged.get(binding.name.as_str()) {
5505                Some(existing) if !existing.has_same_composition_domain_shape(&binding.rust) => {
5506                    return Err(CompositionTlaError::DivergentNamedTypeBinding {
5507                        composition: schema.name.as_str().to_owned(),
5508                        named_type: binding.name.as_str().to_owned(),
5509                    });
5510                }
5511                Some(_) => {}
5512                None => {
5513                    merged.insert(binding.name.as_str(), &binding.rust);
5514                }
5515            }
5516        }
5517    }
5518    let machines = machine_catalog.iter().collect::<Vec<_>>();
5519    schema.validate_against(&machines).map_err(|error| {
5520        CompositionTlaError::InvalidCompositionForCatalog {
5521            composition: schema.name.as_str().to_owned(),
5522            error: error.to_string(),
5523        }
5524    })
5525}
5526
5527/// Merge every machine's named-type bindings into one map for
5528/// composition-level TLA rendering. Duplicate names must agree on generated
5529/// domain shape across machines (validation enforces this by construction).
5530fn collect_composition_named_bindings<'a>(
5531    machines_by_instance: impl IntoIterator<Item = &'a MachineSchema>,
5532) -> BTreeMap<String, meerkat_machine_schema::RustTypeAtom> {
5533    let mut merged: BTreeMap<String, meerkat_machine_schema::RustTypeAtom> = BTreeMap::new();
5534    for machine in machines_by_instance {
5535        assert_machine_named_bindings_match_canonical(machine);
5536        for binding in &machine.named_types {
5537            let slug = binding.name.as_str().to_owned();
5538            if let Some(existing) = merged.get(&slug) {
5539                assert!(
5540                    existing.has_same_composition_domain_shape(&binding.rust),
5541                    "composition named-type `{slug}` binding must agree across machine schemas"
5542                );
5543            } else {
5544                merged.insert(slug, binding.rust.clone());
5545            }
5546        }
5547    }
5548    merged
5549}
5550
5551#[cfg(test)]
5552mod tests {
5553    use super::*;
5554
5555    /// A populated witness map literal renders as a TLC function in both the
5556    /// witness-literal path and the expression path, never as the `None`
5557    /// fallback (#1811).
5558    #[test]
5559    fn a_witness_map_literal_renders_as_a_tlc_function() {
5560        let machines = meerkat_machine_schema::canonical_machine_schemas();
5561        let compositions = meerkat_machine_schema::canonical_composition_schemas();
5562        let composition = compositions
5563            .iter()
5564            .find(|candidate| candidate.name.as_str() == "job_runtime_delivery")
5565            .expect("job_runtime_delivery composition");
5566        let compiler =
5567            CompositionTlaCompiler::new(composition, &machines).expect("composition compiler");
5568        let literal = Expr::MapLiteral(vec![
5569            (
5570                Expr::String("alpha".into()),
5571                Expr::String("member-a".into()),
5572            ),
5573            (Expr::String("beta".into()), Expr::U64(2)),
5574        ]);
5575        assert_eq!(
5576            compiler.render_literal_expr(&literal),
5577            "(\"alpha\" :> \"member-a\" @@ \"beta\" :> 2)"
5578        );
5579        assert_eq!(
5580            crate::render::render_expr_for_tests(&literal),
5581            "(\"alpha\" :> \"member-a\" @@ \"beta\" :> 2)"
5582        );
5583    }
5584
5585    /// Every quantified Next disjunct leads with its transition's source-phase
5586    /// guard, so TLC rejects the whole disjunct in other phases instead of
5587    /// enumerating each parameter tuple per state (#1499 measured 464 s
5588    /// unhoisted against 158 s hoisted on work_graph_lifecycle ci, identical
5589    /// state counts).
5590    #[test]
5591    fn quantified_next_disjuncts_lead_with_the_source_phase_guard() {
5592        let model =
5593            render_machine_semantic_model(&meerkat_machine()).expect("render MeerkatMachine model");
5594        let next = model
5595            .split_once("\nNext ==\n")
5596            .map(|(_, rest)| rest.split("\n\n").next().unwrap_or(""))
5597            .expect("Next block");
5598        let quantified = next
5599            .lines()
5600            .filter(|line| line.contains("\\E "))
5601            .collect::<Vec<_>>();
5602        assert!(
5603            !quantified.is_empty(),
5604            "MeerkatMachine has quantified transitions"
5605        );
5606        for line in &quantified {
5607            assert!(
5608                line.starts_with("    \\/ (phase = "),
5609                "quantified Next disjunct without a leading phase guard: {line}"
5610            );
5611        }
5612        assert!(
5613            next.contains("    \\/ (phase = \"Running\") /\\ \\E run_id \\in RunIdValues : RequestCancelAfterBoundary(run_id)"),
5614            "the guard is the transition's own source phase"
5615        );
5616    }
5617
5618    fn next_disjunct_for<'a>(model: &'a str, action: &str) -> &'a str {
5619        let next = model
5620            .split_once("\nNext ==\n")
5621            .map(|(_, rest)| rest.split("\n\n").next().unwrap_or(""))
5622            .expect("Next block");
5623        next.lines()
5624            .find(|line| line.contains(&format!(" {action}(")))
5625            .expect("Next disjunct for the action")
5626    }
5627
5628    /// A declared domain, not a binding name, decides an input field's TLC
5629    /// domain: additional values extend the default unsigned range, a state
5630    /// binding explores exactly the state field, and an undeclared
5631    /// `expected_revision` gets the plain default (the old name match is gone).
5632    #[test]
5633    fn declared_input_field_domains_decide_the_rendered_domain() {
5634        use meerkat_machine_schema::catalog::dsl::dsl_workgraph_lifecycle_machine;
5635        use meerkat_machine_schema::identity::{FieldId, InputVariantId};
5636        use meerkat_machine_schema::{InputFieldDomain, InputFieldDomainKind};
5637
5638        let shipped = dsl_workgraph_lifecycle_machine();
5639        let model = render_machine_semantic_model(&shipped).expect("render workgraph model");
5640        assert!(
5641            next_disjunct_for(&model, "UpdateOpen")
5642                .contains("\\E expected_revision \\in {revision} : "),
5643            "a state-bound declaration explores exactly the state field"
5644        );
5645
5646        let mut sampled = shipped.clone();
5647        sampled.input_field_domains.push(InputFieldDomain {
5648            input: InputVariantId::parse("CreateOpen").expect("input slug"),
5649            field: FieldId::parse("unresolved_blocker_count").expect("field slug"),
5650            domain: InputFieldDomainKind::AdditionalValues([3, 8].into_iter().collect()),
5651        });
5652        let model = render_machine_semantic_model(&sampled).expect("render sampled model");
5653        assert!(
5654            next_disjunct_for(&model, "CreateOpen")
5655                .contains("\\E arg_unresolved_blocker_count \\in (0..2 \\cup {3, 8}) : "),
5656            "additional values extend the default unsigned domain"
5657        );
5658
5659        let mut undeclared = shipped;
5660        undeclared.input_field_domains.clear();
5661        let model = render_machine_semantic_model(&undeclared).expect("render undeclared model");
5662        assert!(
5663            next_disjunct_for(&model, "UpdateOpen").contains("\\E expected_revision \\in 0..2 : "),
5664            "without a declaration the binding name no longer selects a domain"
5665        );
5666    }
5667
5668    /// A `CiValues` declaration ranges the field over a model constant: the
5669    /// CI config assigns it exactly the declared values, the Deep config those
5670    /// and the default unsigned domain.
5671    #[test]
5672    fn ci_values_narrow_the_ci_profile_alone() {
5673        use meerkat_machine_schema::catalog::dsl::dsl_workgraph_lifecycle_machine;
5674        use meerkat_machine_schema::identity::{FieldId, InputVariantId};
5675        use meerkat_machine_schema::{InputFieldDomain, InputFieldDomainKind};
5676
5677        let mut sampled = dsl_workgraph_lifecycle_machine();
5678        sampled.input_field_domains.push(InputFieldDomain {
5679            input: InputVariantId::parse("CreateOpen").expect("input slug"),
5680            field: FieldId::parse("unresolved_blocker_count").expect("field slug"),
5681            domain: InputFieldDomainKind::CiValues([0, 5].into_iter().collect()),
5682        });
5683        let constant = "InputSamples_CreateOpen_unresolved_blocker_count";
5684        let model = render_machine_semantic_model(&sampled).expect("render sampled model");
5685        assert!(
5686            next_disjunct_for(&model, "CreateOpen").contains(&format!(
5687                "\\E arg_unresolved_blocker_count \\in {constant} : "
5688            )),
5689            "the field ranges over its samples constant"
5690        );
5691        let constants_line = model
5692            .lines()
5693            .find(|line| line.starts_with("CONSTANTS "))
5694            .expect("model constants");
5695        assert!(
5696            constants_line.contains(constant),
5697            "the model declares the samples constant: {constants_line}"
5698        );
5699        assert!(
5700            next_disjunct_for(&model, "UpdateOpen")
5701                .contains("\\E expected_revision \\in {revision} : "),
5702            "the machine's other declarations are unchanged"
5703        );
5704
5705        let ci = render_machine_ci_cfg(&sampled, false).expect("valid CI CFG");
5706        assert!(
5707            ci.contains(&format!("\n  {constant} = {{0, 5}}\n")),
5708            "the CI config assigns exactly the declared values:\n{ci}"
5709        );
5710        let deep = render_machine_ci_cfg(&sampled, true).expect("valid Deep CFG");
5711        assert!(
5712            deep.contains(&format!("\n  {constant} = {{0, 1, 2, 5}}\n")),
5713            "the Deep config keeps the default domain beside the declared values:\n{deep}"
5714        );
5715        assert_eq!(
5716            broad_input_samples(&[0, 5].into_iter().collect::<BTreeSet<u64>>()),
5717            [0, 1, 2, 5].into_iter().collect::<BTreeSet<u64>>(),
5718            "outside the CI profile the field keeps the default domain beside its values"
5719        );
5720    }
5721
5722    /// SessionDocumentMachine's CI bound: under a step bound of 5 the CI
5723    /// profile explores the samples it declares, in every Next disjunct of
5724    /// the input's transitions; the Deep profile keeps `0..2` for each of
5725    /// them and its step bound of 8.
5726    #[test]
5727    fn session_document_narrows_its_ci_samples_only() {
5728        let schema = meerkat_machine_schema::catalog::dsl::dsl_session_document_machine();
5729        let model = render_machine_semantic_model(&schema).expect("render SessionDocumentMachine");
5730        let ci = render_machine_ci_cfg(&schema, false).expect("valid CI CFG");
5731        let deep = render_machine_ci_cfg(&schema, true).expect("valid Deep CFG");
5732        let next = model
5733            .split_once("\nNext ==\n")
5734            .map(|(_, rest)| rest.split("\n\n").next().unwrap_or(""))
5735            .expect("Next block");
5736        for (input, field, ci_values) in [
5737            ("ClassifyDurableTail", "dangling_tool_use_count", "{0}"),
5738            ("ClassifyDurableTail", "orphan_tool_result_count", "{0}"),
5739            ("RecoverSessionInstructionState", "target_generation", "{2}"),
5740            ("RecoverSessionInstructionState", "entry_sequence", "{0}"),
5741            ("RecoverSessionInstructionEffective", "generation", "{0}"),
5742            (
5743                "RecoverSessionInstructionEffective",
5744                "last_entry_sequence",
5745                "{0, 1}",
5746            ),
5747            ("SetSessionInstruction", "body_bytes", "{1}"),
5748        ] {
5749            let constant = format!("InputSamples_{input}_{field}");
5750            let disjuncts = next
5751                .lines()
5752                .filter(|line| line.contains(&format!(": {input}")))
5753                .collect::<Vec<_>>();
5754            assert!(!disjuncts.is_empty(), "{input} has Next disjuncts");
5755            for line in disjuncts {
5756                assert!(
5757                    line.contains(&format!("\\E {field} \\in {constant} : ")),
5758                    "{input}.{field} ranges over {constant}: {line}"
5759                );
5760            }
5761            assert!(
5762                ci.contains(&format!("\n  {constant} = {ci_values}\n")),
5763                "the CI config samples {input}.{field} as {ci_values}:\n{ci}"
5764            );
5765            assert!(
5766                deep.contains(&format!("\n  {constant} = {{0, 1, 2}}\n")),
5767                "the Deep config keeps 0..2 for {input}.{field}:\n{deep}"
5768            );
5769        }
5770        assert!(
5771            model.contains("\nCiStateConstraint == /\\ model_step_count <= 5 "),
5772            "the CI step bound is 5"
5773        );
5774        assert!(
5775            model.contains("\nDeepStateConstraint == /\\ model_step_count <= 8 "),
5776            "the Deep step bound stays 8"
5777        );
5778    }
5779
5780    #[test]
5781    fn substituted_compound_values_are_delimited_and_atoms_are_not() {
5782        for atom in [
5783            "x",
5784            "packet.payload.run_id",
5785            "Some(run_id)",
5786            "MapSet(m, k, v)",
5787            "m[k]",
5788            "f(a)[b](c)",
5789            "(a + 1)",
5790            "\"a(b\"",
5791            "42",
5792        ] {
5793            assert_eq!(tla_delimited(atom), atom, "{atom} is already an operand");
5794        }
5795        for compound in [
5796            "IF c THEN a ELSE b",
5797            "x + 1",
5798            "s \\cup {x}",
5799            "(a) + (b)",
5800            "f(a) = b",
5801            "~x",
5802        ] {
5803            assert_eq!(
5804                tla_delimited(compound),
5805                format!("({compound})"),
5806                "{compound} must be delimited before splicing"
5807            );
5808        }
5809    }
5810
5811    /// A field assigned by a conditional update earlier in the same block is
5812    /// read through its pending value, a bare `IF c THEN a ELSE b`. Spliced
5813    /// unparenthesized into a later expression, TLA+ precedence captured the
5814    /// surrounding operator. Shipped instance: the meerkat_mob_seam
5815    /// `TurnRunFailed` payload unwraps the conditionally updated
5816    /// `terminal_cause_kind` as `IF "value" \in DOMAIN v THEN v["value"] ELSE
5817    /// None`; with `v` bare, `["value"]` applied to v's ELSE branch only, so
5818    /// the THEN branch emitted the Option record instead of its value.
5819    #[test]
5820    fn a_conditionally_updated_field_read_later_in_the_block_splices_as_one_operand() {
5821        let model = render_composition_semantic_model(&meerkat_mob_seam_composition())
5822            .expect("render meerkat_mob_seam model");
5823        assert!(
5824            model.contains(
5825                "terminal_cause_kind |-> (IF \"value\" \\in DOMAIN (IF (IF (meerkat_terminal_cause_kind = None)"
5826            ),
5827            "the TurnRunFailed unwrap must test the whole conditional value"
5828        );
5829        assert!(
5830            !model.contains("ELSE meerkat_terminal_cause_kind[\"value\"]"),
5831            "no index may bind to one branch of a spliced conditional"
5832        );
5833    }
5834
5835    /// A set insert or remove of a field that a conditional update already
5836    /// changed earlier in the same block takes the field's pending value, a
5837    /// bare `IF c THEN a ELSE b`, as its left operand. Spliced unparenthesized,
5838    /// the ELSE branch captured the set operator, so the THEN branch lost the
5839    /// second update. Shipped instance: MobMachine's topology convergence
5840    /// removes both absent identities from `pending_respawn_topology`; the
5841    /// model removed only `a_identity` when both were absent.
5842    #[test]
5843    fn a_set_update_after_a_conditional_update_takes_the_whole_conditional() {
5844        let model = render_machine_semantic_model(&mob_machine()).expect("render MobMachine model");
5845        assert!(
5846            model.contains(
5847                "((IF ((a_identity \\in DOMAIN identity_to_runtime) = FALSE) THEN (pending_respawn_topology \\ {a_identity}) ELSE pending_respawn_topology) \\ {b_identity})"
5848            ),
5849            "the second removal must apply to the whole conditional value"
5850        );
5851        assert!(
5852            !model.contains("ELSE pending_respawn_topology \\ {b_identity}"),
5853            "no set operator may bind to one branch of a spliced conditional"
5854        );
5855    }
5856
5857    /// Every update kind that reads a field's pending value must splice it so
5858    /// no operator after it can bind into one branch of a pending conditional
5859    /// (`IF c THEN a ELSE b`, left by an earlier conditional update in the
5860    /// same block): each occurrence must close an operand, followed only by
5861    /// `)`, `,` or the end of the value. The match is exhaustive, so a new
5862    /// `Update` kind must be classified here.
5863    #[test]
5864    fn every_update_kind_splices_a_pending_conditional_as_one_operand() {
5865        use meerkat_machine_schema::identity::FieldId;
5866        const PENDING: &str = "IF c THEN a ELSE b";
5867        let field = || FieldId::parse("f").expect("field slug");
5868        let x = || Expr::Binding("x".to_owned());
5869        let samples = vec![
5870            Update::Increment {
5871                field: field(),
5872                amount: 1,
5873            },
5874            Update::Decrement {
5875                field: field(),
5876                amount: 1,
5877            },
5878            Update::MapInsert {
5879                field: field(),
5880                key: x(),
5881                value: x(),
5882            },
5883            Update::MapIncrement {
5884                field: field(),
5885                key: x(),
5886                amount: 1,
5887            },
5888            Update::MapDecrement {
5889                field: field(),
5890                key: x(),
5891                amount: 1,
5892            },
5893            Update::MapRemove {
5894                field: field(),
5895                key: x(),
5896            },
5897            Update::SetInsert {
5898                field: field(),
5899                value: x(),
5900            },
5901            Update::SetRemove {
5902                field: field(),
5903                value: x(),
5904            },
5905            Update::SeqAppend {
5906                field: field(),
5907                value: x(),
5908            },
5909            Update::SeqPrepend {
5910                field: field(),
5911                values: x(),
5912            },
5913            Update::SeqPopFront { field: field() },
5914            Update::SeqRemoveValue {
5915                field: field(),
5916                value: x(),
5917            },
5918            Update::SeqRemoveAll {
5919                field: field(),
5920                values: x(),
5921            },
5922            Update::Conditional {
5923                condition: Expr::Binding("d".to_owned()),
5924                then_updates: vec![Update::SetInsert {
5925                    field: field(),
5926                    value: x(),
5927                }],
5928                else_updates: vec![Update::SetRemove {
5929                    field: field(),
5930                    value: x(),
5931                }],
5932            },
5933            Update::ForEach {
5934                binding: "y".to_owned(),
5935                over: x(),
5936                updates: vec![Update::SetInsert {
5937                    field: field(),
5938                    value: Expr::Binding("y".to_owned()),
5939                }],
5940            },
5941        ];
5942        let schema = mob_machine();
5943        for update in &samples {
5944            // Exhaustive: classify every kind. `Assign` does not read the
5945            // field's pending value, so it cannot splice it.
5946            match update {
5947                Update::Assign { .. } => continue,
5948                Update::Increment { .. }
5949                | Update::Decrement { .. }
5950                | Update::MapInsert { .. }
5951                | Update::MapIncrement { .. }
5952                | Update::MapDecrement { .. }
5953                | Update::MapRemove { .. }
5954                | Update::SetInsert { .. }
5955                | Update::SetRemove { .. }
5956                | Update::SeqAppend { .. }
5957                | Update::SeqPrepend { .. }
5958                | Update::SeqPopFront { .. }
5959                | Update::SeqRemoveValue { .. }
5960                | Update::SeqRemoveAll { .. }
5961                | Update::Conditional { .. }
5962                | Update::ForEach { .. } => {}
5963            }
5964            let mut compiler = MachineTlaCompiler::new(&schema);
5965            let mut env = BTreeMap::from([("f".to_owned(), PENDING.to_owned())]);
5966            let binding_types =
5967                BTreeMap::from([("x".to_owned(), TypeRef::Set(Box::new(TypeRef::U64)))]);
5968            compiler.apply_update("Probe", &mut env, &BTreeMap::new(), &binding_types, update);
5969            let rendered = env.get("f").expect("the update writes f");
5970            assert!(
5971                rendered.contains(PENDING),
5972                "{update:?} must read the pending value: {rendered}"
5973            );
5974            for (at, _) in rendered.match_indices(PENDING) {
5975                let after = rendered[at + PENDING.len()..].chars().next();
5976                assert!(
5977                    matches!(after, None | Some(')' | ',')),
5978                    "{update:?} lets {after:?} bind into the pending conditional: {rendered}"
5979                );
5980            }
5981        }
5982    }
5983
5984    /// A `for` loop lowers to one fold per touched field, and each fold must
5985    /// read the other fields as they were BEFORE the loop, as the sequential
5986    /// kernel does within an iteration. Writing each fold back into the env
5987    /// while lowering handed later folds an earlier field's post-loop value:
5988    /// the causal-tail batch then looked up already-removed cursors and left
5989    /// orphaned queued rows, which the generated outbox invariant caught. So
5990    /// no fold of a loop may take another fold of the same loop as an
5991    /// argument.
5992    #[test]
5993    fn a_for_each_fold_reads_the_other_fields_before_the_loop() {
5994        let model =
5995            render_machine_semantic_model(&meerkat_machine()).expect("render MeerkatMachine model");
5996        let mut checked = 0;
5997        for line in model.lines() {
5998            let Some(eq) = line.find("' = ") else {
5999                continue;
6000            };
6001            let rhs = &line[eq + 4..];
6002            let Some(open) = rhs.find('(') else {
6003                continue;
6004            };
6005            let head = &rhs[..open];
6006            let Some(pos) = head.find("_ForEach") else {
6007                continue;
6008            };
6009            let digits: String = head[pos + "_ForEach".len()..]
6010                .chars()
6011                .take_while(char::is_ascii_digit)
6012                .collect();
6013            let same_loop = format!("{}_ForEach{digits}_", &head[..pos]);
6014            assert!(
6015                !rhs[open..].contains(&same_loop),
6016                "a for-loop fold takes another fold of the same loop as an argument: {line}"
6017            );
6018            checked += 1;
6019        }
6020        assert!(
6021            checked > 0,
6022            "the MeerkatMachine model has for-loop folds to check"
6023        );
6024    }
6025    use meerkat_machine_schema::RustTypeAtom;
6026    use meerkat_machine_schema::catalog::dsl::{
6027        dsl_meerkat_machine as meerkat_machine, dsl_mob_machine as mob_machine,
6028    };
6029    use meerkat_machine_schema::catalog::meerkat_mob_seam_composition;
6030    use meerkat_machine_schema::identity::{
6031        EffectVariantId, MachineId, MachineInstanceId, TransitionId,
6032    };
6033
6034    fn string_domain_values(assignment: &str) -> BTreeSet<String> {
6035        assignment
6036            .trim_start_matches('{')
6037            .trim_end_matches('}')
6038            .split(", ")
6039            .filter(|value| !value.is_empty())
6040            .map(|value| value.trim_matches('"').to_owned())
6041            .collect()
6042    }
6043
6044    fn cfg_string_domain_values(cfg: &str, domain: &str) -> BTreeSet<String> {
6045        let prefix = format!("  {domain} = ");
6046        cfg.lines()
6047            .find_map(|line| line.strip_prefix(&prefix))
6048            .map(string_domain_values)
6049            .unwrap_or_default()
6050    }
6051
6052    fn default_string_domain_values(sample_cardinality: usize) -> BTreeSet<String> {
6053        string_domain_values(&render_default_domain_assignment(
6054            &TypeRef::String,
6055            sample_cardinality,
6056            &BTreeMap::new(),
6057            &BTreeMap::new(),
6058            false,
6059        ))
6060    }
6061
6062    fn assert_session_id_string_overlap(cfg: &str, profile: &str) {
6063        let session_ids = cfg_string_domain_values(cfg, "SessionIdValues");
6064        let strings = cfg_string_domain_values(cfg, "StringValues");
6065        assert!(
6066            !session_ids.is_empty() && !strings.is_empty(),
6067            "{profile} must sample both bridged domains"
6068        );
6069        assert!(
6070            !session_ids.is_disjoint(&strings),
6071            "{profile} must make the SessionId/string equality branch satisfiable"
6072        );
6073        assert!(
6074            strings
6075                .iter()
6076                .any(|candidate| !session_ids.contains(candidate)),
6077            "{profile} must retain a non-matching string candidate for the rejection branch"
6078        );
6079    }
6080
6081    #[test]
6082    fn conjunctive_bool_specialization_is_literal_only_and_conservative() {
6083        let expr = Expr::And(vec![
6084            Expr::Binding("required_true".to_owned()),
6085            Expr::Not(Box::new(Expr::Binding("required_false".to_owned()))),
6086            Expr::Eq(
6087                Box::new(Expr::Binding("equal_true".to_owned())),
6088                Box::new(Expr::Bool(true)),
6089            ),
6090            Expr::Neq(
6091                Box::new(Expr::Bool(true)),
6092                Box::new(Expr::Binding("not_equal_true".to_owned())),
6093            ),
6094            Expr::Or(vec![
6095                Expr::Binding("under_disjunction".to_owned()),
6096                Expr::Binding("alternative".to_owned()),
6097            ]),
6098            Expr::Binding("conflicting".to_owned()),
6099            Expr::Not(Box::new(Expr::Binding("conflicting".to_owned()))),
6100        ]);
6101        let mut requirements = BTreeMap::new();
6102
6103        collect_conjunctive_bool_requirements(&expr, &mut requirements);
6104
6105        assert_eq!(requirements.get("required_true"), Some(&Some(true)));
6106        assert_eq!(requirements.get("required_false"), Some(&Some(false)));
6107        assert_eq!(requirements.get("equal_true"), Some(&Some(true)));
6108        assert_eq!(requirements.get("not_equal_true"), Some(&Some(false)));
6109        assert!(!requirements.contains_key("under_disjunction"));
6110        assert!(!requirements.contains_key("alternative"));
6111        assert_eq!(requirements.get("conflicting"), Some(&None));
6112    }
6113
6114    #[test]
6115    #[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
6116    fn composition_semantic_model_fails_closed_on_undeclared_route_source_machine() {
6117        let mut schema = meerkat_mob_seam_composition();
6118        let route = schema
6119            .routes
6120            .first_mut()
6121            .expect("seam composition has at least one route");
6122        // Repoint the route source at an instance id that is not declared in
6123        // the composition. The CASE builder used to map this to an
6124        // `"unknown_machine"` sentinel; generation must now fail closed.
6125        route.from_machine =
6126            MachineInstanceId::parse("undeclared_source_instance").expect("valid slug");
6127
6128        let result = render_composition_semantic_model(&schema);
6129        assert!(
6130            matches!(
6131                result,
6132                Err(CompositionTlaError::UnknownRouteSourceMachine { .. })
6133            ),
6134            "expected UnknownRouteSourceMachine, got {result:?}"
6135        );
6136    }
6137
6138    #[test]
6139    #[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
6140    fn composition_semantic_model_fails_closed_on_undeclared_route_effect() {
6141        let mut schema = meerkat_mob_seam_composition();
6142        let route = schema
6143            .routes
6144            .first_mut()
6145            .expect("seam composition has at least one route");
6146        // Keep the (declared) source machine but reference an effect variant
6147        // that the source machine does not declare.
6148        route.effect_variant =
6149            EffectVariantId::parse("UndeclaredEffectVariant").expect("valid slug");
6150
6151        let result = render_composition_semantic_model(&schema);
6152        assert!(
6153            matches!(result, Err(CompositionTlaError::UnknownRouteEffect { .. })),
6154            "expected UnknownRouteEffect, got {result:?}"
6155        );
6156    }
6157
6158    #[test]
6159    #[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
6160    fn composition_semantic_model_fails_closed_on_undeclared_witness_transition() {
6161        let mut schema = meerkat_mob_seam_composition();
6162        schema
6163            .witnesses
6164            .first_mut()
6165            .expect("seam composition has at least one witness")
6166            .expected_transitions
6167            .first_mut()
6168            .expect("seam witness has at least one expected transition")
6169            .transition = TransitionId::parse("UndeclaredWitnessTransition").expect("valid slug");
6170
6171        let result = render_composition_semantic_model(&schema);
6172        assert!(
6173            matches!(
6174                result,
6175                Err(CompositionTlaError::UnknownWitnessTransition { .. })
6176            ),
6177            "expected UnknownWitnessTransition, got {result:?}"
6178        );
6179    }
6180
6181    #[test]
6182    #[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
6183    fn composition_semantic_model_renders_for_valid_schema() {
6184        // Sanity: the fail-closed gate does not reject a currently-valid
6185        // composition. (Byte-identity of the output is enforced separately by
6186        // `make machine-check-drift`.)
6187        let schema = meerkat_mob_seam_composition();
6188        let result = render_composition_semantic_model(&schema);
6189        assert!(
6190            result.is_ok(),
6191            "valid composition should render: {result:?}"
6192        );
6193    }
6194
6195    #[test]
6196    #[should_panic(
6197        expected = "composition named-type `AgentRuntimeId` binding must agree across machine schemas"
6198    )]
6199    fn composition_named_binding_merge_rejects_divergent_domain_shapes() {
6200        let mut meerkat = meerkat_machine();
6201        meerkat.machine = MachineId::parse("CompositionMergeLeft").expect("test machine id");
6202        let mut mob = mob_machine();
6203        mob.machine = MachineId::parse("CompositionMergeRight").expect("test machine id");
6204        let binding = mob
6205            .named_types
6206            .iter_mut()
6207            .find(|binding| binding.name.as_str() == "AgentRuntimeId")
6208            .expect("MobMachine AgentRuntimeId binding");
6209        binding.rust = RustTypeAtom::U64;
6210
6211        let _ = collect_composition_named_bindings([&meerkat, &mob]);
6212    }
6213
6214    #[test]
6215    fn composition_named_binding_merge_allows_machine_local_type_path_twins() {
6216        let meerkat = meerkat_machine();
6217        let mob = mob_machine();
6218
6219        let bindings = collect_composition_named_bindings([&meerkat, &mob]);
6220
6221        assert!(
6222            matches!(
6223                bindings.get("PeerAddress"),
6224                Some(RustTypeAtom::TypePath(path))
6225                    if path == "crate::catalog::dsl::meerkat_machine::PeerAddress"
6226            ),
6227            "path-only TypePath twins should not block composition-domain binding merge"
6228        );
6229    }
6230
6231    #[test]
6232    fn mob_generation_native_helper_declares_and_assigns_u64_boundary() {
6233        let schema = mob_machine();
6234        assert!(machine_uses_u64_max(&schema));
6235
6236        let model = render_machine_semantic_model(&schema).expect("render MobMachine model");
6237        let constants_line = model
6238            .lines()
6239            .find(|line| line.starts_with("CONSTANTS "))
6240            .expect("MobMachine model constants");
6241        assert!(constants_line.contains(TLA_RUST_U64_MAX_CONSTANT));
6242
6243        for deep in [false, true] {
6244            let cfg = render_machine_ci_cfg(&schema, deep).expect("valid machine CFG");
6245            assert!(
6246                cfg.contains(&format!(
6247                    "  {TLA_RUST_U64_MAX_CONSTANT} = {TLC_SAFE_RUST_U64_MAX_VALUE}"
6248                )),
6249                "{} config must assign the boundary",
6250                if deep { "deep" } else { "ci" }
6251            );
6252        }
6253    }
6254
6255    #[test]
6256    fn meerkat_deep_cfg_samples_the_native_session_id_string_bridge() {
6257        let schema = meerkat_machine();
6258        assert!(machine_uses_session_id_string_bridge(&schema));
6259
6260        let deep_cfg = render_machine_ci_cfg(&schema, true).expect("valid deep CFG");
6261        assert_session_id_string_overlap(&deep_cfg, "MeerkatMachine Deep config");
6262        assert_eq!(
6263            cfg_string_domain_values(&deep_cfg, "StringValues").len(),
6264            default_string_domain_values(default_sample_cardinality(true)).len(),
6265            "bridge reachability must substitute a Deep string sample, not add one"
6266        );
6267
6268        let ci_cfg = render_machine_ci_cfg(&schema, false).expect("valid CI CFG");
6269        assert!(
6270            cfg_string_domain_values(&ci_cfg, "SessionIdValues").is_empty()
6271                && cfg_string_domain_values(&ci_cfg, "StringValues").is_empty(),
6272            "the step-limit-one CI profile must remain uninflated"
6273        );
6274    }
6275
6276    #[test]
6277    fn mob_deep_cfg_does_not_inflate_unrelated_string_domains() {
6278        let schema = mob_machine();
6279        assert!(!machine_uses_session_id_string_bridge(&schema));
6280
6281        let deep_cfg = render_machine_ci_cfg(&schema, true).expect("valid deep CFG");
6282        let session_ids = cfg_string_domain_values(&deep_cfg, "SessionIdValues");
6283        let strings = cfg_string_domain_values(&deep_cfg, "StringValues");
6284        assert!(
6285            session_ids.is_disjoint(&strings),
6286            "a machine without the native bridge must retain independent domains"
6287        );
6288    }
6289
6290    #[test]
6291    fn mob_identity_classifier_uses_a_typed_tlc_lifecycle_representative() {
6292        let schema = mob_machine();
6293        assert_eq!(
6294            schema
6295                .tlc_representative_inputs
6296                .iter()
6297                .map(|input| input.as_str())
6298                .collect::<Vec<_>>(),
6299            vec!["ClassifyIdentityReconciliation"],
6300            "the schema must explicitly own the TLC-only classifier abstraction"
6301        );
6302
6303        let model = render_machine_semantic_model(&schema).expect("render MobMachine model");
6304        assert!(
6305            model.contains(
6306                "TlcRepresentativeDomain(values) == IF values = {} THEN {} ELSE {CHOOSE value \\in values : TRUE}"
6307            ),
6308            "the representative domain must remain typed and nonempty-aware"
6309        );
6310        assert!(
6311            model.contains(
6312                "\\E intent \\in TlcRepresentativeDomain(IdentityAuthorityConditionValues) : \\E lease \\in TlcRepresentativeDomain(IdentityLeaseConditionValues)"
6313            ),
6314            "MobMachine lifecycle Next must sample one typed identity-classifier tuple"
6315        );
6316        assert!(
6317            !model.contains(
6318                "\\E intent \\in IdentityAuthorityConditionValues : \\E lease \\in IdentityLeaseConditionValues : \\E external_binding_required \\in BOOLEAN"
6319            ),
6320            "MobMachine lifecycle Next must not reintroduce the exhaustive classifier cartesian product"
6321        );
6322
6323        let composition = render_composition_semantic_model(&meerkat_mob_seam_composition())
6324            .expect("render Meerkat/Mob composition");
6325        assert!(
6326            composition.contains(
6327                "\\E arg_intent \\in TlcRepresentativeDomain(IdentityAuthorityConditionValues) : \\E arg_lease \\in TlcRepresentativeDomain(IdentityLeaseConditionValues)"
6328            ),
6329            "composition lifecycle exploration must honor the same schema-owned abstraction"
6330        );
6331    }
6332
6333    #[test]
6334    fn meerkat_mob_composition_deep_cfg_samples_the_included_native_bridge() {
6335        let schema = meerkat_mob_seam_composition();
6336        let deep_cfg = render_composition_ci_cfg(&schema, true);
6337
6338        assert_session_id_string_overlap(&deep_cfg, "Meerkat/Mob composition Deep config");
6339        let string_cardinality = schema
6340            .deep_domain_overrides
6341            .get("StringValues")
6342            .copied()
6343            .unwrap_or(schema.deep_domain_cardinality);
6344        assert_eq!(
6345            cfg_string_domain_values(&deep_cfg, "StringValues").len(),
6346            default_string_domain_values(string_cardinality).len(),
6347            "composition bridge reachability must substitute a string sample, not add one"
6348        );
6349
6350        let ci_cfg = render_composition_ci_cfg(&schema, false);
6351        assert!(
6352            cfg_string_domain_values(&ci_cfg, "SessionIdValues")
6353                .is_disjoint(&cfg_string_domain_values(&ci_cfg, "StringValues")),
6354            "the composition CI profile must remain unchanged"
6355        );
6356    }
6357
6358    #[test]
6359    fn runtime_delivery_recipient_insert_has_identical_local_map_semantics_in_tla() {
6360        let schema = meerkat_machine_schema::catalog::dsl::dsl_runtime_delivery_machine();
6361        let model = render_machine_semantic_model(&schema).expect("render recipient model");
6362        let definition = "runtime_delivery_recipient_outcomes_after_set(current, recipient, outcome) ==\n    MapSet(current, recipient, outcome)\n";
6363        assert!(model.contains(definition));
6364        assert!(
6365            model
6366                .matches("runtime_delivery_recipient_outcomes_after_set(")
6367                .count()
6368                > 1,
6369            "the generated settlement must call the formally defined insert"
6370        );
6371        let composition = render_composition_semantic_model(
6372            &meerkat_machine_schema::catalog::job_runtime_delivery_composition(),
6373        )
6374        .expect("render embedded recipient model");
6375        assert!(
6376            composition.contains(&format!("runtime_delivery__{definition}")),
6377            "embedded delivery machines require their scoped helper definition too"
6378        );
6379    }
6380
6381    #[test]
6382    fn session_document_instruction_natives_have_the_rust_semantics_in_tla() {
6383        // The DSL authority, the kernel oracle and the Core mirror give these
6384        // natives one meaning, pinned here as the generated TLA renders it:
6385        // a slot map with one slot set (insert or replace), the body bytes of
6386        // a slot set's Active slots (a slot the bytes map does not name
6387        // counts nothing), and the entries of a slot map whose slot is
6388        // Active.
6389        let schema = meerkat_machine_schema::catalog::dsl::dsl_session_document_machine();
6390        let model = render_machine_semantic_model(&schema).expect("render model");
6391        let slot_after_set = r"session_document_instruction_slot_after_set(current, slot, value) ==
6392    MapSet(current, slot, value)
6393";
6394        let active_bytes = r#"session_document_instruction_active_bytes(slot_effect, slot_bytes) ==
6395    LET RECURSIVE SessionDocumentInstructionActiveBytesOver(_)
6396        SessionDocumentInstructionActiveBytesOver(instruction_slots) ==
6397            IF instruction_slots = {} THEN 0
6398            ELSE LET instruction_slot == CHOOSE candidate_slot \in instruction_slots : TRUE
6399                 IN (IF slot_effect[instruction_slot] = "Active" /\ instruction_slot \in DOMAIN slot_bytes
6400                     THEN slot_bytes[instruction_slot] ELSE 0)
6401                    + SessionDocumentInstructionActiveBytesOver(instruction_slots \ {instruction_slot})
6402    IN SessionDocumentInstructionActiveBytesOver(DOMAIN slot_effect)
6403"#;
6404        let active_slots = r#"session_document_instruction_active_slots(slot_effect, slot_values) ==
6405    [instruction_slot \in {candidate_slot \in DOMAIN slot_values :
6406            candidate_slot \in DOMAIN slot_effect /\ slot_effect[candidate_slot] = "Active"}
6407        |-> slot_values[instruction_slot]]
6408"#;
6409        let retired_after = r"session_document_activation_retired_after(activation_rows, activation_retired) ==
6410    [activation_key \in DOMAIN activation_rows |->
6411        LET retired_count == IF activation_key \in DOMAIN activation_retired THEN activation_retired[activation_key] ELSE 0
6412            superseded_count == IF activation_rows[activation_key] > 0 THEN activation_rows[activation_key] - 1 ELSE 0
6413        IN IF retired_count >= superseded_count THEN retired_count ELSE superseded_count]
6414";
6415        for (native, definition) in [
6416            (
6417                "session_document_instruction_slot_after_set",
6418                slot_after_set,
6419            ),
6420            ("session_document_instruction_active_bytes", active_bytes),
6421            ("session_document_instruction_active_slots", active_slots),
6422            ("session_document_activation_retired_after", retired_after),
6423        ] {
6424            assert!(
6425                model.contains(definition),
6426                "the generated model must define {native} with its Rust semantics"
6427            );
6428            assert!(
6429                model.matches(&format!("{native}(")).count() > 1,
6430                "the generated arms must call the formally defined {native}"
6431            );
6432        }
6433    }
6434
6435    #[test]
6436    fn meerkat_session_id_native_helper_matches_typed_option_contract() {
6437        let model =
6438            render_machine_semantic_model(&meerkat_machine()).expect("render MeerkatMachine model");
6439        let expected = r"meerkat_machine_session_id_matches_string(current, candidate) ==
6440    current # None /\ current.value = candidate
6441";
6442
6443        assert!(
6444            model.contains(expected),
6445            "MeerkatMachine TLA session identity operator must preserve the Rust typed-option/string comparison contract"
6446        );
6447    }
6448
6449    #[test]
6450    fn mob_placed_native_helpers_are_defined_in_the_tla_model() {
6451        let model = render_machine_semantic_model(&mob_machine()).expect("render MobMachine model");
6452
6453        for operator in [
6454            "mob_machine_finalized_placed_kickoff_recovery_well_formed(",
6455            "mob_machine_placed_completion_obligation_well_formed(",
6456            "mob_machine_placed_completion_custody_admits(",
6457            "mob_machine_adaptive_lifecycle_drained(",
6458            "mob_machine_adaptive_run_custody_drained(",
6459            "mob_machine_placed_kickoff_obligation_well_formed(",
6460            "mob_machine_placed_kickoff_correlation_available(",
6461            "mob_machine_placed_kickoff_custody_absent_for_identity(",
6462            "mob_machine_placed_kickoff_custody_absent_for_host(",
6463            "mob_machine_remote_turn_input_id_available_to_kickoff(",
6464            "mob_machine_placed_carrier_binding_active(",
6465            "mob_machine_placed_carrier_binding_confirmed_revoked(",
6466            "mob_machine_host_binding_generation_tombstone(",
6467        ] {
6468            assert!(
6469                model
6470                    .lines()
6471                    .any(|line| line.starts_with(operator) && line.ends_with(" ==")),
6472                "MobMachine TLA model must define native operator {operator}"
6473            );
6474        }
6475    }
6476
6477    #[test]
6478    fn mob_placed_kickoff_correlation_tla_helper_covers_every_shared_input_namespace() {
6479        let model = render_machine_semantic_model(&mob_machine()).expect("render MobMachine model");
6480        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) ==
6481    /\ \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)
6482    /\ \A identity \in DOMAIN retained_kickoffs : retained_kickoffs[identity].agent_identity # candidate.agent_identity
6483    /\ \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)
6484    /\ \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)
6485";
6486
6487        assert!(
6488            model.contains(expected),
6489            "MobMachine TLA kickoff-correlation helper must reject collisions across kickoff, remote-turn, and placed-completion custody"
6490        );
6491    }
6492
6493    #[test]
6494    fn mob_placed_kickoff_recovery_tla_helper_does_not_shadow_machine_phase() {
6495        let model = render_machine_semantic_model(&mob_machine()).expect("render MobMachine model");
6496        assert!(
6497            model.contains(
6498                r#"Cardinality({ kickoff_phase \in {"Started", "CallbackPending", "Failed", "Cancelled"} :"#
6499            ),
6500            "kickoff recovery helper must bind a helper-local identifier"
6501        );
6502        assert!(
6503            !model.contains(
6504                r#"Cardinality({ phase \in {"Started", "CallbackPending", "Failed", "Cancelled"} :"#
6505            ),
6506            "TLA forbids the helper-local binder from shadowing the machine's phase variable"
6507        );
6508    }
6509
6510    #[test]
6511    fn mob_adaptive_run_custody_native_helper_matches_rust_contract() {
6512        let model = render_machine_semantic_model(&mob_machine()).expect("render MobMachine model");
6513        let expected = r#"mob_machine_adaptive_run_custody_drained(adaptive_run_id, active_layer, active_members, layer_run, layer_phases, layer_dispositions) ==
6514    /\ adaptive_run_id \notin DOMAIN active_layer
6515    /\ (IF adaptive_run_id \in DOMAIN active_members THEN active_members[adaptive_run_id] ELSE 0) = 0
6516    /\ \A layer_id \in DOMAIN layer_run :
6517           \/ layer_run[layer_id] # adaptive_run_id
6518           \/ /\ layer_id \in DOMAIN layer_dispositions
6519              /\ layer_id \in DOMAIN layer_phases
6520              /\ layer_phases[layer_id] \in {"Completed", "SetupFailed", "RunFailed", "ResultInvalid", "Canceled"}
6521"#;
6522
6523        assert!(
6524            model.contains(expected),
6525            "MobMachine TLA adaptive-run custody operator must preserve the Rust absence, zero-active-member, and terminal-layer contract"
6526        );
6527    }
6528
6529    /// Every conjunct of the option-order ASSUME table states what Rust's
6530    /// `Option` order computes, so a TLC run that accepts the ASSUMEs proves
6531    /// `OptionLt` / `OptionLe` right. The table covers both operators over
6532    /// None/None, None/Some, Some/None and Some/Some below, equal and above.
6533    #[test]
6534    #[allow(clippy::panic)]
6535    fn the_option_order_assume_table_is_rusts_option_order() {
6536        use std::cmp::Ordering;
6537
6538        fn operand(text: &str) -> Option<u64> {
6539            if text == "None" {
6540                return None;
6541            }
6542            let value = text
6543                .strip_prefix("Some(")
6544                .and_then(|rest| rest.strip_suffix(')'))
6545                .unwrap_or_else(|| panic!("unexpected operand {text}"));
6546            Some(
6547                value
6548                    .parse()
6549                    .unwrap_or_else(|_| panic!("unexpected operand {text}")),
6550            )
6551        }
6552
6553        // TLC evaluates every disjunct of an action-level `\/`, so a `\/` in
6554        // either definition would read a `None` record's `value` inside a
6555        // guard; the ASSUMEs alone cannot see that.
6556        for line in TLA_OPTION_ORDER_DEFINITIONS
6557            .lines()
6558            .filter(|line| line.starts_with("OptionL"))
6559        {
6560            assert!(!line.contains("\\/"), "{line} branches with a disjunction");
6561        }
6562
6563        let mut covered = BTreeSet::new();
6564        for line in TLA_OPTION_ORDER_DEFINITIONS.lines() {
6565            let Some(table) = line.strip_prefix("ASSUME ") else {
6566                continue;
6567            };
6568            for conjunct in table.split(" /\\ ") {
6569                let (expected, call) = match conjunct.strip_prefix('~') {
6570                    Some(call) => (false, call),
6571                    None => (true, conjunct),
6572                };
6573                let (operator, operands) = call.split_once('(').expect("an operator call");
6574                let (left, right) = operands
6575                    .strip_suffix(')')
6576                    .and_then(|operands| operands.split_once(", "))
6577                    .expect("two operands");
6578                let (left, right) = (operand(left), operand(right));
6579                let rust = match operator {
6580                    "OptionLt" => left < right,
6581                    "OptionLe" => left <= right,
6582                    other => panic!("unexpected operator {other}"),
6583                };
6584                assert_eq!(
6585                    expected, rust,
6586                    "{conjunct} disagrees with Rust's Option order"
6587                );
6588                covered.insert((operator, left.is_some(), right.is_some(), left.cmp(&right)));
6589            }
6590        }
6591        for operator in ["OptionLt", "OptionLe"] {
6592            for case in [
6593                (false, false, Ordering::Equal),
6594                (false, true, Ordering::Less),
6595                (true, false, Ordering::Greater),
6596                (true, true, Ordering::Less),
6597                (true, true, Ordering::Equal),
6598                (true, true, Ordering::Greater),
6599            ] {
6600                assert!(
6601                    covered.contains(&(operator, case.0, case.1, case.2)),
6602                    "the ASSUME table misses {operator} over {case:?}"
6603                );
6604            }
6605        }
6606    }
6607
6608    /// An ordering comparison with an option operand renders through
6609    /// `OptionLt` / `OptionLe` (`>` and `>=` with the operands swapped) for
6610    /// every way an operand is an option, on either side; a plain ordering
6611    /// keeps its TLA+ operator and leaves the module without the definitions.
6612    #[test]
6613    fn an_ordering_with_an_option_operand_renders_in_rusts_option_order() {
6614        let mut schema = mob_machine();
6615        schema.helpers.push(HelperSchema {
6616            name: "maybe_epoch".into(),
6617            params: Vec::new(),
6618            returns: TypeRef::Option(Box::new(TypeRef::U64)),
6619            body: Expr::None,
6620        });
6621        let field = |name: &str| {
6622            Box::new(Expr::Field(
6623                meerkat_machine_schema::identity::FieldId::parse(name).expect("field id"),
6624            ))
6625        };
6626        let binding = |name: &str| Box::new(Expr::Binding(name.to_owned()));
6627        let binding_types = BTreeMap::from([
6628            ("agent_identity".to_owned(), TypeRef::String),
6629            ("maybe".to_owned(), TypeRef::Option(Box::new(TypeRef::U64))),
6630            ("n".to_owned(), TypeRef::U64),
6631            ("run_id".to_owned(), TypeRef::String),
6632        ]);
6633        let options = [
6634            ("a None literal", Expr::None),
6635            ("a Some literal", Expr::Some(Box::new(Expr::U64(3)))),
6636            ("an option binding", Expr::Binding("maybe".to_owned())),
6637            ("an option field", *field("supervisor_authority_epoch")),
6638            (
6639                "the get_copied lowering",
6640                Expr::IfElse {
6641                    condition: Box::new(Expr::MapContainsKey {
6642                        map: field("member_last_observed_at_ms"),
6643                        key: binding("agent_identity"),
6644                    }),
6645                    then_expr: Box::new(Expr::Some(Box::new(Expr::MapGet {
6646                        map: field("member_last_observed_at_ms"),
6647                        key: binding("agent_identity"),
6648                    }))),
6649                    else_expr: Box::new(Expr::None),
6650                },
6651            ),
6652            (
6653                "a read of a map with option values",
6654                Expr::MapGet {
6655                    map: field("run_last_granted_frame"),
6656                    key: binding("run_id"),
6657                },
6658            ),
6659            (
6660                "a helper returning an option",
6661                Expr::Call {
6662                    helper: "maybe_epoch".to_owned(),
6663                    args: Vec::new(),
6664                },
6665            ),
6666        ];
6667        let other = Expr::Some(binding("n"));
6668        for (shape, option) in &options {
6669            let compiler = MachineTlaCompiler::new(&schema);
6670            let render = |expr: &Expr| {
6671                compiler.render_expr_with_types(
6672                    expr,
6673                    &BTreeMap::new(),
6674                    &BTreeMap::new(),
6675                    &binding_types,
6676                )
6677            };
6678            let (a, b) = (render(option), render(&other));
6679            let pair = || (Box::new(option.clone()), Box::new(other.clone()));
6680            let swapped = || (Box::new(other.clone()), Box::new(option.clone()));
6681            for (expr, expected) in [
6682                (Expr::Lt(pair().0, pair().1), format!("OptionLt({a}, {b})")),
6683                (Expr::Lte(pair().0, pair().1), format!("OptionLe({a}, {b})")),
6684                (Expr::Gt(pair().0, pair().1), format!("OptionLt({b}, {a})")),
6685                (Expr::Gte(pair().0, pair().1), format!("OptionLe({b}, {a})")),
6686                (
6687                    Expr::Lt(swapped().0, swapped().1),
6688                    format!("OptionLt({b}, {a})"),
6689                ),
6690                (
6691                    Expr::Gte(swapped().0, swapped().1),
6692                    format!("OptionLe({a}, {b})"),
6693                ),
6694            ] {
6695                assert_eq!(render(&expr), expected, "{shape}: {expr:?}");
6696            }
6697            assert!(compiler.option_order_used.get(), "{shape} marks the module");
6698        }
6699
6700        let compiler = MachineTlaCompiler::new(&schema);
6701        let render = |expr: Expr| {
6702            compiler.render_expr_with_types(
6703                &expr,
6704                &BTreeMap::new(),
6705                &BTreeMap::new(),
6706                &binding_types,
6707            )
6708        };
6709        let one = || Box::new(Expr::U64(1));
6710        assert_eq!(render(Expr::Lt(binding("n"), one())), "(n < 1)");
6711        assert_eq!(render(Expr::Lte(binding("n"), one())), "(n <= 1)");
6712        assert_eq!(render(Expr::Gt(binding("n"), one())), "(n > 1)");
6713        assert_eq!(render(Expr::Gte(binding("n"), one())), "(n >= 1)");
6714        assert!(
6715            !compiler.option_order_used.get(),
6716            "a plain ordering needs no option-order definitions"
6717        );
6718    }
6719
6720    /// A machine or composition module defines `OptionLt` / `OptionLe` if
6721    /// and only if it calls them, so the definitions land only beside an
6722    /// option ordering.
6723    #[test]
6724    fn a_module_defines_the_option_order_operators_iff_it_calls_them() {
6725        let calls_operators = |module: &str, model: &str| {
6726            let defined = model.matches(TLA_OPTION_ORDER_DEFINITIONS).count();
6727            assert!(
6728                defined <= 1,
6729                "{module} defines the operators {defined} times"
6730            );
6731            let body = model.replacen(TLA_OPTION_ORDER_DEFINITIONS, "", 1);
6732            let called = body.contains("OptionLt(") || body.contains("OptionLe(");
6733            assert_eq!(
6734                defined == 1,
6735                called,
6736                "{module}: defined {defined} time(s), called: {called}"
6737            );
6738            called
6739        };
6740        let mut callers = Vec::new();
6741        for machine in canonical_machine_schemas() {
6742            let model = render_machine_semantic_model(&machine).expect("render machine model");
6743            if calls_operators(machine.machine.as_str(), &model) {
6744                callers.push(machine.machine.as_str().to_owned());
6745            }
6746        }
6747        for composition in meerkat_machine_schema::canonical_composition_schemas() {
6748            // meerkat_mob_seam takes about 45 s to render. Its MobMachine part
6749            // goes through the same per-instance compilers as
6750            // adaptive_mob_bundle's two MobMachine instances below, and
6751            // machine-check-drift holds its regenerated model.
6752            if composition.name.as_str() == "meerkat_mob_seam" {
6753                continue;
6754            }
6755            let model =
6756                render_composition_semantic_model(&composition).expect("render composition model");
6757            if calls_operators(composition.name.as_str(), &model) {
6758                callers.push(composition.name.as_str().to_owned());
6759            }
6760        }
6761        for caller in ["MobMachine", "adaptive_mob_bundle"] {
6762            assert!(
6763                callers.iter().any(|candidate| candidate == caller),
6764                "{caller} orders options (MobMachine's member progress guards): {callers:?}"
6765            );
6766        }
6767    }
6768
6769    /// The option-ordering contract: every ordering comparison in a
6770    /// canonical machine whose operand is option-shaped renders through
6771    /// `OptionLt` / `OptionLe`, never as a plain comparison TLC cannot
6772    /// evaluate. The walk decides "option-shaped" from the schema's declared
6773    /// types (state fields, trigger bindings, helper parameters and returns,
6774    /// map value types, `Some` / `None` literals), independently of the
6775    /// renderer's own inference, so a new guard cannot bring the class back
6776    /// through a shape the renderer misses.
6777    #[test]
6778    fn every_canonical_option_ordering_renders_in_rusts_option_order() {
6779        struct Walk<'a> {
6780            schema: &'a MachineSchema,
6781            compiler: MachineTlaCompiler<'a>,
6782            checked: usize,
6783            plain: Vec<String>,
6784        }
6785
6786        impl Walk<'_> {
6787            fn declared<'t>(
6788                &'t self,
6789                expr: &Expr,
6790                bindings: &'t BTreeMap<String, TypeRef>,
6791            ) -> Option<&'t TypeRef> {
6792                match expr {
6793                    Expr::Field(field) => self
6794                        .schema
6795                        .state
6796                        .fields
6797                        .iter()
6798                        .find(|candidate| candidate.name == *field)
6799                        .map(|candidate| &candidate.ty),
6800                    Expr::Binding(name) => bindings.get(name),
6801                    Expr::Call { helper, .. } => self
6802                        .schema
6803                        .helpers
6804                        .iter()
6805                        .chain(self.schema.derived.iter())
6806                        .find(|candidate| candidate.name == *helper)
6807                        .map(|candidate| &candidate.returns),
6808                    Expr::MapGet { map, .. } | Expr::MapValue { map, .. } => {
6809                        match self.declared(map, bindings)? {
6810                            TypeRef::Map(_, value) => Some(value.as_ref()),
6811                            _ => None,
6812                        }
6813                    }
6814                    _ => None,
6815                }
6816            }
6817
6818            fn option_shaped(&self, expr: &Expr, bindings: &BTreeMap<String, TypeRef>) -> bool {
6819                match expr {
6820                    Expr::Some(_) | Expr::None => true,
6821                    Expr::IfElse {
6822                        then_expr,
6823                        else_expr,
6824                        ..
6825                    } => {
6826                        self.option_shaped(then_expr, bindings)
6827                            || self.option_shaped(else_expr, bindings)
6828                    }
6829                    other => matches!(self.declared(other, bindings), Some(TypeRef::Option(_))),
6830                }
6831            }
6832
6833            fn walk(&mut self, site: &str, expr: &Expr, bindings: &BTreeMap<String, TypeRef>) {
6834                match expr {
6835                    Expr::Lt(left, right)
6836                    | Expr::Lte(left, right)
6837                    | Expr::Gt(left, right)
6838                    | Expr::Gte(left, right) => {
6839                        if self.option_shaped(left, bindings) || self.option_shaped(right, bindings)
6840                        {
6841                            self.checked += 1;
6842                            let rendered = self.compiler.render_expr_with_types(
6843                                expr,
6844                                &BTreeMap::new(),
6845                                &BTreeMap::new(),
6846                                bindings,
6847                            );
6848                            if !rendered.starts_with("OptionLt(")
6849                                && !rendered.starts_with("OptionLe(")
6850                            {
6851                                self.plain
6852                                    .push(format!("{} {site}: {rendered}", self.schema.machine));
6853                            }
6854                        }
6855                        self.walk(site, left, bindings);
6856                        self.walk(site, right, bindings);
6857                    }
6858                    Expr::Bool(_)
6859                    | Expr::U64(_)
6860                    | Expr::U64Max
6861                    | Expr::String(_)
6862                    | Expr::NamedVariant { .. }
6863                    | Expr::EmptySet
6864                    | Expr::EmptyMap
6865                    | Expr::CurrentPhase
6866                    | Expr::Phase(_)
6867                    | Expr::Field(_)
6868                    | Expr::Binding(_)
6869                    | Expr::Variant(_)
6870                    | Expr::None => {}
6871                    Expr::FieldAccess { base, .. } => self.walk(site, base, bindings),
6872                    Expr::EnumVariantIs { value, .. }
6873                    | Expr::EnumStringSetPayload { value, .. } => self.walk(site, value, bindings),
6874                    Expr::SeqLiteral(items) | Expr::And(items) | Expr::Or(items) => {
6875                        for item in items {
6876                            self.walk(site, item, bindings);
6877                        }
6878                    }
6879                    Expr::IfElse {
6880                        condition,
6881                        then_expr,
6882                        else_expr,
6883                    } => {
6884                        self.walk(site, condition, bindings);
6885                        self.walk(site, then_expr, bindings);
6886                        self.walk(site, else_expr, bindings);
6887                    }
6888                    Expr::Not(inner)
6889                    | Expr::SeqElements(inner)
6890                    | Expr::Len(inner)
6891                    | Expr::Head(inner)
6892                    | Expr::MapKeys(inner)
6893                    | Expr::Some(inner) => self.walk(site, inner, bindings),
6894                    Expr::Eq(left, right)
6895                    | Expr::Neq(left, right)
6896                    | Expr::Add(left, right)
6897                    | Expr::Sub(left, right) => {
6898                        self.walk(site, left, bindings);
6899                        self.walk(site, right, bindings);
6900                    }
6901                    Expr::Contains { collection, value } | Expr::Count { collection, value } => {
6902                        self.walk(site, collection, bindings);
6903                        self.walk(site, value, bindings);
6904                    }
6905                    Expr::MapContainsKey { map, key }
6906                    | Expr::MapGet { map, key }
6907                    | Expr::MapValue { map, key } => {
6908                        self.walk(site, map, bindings);
6909                        self.walk(site, key, bindings);
6910                    }
6911                    Expr::SeqStartsWith { seq, prefix } => {
6912                        self.walk(site, seq, bindings);
6913                        self.walk(site, prefix, bindings);
6914                    }
6915                    Expr::MapLiteral(entries) => {
6916                        for (key, value) in entries {
6917                            self.walk(site, key, bindings);
6918                            self.walk(site, value, bindings);
6919                        }
6920                    }
6921                    Expr::Call { args, .. } => {
6922                        for arg in args {
6923                            self.walk(site, arg, bindings);
6924                        }
6925                    }
6926                    Expr::Quantified { over, body, .. } => {
6927                        self.walk(site, over, bindings);
6928                        self.walk(site, body, bindings);
6929                    }
6930                }
6931            }
6932
6933            fn walk_updates(
6934                &mut self,
6935                site: &str,
6936                updates: &[Update],
6937                bindings: &BTreeMap<String, TypeRef>,
6938            ) {
6939                for update in updates {
6940                    match update {
6941                        Update::Assign { expr, .. } => self.walk(site, expr, bindings),
6942                        Update::Increment { .. }
6943                        | Update::Decrement { .. }
6944                        | Update::SeqPopFront { .. } => {}
6945                        Update::MapInsert { key, value, .. } => {
6946                            self.walk(site, key, bindings);
6947                            self.walk(site, value, bindings);
6948                        }
6949                        Update::MapIncrement { key, .. }
6950                        | Update::MapDecrement { key, .. }
6951                        | Update::MapRemove { key, .. } => self.walk(site, key, bindings),
6952                        Update::SetInsert { value, .. }
6953                        | Update::SetRemove { value, .. }
6954                        | Update::SeqAppend { value, .. }
6955                        | Update::SeqRemoveValue { value, .. } => self.walk(site, value, bindings),
6956                        Update::SeqPrepend { values, .. } | Update::SeqRemoveAll { values, .. } => {
6957                            self.walk(site, values, bindings)
6958                        }
6959                        Update::Conditional {
6960                            condition,
6961                            then_updates,
6962                            else_updates,
6963                        } => {
6964                            self.walk(site, condition, bindings);
6965                            self.walk_updates(site, then_updates, bindings);
6966                            self.walk_updates(site, else_updates, bindings);
6967                        }
6968                        Update::ForEach { over, updates, .. } => {
6969                            self.walk(site, over, bindings);
6970                            self.walk_updates(site, updates, bindings);
6971                        }
6972                    }
6973                }
6974            }
6975        }
6976
6977        let mut checked = 0;
6978        let mut plain = Vec::new();
6979        for schema in canonical_machine_schemas() {
6980            let mut walk = Walk {
6981                schema: &schema,
6982                compiler: MachineTlaCompiler::new(&schema),
6983                checked: 0,
6984                plain: Vec::new(),
6985            };
6986            let none = BTreeMap::new();
6987            for transition in &schema.transitions {
6988                let bindings = walk.compiler.binding_type_map(transition);
6989                let site = transition.name.as_str();
6990                for guard in &transition.guards {
6991                    walk.walk(site, &guard.expr, &bindings);
6992                }
6993                walk.walk_updates(site, &transition.updates, &bindings);
6994                for emit in &transition.emit {
6995                    for expr in emit.fields.values() {
6996                        walk.walk(site, expr, &bindings);
6997                    }
6998                }
6999            }
7000            for invariant in &schema.invariants {
7001                walk.walk(&invariant.name, &invariant.expr, &none);
7002            }
7003            for helper in schema.helpers.iter().chain(schema.derived.iter()) {
7004                let params = helper
7005                    .params
7006                    .iter()
7007                    .map(|param| (param.name.as_str().to_owned(), param.ty.clone()))
7008                    .collect::<BTreeMap<_, _>>();
7009                walk.walk(&helper.name, &helper.body, &params);
7010            }
7011            checked += walk.checked;
7012            plain.extend(walk.plain);
7013        }
7014        assert!(
7015            plain.is_empty(),
7016            "option orderings rendered as plain comparisons (TLC cannot order option records):\n{}",
7017            plain.join("\n")
7018        );
7019        // MobMachine's seven member-progress guards order options: the walk
7020        // must find them, or the contract passes vacuously.
7021        assert!(checked >= 7, "the walk found {checked} option orderings");
7022    }
7023}
7024
7025fn render_sequence_domain_definition(inner: &TypeRef) -> String {
7026    let inner_domain = render_type_domain_expr(inner);
7027    format!(
7028        "{{<<>>}} \\cup {{<<x>> : x \\in {inner_domain}}} \\cup {{<<x, y>> : x \\in {inner_domain}, y \\in {inner_domain}}}"
7029    )
7030}
7031
7032fn render_option_domain_definition(inner: &TypeRef) -> String {
7033    let inner_domain = render_type_domain_expr(inner);
7034    format!("{{None}} \\cup {{Some(x) : x \\in {inner_domain}}}")
7035}
7036
7037fn render_map_domain_definition(key: &TypeRef, value: &TypeRef) -> String {
7038    let key_domain = render_type_domain_expr(key);
7039    let value_domain = render_type_domain_expr(value);
7040    let empty_map = "[x \\in {} |-> None]";
7041    format!(
7042        "{{{empty_map}}} \\cup {{ [x \\in {{k}} |-> v] : k \\in {key_domain}, v \\in {value_domain} }}"
7043    )
7044}
7045
7046fn ordered_composite_domain_definitions(
7047    constants: &BTreeMap<String, TypeRef>,
7048) -> Vec<(&String, &TypeRef)> {
7049    let mut domains = constants
7050        .iter()
7051        .filter(|(_, ty)| {
7052            matches!(
7053                ty,
7054                TypeRef::Seq(_) | TypeRef::Option(_) | TypeRef::Map(_, _)
7055            )
7056        })
7057        .collect::<Vec<_>>();
7058    domains.sort_by_key(|(name, ty)| (domain_dependency_depth(ty), (*name).clone()));
7059    domains
7060}
7061
7062fn domain_dependency_depth(ty: &TypeRef) -> usize {
7063    match ty {
7064        TypeRef::Option(inner) | TypeRef::Seq(inner) | TypeRef::Set(inner) => {
7065            1 + domain_dependency_depth(inner)
7066        }
7067        TypeRef::Map(key, value) => {
7068            1 + domain_dependency_depth(key).max(domain_dependency_depth(value))
7069        }
7070        TypeRef::Bool
7071        | TypeRef::U32
7072        | TypeRef::U64
7073        | TypeRef::String
7074        | TypeRef::Named(_)
7075        | TypeRef::Enum(_) => 0,
7076    }
7077}
7078
7079/// The rendered payload of one owner feedback input.
7080struct FeedbackPayload {
7081    payload_expr: String,
7082    quantifiers: Vec<String>,
7083    /// `(obligation field, bound member variable)` per `ObligationMember`.
7084    members: Vec<(String, String)>,
7085}
7086
7087/// Whether `NoOpenObligationsOnTerminal_<protocol>` applies: the producer has
7088/// terminal phases and the protocol is `AckRequired`, so only owner feedback
7089/// closes its obligations. Under `AckOrAbort` and `TerminalClosure` the
7090/// terminal phase is itself the closure, and a `PublicationOnly` protocol has
7091/// no feedback (the publication closes it), so for those the invariant would be
7092/// unsatisfiable once the producer reaches a terminal phase.
7093fn terminal_closure_required(
7094    protocol: &meerkat_machine_schema::EffectHandoffProtocol,
7095    producer: &MachineSchema,
7096) -> bool {
7097    !producer.state.terminal_phases.is_empty()
7098        && matches!(
7099            protocol.closure_policy,
7100            meerkat_machine_schema::ClosurePolicy::AckRequired
7101        )
7102}
7103
7104fn render_type_domain_expr(ty: &TypeRef) -> String {
7105    match ty {
7106        TypeRef::Bool => "BOOLEAN".into(),
7107        // dogma #172 (codegen half): U32 and U64 are distinct bounded domains,
7108        // not one collapsed `NatValues`. The domains-map machinery auto-declares
7109        // the `U32Values` CONSTANT and emits its .cfg sample assignment, so a
7110        // u32 field references its own domain (matching the kernel's u32 width
7111        // check) rather than aliasing the unbounded u64 domain.
7112        TypeRef::U32 => "U32Values".into(),
7113        TypeRef::U64 => "NatValues".into(),
7114        TypeRef::String => "StringValues".into(),
7115        TypeRef::Named(_)
7116        | TypeRef::Enum(_)
7117        | TypeRef::Set(_)
7118        | TypeRef::Seq(_)
7119        | TypeRef::Option(_)
7120        | TypeRef::Map(_, _) => domain_constant_name(ty),
7121    }
7122}
7123
7124fn domain_constant_name(ty: &TypeRef) -> String {
7125    match ty {
7126        TypeRef::Named(name) => format!("{}Values", tla_ident(name)),
7127        TypeRef::Enum(name) => format!("{}Values", tla_ident(name)),
7128        TypeRef::Seq(inner) => format!("SeqOf{}Values", tla_ident(type_ref_name(inner))),
7129        TypeRef::Set(inner) => format!("SetOf{}Values", tla_ident(type_ref_name(inner))),
7130        TypeRef::String => "StringValues".into(),
7131        TypeRef::Bool => "BooleanValues".into(),
7132        TypeRef::U32 => "U32Values".into(),
7133        TypeRef::U64 => "NatValues".into(),
7134        TypeRef::Option(inner) => format!("Option{}Values", tla_ident(type_ref_name(inner))),
7135        TypeRef::Map(key, value) => {
7136            format!(
7137                "Map{}{}Values",
7138                tla_ident(type_ref_name(key)),
7139                tla_ident(type_ref_name(value))
7140            )
7141        }
7142    }
7143}
7144
7145fn type_ref_name(ty: &TypeRef) -> String {
7146    match ty {
7147        TypeRef::Bool => "Bool".into(),
7148        TypeRef::U32 => "U32".into(),
7149        TypeRef::U64 => "U64".into(),
7150        TypeRef::String => "String".into(),
7151        TypeRef::Named(name) => name.as_str().to_owned(),
7152        TypeRef::Enum(name) => name.as_str().to_owned(),
7153        TypeRef::Option(inner) => format!("Option{}", type_ref_name(inner)),
7154        TypeRef::Set(inner) => format!("Set{}", type_ref_name(inner)),
7155        TypeRef::Seq(inner) => format!("Seq{}", type_ref_name(inner)),
7156        TypeRef::Map(key, value) => format!("Map{}{}", type_ref_name(key), type_ref_name(value)),
7157    }
7158}
7159
7160struct CompositionTlaCompiler<'a> {
7161    schema: &'a CompositionSchema,
7162    machine_by_instance: BTreeMap<&'a str, &'a MachineSchema>,
7163    named_bindings: BTreeMap<String, meerkat_machine_schema::RustTypeAtom>,
7164    fallback_machine: &'a MachineSchema,
7165    unchanged_frames: RefCell<UnchangedFrameInterner>,
7166    /// Shared with every machine compiler that renders into this module (see
7167    /// `MachineTlaCompiler::option_order_used`).
7168    option_order_used: Rc<Cell<bool>>,
7169}
7170
7171const COMPOSITION_UNCHANGED_CHUNK_SIZE: usize = 64;
7172const COMPOSITION_UNCHANGED_SPLIT_THRESHOLD: usize = 96;
7173
7174/// Prefix for the generated named UNCHANGED frame operators.
7175///
7176/// Deliberately upper-camel: the machine-poster TLA reader treats a
7177/// `^[a-z_][A-Za-z0-9_]* == ...` line before `THEOREM` as a machine invariant,
7178/// and a line ending in bare `==` as the head of a multi-line definition. An
7179/// upper-case name on a single line is invisible to both.
7180const UNCHANGED_FRAME_PREFIX: &str = "UnchangedFrame_";
7181
7182/// Stable 64-bit FNV-1a.
7183///
7184/// Frame operator names are derived from frame content so that adding or
7185/// removing a transition perturbs exactly the frames it touches instead of
7186/// renumbering every later one. That only holds if the hash itself is stable:
7187/// `std::collections::hash_map::DefaultHasher` is explicitly documented as not
7188/// stable across Rust releases, so a toolchain bump would rename every frame
7189/// and turn `machine-check-drift` red with no source change. FNV-1a is pinned
7190/// here for that reason.
7191fn fnv1a64(bytes: &[u8]) -> u64 {
7192    const OFFSET_BASIS: u64 = 0xcbf2_9ce4_8422_2325;
7193    const PRIME: u64 = 0x0000_0100_0000_01b3;
7194    let mut hash = OFFSET_BASIS;
7195    for byte in bytes {
7196        hash ^= u64::from(*byte);
7197        hash = hash.wrapping_mul(PRIME);
7198    }
7199    hash
7200}
7201
7202/// Renders one UNCHANGED frame as a single TLA line.
7203///
7204/// `chunking` carries the composition-only `(split_threshold, chunk_size)`
7205/// policy: TLC's semantic pass can overflow on very large tuple frames, so a
7206/// composition frame past the threshold is expressed as a conjunction of
7207/// smaller tuples. `/\` is an ordinary infix operator, so the conjunction is
7208/// the same formula as the previously emitted bulleted list. Machines pass
7209/// `None` and keep their single-tuple frame verbatim.
7210fn unchanged_frame_body(vars: &[String], chunking: Option<(usize, usize)>) -> String {
7211    if let Some((split_threshold, chunk_size)) = chunking
7212        && vars.len() > split_threshold
7213    {
7214        return vars
7215            .chunks(chunk_size)
7216            .map(|chunk| format!("UNCHANGED << {} >>", chunk.join(", ")))
7217            .collect::<Vec<_>>()
7218            .join(" /\\ ");
7219    }
7220    format!("UNCHANGED << {} >>", vars.join(", "))
7221}
7222
7223/// Interns the distinct UNCHANGED frames of one generated TLA module.
7224///
7225/// The renderer used to expand a full frame tuple inline at every action. On
7226/// the largest composition that was 32,850 expansions of 650 distinct frames,
7227/// which is where ~85% of the emitted bytes went. Each distinct frame is now
7228/// emitted once as a named operator and referenced by name.
7229#[derive(Default)]
7230struct UnchangedFrameInterner {
7231    /// Frame operator name -> single-line frame body. Names are derived from
7232    /// the body, so a name already bound to a *different* body is a hash
7233    /// collision, never a rename.
7234    frames: BTreeMap<String, String>,
7235    /// First observed collision, if any. Recorded rather than resolved: a
7236    /// counter suffix would be order-dependent across schema edits and, worse,
7237    /// would silently hand one action a different frame condition than it had.
7238    /// The owning `render` turns this into a typed error and emits nothing.
7239    collision: Option<UnchangedFrameCollision>,
7240}
7241
7242/// Two distinct frames that derive the same operator name.
7243#[derive(Debug, Clone, PartialEq, Eq)]
7244pub struct UnchangedFrameCollision {
7245    pub name: String,
7246    pub first: String,
7247    pub second: String,
7248}
7249
7250impl std::fmt::Display for UnchangedFrameCollision {
7251    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
7252        write!(
7253            f,
7254            "frame operator `{}` derives from two different frames:\n  {}\n  {}",
7255            self.name, self.first, self.second
7256        )
7257    }
7258}
7259
7260impl UnchangedFrameInterner {
7261    /// Returns the operator name for `body`, registering the definition on
7262    /// first sight.
7263    fn intern(&mut self, body: String) -> String {
7264        let name = format!("{UNCHANGED_FRAME_PREFIX}{:016x}", fnv1a64(body.as_bytes()));
7265        match self.frames.get(&name) {
7266            Some(existing) if *existing == body => {}
7267            Some(existing) => {
7268                if self.collision.is_none() {
7269                    self.collision = Some(UnchangedFrameCollision {
7270                        name: name.clone(),
7271                        first: existing.clone(),
7272                        second: body,
7273                    });
7274                }
7275            }
7276            None => {
7277                self.frames.insert(name.clone(), body);
7278            }
7279        }
7280        name
7281    }
7282
7283    fn collision(&self) -> Option<&UnchangedFrameCollision> {
7284        self.collision.as_ref()
7285    }
7286
7287    /// Renders the definition block, sorted by operator name.
7288    ///
7289    /// Sorted rather than first-use order so that a later schema edit inserts
7290    /// or drops a single definition line instead of shifting every definition
7291    /// after it. Returns `String::new()` when the module has no frames.
7292    fn definitions_block(&self) -> String {
7293        if self.frames.is_empty() {
7294            return String::new();
7295        }
7296        let mut out = String::new();
7297        pushln!(
7298            &mut out,
7299            "\\* Named UNCHANGED frames. One definition per distinct frame; every action"
7300        );
7301        pushln!(
7302            &mut out,
7303            "\\* that leaves those variables unchanged references the definition by name."
7304        );
7305        for (name, body) in &self.frames {
7306            pushln!(&mut out, "{name} == {body}");
7307        }
7308        pushln!(&mut out);
7309        out
7310    }
7311}
7312
7313impl<'a> CompositionTlaCompiler<'a> {
7314    fn new(
7315        schema: &'a CompositionSchema,
7316        machine_catalog: &'a [MachineSchema],
7317    ) -> Result<Self, String> {
7318        let machine_catalog_by_name = machine_catalog
7319            .iter()
7320            .map(|machine| (machine.machine.as_str(), machine))
7321            .collect::<BTreeMap<_, _>>();
7322
7323        let mut machine_by_instance = BTreeMap::new();
7324        for instance in &schema.machines {
7325            let machine = machine_catalog_by_name
7326                .get(instance.machine_name.as_str())
7327                .copied()
7328                .ok_or_else(|| {
7329                    format!(
7330                        "unknown machine schema `{}` for composition `{}`",
7331                        instance.machine_name, schema.name
7332                    )
7333                })?;
7334            machine_by_instance.insert(instance.instance_id.as_str(), machine);
7335        }
7336        let named_bindings =
7337            collect_composition_named_bindings(machine_by_instance.values().copied());
7338
7339        Ok(Self {
7340            schema,
7341            machine_by_instance,
7342            named_bindings,
7343            fallback_machine: machine_catalog.first().ok_or_else(|| {
7344                format!(
7345                    "no machine catalog available for composition `{}`",
7346                    schema.name
7347                )
7348            })?,
7349            unchanged_frames: RefCell::new(UnchangedFrameInterner::default()),
7350            option_order_used: Rc::default(),
7351        })
7352    }
7353
7354    /// The machine compiler for one instance's part of this module. Every
7355    /// compiler that renders into the module shares its option-order flag, so
7356    /// an `OptionLt` / `OptionLe` call never reaches the module without the
7357    /// definitions.
7358    fn instance_compiler(
7359        &self,
7360        instance_id: &str,
7361        helper_prefix: String,
7362    ) -> MachineTlaCompiler<'_> {
7363        MachineTlaCompiler::new_with_helper_prefix(self.machine(instance_id), helper_prefix)
7364            .with_phase_symbol(self.phase_var(instance_id))
7365            .with_field_env_override(self.machine_field_env(instance_id))
7366            .with_option_order_flag(Rc::clone(&self.option_order_used))
7367    }
7368
7369    fn render_unchanged_vars(&self, out: &mut String, prefix: &str, vars: &[String]) {
7370        if vars.is_empty() {
7371            return;
7372        }
7373        // The frame is interned on its variable list alone and referenced at
7374        // the caller's own `prefix`, so the conjunct keeps its original column.
7375        // Indentation is semantically load-bearing in TLA bulleted lists.
7376        let body = unchanged_frame_body(
7377            vars,
7378            Some((
7379                COMPOSITION_UNCHANGED_SPLIT_THRESHOLD,
7380                COMPOSITION_UNCHANGED_CHUNK_SIZE,
7381            )),
7382        );
7383        let name = self.unchanged_frames.borrow_mut().intern(body);
7384        writeln!(out, "{prefix}{name}").expect("write to string");
7385    }
7386
7387    fn render(&self) -> std::result::Result<String, CompositionTlaError> {
7388        // Fail-closed gate: every route component must resolve against the
7389        // composition schema before any CASE expression is emitted. This makes
7390        // the defensive `OTHER -> "unknown_*"` branches in the generated TLA
7391        // provably unreachable rather than silent catch-alls.
7392        self.validate_routes()?;
7393
7394        let mut out = String::new();
7395        let constants = self.collect_binding_domains();
7396        let named_samples =
7397            collect_composition_named_type_samples(self.schema, &self.machine_by_instance);
7398        let machine_vars = self.machine_vars();
7399        let obligation_vars = self.obligation_vars();
7400        let mut machine_invariant_names = Vec::new();
7401
7402        pushln!(&mut out, "---- MODULE model ----");
7403        pushln!(&mut out, "EXTENDS TLC, Naturals, Sequences, FiniteSets");
7404        pushln!(&mut out);
7405        writeln!(
7406            &mut out,
7407            "\\* Generated composition model for {}.",
7408            self.schema.name
7409        )
7410        .expect("write to string");
7411        pushln!(&mut out);
7412
7413        let mut model_constants = constants
7414            .iter()
7415            .filter(|(_, ty)| {
7416                !matches!(
7417                    ty,
7418                    TypeRef::Seq(_) | TypeRef::Option(_) | TypeRef::Map(_, _)
7419                )
7420            })
7421            .map(|(name, _)| name)
7422            .cloned()
7423            .collect::<Vec<_>>();
7424        if composition_uses_u64_max(self.schema, &self.machine_by_instance) {
7425            model_constants.push(TLA_RUST_U64_MAX_CONSTANT.to_owned());
7426        }
7427        if !model_constants.is_empty() {
7428            if model_constants
7429                .iter()
7430                .any(|constant| constant == TLA_RUST_U64_MAX_CONSTANT)
7431            {
7432                pushln!(
7433                    &mut out,
7434                    "\\* RustU64Max is the TLA boundary for Expr::U64Max; production generated Rust renders u64::MAX."
7435                );
7436            }
7437            writeln!(&mut out, "CONSTANTS {}", model_constants.join(", "))
7438                .expect("write to string");
7439            pushln!(&mut out);
7440        }
7441
7442        writeln!(&mut out, "None == [tag |-> \"none\", value |-> \"none\"]")
7443            .expect("write to string");
7444        writeln!(&mut out, "Some(v) == [tag |-> \"some\", value |-> v]");
7445        pushln!(&mut out);
7446        let option_order_anchor = out.len();
7447
7448        push_cfg_assignment_operator_definitions(
7449            &mut out,
7450            &constants,
7451            &self.named_bindings,
7452            &CfgAssignmentOperatorProfile {
7453                suffix: "Ci".to_owned(),
7454                explicit_values: None,
7455                sample_cardinality: default_sample_cardinality(false),
7456                domain_overrides: None,
7457                named_samples: &named_samples,
7458                include_string_samples: false,
7459            },
7460        );
7461        push_cfg_assignment_operator_definitions(
7462            &mut out,
7463            &constants,
7464            &self.named_bindings,
7465            &CfgAssignmentOperatorProfile {
7466                suffix: "Deep".to_owned(),
7467                explicit_values: None,
7468                sample_cardinality: self.schema.deep_domain_cardinality,
7469                domain_overrides: Some(&self.schema.deep_domain_overrides),
7470                named_samples: &named_samples,
7471                include_string_samples: false,
7472            },
7473        );
7474        for witness in &self.schema.witnesses {
7475            let witness_samples = collect_composition_witness_named_type_samples(
7476                self.schema,
7477                witness,
7478                &self.machine_by_instance,
7479            );
7480            push_cfg_assignment_operator_definitions(
7481                &mut out,
7482                &constants,
7483                &self.named_bindings,
7484                &CfgAssignmentOperatorProfile {
7485                    suffix: witness_cfg_operator_suffix(witness),
7486                    explicit_values: None,
7487                    sample_cardinality: self
7488                        .schema
7489                        .witness_domain_cardinality
7490                        .max(max_named_sample_cardinality(&witness_samples)),
7491                    domain_overrides: None,
7492                    named_samples: &witness_samples,
7493                    include_string_samples: true,
7494                },
7495            );
7496        }
7497        for (name, ty) in ordered_composite_domain_definitions(&constants) {
7498            let definition = match ty {
7499                TypeRef::Seq(inner) => render_sequence_domain_definition(inner),
7500                TypeRef::Option(inner) => render_option_domain_definition(inner),
7501                TypeRef::Map(key, value) => render_map_domain_definition(key, value),
7502                _ => continue,
7503            };
7504            writeln!(&mut out, "{} == {}", name, definition).expect("write to string");
7505        }
7506        if constants.values().any(|ty| {
7507            matches!(
7508                ty,
7509                TypeRef::Seq(_) | TypeRef::Option(_) | TypeRef::Map(_, _)
7510            )
7511        }) {
7512            pushln!(&mut out);
7513        }
7514        writeln!(
7515            &mut out,
7516            "MapLookup(map, key) == IF key \\in DOMAIN map THEN map[key] ELSE None"
7517        )
7518        .expect("write to string");
7519        writeln!(
7520            &mut out,
7521            "MapSet(map, key, value) == [x \\in DOMAIN map \\cup {{key}} |-> IF x = key THEN value ELSE map[x]]"
7522        )
7523        .expect("write to string");
7524        writeln!(
7525            &mut out,
7526            "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]]"
7527        )
7528        .expect("write to string");
7529        writeln!(
7530            &mut out,
7531            "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]]"
7532        )
7533        .expect("write to string");
7534        writeln!(
7535            &mut out,
7536            "MapRemove(map, key) == [x \\in DOMAIN map \\ {{key}} |-> map[x]]"
7537        )
7538        .expect("write to string");
7539        writeln!(
7540            &mut out,
7541            "StartsWith(seq, prefix) == /\\ Len(prefix) <= Len(seq) /\\ SubSeq(seq, 1, Len(prefix)) = prefix"
7542        )
7543        .expect("write to string");
7544        writeln!(
7545            &mut out,
7546            "SeqElements(seq) == {{seq[i] : i \\in 1..Len(seq)}}"
7547        )
7548        .expect("write to string");
7549        writeln!(
7550            &mut out,
7551            "Count(seq, value) == Cardinality({{i \\in DOMAIN seq : seq[i] = value}})"
7552        )
7553        .expect("write to string");
7554        if self.schema.machines.iter().any(|instance| {
7555            !self
7556                .machine(instance.instance_id.as_str())
7557                .tlc_representative_inputs
7558                .is_empty()
7559        }) {
7560            writeln!(
7561                &mut out,
7562                "{TLC_REPRESENTATIVE_DOMAIN_HELPER}(values) == IF values = {{}} THEN {{}} ELSE {{CHOOSE value \\in values : TRUE}}"
7563            )
7564            .expect("write to string");
7565        }
7566        writeln!(
7567            &mut out,
7568            "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)"
7569        )
7570        .expect("write to string");
7571        writeln!(
7572            &mut out,
7573            "RECURSIVE SeqRemoveAll(_, _)\nSeqRemoveAll(seq, values) == IF Len(values) = 0 THEN seq ELSE SeqRemoveAll(SeqRemove(seq, Head(values)), Tail(values))"
7574        )
7575        .expect("write to string");
7576        writeln!(
7577            &mut out,
7578            "AppendIfMissing(seq, value) == IF value \\in SeqElements(seq) THEN seq ELSE Append(seq, value)"
7579        )
7580        .expect("write to string");
7581        self.render_static_sets(&mut out)?;
7582
7583        let all_vars = {
7584            let mut v = machine_vars;
7585            v.extend(obligation_vars.clone());
7586            v.push("model_step_count".into());
7587            v.push("pending_inputs".into());
7588            v.push("observed_inputs".into());
7589            v.push("pending_routes".into());
7590            v.push("delivered_routes".into());
7591            v.push("emitted_effects".into());
7592            v.push("observed_transitions".into());
7593            v.push("witness_current_script_input".into());
7594            v.push("witness_remaining_script_inputs".into());
7595            v
7596        };
7597        writeln!(&mut out, "VARIABLES {}", all_vars.join(", ")).expect("write to string");
7598        writeln!(&mut out, "vars == << {} >>", all_vars.join(", ")).expect("write to string");
7599        pushln!(&mut out);
7600
7601        // Named UNCHANGED frames are spliced back in here once the whole module
7602        // body is rendered: the frames are discovered while rendering actions,
7603        // but TLA requires an operator to be defined before it is referenced.
7604        // This is the first point where every frame variable is in scope.
7605        let unchanged_frame_anchor = out.len();
7606
7607        writeln!(
7608            &mut out,
7609            "RoutePackets == SeqElements(pending_routes) \\cup delivered_routes"
7610        )
7611        .expect("write to string");
7612        writeln!(
7613            &mut out,
7614            "PendingActors == {{ActorOfMachine(packet.machine) : packet \\in SeqElements(pending_inputs)}}"
7615        )
7616        .expect("write to string");
7617        writeln!(
7618            &mut out,
7619            "HigherPriorityReady(actor) == \\E priority \\in ActorPriorities : /\\ priority[2] = actor /\\ priority[1] \\in PendingActors"
7620        )
7621        .expect("write to string");
7622        pushln!(&mut out);
7623
7624        pushln!(&mut out, "BaseInit ==");
7625        for instance in &self.schema.machines {
7626            let machine = self.machine(instance.instance_id.as_str());
7627            writeln!(
7628                &mut out,
7629                "    /\\ {} = {}",
7630                self.phase_var(instance.instance_id.as_str()),
7631                tla_string(&machine.state.init.phase)
7632            )
7633            .expect("write to string");
7634            for field in &machine.state.fields {
7635                let init_expr = machine
7636                    .state
7637                    .init
7638                    .fields
7639                    .iter()
7640                    .find(|item| item.field == field.name)
7641                    .map(|item| {
7642                        let compiler = self.instance_compiler(
7643                            instance.instance_id.as_str(),
7644                            format!("{}__", tla_ident(&instance.instance_id)),
7645                        );
7646                        compiler.render_expr(&item.expr, &BTreeMap::new(), &BTreeMap::new())
7647                    })
7648                    .unwrap_or_else(|| default_state_init_expr(&field.ty));
7649                writeln!(
7650                    &mut out,
7651                    "    /\\ {} = {}",
7652                    self.field_var(instance.instance_id.as_str(), field.name.as_str()),
7653                    init_expr
7654                )
7655                .expect("write to string");
7656            }
7657        }
7658        for var in &obligation_vars {
7659            pushln!(&mut out, "    /\\ {} = {{}}", var);
7660        }
7661        pushln!(&mut out, "    /\\ model_step_count = 0");
7662        pushln!(&mut out, "    /\\ pending_routes = <<>>");
7663        pushln!(&mut out, "    /\\ delivered_routes = {{}}");
7664        pushln!(&mut out, "    /\\ emitted_effects = {{}}");
7665        pushln!(&mut out, "    /\\ observed_transitions = {{}}");
7666        pushln!(&mut out);
7667
7668        pushln!(&mut out, "Init ==");
7669        pushln!(&mut out, "    /\\ BaseInit");
7670        pushln!(&mut out, "    /\\ pending_inputs = <<>>");
7671        pushln!(&mut out, "    /\\ observed_inputs = {{}}");
7672        pushln!(&mut out, "    /\\ witness_current_script_input = None");
7673        pushln!(&mut out, "    /\\ witness_remaining_script_inputs = <<>>");
7674        pushln!(&mut out);
7675
7676        for witness in &self.schema.witnesses {
7677            writeln!(
7678                &mut out,
7679                "{} ==",
7680                composition_witness_init_name(&witness.name)
7681            )
7682            .expect("write to string");
7683            writeln!(&mut out, "    /\\ BaseInit");
7684            writeln!(
7685                &mut out,
7686                "    /\\ pending_inputs = {}",
7687                self.witness_initial_pending_inputs_expr(witness)
7688            )
7689            .expect("write to string");
7690            writeln!(
7691                &mut out,
7692                "    /\\ observed_inputs = {}",
7693                self.witness_initial_observed_inputs_expr(witness)
7694            )
7695            .expect("write to string");
7696            writeln!(
7697                &mut out,
7698                "    /\\ witness_current_script_input = {}",
7699                self.witness_current_script_input_expr(witness)
7700            )
7701            .expect("write to string");
7702            writeln!(
7703                &mut out,
7704                "    /\\ witness_remaining_script_inputs = {}",
7705                self.witness_remaining_script_inputs_expr(witness)
7706            )
7707            .expect("write to string");
7708            pushln!(&mut out);
7709        }
7710
7711        for instance in &self.schema.machines {
7712            let machine = self.machine(instance.instance_id.as_str());
7713            let helper_prefix = format!("{}__", tla_ident(&instance.instance_id));
7714            let mut compiler = self.instance_compiler(instance.instance_id.as_str(), helper_prefix);
7715            for derived in helper_dependency_order(machine)? {
7716                compiler.render_helper(&mut out, derived);
7717                pushln!(&mut out);
7718            }
7719            if machine.machine.as_str() == "MobMachine" {
7720                compiler.render_mob_machine_native_helpers(&mut out);
7721                pushln!(&mut out);
7722            }
7723            if machine.machine.as_str() == "MeerkatMachine" {
7724                compiler.render_meerkat_machine_native_helpers(&mut out);
7725                pushln!(&mut out);
7726            }
7727            if machine.machine.as_str() == "RuntimeDeliveryMachine" {
7728                compiler.render_runtime_delivery_native_helpers(&mut out);
7729                pushln!(&mut out);
7730            }
7731            if machine.machine.as_str() == "SessionDocumentMachine" {
7732                compiler.render_session_document_native_helpers(&mut out);
7733                pushln!(&mut out);
7734            }
7735
7736            let mut rendered_actions = Vec::new();
7737            for transition in &machine.transitions {
7738                let mut action = String::new();
7739                self.render_machine_transition_action(
7740                    &mut compiler,
7741                    instance.instance_id.as_str(),
7742                    transition,
7743                    &mut action,
7744                )?;
7745                rendered_actions.push(action);
7746            }
7747
7748            for helper in &compiler.helper_defs {
7749                pushln!(&mut out, "{helper}");
7750                pushln!(&mut out);
7751            }
7752
7753            for action in &rendered_actions {
7754                pushln!(&mut out, "{action}");
7755                pushln!(&mut out);
7756            }
7757
7758            let invariant_field_env = self.machine_field_env(instance.instance_id.as_str());
7759            let invariant_binding_env = BTreeMap::new();
7760            let invariant_types = BTreeMap::new();
7761            for invariant in &machine.invariants {
7762                let invariant_name =
7763                    self.machine_invariant_name(instance.instance_id.as_str(), &invariant.name);
7764                machine_invariant_names.push(invariant_name.clone());
7765                writeln!(
7766                    &mut out,
7767                    "{} == {}",
7768                    invariant_name,
7769                    compiler.render_expr_with_types(
7770                        &invariant.expr,
7771                        &invariant_field_env,
7772                        &invariant_binding_env,
7773                        &invariant_types
7774                    )
7775                )
7776                .expect("write to string");
7777            }
7778            if !machine.invariants.is_empty() {
7779                pushln!(&mut out);
7780            }
7781        }
7782
7783        self.render_entry_packet_admissibility_helpers(&mut out)?;
7784        self.render_entry_input_actions(&mut out);
7785        self.render_deliver_queued_route_action(&mut out);
7786        self.render_reject_pending_entry_input_action(&mut out);
7787        self.render_quiescent_stutter(&mut out);
7788        self.render_witness_inject_actions(&mut out);
7789        self.render_witness_completion_operators(&mut out);
7790        self.render_witness_action_constraint_operators(&mut out);
7791        self.render_witness_satisfied_stutter_actions(&mut out);
7792        // TLA+ does not permit action references before their definitions.
7793        // Owner-feedback actions participate in CoreNext and witness Next, so
7794        // render them before either dispatcher is declared.
7795        self.render_owner_actor_processes(&mut out)?;
7796
7797        let core_next_branches = self.core_next_branches();
7798
7799        pushln!(&mut out, "CoreNext ==");
7800        for branch in &core_next_branches {
7801            pushln!(&mut out, "    \\/ {branch}");
7802        }
7803        pushln!(&mut out);
7804
7805        let inject_branches = self
7806            .schema
7807            .entry_inputs
7808            .iter()
7809            .map(|entry_input| self.render_entry_input_call(entry_input))
7810            .collect::<Vec<_>>();
7811
7812        pushln!(&mut out, "InjectNext ==");
7813        if inject_branches.is_empty() {
7814            pushln!(&mut out, "    FALSE");
7815        } else {
7816            for branch in &inject_branches {
7817                pushln!(&mut out, "    \\/ {branch}");
7818            }
7819        }
7820        pushln!(&mut out);
7821
7822        pushln!(&mut out, "Next ==");
7823        pushln!(&mut out, "    \\/ CoreNext");
7824        if !inject_branches.is_empty() {
7825            pushln!(&mut out, "    \\/ InjectNext");
7826        }
7827        pushln!(&mut out);
7828
7829        for witness in &self.schema.witnesses {
7830            let witness_branches = self.witness_next_branches(witness)?;
7831            writeln!(
7832                &mut out,
7833                "{} ==",
7834                composition_witness_next_name(&witness.name)
7835            )
7836            .expect("write to string");
7837            for branch in &witness_branches {
7838                pushln!(&mut out, "    \\/ {branch}");
7839            }
7840            writeln!(
7841                &mut out,
7842                "    \\/ {}",
7843                self.render_witness_inject_next_call(witness)
7844            )
7845            .expect("write to string");
7846            pushln!(&mut out);
7847        }
7848        pushln!(&mut out);
7849
7850        for invariant in &self.schema.invariants {
7851            writeln!(
7852                &mut out,
7853                "{} == {}",
7854                invariant.name,
7855                render_composition_invariant_formula(self.schema, &invariant.kind)
7856            )
7857            .expect("write to string");
7858        }
7859        if !self.schema.invariants.is_empty() {
7860            pushln!(&mut out);
7861        }
7862
7863        self.render_obligation_invariants(&mut out, &mut machine_invariant_names)?;
7864
7865        self.render_coverage_instrumentation(&mut out);
7866
7867        writeln!(
7868            &mut out,
7869            "CiStateConstraint == {}",
7870            render_composition_state_constraint(
7871                self.schema,
7872                self.schema
7873                    .ci_limits
7874                    .as_ref()
7875                    .unwrap_or(&CompositionStateLimits::ci_defaults()),
7876                self
7877            )
7878        )
7879        .expect("write to string");
7880        writeln!(
7881            &mut out,
7882            "DeepStateConstraint == {}",
7883            render_composition_state_constraint(
7884                self.schema,
7885                &composition_deep_state_limits(self.schema),
7886                self
7887            )
7888        )
7889        .expect("write to string");
7890        for witness in &self.schema.witnesses {
7891            writeln!(
7892                &mut out,
7893                "{} == {}",
7894                composition_witness_state_constraint_name(&witness.name),
7895                render_composition_state_constraint(
7896                    self.schema,
7897                    &effective_composition_state_limits(&witness.state_limits, Some(witness)),
7898                    self
7899                )
7900            )
7901            .expect("write to string");
7902        }
7903        pushln!(&mut out);
7904
7905        pushln!(&mut out, "Spec ==");
7906        pushln!(&mut out, "    /\\ Init");
7907        pushln!(&mut out, "    /\\ [][Next]_vars");
7908        pushln!(&mut out);
7909
7910        for witness in &self.schema.witnesses {
7911            let fairness_clauses = self.witness_fairness_clauses(witness)?;
7912            let fairness_chunk_names = fairness_clauses
7913                .chunks(24)
7914                .enumerate()
7915                .map(|(index, chunk)| {
7916                    let chunk_name = composition_witness_fairness_name(&witness.name, index);
7917                    writeln!(&mut out, "{chunk_name} ==").expect("write to string");
7918                    for clause in chunk {
7919                        writeln!(&mut out, "    /\\ WF_vars({clause})").expect("write to string");
7920                    }
7921                    pushln!(&mut out);
7922                    chunk_name
7923                })
7924                .collect::<Vec<_>>();
7925
7926            writeln!(
7927                &mut out,
7928                "{} ==",
7929                composition_witness_spec_name(&witness.name),
7930            )
7931            .expect("write to string");
7932            writeln!(
7933                &mut out,
7934                "    /\\ {}",
7935                composition_witness_init_name(&witness.name),
7936            )
7937            .expect("write to string");
7938            writeln!(
7939                &mut out,
7940                "    /\\ [] [{}]_vars",
7941                composition_witness_next_name(&witness.name)
7942            )
7943            .expect("write to string");
7944            for chunk_name in fairness_chunk_names {
7945                writeln!(&mut out, "    /\\ {chunk_name}").expect("write to string");
7946            }
7947            pushln!(&mut out);
7948        }
7949        for witness in &self.schema.witnesses {
7950            for route in &witness.expected_routes {
7951                let formula = composition_route_observed_operator_name(route);
7952                writeln!(
7953                    &mut out,
7954                    "{} == {}",
7955                    composition_witness_route_property_name(&witness.name, route),
7956                    self.render_witness_obligation_formula(witness, formula)
7957                )
7958                .expect("write to string");
7959            }
7960            for rule in &witness.expected_scheduler_rules {
7961                let formula = composition_scheduler_triggered_operator_name(rule);
7962                writeln!(
7963                    &mut out,
7964                    "{} == {}",
7965                    composition_witness_scheduler_property_name(&witness.name, rule),
7966                    self.render_witness_obligation_formula(witness, formula)
7967                )
7968                .expect("write to string");
7969            }
7970            for (idx, state) in witness.expected_states.iter().enumerate() {
7971                let formula = self.render_witness_state_formula(state);
7972                writeln!(
7973                    &mut out,
7974                    "{} == {}",
7975                    composition_witness_state_property_name(&witness.name, idx),
7976                    self.render_witness_obligation_formula(witness, formula)
7977                )
7978                .expect("write to string");
7979            }
7980            for transition in &witness.expected_transitions {
7981                let formula = self.render_witness_transition_formula(transition);
7982                writeln!(
7983                    &mut out,
7984                    "{} == {}",
7985                    composition_witness_transition_property_name(
7986                        &witness.name,
7987                        &transition.machine,
7988                        &transition.transition,
7989                    ),
7990                    self.render_witness_obligation_formula(witness, formula)
7991                )
7992                .expect("write to string");
7993            }
7994            for (idx, ordering) in witness.expected_transition_order.iter().enumerate() {
7995                let formula = self.render_witness_transition_order_formula(ordering);
7996                writeln!(
7997                    &mut out,
7998                    "{} == {}",
7999                    composition_witness_transition_order_property_name(&witness.name, idx),
8000                    self.render_witness_obligation_formula(witness, formula)
8001                )
8002                .expect("write to string");
8003            }
8004        }
8005        if !self.schema.witnesses.is_empty() {
8006            pushln!(&mut out);
8007        }
8008        for invariant in &self.schema.invariants {
8009            pushln!(&mut out, "THEOREM Spec => []{}", invariant.name);
8010        }
8011        for invariant_name in &machine_invariant_names {
8012            pushln!(&mut out, "THEOREM Spec => []{}", invariant_name);
8013        }
8014        pushln!(&mut out);
8015        writeln!(
8016            &mut out,
8017            "============================================================================="
8018        )
8019        .expect("write to string");
8020
8021        // Fail closed on a frame-name collision: the rendered body already
8022        // references one name for two different frames, so returning it would
8023        // silently give an action the wrong frame condition.
8024        let frames = self.unchanged_frames.borrow();
8025        if let Some(collision) = frames.collision() {
8026            return Err(CompositionTlaError::UnchangedFrameCollision {
8027                composition: self.schema.name.as_str().to_owned(),
8028                collision: collision.clone(),
8029            });
8030        }
8031        out.insert_str(unchanged_frame_anchor, &frames.definitions_block());
8032        // Before the frame anchor, so inserting it last leaves that one valid.
8033        if self.option_order_used.get() {
8034            out.insert_str(option_order_anchor, TLA_OPTION_ORDER_DEFINITIONS);
8035        }
8036
8037        Ok(out)
8038    }
8039
8040    fn collect_binding_domains(&self) -> BTreeMap<String, TypeRef> {
8041        collect_composition_binding_domains(self.schema, &self.machine_by_instance)
8042    }
8043
8044    fn machine(&self, instance_id: impl AsRef<str>) -> &MachineSchema {
8045        self.machine_by_instance
8046            .get(instance_id.as_ref())
8047            .copied()
8048            .unwrap_or(self.fallback_machine)
8049    }
8050
8051    fn actor(&self, instance_id: impl AsRef<str>) -> &str {
8052        let instance_id = instance_id.as_ref();
8053        self.schema
8054            .machines
8055            .iter()
8056            .find(|machine| machine.instance_id.as_str() == instance_id)
8057            .map(|machine| machine.actor.as_str())
8058            .unwrap_or("")
8059    }
8060
8061    fn phase_var(&self, instance_id: impl AsRef<str>) -> String {
8062        format!("{}_phase", tla_ident(instance_id))
8063    }
8064
8065    fn field_var(&self, instance_id: impl AsRef<str>, field: impl AsRef<str>) -> String {
8066        format!("{}_{}", tla_ident(instance_id), tla_ident(field))
8067    }
8068
8069    fn machine_invariant_name(
8070        &self,
8071        instance_id: impl AsRef<str>,
8072        invariant: impl AsRef<str>,
8073    ) -> String {
8074        format!("{}_{}", tla_ident(instance_id), tla_ident(invariant))
8075    }
8076
8077    fn machine_transition_name(
8078        &self,
8079        instance_id: impl AsRef<str>,
8080        transition: &TransitionSchema,
8081    ) -> String {
8082        format!("{}_{}", tla_ident(instance_id), tla_ident(&transition.name))
8083    }
8084
8085    fn machine_transition_call(&self, instance_id: &str, transition: &TransitionSchema) -> String {
8086        if transition.on.bindings().is_empty() {
8087            self.machine_transition_name(instance_id, transition)
8088        } else {
8089            let binding_types = transition_trigger_variant(self.machine(instance_id), transition)
8090                .map(|variant| {
8091                    variant
8092                        .fields
8093                        .iter()
8094                        .filter(|field| {
8095                            transition
8096                                .on
8097                                .bindings()
8098                                .iter()
8099                                .any(|binding| binding == &field.name)
8100                        })
8101                        .map(|field| (field.name.as_str().to_owned(), field.ty.clone()))
8102                        .collect::<BTreeMap<_, _>>()
8103                })
8104                .unwrap_or_default();
8105            let forced_bool_literals = transition_forced_bool_literals(transition, &binding_types);
8106            let mut prefix = String::new();
8107            for binding in transition.on.bindings() {
8108                if forced_bool_literals.contains_key(binding.as_str()) {
8109                    continue;
8110                }
8111                let local = format!("arg_{}", tla_ident(binding.as_str()));
8112                let Some(ty) = binding_types.get(binding.as_str()) else {
8113                    return self.machine_transition_name(instance_id, transition);
8114                };
8115                let domain = self.binding_domain_for_binding(
8116                    instance_id,
8117                    trigger_input_variant(transition),
8118                    binding.as_str(),
8119                    ty,
8120                );
8121                let domain = if transition_uses_tlc_representative_payload(
8122                    self.machine(instance_id),
8123                    transition,
8124                ) {
8125                    tlc_representative_domain(domain)
8126                } else {
8127                    domain
8128                };
8129                push_fmt(&mut prefix, format_args!("\\E {local} \\in {domain} : "));
8130            }
8131            let args = transition
8132                .on
8133                .bindings()
8134                .iter()
8135                .map(|binding| {
8136                    forced_bool_literals
8137                        .get(binding.as_str())
8138                        .map(|value| tla_bool_literal(*value).to_owned())
8139                        .unwrap_or_else(|| format!("arg_{}", tla_ident(binding.as_str())))
8140                })
8141                .collect::<Vec<_>>()
8142                .join(", ");
8143            format!(
8144                "{prefix}{}({args})",
8145                self.machine_transition_name(instance_id, transition)
8146            )
8147        }
8148    }
8149
8150    fn binding_domain_for_type(&self, ty: &TypeRef) -> String {
8151        match ty {
8152            TypeRef::Bool => "BOOLEAN".into(),
8153            TypeRef::U32 | TypeRef::U64 => "0..2".into(),
8154            TypeRef::String => "StringValues".into(),
8155            TypeRef::Named(_)
8156            | TypeRef::Enum(_)
8157            | TypeRef::Seq(_)
8158            | TypeRef::Set(_)
8159            | TypeRef::Option(_)
8160            | TypeRef::Map(_, _) => domain_constant_name(ty),
8161        }
8162    }
8163
8164    /// Payload domain for one bound field of `input` on `instance_id`: the
8165    /// machine's declared input field domain if it has one, otherwise the
8166    /// type's default domain.
8167    fn binding_domain_for_binding(
8168        &self,
8169        instance_id: &str,
8170        input: Option<&str>,
8171        binding: &str,
8172        ty: &TypeRef,
8173    ) -> String {
8174        let declared =
8175            input.and_then(|input| self.machine(instance_id).input_field_domain(input, binding));
8176        match declared {
8177            Some(meerkat_machine_schema::InputFieldDomainKind::StateField(state_field)) => {
8178                format!("{{{}}}", self.field_var(instance_id, state_field.as_str()))
8179            }
8180            Some(meerkat_machine_schema::InputFieldDomainKind::AdditionalValues(values)) => {
8181                additional_values_domain(&self.binding_domain_for_type(ty), values)
8182            }
8183            // A composition has no machine CI profile: it explores the
8184            // field's Deep samples, the declared values and `0..2`.
8185            Some(meerkat_machine_schema::InputFieldDomainKind::CiValues(values)) => {
8186                render_u64_set(&broad_input_samples(values))
8187            }
8188            None => self.binding_domain_for_type(ty),
8189        }
8190    }
8191
8192    fn machine_vars(&self) -> Vec<String> {
8193        let mut vars = Vec::new();
8194        for instance in &self.schema.machines {
8195            vars.push(self.phase_var(instance.instance_id.as_str()));
8196            let machine = self.machine(instance.instance_id.as_str());
8197            for field in &machine.state.fields {
8198                vars.push(self.field_var(instance.instance_id.as_str(), field.name.as_str()));
8199            }
8200        }
8201        vars
8202    }
8203
8204    fn machine_field_env(&self, instance_id: &str) -> BTreeMap<String, String> {
8205        let machine = self.machine(instance_id);
8206        machine
8207            .state
8208            .fields
8209            .iter()
8210            .map(|field| {
8211                (
8212                    field.name.as_str().to_owned(),
8213                    self.field_var(instance_id, field.name.as_str()),
8214                )
8215            })
8216            .collect()
8217    }
8218
8219    fn obligation_symbol_suffix(
8220        &self,
8221        protocol: &meerkat_machine_schema::EffectHandoffProtocol,
8222    ) -> String {
8223        format!(
8224            "{}_{}",
8225            tla_ident(&protocol.producer_instance),
8226            tla_ident(&protocol.name)
8227        )
8228    }
8229
8230    fn obligation_var(&self, protocol: &meerkat_machine_schema::EffectHandoffProtocol) -> String {
8231        format!("obligation_{}", self.obligation_symbol_suffix(protocol))
8232    }
8233
8234    /// Returns TLA+ variable names for obligation tracking — one per
8235    /// concrete producer/protocol pair.
8236    fn obligation_vars(&self) -> Vec<String> {
8237        self.schema
8238            .handoff_protocols
8239            .iter()
8240            .map(|protocol| self.obligation_var(protocol))
8241            .collect()
8242    }
8243
8244    fn feedback_variant(
8245        &self,
8246        feedback: &FeedbackInputRef,
8247    ) -> std::result::Result<&VariantSchema, String> {
8248        self.machine(&feedback.machine_instance)
8249            .inputs
8250            .variant_named(&feedback.input_variant)
8251            .map_err(|_| {
8252                format!(
8253                    "feedback variant `{}` not found for machine `{}`",
8254                    feedback.input_variant, feedback.machine_instance
8255                )
8256            })
8257    }
8258
8259    /// The feedback input's payload record, the quantifiers over the values it
8260    /// leaves open, and the obligation members it names. An `ObligationMember`
8261    /// value ranges over that set field of the obligation token, so the owner
8262    /// can only name a member the obligation actually carries.
8263    fn feedback_payload_expr(
8264        &self,
8265        feedback: &FeedbackInputRef,
8266        token_var: &str,
8267    ) -> std::result::Result<FeedbackPayload, String> {
8268        let variant = self.feedback_variant(feedback)?;
8269        let mut owner_context_quantifiers = Vec::new();
8270        let mut payload_fields = Vec::new();
8271        let mut members = Vec::new();
8272
8273        for field in &variant.fields {
8274            let binding = feedback
8275                .field_bindings
8276                .iter()
8277                .find(|binding| binding.input_field == field.name)
8278                .ok_or_else(|| format!("feedback binding for field `{}` not found", field.name))?;
8279            let expr = match &binding.source {
8280                FeedbackFieldSource::ObligationField(source_field) => {
8281                    format!("{token_var}.{}", tla_ident(source_field))
8282                }
8283                FeedbackFieldSource::ObligationMember(source_field) => {
8284                    let var_name = format!("member_{}", tla_ident(source_field));
8285                    owner_context_quantifiers.push(format!(
8286                        "{var_name} \\in {token_var}.{}",
8287                        tla_ident(source_field)
8288                    ));
8289                    members.push((tla_ident(source_field), var_name.clone()));
8290                    var_name
8291                }
8292                FeedbackFieldSource::OwnerContext(name) => {
8293                    let var_name = format!("owner_ctx_{}", tla_ident(name));
8294                    let domain = render_type_domain_expr(&field.ty);
8295                    owner_context_quantifiers.push(format!("{var_name} \\in {domain}"));
8296                    var_name
8297                }
8298            };
8299            payload_fields.push(format!("{} |-> {}", tla_ident(&field.name), expr));
8300        }
8301
8302        let payload_expr = if payload_fields.is_empty() {
8303            "[tag |-> \"unit\"]".to_string()
8304        } else {
8305            format!("[{}]", payload_fields.join(", "))
8306        };
8307
8308        Ok(FeedbackPayload {
8309            payload_expr,
8310            quantifiers: owner_context_quantifiers,
8311            members,
8312        })
8313    }
8314
8315    /// Obligation fields some feedback input of `protocol` names members of.
8316    /// The obligation token stays open while any of them is non-empty.
8317    fn protocol_member_fields(
8318        protocol: &meerkat_machine_schema::EffectHandoffProtocol,
8319    ) -> BTreeSet<String> {
8320        protocol
8321            .allowed_feedback_inputs
8322            .iter()
8323            .flat_map(|feedback| feedback.field_bindings.iter())
8324            .filter_map(|binding| match &binding.source {
8325                FeedbackFieldSource::ObligationMember(field) => Some(tla_ident(field)),
8326                _ => None,
8327            })
8328            .collect()
8329    }
8330
8331    /// Renders obligation closure invariants into the TLA+ output.
8332    ///
8333    /// For each handoff protocol, generates:
8334    /// - `NoOpenObligationsOnTerminal_<protocol>`: when the producer machine is
8335    ///   in a terminal phase, the obligation set must be empty.
8336    /// - `NoFeedbackWithoutObligation_<protocol>`: a feedback input can only be
8337    ///   observed if there's a corresponding outstanding obligation.
8338    fn render_obligation_invariants(
8339        &self,
8340        out: &mut String,
8341        invariant_names: &mut Vec<String>,
8342    ) -> std::result::Result<(), String> {
8343        for protocol in &self.schema.handoff_protocols {
8344            let suffix = self.obligation_symbol_suffix(protocol);
8345            let var = self.obligation_var(protocol);
8346            let phase_var = self.phase_var(&protocol.producer_instance);
8347
8348            // Find terminal phases for the producer machine.
8349            let machine = self.machine(&protocol.producer_instance);
8350            let terminal_phases: Vec<&str> = machine
8351                .state
8352                .terminal_phases
8353                .iter()
8354                .map(meerkat_machine_schema::identity::PhaseId::as_str)
8355                .collect();
8356
8357            // NoOpenObligationsOnTerminal: terminal phase => obligation set is
8358            // empty. Only an AckRequired protocol needs owner feedback to close
8359            // its obligations; under AckOrAbort and TerminalClosure the terminal
8360            // phase is itself the closure, and a PublicationOnly protocol has no
8361            // feedback (the publication closes it), so for those the invariant
8362            // would be unsatisfiable once the producer reaches a terminal phase.
8363            if terminal_closure_required(protocol, machine) {
8364                let inv_name = format!("NoOpenObligationsOnTerminal_{}", suffix);
8365                let terminal_disjuncts: Vec<String> = terminal_phases
8366                    .iter()
8367                    .map(|phase| format!("{} = {}", phase_var, tla_string(phase)))
8368                    .collect();
8369                writeln!(
8370                    out,
8371                    "{} == ({}) => {} = {{}}",
8372                    inv_name,
8373                    terminal_disjuncts.join(" \\/ "),
8374                    var
8375                )
8376                .expect("write to string");
8377                invariant_names.push(inv_name);
8378            }
8379        }
8380
8381        let owner_feedback_sources = self
8382            .schema
8383            .handoff_protocols
8384            .iter()
8385            .flat_map(|protocol| {
8386                protocol.allowed_feedback_inputs.iter().map(move |feedback| {
8387                    format!(
8388                        "(/\\ 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)",
8389                        tla_string(&feedback.machine_instance),
8390                        tla_string(&feedback.input_variant),
8391                        tla_string(&protocol.producer_instance),
8392                        tla_string(&protocol.effect_variant),
8393                        tla_string(&protocol.producer_instance),
8394                        tla_string(&protocol.effect_variant),
8395                    )
8396                })
8397            })
8398            .collect::<Vec<_>>();
8399        if !owner_feedback_sources.is_empty() {
8400            pushln!(out, "OwnerFeedbackHasProtocolProvenance ==");
8401            pushln!(out, "    \\A input_packet \\in observed_inputs :");
8402            pushln!(out, "        input_packet.source_kind /= \"owner\"");
8403            writeln!(
8404                out,
8405                "        \\/ ({})",
8406                owner_feedback_sources.join(" \\/ ")
8407            )
8408            .expect("write to string");
8409            invariant_names.push("OwnerFeedbackHasProtocolProvenance".to_string());
8410        }
8411
8412        if !self.schema.handoff_protocols.is_empty() {
8413            pushln!(out);
8414        }
8415        Ok(())
8416    }
8417
8418    /// Renders owner-actor process definitions: nondeterministic actions that
8419    /// model the owner choosing to submit protocol-allowed feedback when an
8420    /// obligation is outstanding.
8421    ///
8422    /// Each allowed feedback input generates an
8423    /// `OwnerFeedback_<protocol>_<input>` action that:
8424    /// - Is enabled when the obligation set is non-empty
8425    /// - Nondeterministically picks one of the allowed feedback inputs
8426    /// - Removes one obligation token from the set
8427    /// - Injects the feedback as a pending input
8428    ///
8429    /// If any protocols have `liveness_annotation`, fairness comments are added.
8430    fn render_owner_actor_processes(&self, out: &mut String) -> std::result::Result<(), String> {
8431        for protocol in &self.schema.handoff_protocols {
8432            let var = self.obligation_var(protocol);
8433
8434            if protocol.allowed_feedback_inputs.is_empty() {
8435                continue;
8436            }
8437
8438            if let Some(liveness) = &protocol.liveness_annotation {
8439                writeln!(out, "\\* Liveness: {liveness}").expect("write to string");
8440            }
8441
8442            for feedback in &protocol.allowed_feedback_inputs {
8443                let action_name = self.owner_feedback_action_name(protocol, feedback);
8444                let FeedbackPayload {
8445                    payload_expr,
8446                    quantifiers: owner_context_quantifiers,
8447                    members,
8448                } = self.feedback_payload_expr(feedback, "token")?;
8449                let input_expr = format!(
8450                    "[machine |-> {}, variant |-> {}, source_kind |-> \"owner\", source_machine |-> {}, source_effect |-> {}, source_route |-> \"none\", effect_id |-> token.effect_id, payload |-> {}]",
8451                    tla_string(&feedback.machine_instance),
8452                    tla_string(&feedback.input_variant),
8453                    tla_string(&protocol.producer_instance),
8454                    tla_string(&protocol.effect_variant),
8455                    payload_expr,
8456                );
8457
8458                writeln!(out, "{action_name} ==").expect("write to string");
8459                writeln!(out, "    /\\ {} /= {{}}", var).expect("write to string");
8460                writeln!(out, "    /\\ \\E token \\in {} :", var).expect("write to string");
8461                let quantifier_prefix = if owner_context_quantifiers.is_empty() {
8462                    String::new()
8463                } else {
8464                    format!("\\E {} : ", owner_context_quantifiers.join(", "))
8465                };
8466                // Feedback naming obligation members discharges only those
8467                // members; the token closes once every member-bearing field of
8468                // the protocol is empty. Other feedback closes the token.
8469                let obligation_update = if members.is_empty() {
8470                    format!("{var}' = {var} \\ {{token}}")
8471                } else {
8472                    let residual = format!(
8473                        "[token EXCEPT {}]",
8474                        members
8475                            .iter()
8476                            .map(|(field, member)| format!("!.{field} = @ \\ {{{member}}}"))
8477                            .collect::<Vec<_>>()
8478                            .join(", ")
8479                    );
8480                    let drained = Self::protocol_member_fields(protocol)
8481                        .iter()
8482                        .map(|field| format!("{residual}.{field} = {{}}"))
8483                        .collect::<Vec<_>>()
8484                        .join(" /\\ ");
8485                    // Parenthesised: an unbracketed ELSE would swallow the
8486                    // conjuncts that follow it in the action.
8487                    format!(
8488                        "{var}' = (IF {drained} THEN {var} \\ {{token}} ELSE ({var} \\ {{token}}) \\cup {{{residual}}})"
8489                    )
8490                };
8491                writeln!(
8492                    out,
8493                    "        /\\ {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)"
8494                )
8495                .expect("write to string");
8496
8497                let unchanged_vars: Vec<String> = self
8498                    .machine_vars()
8499                    .into_iter()
8500                    .chain(self.obligation_vars().into_iter().filter(|v| *v != var))
8501                    .chain(
8502                        [
8503                            "pending_routes",
8504                            "delivered_routes",
8505                            "emitted_effects",
8506                            "observed_transitions",
8507                            "witness_current_script_input",
8508                            "witness_remaining_script_inputs",
8509                        ]
8510                        .iter()
8511                        .map(std::string::ToString::to_string),
8512                    )
8513                    .collect();
8514                self.render_unchanged_vars(out, "    /\\ ", &unchanged_vars);
8515                pushln!(out);
8516            }
8517        }
8518        Ok(())
8519    }
8520
8521    fn render_coverage_instrumentation(&self, out: &mut String) {
8522        let route_ops = self
8523            .schema
8524            .routes
8525            .iter()
8526            .map(|route| composition_route_coverage_operator_name(&route.name))
8527            .collect::<Vec<_>>();
8528        let scheduler_ops = self
8529            .schema
8530            .scheduler_rules
8531            .iter()
8532            .map(composition_scheduler_coverage_operator_name)
8533            .collect::<Vec<_>>();
8534
8535        for route in &self.schema.routes {
8536            writeln!(
8537                out,
8538                "{} == \\E packet \\in delivered_routes : packet.route = {}",
8539                composition_route_observed_operator_name(&route.name),
8540                tla_string(&route.name)
8541            )
8542            .expect("write to string");
8543            writeln!(
8544                out,
8545                "{} == ({} \\/ ~{})",
8546                composition_route_coverage_operator_name(&route.name),
8547                composition_route_observed_operator_name(&route.name),
8548                composition_route_observed_operator_name(&route.name)
8549            )
8550            .expect("write to string");
8551        }
8552        for rule in &self.schema.scheduler_rules {
8553            writeln!(
8554                out,
8555                "{} == {}",
8556                composition_scheduler_triggered_operator_name(rule),
8557                render_scheduler_trigger_formula(rule)
8558            )
8559            .expect("write to string");
8560            writeln!(
8561                out,
8562                "{} == ({} \\/ ~{})",
8563                composition_scheduler_coverage_operator_name(rule),
8564                composition_scheduler_triggered_operator_name(rule),
8565                composition_scheduler_triggered_operator_name(rule)
8566            )
8567            .expect("write to string");
8568        }
8569
8570        let mut instrumentation_terms = Vec::new();
8571        instrumentation_terms.extend(route_ops.into_iter());
8572        instrumentation_terms.extend(scheduler_ops.into_iter());
8573
8574        let instrumentation = if instrumentation_terms.is_empty() {
8575            "TRUE".to_string()
8576        } else {
8577            instrumentation_terms.join(" /\\ ")
8578        };
8579
8580        pushln!(out, "CoverageInstrumentation == {instrumentation}");
8581        pushln!(out);
8582    }
8583
8584    /// Fail-closed resolution check for every route in the composition.
8585    ///
8586    /// Confirms that each route's `from_machine` and `to.machine` is a declared
8587    /// machine instance, that `effect_variant` is a declared effect on the
8588    /// source machine, and that `to.input_variant` is a declared input/signal
8589    /// (per `to.kind`) on the target machine. The composition CASE builders
8590    /// (`ActorOfMachine`, `RouteSource`, `RouteEffect`, `RouteTargetMachine`,
8591    /// `RouteTargetInput`) used to map an unresolved component to a sentinel
8592    /// (`"unknown_*"`) default; with this gate run first, those sentinels are
8593    /// unreachable-by-construction for valid input, and malformed input fails
8594    /// closed instead of silently emitting a broken model.
8595    fn validate_routes(&self) -> std::result::Result<(), CompositionTlaError> {
8596        let composition = self.schema.name.as_str();
8597        for route in &self.schema.routes {
8598            let route_name = route.name.as_str();
8599
8600            // Source machine instance must be declared.
8601            let source = self
8602                .machine_by_instance
8603                .get(route.from_machine.as_str())
8604                .copied()
8605                .ok_or_else(|| CompositionTlaError::UnknownRouteSourceMachine {
8606                    composition: composition.to_owned(),
8607                    route: route_name.to_owned(),
8608                    machine: route.from_machine.as_str().to_owned(),
8609                })?;
8610
8611            // Effect variant must be declared on the source machine.
8612            if source
8613                .effects
8614                .variant_named(route.effect_variant.as_str())
8615                .is_err()
8616            {
8617                return Err(CompositionTlaError::UnknownRouteEffect {
8618                    composition: composition.to_owned(),
8619                    route: route_name.to_owned(),
8620                    machine: route.from_machine.as_str().to_owned(),
8621                    effect: route.effect_variant.as_str().to_owned(),
8622                });
8623            }
8624
8625            // Target machine instance must be declared.
8626            let target = self
8627                .machine_by_instance
8628                .get(route.to.machine.as_str())
8629                .copied()
8630                .ok_or_else(|| CompositionTlaError::UnknownRouteTargetMachine {
8631                    composition: composition.to_owned(),
8632                    route: route_name.to_owned(),
8633                    machine: route.to.machine.as_str().to_owned(),
8634                })?;
8635
8636            // Target input/signal variant must be declared on the target
8637            // machine, dispatching on the route's structural kind.
8638            match route.to.kind {
8639                RouteTargetKind::Input => {
8640                    if target
8641                        .inputs
8642                        .variant_named(route.to.input_variant.as_str())
8643                        .is_err()
8644                    {
8645                        return Err(CompositionTlaError::UnknownRouteTargetInput {
8646                            composition: composition.to_owned(),
8647                            route: route_name.to_owned(),
8648                            machine: route.to.machine.as_str().to_owned(),
8649                            input: route.to.input_variant.as_str().to_owned(),
8650                        });
8651                    }
8652                }
8653                RouteTargetKind::Signal => {
8654                    if target
8655                        .signals
8656                        .variant_named(route.to.input_variant.as_str())
8657                        .is_err()
8658                    {
8659                        return Err(CompositionTlaError::UnknownRouteTargetSignal {
8660                            composition: composition.to_owned(),
8661                            route: route_name.to_owned(),
8662                            machine: route.to.machine.as_str().to_owned(),
8663                            signal: route.to.input_variant.as_str().to_owned(),
8664                        });
8665                    }
8666                }
8667            }
8668        }
8669        Ok(())
8670    }
8671
8672    fn render_static_sets(&self, out: &mut String) -> std::result::Result<(), CompositionTlaError> {
8673        pushln!(out, "Machines == {{");
8674        for (idx, machine) in self.schema.machines.iter().enumerate() {
8675            let suffix = if idx + 1 == self.schema.machines.len() {
8676                ""
8677            } else {
8678                ","
8679            };
8680            writeln!(
8681                out,
8682                "    <<{}, {}, {}>>{}",
8683                tla_string(&machine.instance_id),
8684                tla_string(&machine.machine_name),
8685                tla_string(&machine.actor),
8686                suffix
8687            )
8688            .expect("write to string");
8689        }
8690        pushln!(out, "}}");
8691        pushln!(out);
8692
8693        pushln!(out, "RouteNames == {{");
8694        for (idx, route) in self.schema.routes.iter().enumerate() {
8695            let suffix = if idx + 1 == self.schema.routes.len() {
8696                ""
8697            } else {
8698                ","
8699            };
8700            pushln!(out, "    {}{}", tla_string(&route.name), suffix);
8701        }
8702        pushln!(out, "}}");
8703        pushln!(out);
8704
8705        pushln!(out, "Actors == {{");
8706        for (idx, machine) in self.schema.machines.iter().enumerate() {
8707            let suffix = if idx + 1 == self.schema.machines.len() {
8708                ""
8709            } else {
8710                ","
8711            };
8712            pushln!(out, "    {}{}", tla_string(&machine.actor), suffix);
8713        }
8714        pushln!(out, "}}");
8715        pushln!(out);
8716
8717        pushln!(out, "ActorPriorities == {{");
8718        for (idx, priority) in self.schema.actor_priorities.iter().enumerate() {
8719            let suffix = if idx + 1 == self.schema.actor_priorities.len() {
8720                ""
8721            } else {
8722                ","
8723            };
8724            writeln!(
8725                out,
8726                "    <<{}, {}>>{}",
8727                tla_string(&priority.higher),
8728                tla_string(&priority.lower),
8729                suffix
8730            )
8731            .expect("write to string");
8732        }
8733        pushln!(out, "}}");
8734        pushln!(out);
8735
8736        pushln!(out, "SchedulerRules == {{");
8737        for (idx, rule) in self.schema.scheduler_rules.iter().enumerate() {
8738            let suffix = if idx + 1 == self.schema.scheduler_rules.len() {
8739                ""
8740            } else {
8741                ","
8742            };
8743            pushln!(out, "    {}{}", render_scheduler_rule_tuple(rule), suffix);
8744        }
8745        writeln!(out, "}}");
8746        pushln!(out);
8747
8748        let composition_name = self.schema.name.as_str();
8749        render_composition_case_fn(
8750            out,
8751            composition_name,
8752            "ActorOfMachine",
8753            "machine_id",
8754            self.schema
8755                .machines
8756                .iter()
8757                .map(|machine| (machine.instance_id.as_str(), tla_string(&machine.actor)))
8758                .collect(),
8759            CaseDefault::FailClosed {
8760                component: "actor",
8761                require_mapping: true,
8762            },
8763        )?;
8764        render_composition_case_fn(
8765            out,
8766            composition_name,
8767            "RouteSource",
8768            "route_name",
8769            self.schema
8770                .routes
8771                .iter()
8772                .map(|route| (route.name.as_str(), tla_string(&route.from_machine)))
8773                .collect(),
8774            CaseDefault::FailClosed {
8775                component: "route_source_machine",
8776                require_mapping: false,
8777            },
8778        )?;
8779        render_composition_case_fn(
8780            out,
8781            composition_name,
8782            "RouteEffect",
8783            "route_name",
8784            self.schema
8785                .routes
8786                .iter()
8787                .map(|route| (route.name.as_str(), tla_string(&route.effect_variant)))
8788                .collect(),
8789            CaseDefault::FailClosed {
8790                component: "route_effect",
8791                require_mapping: false,
8792            },
8793        )?;
8794        render_composition_case_fn(
8795            out,
8796            composition_name,
8797            "RouteTargetMachine",
8798            "route_name",
8799            self.schema
8800                .routes
8801                .iter()
8802                .map(|route| (route.name.as_str(), tla_string(&route.to.machine)))
8803                .collect(),
8804            CaseDefault::FailClosed {
8805                component: "route_target_machine",
8806                require_mapping: false,
8807            },
8808        )?;
8809        render_composition_case_fn(
8810            out,
8811            composition_name,
8812            "RouteTargetInput",
8813            "route_name",
8814            self.schema
8815                .routes
8816                .iter()
8817                .map(|route| (route.name.as_str(), tla_string(&route.to.input_variant)))
8818                .collect(),
8819            CaseDefault::FailClosed {
8820                component: "route_target_input",
8821                require_mapping: false,
8822            },
8823        )?;
8824        render_composition_case_fn(
8825            out,
8826            composition_name,
8827            "RouteTargetKind",
8828            "route_name",
8829            self.schema
8830                .routes
8831                .iter()
8832                .map(|route| {
8833                    (
8834                        route.name.as_str(),
8835                        tla_string(match route.to.kind {
8836                            RouteTargetKind::Input => "Input",
8837                            RouteTargetKind::Signal => "Signal",
8838                        }),
8839                    )
8840                })
8841                .collect(),
8842            CaseDefault::ClosedEnum(tla_string("Unknown")),
8843        )?;
8844        render_composition_case_fn(
8845            out,
8846            composition_name,
8847            "RouteDeliveryKind",
8848            "route_name",
8849            self.schema
8850                .routes
8851                .iter()
8852                .map(|route| {
8853                    (
8854                        route.name.as_str(),
8855                        tla_string(match route.delivery {
8856                            RouteDelivery::Immediate => "Immediate",
8857                            RouteDelivery::Enqueue => "Enqueue",
8858                        }),
8859                    )
8860                })
8861                .collect(),
8862            CaseDefault::ClosedEnum(tla_string("Unknown")),
8863        )?;
8864        writeln!(
8865            out,
8866            "RouteTargetActor(route_name) == ActorOfMachine(RouteTargetMachine(route_name))"
8867        );
8868        pushln!(out);
8869        Ok(())
8870    }
8871
8872    fn render_entry_input_actions(&self, out: &mut String) {
8873        for entry_input in &self.schema.entry_inputs {
8874            let machine = self.machine(entry_input.machine.as_str());
8875            let Ok(variant) = machine.inputs.variant_named(&entry_input.input_variant) else {
8876                continue;
8877            };
8878            let action_name = self.entry_input_action_name(entry_input);
8879            let params = variant
8880                .fields
8881                .iter()
8882                .map(|field| format!("arg_{}", tla_ident(&field.name)))
8883                .collect::<Vec<_>>();
8884            let packet_expr = self.input_packet_expr(
8885                entry_input.machine.as_str(),
8886                &entry_input.input_variant,
8887                &variant
8888                    .fields
8889                    .iter()
8890                    .map(|field| {
8891                        (
8892                            field.name.as_str().to_owned(),
8893                            format!("arg_{}", tla_ident(&field.name)),
8894                        )
8895                    })
8896                    .collect::<BTreeMap<String, _>>(),
8897                "entry",
8898                &entry_input.name,
8899                "external_entry",
8900                &entry_input.input_variant,
8901                "0",
8902            );
8903
8904            if params.is_empty() {
8905                pushln!(out, "{} ==", action_name);
8906            } else {
8907                pushln!(out, "{}({}) ==", action_name, params.join(", "));
8908            }
8909            writeln!(
8910                out,
8911                "    /\\ ~({} \\in SeqElements(pending_inputs))",
8912                packet_expr
8913            )
8914            .expect("write to string");
8915            writeln!(out, "    /\\ EntryPacketAdmissible({packet_expr})").expect("write to string");
8916            writeln!(
8917                out,
8918                "    /\\ pending_inputs' = Append(pending_inputs, {})",
8919                packet_expr
8920            )
8921            .expect("write to string");
8922            writeln!(
8923                out,
8924                "    /\\ observed_inputs' = observed_inputs \\cup {{{}}}",
8925                packet_expr
8926            )
8927            .expect("write to string");
8928            writeln!(out, "    /\\ model_step_count' = model_step_count + 1")
8929                .expect("write to string");
8930            {
8931                let mut unchanged = self.machine_vars();
8932                unchanged.extend(self.obligation_vars());
8933                unchanged.extend([
8934                    "pending_routes".into(),
8935                    "delivered_routes".into(),
8936                    "emitted_effects".into(),
8937                    "observed_transitions".into(),
8938                    "witness_current_script_input".into(),
8939                    "witness_remaining_script_inputs".into(),
8940                ]);
8941                self.render_unchanged_vars(out, "    /\\ ", &unchanged);
8942            }
8943            pushln!(out);
8944        }
8945    }
8946
8947    fn render_entry_input_call(&self, entry_input: &EntryInput) -> String {
8948        let machine = self.machine(entry_input.machine.as_str());
8949        let Ok(variant) = machine.inputs.variant_named(&entry_input.input_variant) else {
8950            return self.entry_input_action_name(entry_input);
8951        };
8952        let action_name = self.entry_input_action_name(entry_input);
8953        if variant.fields.is_empty() {
8954            action_name
8955        } else {
8956            let prefix = variant
8957                .fields
8958                .iter()
8959                .map(|field| {
8960                    let local = format!("arg_{}", tla_ident(&field.name));
8961                    let domain = self.binding_domain_for_type(&field.ty);
8962                    format!("\\E {local} \\in {domain} : ")
8963                })
8964                .collect::<String>();
8965            let args = variant
8966                .fields
8967                .iter()
8968                .map(|field| format!("arg_{}", tla_ident(&field.name)))
8969                .collect::<Vec<_>>()
8970                .join(", ");
8971            format!("{prefix}{action_name}({args})")
8972        }
8973    }
8974
8975    fn render_deliver_queued_route_action(&self, out: &mut String) {
8976        writeln!(out, "DeliverQueuedRoute ==");
8977        pushln!(out, "    /\\ Len(pending_routes) > 0");
8978        pushln!(out, "    /\\ LET route == Head(pending_routes) IN");
8979        pushln!(out, "       /\\ pending_routes' = Tail(pending_routes)");
8980        writeln!(
8981            out,
8982            "       /\\ delivered_routes' = delivered_routes \\cup {{route}}"
8983        )
8984        .expect("write to string");
8985        writeln!(out, "       /\\ model_step_count' = model_step_count + 1")
8986            .expect("write to string");
8987        writeln!(
8988            out,
8989            "       /\\ 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])"
8990        )
8991        .expect("write to string");
8992        writeln!(
8993            out,
8994            "       /\\ 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]}}"
8995        )
8996        .expect("write to string");
8997        {
8998            let mut unchanged = self.machine_vars();
8999            unchanged.extend(self.obligation_vars());
9000            unchanged.extend([
9001                "emitted_effects".into(),
9002                "observed_transitions".into(),
9003                "witness_current_script_input".into(),
9004                "witness_remaining_script_inputs".into(),
9005            ]);
9006            self.render_unchanged_vars(out, "       /\\ ", &unchanged);
9007        }
9008        pushln!(out);
9009    }
9010
9011    fn entry_packet_admissibility_name(&self, instance_id: &str) -> String {
9012        format!("EntryPacketAdmissible_{}", tla_ident(instance_id))
9013    }
9014
9015    fn render_entry_packet_admissibility_helpers(
9016        &self,
9017        out: &mut String,
9018    ) -> std::result::Result<(), CompositionTlaError> {
9019        if self.schema.entry_inputs.is_empty()
9020            && !self
9021                .schema
9022                .witnesses
9023                .iter()
9024                .any(|witness| !witness.preload_inputs.is_empty())
9025        {
9026            return Ok(());
9027        }
9028
9029        for instance in &self.schema.machines {
9030            let machine = self.machine(instance.instance_id.as_str());
9031            let helper_prefix = format!("{}__entry_packet__", tla_ident(&instance.instance_id));
9032            let mut compiler = self.instance_compiler(instance.instance_id.as_str(), helper_prefix);
9033
9034            for derived in helper_dependency_order(machine)? {
9035                compiler.render_helper(out, derived);
9036                pushln!(out);
9037            }
9038            if machine.machine.as_str() == "MobMachine" {
9039                compiler.render_mob_machine_native_helpers(out);
9040                pushln!(out);
9041            }
9042            if machine.machine.as_str() == "MeerkatMachine" {
9043                compiler.render_meerkat_machine_native_helpers(out);
9044                pushln!(out);
9045            }
9046            if machine.machine.as_str() == "RuntimeDeliveryMachine" {
9047                compiler.render_runtime_delivery_native_helpers(out);
9048                pushln!(out);
9049            }
9050            if machine.machine.as_str() == "SessionDocumentMachine" {
9051                compiler.render_session_document_native_helpers(out);
9052                pushln!(out);
9053            }
9054
9055            let branches = machine
9056                .transitions
9057                .iter()
9058                .map(|transition| {
9059                    self.render_machine_packet_admissibility_branch(
9060                        &mut compiler,
9061                        instance.instance_id.as_str(),
9062                        transition,
9063                    )
9064                })
9065                .collect::<Vec<_>>();
9066
9067            for helper in &compiler.helper_defs {
9068                pushln!(out, "{helper}");
9069                pushln!(out);
9070            }
9071
9072            writeln!(
9073                out,
9074                "{}(packet) ==",
9075                self.entry_packet_admissibility_name(instance.instance_id.as_str())
9076            )
9077            .expect("write to string");
9078            if branches.is_empty() {
9079                pushln!(out, "    FALSE");
9080            } else {
9081                for branch in &branches {
9082                    pushln!(out, "    \\/ {branch}");
9083                }
9084            }
9085            pushln!(out);
9086        }
9087
9088        writeln!(out, "EntryPacketAdmissible(packet) ==").expect("write to string");
9089        pushln!(out, "    CASE");
9090        for (idx, instance) in self.schema.machines.iter().enumerate() {
9091            let prefix = if idx == 0 { "      " } else { "      [] " };
9092            writeln!(
9093                out,
9094                "{}packet.machine = {} -> {}(packet)",
9095                prefix,
9096                tla_string(&instance.instance_id),
9097                self.entry_packet_admissibility_name(instance.instance_id.as_str())
9098            )
9099            .expect("write to string");
9100        }
9101        pushln!(out, "      [] OTHER -> FALSE");
9102        pushln!(out);
9103        Ok(())
9104    }
9105
9106    fn render_machine_packet_admissibility_branch(
9107        &self,
9108        compiler: &mut MachineTlaCompiler<'_>,
9109        instance_id: &str,
9110        transition: &TransitionSchema,
9111    ) -> String {
9112        let phase_var = self.phase_var(instance_id);
9113        let from_guard = if transition.from.len() == 1 {
9114            format!("{phase_var} = {}", tla_string(&transition.from[0]))
9115        } else {
9116            transition
9117                .from
9118                .iter()
9119                .map(|phase| format!("{phase_var} = {}", tla_string(phase)))
9120                .collect::<Vec<_>>()
9121                .join(" \\/ ")
9122        };
9123
9124        let binding_types = compiler.binding_type_map(transition);
9125        let binding_env = transition
9126            .on
9127            .bindings()
9128            .iter()
9129            .map(|binding| {
9130                (
9131                    binding.as_str().to_owned(),
9132                    format!("packet.payload.{}", tla_ident(binding)),
9133                )
9134            })
9135            .collect::<BTreeMap<_, _>>();
9136        let field_env = self.machine_field_env(instance_id);
9137
9138        let mut clauses = vec![
9139            format!(
9140                "packet.variant = {}",
9141                tla_string(transition.on.variant_str())
9142            ),
9143            from_guard,
9144        ];
9145        clauses.extend(
9146            transition.guards.iter().map(|guard| {
9147                compiler.render_guard(guard, &field_env, &binding_env, &binding_types)
9148            }),
9149        );
9150
9151        format!(
9152            "/\\ {}",
9153            clauses
9154                .into_iter()
9155                .map(|clause| format!("({clause})"))
9156                .collect::<Vec<_>>()
9157                .join(" /\\ ")
9158        )
9159    }
9160
9161    fn render_reject_pending_entry_input_action(&self, out: &mut String) {
9162        if self.schema.entry_inputs.is_empty() {
9163            return;
9164        }
9165
9166        writeln!(out, "RejectPendingEntryInput ==").expect("write to string");
9167        pushln!(out, "    /\\ \\E packet \\in SeqElements(pending_inputs) :");
9168        pushln!(out, "       /\\ packet.source_kind = \"entry\"");
9169        pushln!(out, "       /\\ ~EntryPacketAdmissible(packet)");
9170        pushln!(
9171            out,
9172            "       /\\ pending_inputs' = SeqRemove(pending_inputs, packet)"
9173        );
9174        pushln!(out, "       /\\ observed_inputs' = observed_inputs");
9175        pushln!(out, "       /\\ pending_routes' = pending_routes");
9176        pushln!(out, "       /\\ delivered_routes' = delivered_routes");
9177        pushln!(out, "       /\\ emitted_effects' = emitted_effects");
9178        pushln!(
9179            out,
9180            "       /\\ observed_transitions' = observed_transitions"
9181        );
9182        writeln!(out, "       /\\ model_step_count' = model_step_count + 1")
9183            .expect("write to string");
9184        let mut unchanged = self.machine_vars();
9185        unchanged.extend(self.obligation_vars());
9186        unchanged.extend([
9187            "witness_current_script_input".into(),
9188            "witness_remaining_script_inputs".into(),
9189        ]);
9190        self.render_unchanged_vars(out, "       /\\ ", &unchanged);
9191        pushln!(out);
9192    }
9193
9194    fn render_quiescent_stutter(&self, out: &mut String) {
9195        writeln!(out, "QuiescentStutter ==");
9196        pushln!(out, "    /\\ Len(pending_routes) = 0");
9197        pushln!(out, "    /\\ Len(pending_inputs) = 0");
9198        pushln!(out, "    /\\ UNCHANGED vars");
9199        pushln!(out);
9200    }
9201
9202    fn render_witness_inject_next_call(&self, witness: &CompositionWitness) -> String {
9203        format!("WitnessInjectNext_{}", tla_ident(&witness.name))
9204    }
9205
9206    fn render_witness_satisfied_stutter_call(&self, witness: &CompositionWitness) -> String {
9207        format!("WitnessSatisfiedStutter_{}", tla_ident(&witness.name))
9208    }
9209
9210    fn core_next_branches(&self) -> Vec<String> {
9211        let mut branches = Vec::new();
9212        if !self.schema.routes.is_empty() {
9213            branches.push("DeliverQueuedRoute".into());
9214        }
9215        if !self.schema.entry_inputs.is_empty() {
9216            branches.push("RejectPendingEntryInput".into());
9217        }
9218        for instance in &self.schema.machines {
9219            let machine = self.machine(instance.instance_id.as_str());
9220            for transition in &machine.transitions {
9221                branches
9222                    .push(self.machine_transition_call(instance.instance_id.as_str(), transition));
9223            }
9224        }
9225        branches.extend(self.owner_feedback_branches());
9226        branches.push("QuiescentStutter".into());
9227        branches
9228    }
9229
9230    fn owner_feedback_branches(&self) -> Vec<String> {
9231        self.schema
9232            .handoff_protocols
9233            .iter()
9234            .flat_map(|protocol| {
9235                protocol
9236                    .allowed_feedback_inputs
9237                    .iter()
9238                    .map(move |feedback| self.owner_feedback_action_name(protocol, feedback))
9239            })
9240            .collect()
9241    }
9242
9243    fn owner_feedback_action_name(
9244        &self,
9245        protocol: &meerkat_machine_schema::EffectHandoffProtocol,
9246        feedback: &FeedbackInputRef,
9247    ) -> String {
9248        format!(
9249            "OwnerFeedback_{}_{}",
9250            self.obligation_symbol_suffix(protocol),
9251            tla_ident(&feedback.input_variant)
9252        )
9253    }
9254
9255    fn witness_owner_feedback_branches(&self, witness: &CompositionWitness) -> Vec<String> {
9256        let expected_inputs = witness
9257            .expected_transitions
9258            .iter()
9259            .filter_map(|expected| {
9260                let machine = self.machine_by_instance.get(expected.machine.as_str())?;
9261                let transition = machine
9262                    .transitions
9263                    .iter()
9264                    .find(|transition| transition.name == expected.transition)?;
9265                match &transition.on {
9266                    TriggerMatch::Input { variant, .. } => {
9267                        Some((expected.machine.clone(), variant.clone()))
9268                    }
9269                    TriggerMatch::Signal { .. } => None,
9270                }
9271            })
9272            .collect::<BTreeSet<_>>();
9273
9274        let ordered_predecessor_effects = witness
9275            .expected_transition_order
9276            .iter()
9277            .filter_map(|order| {
9278                let predecessor_machine = self
9279                    .machine_by_instance
9280                    .get(order.earlier.machine.as_str())?;
9281                let predecessor = predecessor_machine
9282                    .transitions
9283                    .iter()
9284                    .find(|transition| transition.name == order.earlier.transition)?;
9285                Some((
9286                    (order.later.machine.clone(), order.later.transition.clone()),
9287                    predecessor
9288                        .emit
9289                        .iter()
9290                        .map(|effect| (order.earlier.machine.clone(), effect.variant.clone()))
9291                        .collect::<BTreeSet<_>>(),
9292                ))
9293            })
9294            .fold(
9295                BTreeMap::<_, BTreeSet<_>>::new(),
9296                |mut effects, (transition, predecessor_effects)| {
9297                    effects
9298                        .entry(transition)
9299                        .or_default()
9300                        .extend(predecessor_effects);
9301                    effects
9302                },
9303            );
9304
9305        self.schema
9306            .handoff_protocols
9307            .iter()
9308            .flat_map(|protocol| {
9309                protocol
9310                    .allowed_feedback_inputs
9311                    .iter()
9312                    .filter_map(|feedback| {
9313                        let input = (
9314                            feedback.machine_instance.clone(),
9315                            feedback.input_variant.clone(),
9316                        );
9317                        if !expected_inputs.contains(&input) {
9318                            return None;
9319                        }
9320                        let receiver_machine = self
9321                            .machine_by_instance
9322                            .get(feedback.machine_instance.as_str())?;
9323                        let receiver = receiver_machine.transitions.iter().find(|transition| {
9324                            matches!(
9325                                &transition.on,
9326                                TriggerMatch::Input { variant, .. }
9327                                    if variant == &feedback.input_variant
9328                            )
9329                        })?;
9330                        let receiver_key =
9331                            (feedback.machine_instance.clone(), receiver.name.clone());
9332                        if let Some(predecessor_effects) =
9333                            ordered_predecessor_effects.get(&receiver_key)
9334                        {
9335                            let producer = (
9336                                protocol.producer_instance.clone(),
9337                                protocol.effect_variant.clone(),
9338                            );
9339                            if !predecessor_effects.contains(&producer) {
9340                                return None;
9341                            }
9342                        }
9343                        Some(self.owner_feedback_action_name(protocol, feedback))
9344                    })
9345            })
9346            .collect::<BTreeSet<_>>()
9347            .into_iter()
9348            .collect()
9349    }
9350
9351    fn witness_next_branches(
9352        &self,
9353        witness: &CompositionWitness,
9354    ) -> Result<Vec<String>, CompositionTlaError> {
9355        if !Self::witness_has_explicit_progress(witness) {
9356            let mut branches = vec!["CoreNext".into()];
9357            branches.push(self.render_witness_satisfied_stutter_call(witness));
9358            return Ok(branches);
9359        }
9360        let mut branches = self.witness_progress_branches(witness)?;
9361        branches.push(self.render_witness_satisfied_stutter_call(witness));
9362        Ok(branches)
9363    }
9364
9365    fn witness_progress_branches(
9366        &self,
9367        witness: &CompositionWitness,
9368    ) -> Result<Vec<String>, CompositionTlaError> {
9369        let mut branches = Vec::new();
9370        if !witness.expected_routes.is_empty() {
9371            branches.push("DeliverQueuedRoute".into());
9372        }
9373        for expected in &witness.expected_transitions {
9374            branches.push(self.witness_transition_call(witness, expected)?);
9375        }
9376        branches.extend(self.witness_owner_feedback_branches(witness));
9377        Ok(branches)
9378    }
9379
9380    fn witness_transition_call(
9381        &self,
9382        witness: &CompositionWitness,
9383        expected: &meerkat_machine_schema::CompositionWitnessTransition,
9384    ) -> Result<String, CompositionTlaError> {
9385        let machine = self
9386            .machine_by_instance
9387            .get(expected.machine.as_str())
9388            .ok_or_else(|| CompositionTlaError::UnknownWitnessMachine {
9389                composition: self.schema.name.to_string(),
9390                witness: witness.name.to_string(),
9391                machine: expected.machine.to_string(),
9392            })?;
9393        let transition = machine
9394            .transitions
9395            .iter()
9396            .find(|transition| transition.name == expected.transition)
9397            .ok_or_else(|| CompositionTlaError::UnknownWitnessTransition {
9398                composition: self.schema.name.to_string(),
9399                witness: witness.name.to_string(),
9400                machine: expected.machine.to_string(),
9401                transition: expected.transition.to_string(),
9402            })?;
9403        if transition.on.bindings().is_empty() {
9404            return Ok(self.machine_transition_name(expected.machine.as_str(), transition));
9405        }
9406        // A scripted witness supplies exact typed packets. Sampling the ordinary
9407        // exploration domains again can make those packets impossible to consume
9408        // (for example, revisions 3 and 4 outside the bounded 0..2 sample).
9409        // Reuse the same guarded action with the queued payload, without changing
9410        // ordinary exploration bounds or bypassing action admission checks.
9411        let args = transition
9412            .on
9413            .bindings()
9414            .iter()
9415            .map(|binding| format!("witness_packet.payload.{}", tla_ident(binding)))
9416            .collect::<Vec<_>>()
9417            .join(", ");
9418        Ok(format!(
9419            "\\E witness_packet \\in SeqElements(pending_inputs) : /\\ witness_packet.machine = {} /\\ witness_packet.variant = {} /\\ {}({args})",
9420            tla_string(expected.machine.as_str()),
9421            tla_string(transition.on.variant_str()),
9422            self.machine_transition_name(expected.machine.as_str(), transition),
9423        ))
9424    }
9425
9426    fn witness_fairness_clauses(
9427        &self,
9428        witness: &CompositionWitness,
9429    ) -> Result<Vec<String>, CompositionTlaError> {
9430        if Self::witness_has_explicit_progress(witness) {
9431            return Ok(Vec::new());
9432        }
9433
9434        let mut clauses = self.core_fairness_clauses();
9435        if witness.preload_inputs.len() > 1 {
9436            clauses.push(self.render_witness_inject_next_call(witness));
9437        }
9438        Ok(clauses)
9439    }
9440
9441    fn core_fairness_clauses(&self) -> Vec<String> {
9442        let mut clauses = Vec::new();
9443        if !self.schema.routes.is_empty() {
9444            clauses.push("DeliverQueuedRoute".into());
9445        }
9446        if !self.schema.entry_inputs.is_empty() {
9447            clauses.push("RejectPendingEntryInput".into());
9448        }
9449        clauses.extend(self.schema.machines.iter().flat_map(|instance| {
9450            let machine = self.machine(instance.instance_id.as_str());
9451            machine
9452                .transitions
9453                .iter()
9454                .map(|transition| {
9455                    self.machine_transition_call(instance.instance_id.as_str(), transition)
9456                })
9457                .collect::<Vec<_>>()
9458        }));
9459        clauses
9460    }
9461
9462    fn witness_has_explicit_progress(witness: &CompositionWitness) -> bool {
9463        !witness.preload_inputs.is_empty() || !witness.expected_transitions.is_empty()
9464    }
9465
9466    fn entry_input_action_name(&self, entry_input: &EntryInput) -> String {
9467        format!("Inject_{}", tla_ident(&entry_input.name))
9468    }
9469
9470    fn input_packet_expr(
9471        &self,
9472        machine_id: impl AsRef<str>,
9473        input_variant: impl AsRef<str>,
9474        payload_fields: &BTreeMap<String, String>,
9475        source_kind: impl AsRef<str>,
9476        source_route: impl AsRef<str>,
9477        source_machine: impl AsRef<str>,
9478        source_effect: impl AsRef<str>,
9479        effect_id: impl AsRef<str>,
9480    ) -> String {
9481        format!(
9482            "[machine |-> {}, variant |-> {}, payload |-> {}, source_kind |-> {}, source_route |-> {}, source_machine |-> {}, source_effect |-> {}, effect_id |-> {}]",
9483            tla_string(machine_id),
9484            tla_string(input_variant),
9485            self.payload_record_expr(payload_fields),
9486            tla_string(source_kind),
9487            tla_string(source_route),
9488            tla_string(source_machine),
9489            tla_string(source_effect),
9490            effect_id.as_ref()
9491        )
9492    }
9493
9494    fn input_packet_expr_from_payload_expr(
9495        &self,
9496        machine_id: impl AsRef<str>,
9497        input_variant: impl AsRef<str>,
9498        payload_expr: &str,
9499        source_kind: impl AsRef<str>,
9500        source_route: impl AsRef<str>,
9501        source_machine: impl AsRef<str>,
9502        source_effect: impl AsRef<str>,
9503        effect_id: impl AsRef<str>,
9504    ) -> String {
9505        format!(
9506            "[machine |-> {}, variant |-> {}, payload |-> {}, source_kind |-> {}, source_route |-> {}, source_machine |-> {}, source_effect |-> {}, effect_id |-> {}]",
9507            tla_string(machine_id),
9508            tla_string(input_variant),
9509            payload_expr,
9510            tla_string(source_kind),
9511            tla_string(source_route),
9512            tla_string(source_machine),
9513            tla_string(source_effect),
9514            effect_id.as_ref()
9515        )
9516    }
9517
9518    fn payload_record_expr(&self, payload_fields: &BTreeMap<String, String>) -> String {
9519        if payload_fields.is_empty() {
9520            "[tag |-> \"unit\"]".into()
9521        } else {
9522            format!(
9523                "[{}]",
9524                payload_fields
9525                    .iter()
9526                    .map(|(field, expr)| format!("{field} |-> {expr}"))
9527                    .collect::<Vec<_>>()
9528                    .join(", ")
9529            )
9530        }
9531    }
9532
9533    fn witness_packet_exprs(&self, witness: &CompositionWitness) -> Vec<String> {
9534        witness
9535            .preload_inputs
9536            .iter()
9537            .enumerate()
9538            .map(|(idx, packet)| {
9539                let payload_fields = packet
9540                    .fields
9541                    .iter()
9542                    .map(|field| {
9543                        (
9544                            field.field.as_str().to_owned(),
9545                            self.render_literal_expr(&field.expr),
9546                        )
9547                    })
9548                    .collect::<BTreeMap<String, _>>();
9549                self.input_packet_expr(
9550                    packet.machine.as_str(),
9551                    packet.input_variant.as_str(),
9552                    &payload_fields,
9553                    "entry",
9554                    format!("witness:{}:{}", witness.name, idx + 1),
9555                    "external_entry",
9556                    &packet.input_variant,
9557                    "0",
9558                )
9559            })
9560            .collect()
9561    }
9562
9563    fn witness_initial_batch_size(&self, witness: &CompositionWitness) -> usize {
9564        if witness.expected_scheduler_rules.is_empty() {
9565            1
9566        } else {
9567            witness.preload_inputs.len().min(2).max(1)
9568        }
9569    }
9570
9571    fn witness_initial_observed_inputs_expr(&self, witness: &CompositionWitness) -> String {
9572        let packets = self.witness_packet_exprs(witness);
9573        let batch_size = self.witness_initial_batch_size(witness);
9574        if packets.is_empty() {
9575            "{}".into()
9576        } else {
9577            format!(
9578                "{{{}}}",
9579                packets
9580                    .into_iter()
9581                    .take(batch_size)
9582                    .collect::<Vec<_>>()
9583                    .join(", ")
9584            )
9585        }
9586    }
9587
9588    fn witness_initial_pending_inputs_expr(&self, witness: &CompositionWitness) -> String {
9589        let packets = self.witness_packet_exprs(witness);
9590        let batch_size = self.witness_initial_batch_size(witness);
9591        if packets.is_empty() {
9592            "<<>>".into()
9593        } else {
9594            format!(
9595                "<<{}>>",
9596                packets
9597                    .into_iter()
9598                    .take(batch_size)
9599                    .collect::<Vec<_>>()
9600                    .join(", ")
9601            )
9602        }
9603    }
9604
9605    fn witness_current_script_input_expr(&self, witness: &CompositionWitness) -> String {
9606        let packets = self.witness_packet_exprs(witness);
9607        let batch_size = self.witness_initial_batch_size(witness);
9608        packets
9609            .into_iter()
9610            .take(batch_size)
9611            .last()
9612            .unwrap_or_else(|| "None".into())
9613    }
9614
9615    fn witness_remaining_script_inputs_expr(&self, witness: &CompositionWitness) -> String {
9616        let packets = self.witness_packet_exprs(witness);
9617        let batch_size = self.witness_initial_batch_size(witness);
9618        if packets.len() <= batch_size {
9619            return "<<>>".into();
9620        }
9621
9622        format!(
9623            "<<{}>>",
9624            packets
9625                .into_iter()
9626                .skip(batch_size)
9627                .collect::<Vec<_>>()
9628                .join(", ")
9629        )
9630    }
9631
9632    fn render_witness_inject_actions(&self, out: &mut String) {
9633        for witness in &self.schema.witnesses {
9634            let action_name = self.render_witness_inject_next_call(witness);
9635            pushln!(out, "{action_name} ==");
9636            if witness.preload_inputs.len() <= 1 {
9637                pushln!(out, "    FALSE");
9638                pushln!(out);
9639                continue;
9640            }
9641
9642            pushln!(
9643                out,
9644                "    LET next_script_input == IF Len(witness_remaining_script_inputs) > 0 THEN Head(witness_remaining_script_inputs) ELSE witness_current_script_input"
9645            );
9646            pushln!(
9647                out,
9648                "        next_remaining_script_inputs == IF Len(witness_remaining_script_inputs) > 0 THEN Tail(witness_remaining_script_inputs) ELSE <<>>"
9649            );
9650            pushln!(out, "    IN");
9651            pushln!(out, "    /\\ witness_current_script_input # None");
9652            writeln!(
9653                out,
9654                "    /\\ ~(witness_current_script_input \\in SeqElements(pending_inputs))"
9655            )
9656            .expect("write to string");
9657            pushln!(out, "    /\\ EntryPacketAdmissible(next_script_input)");
9658            pushln!(out, "    /\\ Len(pending_inputs) = 0");
9659            pushln!(out, "    /\\ Len(pending_routes) = 0");
9660            pushln!(out, "    /\\ Len(witness_remaining_script_inputs) > 0");
9661            writeln!(
9662                out,
9663                "    /\\ pending_inputs' = Append(pending_inputs, next_script_input)"
9664            )
9665            .expect("write to string");
9666            writeln!(
9667                out,
9668                "    /\\ observed_inputs' = observed_inputs \\cup {{next_script_input}}"
9669            )
9670            .expect("write to string");
9671            writeln!(
9672                out,
9673                "    /\\ witness_current_script_input' = next_script_input"
9674            )
9675            .expect("write to string");
9676            writeln!(
9677                out,
9678                "    /\\ witness_remaining_script_inputs' = next_remaining_script_inputs"
9679            )
9680            .expect("write to string");
9681            writeln!(out, "    /\\ model_step_count' = model_step_count + 1")
9682                .expect("write to string");
9683            {
9684                let mut unchanged = self.machine_vars();
9685                unchanged.extend(self.obligation_vars());
9686                unchanged.extend([
9687                    "pending_routes".into(),
9688                    "delivered_routes".into(),
9689                    "emitted_effects".into(),
9690                    "observed_transitions".into(),
9691                ]);
9692                self.render_unchanged_vars(out, "    /\\ ", &unchanged);
9693            }
9694            pushln!(out);
9695        }
9696    }
9697
9698    fn render_witness_satisfied_stutter_actions(&self, out: &mut String) {
9699        for witness in &self.schema.witnesses {
9700            let action_name = self.render_witness_satisfied_stutter_call(witness);
9701            pushln!(out, "{action_name} ==");
9702            let mut conditions = self.witness_satisfaction_conditions(witness);
9703            if Self::witness_has_explicit_progress(witness) {
9704                conditions.insert(0, composition_witness_completion_name(&witness.name));
9705            }
9706            if conditions.is_empty() {
9707                pushln!(out, "    /\\ FALSE");
9708            } else {
9709                for condition in conditions {
9710                    pushln!(out, "    /\\ {condition}");
9711                }
9712                pushln!(out, "    /\\ UNCHANGED vars");
9713            }
9714            pushln!(out);
9715        }
9716    }
9717
9718    fn render_witness_completion_operators(&self, out: &mut String) {
9719        for witness in &self.schema.witnesses {
9720            if !Self::witness_has_explicit_progress(witness) {
9721                continue;
9722            }
9723            writeln!(
9724                out,
9725                "{} ==",
9726                composition_witness_completion_name(&witness.name)
9727            )
9728            .expect("write to string");
9729            pushln!(out, "    /\\ Len(witness_remaining_script_inputs) = 0");
9730            pushln!(
9731                out,
9732                "    /\\ ~(witness_current_script_input \\in SeqElements(pending_inputs))"
9733            );
9734            pushln!(out, "    /\\ Len(pending_routes) = 0");
9735            for condition in self.witness_satisfaction_conditions(witness) {
9736                pushln!(out, "    /\\ {condition}");
9737            }
9738            pushln!(out);
9739        }
9740    }
9741
9742    fn render_witness_action_constraint_operators(&self, out: &mut String) {
9743        for witness in &self.schema.witnesses {
9744            if !Self::witness_has_explicit_progress(witness) {
9745                continue;
9746            }
9747            writeln!(
9748                out,
9749                "{} ==",
9750                composition_witness_action_constraint_name(&witness.name)
9751            )
9752            .expect("write to string");
9753            writeln!(
9754                out,
9755                "    \\/ {}",
9756                composition_witness_completion_name(&witness.name)
9757            )
9758            .expect("write to string");
9759            pushln!(out, "    \\/ model_step_count' # model_step_count");
9760            pushln!(out);
9761        }
9762    }
9763
9764    fn witness_satisfaction_conditions(&self, witness: &CompositionWitness) -> Vec<String> {
9765        let mut conditions = Vec::new();
9766        conditions.extend(witness.expected_routes.iter().map(|route| {
9767            format!(
9768                "\\E packet \\in delivered_routes : packet.route = {}",
9769                tla_string(route)
9770            )
9771        }));
9772        conditions.extend(
9773            witness
9774                .expected_scheduler_rules
9775                .iter()
9776                .map(render_scheduler_trigger_formula),
9777        );
9778        conditions.extend(
9779            witness
9780                .expected_states
9781                .iter()
9782                .map(|state| format!("({})", self.render_witness_state_formula(state))),
9783        );
9784        conditions.extend(
9785            witness.expected_transitions.iter().map(|transition| {
9786                format!("({})", self.render_witness_transition_formula(transition))
9787            }),
9788        );
9789        conditions.extend(
9790            witness
9791                .expected_transition_order
9792                .iter()
9793                .map(|order| format!("({})", self.render_witness_transition_order_formula(order))),
9794        );
9795        conditions
9796    }
9797
9798    fn render_witness_obligation_formula(
9799        &self,
9800        witness: &CompositionWitness,
9801        formula: String,
9802    ) -> String {
9803        if Self::witness_has_explicit_progress(witness) {
9804            format!(
9805                "{} => ({formula})",
9806                composition_witness_completion_name(&witness.name)
9807            )
9808        } else {
9809            format!("<> ({formula})")
9810        }
9811    }
9812
9813    fn render_literal_expr(&self, expr: &Expr) -> String {
9814        match expr {
9815            Expr::Bool(value) => {
9816                if *value {
9817                    "TRUE".into()
9818                } else {
9819                    "FALSE".into()
9820                }
9821            }
9822            Expr::U64(value) => value.to_string(),
9823            Expr::U64Max => TLA_RUST_U64_MAX_CONSTANT.to_owned(),
9824            Expr::String(value) => tla_string(value),
9825            Expr::NamedVariant { enum_name, variant } => render_named_variant_value(
9826                enum_name.as_str(),
9827                variant.as_str(),
9828                &self.named_bindings,
9829            ),
9830            Expr::None => "None".into(),
9831            Expr::Some(inner) => format!("Some({})", self.render_literal_expr(inner)),
9832            Expr::SeqLiteral(items) => {
9833                let rendered = items
9834                    .iter()
9835                    .map(|item| self.render_literal_expr(item))
9836                    .collect::<Vec<_>>()
9837                    .join(", ");
9838                format!("<<{rendered}>>")
9839            }
9840            Expr::EmptySet => "{}".into(),
9841            Expr::EmptyMap => "<< >>".into(),
9842            // A populated map literal (witness inputs, manifests) as a TLC
9843            // function; never the `None` fallback below.
9844            Expr::MapLiteral(entries) => {
9845                let rendered = entries
9846                    .iter()
9847                    .map(|(key, value)| {
9848                        format!(
9849                            "{} :> {}",
9850                            self.render_literal_expr(key),
9851                            self.render_literal_expr(value)
9852                        )
9853                    })
9854                    .collect::<Vec<_>>()
9855                    .join(" @@ ");
9856                format!("({rendered})")
9857            }
9858            _ => "None".into(),
9859        }
9860    }
9861
9862    fn render_witness_state_formula(
9863        &self,
9864        state: &meerkat_machine_schema::CompositionWitnessState,
9865    ) -> String {
9866        let mut clauses = Vec::new();
9867        if let Some(phase) = &state.phase {
9868            clauses.push(format!(
9869                "{} = {}",
9870                self.phase_var(&state.machine),
9871                tla_string(phase)
9872            ));
9873        }
9874        for field in &state.fields {
9875            clauses.push(format!(
9876                "{} = {}",
9877                self.field_var(&state.machine, &field.field),
9878                self.render_literal_expr(&field.expr)
9879            ));
9880        }
9881        if clauses.is_empty() {
9882            "TRUE".into()
9883        } else {
9884            clauses.join(" /\\ ")
9885        }
9886    }
9887
9888    fn render_witness_transition_formula(
9889        &self,
9890        transition: &meerkat_machine_schema::CompositionWitnessTransition,
9891    ) -> String {
9892        format!(
9893            "\\E packet \\in observed_transitions : /\\ packet.machine = {} /\\ packet.transition = {}",
9894            tla_string(&transition.machine),
9895            tla_string(&transition.transition)
9896        )
9897    }
9898
9899    fn render_witness_transition_order_formula(
9900        &self,
9901        ordering: &meerkat_machine_schema::CompositionWitnessTransitionOrder,
9902    ) -> String {
9903        format!(
9904            "\\E earlier \\in observed_transitions, later \\in observed_transitions : /\\ earlier.machine = {} /\\ earlier.transition = {} /\\ later.machine = {} /\\ later.transition = {} /\\ earlier.step < later.step",
9905            tla_string(&ordering.earlier.machine),
9906            tla_string(&ordering.earlier.transition),
9907            tla_string(&ordering.later.machine),
9908            tla_string(&ordering.later.transition),
9909        )
9910    }
9911
9912    fn route_packet_expr(
9913        &self,
9914        route_name: impl AsRef<str>,
9915        from_machine: impl AsRef<str>,
9916        effect_variant: impl AsRef<str>,
9917        to_machine: impl AsRef<str>,
9918        to_input_variant: impl AsRef<str>,
9919        payload_expr: &str,
9920        effect_id_expr: &str,
9921        source_transition: impl AsRef<str>,
9922    ) -> String {
9923        let to_machine = to_machine.as_ref();
9924        format!(
9925            "[route |-> {}, source_machine |-> {}, effect |-> {}, target_machine |-> {}, target_input |-> {}, payload |-> {}, actor |-> {}, effect_id |-> {}, source_transition |-> {}]",
9926            tla_string(route_name),
9927            tla_string(from_machine),
9928            tla_string(effect_variant),
9929            tla_string(to_machine),
9930            tla_string(to_input_variant),
9931            payload_expr,
9932            tla_string(self.actor(to_machine)),
9933            effect_id_expr,
9934            tla_string(source_transition)
9935        )
9936    }
9937
9938    fn render_machine_transition_action(
9939        &self,
9940        compiler: &mut MachineTlaCompiler<'_>,
9941        instance_id: &str,
9942        transition: &TransitionSchema,
9943        out: &mut String,
9944    ) -> std::result::Result<(), CompositionTlaError> {
9945        let machine = self.machine(instance_id);
9946        let action_name = self.machine_transition_name(instance_id, transition);
9947        let binding_types = compiler.binding_type_map(transition);
9948        let binding_env = transition
9949            .on
9950            .bindings()
9951            .iter()
9952            .map(|binding| {
9953                (
9954                    binding.as_str().to_owned(),
9955                    format!("packet.payload.{}", tla_ident(binding)),
9956                )
9957            })
9958            .collect::<BTreeMap<String, _>>();
9959        let params = transition
9960            .on
9961            .bindings()
9962            .iter()
9963            .map(|binding| format!("arg_{}", tla_ident(binding)))
9964            .collect::<Vec<_>>();
9965
9966        if params.is_empty() {
9967            writeln!(out, "{} ==", action_name);
9968        } else {
9969            pushln!(out, "{}({}) ==", action_name, params.join(", "));
9970        }
9971
9972        let phase_var = self.phase_var(instance_id);
9973        let from_guard = if transition.from.len() == 1 {
9974            format!("{} = {}", phase_var, tla_string(&transition.from[0]))
9975        } else {
9976            transition
9977                .from
9978                .iter()
9979                .map(|phase| format!("{} = {}", phase_var, tla_string(phase)))
9980                .collect::<Vec<_>>()
9981                .join(" \\/ ")
9982        };
9983
9984        pushln!(out, "    /\\ \\E packet \\in SeqElements(pending_inputs) :");
9985        writeln!(
9986            out,
9987            "       /\\ packet.machine = {}",
9988            tla_string(instance_id)
9989        )
9990        .expect("write to string");
9991        writeln!(
9992            out,
9993            "       /\\ packet.variant = {}",
9994            tla_string(transition.on.variant_str())
9995        )
9996        .expect("write to string");
9997        for binding in transition.on.bindings() {
9998            let arg_name = format!("arg_{}", tla_ident(binding));
9999            writeln!(
10000                out,
10001                "       /\\ packet.payload.{} = {}",
10002                tla_ident(binding),
10003                arg_name
10004            )
10005            .expect("write to string");
10006        }
10007        writeln!(
10008            out,
10009            "       /\\ ~HigherPriorityReady({})",
10010            tla_string(self.actor(instance_id))
10011        )
10012        .expect("write to string");
10013        writeln!(out, "       /\\ {}", from_guard);
10014
10015        let field_env = self.machine_field_env(instance_id);
10016        for guard in &transition.guards {
10017            writeln!(
10018                out,
10019                "       /\\ {}",
10020                compiler.render_guard(guard, &field_env, &binding_env, &binding_types)
10021            )
10022            .expect("write to string");
10023        }
10024
10025        let next_env = compiler.compile_updates(
10026            &action_name,
10027            &field_env,
10028            &binding_env,
10029            &binding_types,
10030            &transition.updates,
10031        );
10032        let effect_id_expr = "(model_step_count + 1)".to_string();
10033        let current_phase_symbol = compiler.phase_symbol.clone();
10034        compiler.phase_symbol = Some(tla_string(&transition.to));
10035        let effect_packets = transition
10036            .emit
10037            .iter()
10038            .map(|effect| {
10039                let payload_fields = effect
10040                    .fields
10041                    .iter()
10042                    .map(|(field, expr)| {
10043                        (
10044                            field.as_str().to_owned(),
10045                            compiler.render_expr_with_types(
10046                                expr,
10047                                &next_env,
10048                                &binding_env,
10049                                &binding_types,
10050                            ),
10051                        )
10052                    })
10053                    .collect::<BTreeMap<String, _>>();
10054                (
10055                    effect.variant.as_str().to_owned(),
10056                    format!(
10057                        "[machine |-> {}, variant |-> {}, payload |-> {}, effect_id |-> {}, source_transition |-> {}]",
10058                        tla_string(instance_id),
10059                        tla_string(&effect.variant),
10060                        self.payload_record_expr(&payload_fields),
10061                        effect_id_expr,
10062                        tla_string(&transition.name)
10063                    ),
10064                    payload_fields,
10065                )
10066            })
10067            .collect::<Vec<_>>();
10068        compiler.phase_symbol = current_phase_symbol;
10069
10070        let mut queued_route_packets = Vec::new();
10071        let mut immediate_route_packets = Vec::new();
10072        let mut owner_route_quantifiers = Vec::new();
10073        for (effect_variant, _effect_packet, payload_fields) in &effect_packets {
10074            for route in self.schema.routes.iter().filter(|route| {
10075                route.from_machine.as_str() == instance_id
10076                    && route.effect_variant.as_str() == effect_variant.as_str()
10077            }) {
10078                let (target_payload, route_owner_quantifiers) = self.target_payload_for_route(
10079                    machine,
10080                    effect_variant,
10081                    payload_fields,
10082                    route,
10083                    compiler,
10084                    &next_env,
10085                    &binding_env,
10086                    &binding_types,
10087                );
10088                for quantifier in route_owner_quantifiers {
10089                    if !owner_route_quantifiers.contains(&quantifier) {
10090                        owner_route_quantifiers.push(quantifier);
10091                    }
10092                }
10093                let route_packet = self.route_packet_expr(
10094                    &route.name,
10095                    instance_id,
10096                    effect_variant,
10097                    &route.to.machine,
10098                    &route.to.input_variant,
10099                    &target_payload,
10100                    &effect_id_expr,
10101                    &transition.name,
10102                );
10103                match route.delivery {
10104                    RouteDelivery::Enqueue => {
10105                        queued_route_packets.push((route_packet, target_payload))
10106                    }
10107                    RouteDelivery::Immediate => immediate_route_packets.push((
10108                        route_packet,
10109                        self.input_packet_expr_from_payload_expr(
10110                            &route.to.machine,
10111                            &route.to.input_variant,
10112                            &target_payload,
10113                            "route",
10114                            &route.name,
10115                            instance_id,
10116                            effect_variant,
10117                            &effect_id_expr,
10118                        ),
10119                    )),
10120                }
10121            }
10122        }
10123
10124        writeln!(
10125            out,
10126            "       /\\ {}' = {}",
10127            phase_var,
10128            tla_string(&transition.to)
10129        )
10130        .expect("write to string");
10131        let touched = machine
10132            .state
10133            .fields
10134            .iter()
10135            .filter_map(|field| {
10136                let next = next_env.get(field.name.as_str())?;
10137                if field_env
10138                    .get(field.name.as_str())
10139                    .is_some_and(|current| next != current)
10140                {
10141                    Some((field.name.as_str(), next.as_str()))
10142                } else {
10143                    None
10144                }
10145            })
10146            .collect::<Vec<_>>();
10147        for (field, expr) in &touched {
10148            writeln!(
10149                out,
10150                "       /\\ {}' = {}",
10151                self.field_var(instance_id, field),
10152                expr
10153            )
10154            .expect("write to string");
10155        }
10156
10157        let mut unchanged_machine_vars = Vec::new();
10158        for instance in &self.schema.machines {
10159            if instance.instance_id.as_str() == instance_id {
10160                for field in &machine.state.fields {
10161                    if !touched.iter().any(|(name, _)| *name == field.name.as_str()) {
10162                        unchanged_machine_vars
10163                            .push(self.field_var(instance_id, field.name.as_str()));
10164                    }
10165                }
10166            } else {
10167                unchanged_machine_vars.push(self.phase_var(instance.instance_id.as_str()));
10168                let other_machine = self.machine(instance.instance_id.as_str());
10169                for field in &other_machine.state.fields {
10170                    unchanged_machine_vars
10171                        .push(self.field_var(instance.instance_id.as_str(), field.name.as_str()));
10172                }
10173            }
10174        }
10175
10176        unchanged_machine_vars.push("witness_current_script_input".into());
10177        unchanged_machine_vars.push("witness_remaining_script_inputs".into());
10178
10179        if !unchanged_machine_vars.is_empty() {
10180            self.render_unchanged_vars(out, "       /\\ ", &unchanged_machine_vars);
10181        }
10182
10183        let pending_inputs_next = self.append_if_missing_chain(
10184            format!("SeqRemove(pending_inputs, packet)"),
10185            &immediate_route_packets
10186                .iter()
10187                .map(|(_, input_packet)| input_packet)
10188                .cloned()
10189                .collect::<Vec<_>>(),
10190        );
10191        let pending_routes_next = self.append_if_missing_chain(
10192            "pending_routes".into(),
10193            &queued_route_packets
10194                .iter()
10195                .map(|(route_packet, _)| route_packet)
10196                .cloned()
10197                .collect::<Vec<_>>(),
10198        );
10199        let delivered_routes_next = if immediate_route_packets.is_empty() {
10200            "delivered_routes".into()
10201        } else {
10202            format!(
10203                "delivered_routes \\cup {{ {} }}",
10204                immediate_route_packets
10205                    .iter()
10206                    .map(|(route_packet, _)| route_packet)
10207                    .cloned()
10208                    .collect::<Vec<_>>()
10209                    .join(", ")
10210            )
10211        };
10212        let observed_inputs_next = {
10213            let immediate_inputs = immediate_route_packets
10214                .iter()
10215                .map(|(_, input_packet)| input_packet)
10216                .cloned()
10217                .collect::<Vec<_>>();
10218            self.union_set_items("observed_inputs".into(), &immediate_inputs)
10219        };
10220        let emitted_effects_next = if effect_packets.is_empty() {
10221            "emitted_effects".into()
10222        } else {
10223            format!(
10224                "emitted_effects \\cup {{ {} }}",
10225                effect_packets
10226                    .iter()
10227                    .map(|(_, effect_packet, _)| effect_packet)
10228                    .cloned()
10229                    .collect::<Vec<_>>()
10230                    .join(", ")
10231            )
10232        };
10233        let observed_transitions_next = format!(
10234            "observed_transitions \\cup {{{}}}",
10235            self.transition_packet_expr(instance_id, transition)
10236        );
10237
10238        // Compute obligation set updates: when a transition emits an effect
10239        // that matches a handoff_protocol, add a record to the obligation set
10240        // with the protocol's declared obligation fields from the effect payload.
10241        let mut obligation_updates: BTreeMap<String, String> = BTreeMap::new();
10242        for (effect_variant, _effect_packet, payload_fields) in &effect_packets {
10243            for protocol in &self.schema.handoff_protocols {
10244                if protocol.producer_instance.as_str() == instance_id
10245                    && protocol.effect_variant.as_str() == effect_variant.as_str()
10246                {
10247                    let var = self.obligation_var(protocol);
10248                    let mut record_fields: Vec<String> =
10249                        Vec::with_capacity(protocol.obligation_fields.len() + 1);
10250                    record_fields.push("effect_id |-> (model_step_count + 1)".to_string());
10251                    for field in &protocol.obligation_fields {
10252                        let tla_field = tla_ident(field);
10253                        // Fail closed: an obligation field that is absent from
10254                        // the matching effect's payload used to be papered over
10255                        // with an `"unknown_<field>"` sentinel literal.
10256                        let value =
10257                            payload_fields.get(field.as_str()).cloned().ok_or_else(|| {
10258                                CompositionTlaError::UnknownObligationField {
10259                                    composition: self.schema.name.as_str().to_owned(),
10260                                    protocol: protocol.name.as_str().to_owned(),
10261                                    effect: effect_variant.clone(),
10262                                    field: field.as_str().to_owned(),
10263                                }
10264                            })?;
10265                        record_fields.push(format!("{} |-> {}", tla_field, value));
10266                    }
10267                    let record = if record_fields.is_empty() {
10268                        "\"token\"".to_string()
10269                    } else {
10270                        format!("[{}]", record_fields.join(", "))
10271                    };
10272                    obligation_updates.insert(var.clone(), format!("{} \\cup {{{}}}", var, record));
10273                }
10274            }
10275        }
10276
10277        let route_update_prefix = if owner_route_quantifiers.is_empty() {
10278            "       /\\"
10279        } else {
10280            writeln!(
10281                out,
10282                "       /\\ \\E {} :",
10283                owner_route_quantifiers.join(", ")
10284            )
10285            .expect("write to string");
10286            "           /\\"
10287        };
10288        writeln!(
10289            out,
10290            "{route_update_prefix} pending_inputs' = {pending_inputs_next}"
10291        )
10292        .expect("write to string");
10293        writeln!(
10294            out,
10295            "{route_update_prefix} observed_inputs' = {observed_inputs_next}"
10296        )
10297        .expect("write to string");
10298        writeln!(
10299            out,
10300            "{route_update_prefix} pending_routes' = {pending_routes_next}"
10301        )
10302        .expect("write to string");
10303        writeln!(
10304            out,
10305            "{route_update_prefix} delivered_routes' = {delivered_routes_next}"
10306        )
10307        .expect("write to string");
10308        writeln!(
10309            out,
10310            "{route_update_prefix} emitted_effects' = {emitted_effects_next}"
10311        )
10312        .expect("write to string");
10313        writeln!(
10314            out,
10315            "{route_update_prefix} observed_transitions' = {observed_transitions_next}"
10316        )
10317        .expect("write to string");
10318        // Write obligation variable updates — touched protocols get \cup, untouched get UNCHANGED
10319        let all_obligation_vars = self.obligation_vars();
10320        let mut unchanged_obligation_vars = Vec::new();
10321        for ovar in &all_obligation_vars {
10322            if let Some(next_expr) = obligation_updates.get(ovar) {
10323                writeln!(out, "{route_update_prefix} {}' = {}", ovar, next_expr)
10324                    .expect("write to string");
10325            } else {
10326                unchanged_obligation_vars.push(ovar.clone());
10327            }
10328        }
10329        if !unchanged_obligation_vars.is_empty() {
10330            let unchanged_prefix = format!("{route_update_prefix} ");
10331            self.render_unchanged_vars(out, &unchanged_prefix, &unchanged_obligation_vars);
10332        }
10333        writeln!(
10334            out,
10335            "{route_update_prefix} model_step_count' = model_step_count + 1"
10336        )
10337        .expect("write to string");
10338        Ok(())
10339    }
10340
10341    fn target_payload_for_route(
10342        &self,
10343        source_machine: &MachineSchema,
10344        effect_variant: &str,
10345        effect_payload_fields: &BTreeMap<String, String>,
10346        route: &Route,
10347        compiler: &MachineTlaCompiler<'_>,
10348        next_env: &BTreeMap<String, String>,
10349        binding_env: &BTreeMap<String, String>,
10350        binding_types: &BTreeMap<String, TypeRef>,
10351    ) -> (String, Vec<String>) {
10352        let target_machine = self.machine(route.to.machine.as_str());
10353        let Some(target_variant) = route_target_variant(target_machine, &route.to) else {
10354            return (String::new(), Vec::new());
10355        };
10356        let Ok(source_effect_variant) = source_machine.effects.variant_named(effect_variant) else {
10357            return (String::new(), Vec::new());
10358        };
10359        let mut owner_context_quantifiers = Vec::new();
10360        let bindings = route
10361            .bindings
10362            .iter()
10363            .map(|binding| {
10364                let expr = match &binding.source {
10365                    RouteBindingSource::Field {
10366                        from_field,
10367                        allow_named_alias: _,
10368                    } => effect_payload_fields
10369                        .get(from_field.as_str())
10370                        .cloned()
10371                        .or_else(|| {
10372                            source_effect_variant
10373                                .fields
10374                                .iter()
10375                                .find(|field| field.name == *from_field)
10376                                .map(|_| format!("packet.payload.{}", tla_ident(from_field)))
10377                        })
10378                        .unwrap_or_else(|| "None".to_string()),
10379                    RouteBindingSource::Literal(expr) => {
10380                        compiler.render_expr_with_types(expr, next_env, binding_env, binding_types)
10381                    }
10382                    RouteBindingSource::OwnerProvided => {
10383                        if let Some(target_field) = target_variant
10384                            .fields
10385                            .iter()
10386                            .find(|field| field.name == binding.to_field)
10387                        {
10388                            let var_name = format!(
10389                                "route_owner_ctx_{}_{}",
10390                                tla_ident(&route.name),
10391                                tla_ident(&binding.to_field)
10392                            );
10393                            let domain = self.binding_domain_for_binding(
10394                                route.to.machine.as_str(),
10395                                Some(target_variant.name.as_str()),
10396                                binding.to_field.as_str(),
10397                                &target_field.ty,
10398                            );
10399                            owner_context_quantifiers.push(format!("{var_name} \\in {domain}"));
10400                            var_name
10401                        } else {
10402                            "\"owner_val\"".to_string()
10403                        }
10404                    }
10405                };
10406                (binding.to_field.as_str().to_owned(), expr)
10407            })
10408            .collect::<BTreeMap<String, _>>();
10409        let payload_fields = target_variant
10410            .fields
10411            .iter()
10412            .map(|field| {
10413                let expr = bindings
10414                    .get(field.name.as_str())
10415                    .cloned()
10416                    .unwrap_or_else(|| default_state_init_expr(&field.ty));
10417                (field.name.as_str().to_owned(), expr)
10418            })
10419            .collect::<BTreeMap<String, _>>();
10420        (
10421            self.payload_record_expr(&payload_fields),
10422            owner_context_quantifiers,
10423        )
10424    }
10425
10426    fn append_if_missing_chain(&self, base: String, items: &[String]) -> String {
10427        items.iter().fold(base, |expr, item| {
10428            format!("AppendIfMissing({expr}, {item})")
10429        })
10430    }
10431
10432    fn union_set_items(&self, base: String, items: &[String]) -> String {
10433        if items.is_empty() {
10434            base
10435        } else {
10436            format!("{base} \\cup {{{}}}", items.join(", "))
10437        }
10438    }
10439
10440    fn transition_packet_expr(&self, instance_id: &str, transition: &TransitionSchema) -> String {
10441        format!(
10442            "[machine |-> {}, transition |-> {}, actor |-> {}, step |-> (model_step_count + 1), from_phase |-> {}, to_phase |-> {}]",
10443            tla_string(instance_id),
10444            tla_string(&transition.name),
10445            tla_string(self.actor(instance_id)),
10446            self.phase_var(instance_id),
10447            tla_string(&transition.to)
10448        )
10449    }
10450}
10451
10452#[derive(Clone, Copy)]
10453enum OrderingOperator {
10454    Lt,
10455    Lte,
10456    Gt,
10457    Gte,
10458}
10459
10460struct MachineTlaCompiler<'a> {
10461    schema: &'a MachineSchema,
10462    named_bindings: BTreeMap<String, meerkat_machine_schema::RustTypeAtom>,
10463    helper_defs: Vec<String>,
10464    helper_counter: usize,
10465    helper_prefix: Option<String>,
10466    phase_symbol: Option<String>,
10467    field_env_override: Option<BTreeMap<String, String>>,
10468    unchanged_frames: UnchangedFrameInterner,
10469    /// Set when an ordering comparison renders through `OptionLt` /
10470    /// `OptionLe`; the module then defines them. Shared by every compiler
10471    /// that renders into the same module.
10472    option_order_used: Rc<Cell<bool>>,
10473}
10474
10475impl<'a> MachineTlaCompiler<'a> {
10476    fn new(schema: &'a MachineSchema) -> Self {
10477        Self {
10478            schema,
10479            named_bindings: collect_machine_named_bindings(schema),
10480            helper_defs: Vec::new(),
10481            helper_counter: 0,
10482            helper_prefix: None,
10483            phase_symbol: None,
10484            field_env_override: None,
10485            unchanged_frames: UnchangedFrameInterner::default(),
10486            option_order_used: Rc::default(),
10487        }
10488    }
10489
10490    fn new_with_helper_prefix(schema: &'a MachineSchema, helper_prefix: impl Into<String>) -> Self {
10491        Self {
10492            schema,
10493            named_bindings: collect_machine_named_bindings(schema),
10494            helper_defs: Vec::new(),
10495            helper_counter: 0,
10496            helper_prefix: Some(helper_prefix.into()),
10497            phase_symbol: None,
10498            field_env_override: None,
10499            unchanged_frames: UnchangedFrameInterner::default(),
10500            option_order_used: Rc::default(),
10501        }
10502    }
10503
10504    fn with_option_order_flag(mut self, option_order_used: Rc<Cell<bool>>) -> Self {
10505        self.option_order_used = option_order_used;
10506        self
10507    }
10508
10509    fn with_phase_symbol(mut self, phase_symbol: impl Into<String>) -> Self {
10510        self.phase_symbol = Some(phase_symbol.into());
10511        self
10512    }
10513
10514    fn with_field_env_override(mut self, field_env_override: BTreeMap<String, String>) -> Self {
10515        self.field_env_override = Some(field_env_override);
10516        self
10517    }
10518
10519    fn render(&mut self) -> std::result::Result<String, CompositionTlaError> {
10520        let mut out = String::new();
10521        let constants = collect_binding_domains(self.schema);
10522        let named_samples = collect_machine_named_type_samples(self.schema);
10523        let named_bindings = collect_machine_named_bindings(self.schema);
10524
10525        pushln!(&mut out, "---- MODULE model ----");
10526        pushln!(&mut out, "EXTENDS TLC, Naturals, Sequences, FiniteSets");
10527        pushln!(&mut out);
10528        writeln!(
10529            &mut out,
10530            "\\* Generated semantic machine model for {}.",
10531            self.schema.machine
10532        )
10533        .expect("write to string");
10534        pushln!(&mut out);
10535
10536        let mut model_constants = constants
10537            .iter()
10538            .filter(|(_, ty)| {
10539                !matches!(
10540                    ty,
10541                    TypeRef::Seq(_) | TypeRef::Option(_) | TypeRef::Map(_, _)
10542                )
10543            })
10544            .map(|(name, _)| name)
10545            .cloned()
10546            .collect::<Vec<_>>();
10547        model_constants.extend(
10548            machine_input_sample_constants(self.schema)
10549                .into_iter()
10550                .map(|(constant, _)| constant),
10551        );
10552        if machine_uses_u64_max(self.schema) {
10553            model_constants.push(TLA_RUST_U64_MAX_CONSTANT.to_owned());
10554        }
10555        if !model_constants.is_empty() {
10556            let constant_list = model_constants.join(", ");
10557            if model_constants
10558                .iter()
10559                .any(|constant| constant == TLA_RUST_U64_MAX_CONSTANT)
10560            {
10561                pushln!(
10562                    &mut out,
10563                    "\\* RustU64Max is the TLA boundary for Expr::U64Max; production generated Rust renders u64::MAX."
10564                );
10565            }
10566            writeln!(&mut out, "CONSTANTS {constant_list}");
10567            pushln!(&mut out);
10568        }
10569
10570        pushln!(&mut out, "None == [tag |-> \"none\", value |-> \"none\"]");
10571        writeln!(&mut out, "Some(v) == [tag |-> \"some\", value |-> v]");
10572        pushln!(&mut out);
10573        let option_order_anchor = out.len();
10574
10575        push_cfg_assignment_operator_definitions(
10576            &mut out,
10577            &constants,
10578            &named_bindings,
10579            &CfgAssignmentOperatorProfile {
10580                suffix: "Ci".to_owned(),
10581                explicit_values: self.schema.tlc_model.as_ref().map(|model| &model.ci),
10582                sample_cardinality: machine_cfg_sample_cardinality(self.schema, false),
10583                domain_overrides: None,
10584                named_samples: &named_samples,
10585                include_string_samples: false,
10586            },
10587        );
10588        push_cfg_assignment_operator_definitions(
10589            &mut out,
10590            &constants,
10591            &named_bindings,
10592            &CfgAssignmentOperatorProfile {
10593                suffix: "Deep".to_owned(),
10594                explicit_values: self.schema.tlc_model.as_ref().map(|model| &model.deep),
10595                sample_cardinality: machine_cfg_sample_cardinality(self.schema, true),
10596                domain_overrides: Some(&self.schema.deep_domain_overrides),
10597                named_samples: &with_guard_binding_string_samples(&named_samples, self.schema),
10598                include_string_samples: !machine_uses_session_id_string_bridge(self.schema),
10599            },
10600        );
10601
10602        for (name, ty) in ordered_composite_domain_definitions(&constants) {
10603            let definition = match ty {
10604                TypeRef::Seq(inner) => render_sequence_domain_definition(inner),
10605                TypeRef::Option(inner) => render_option_domain_definition(inner),
10606                TypeRef::Map(key, value) => render_map_domain_definition(key, value),
10607                _ => continue,
10608            };
10609            writeln!(&mut out, "{} == {}", name, definition).expect("write to string");
10610        }
10611        if constants.values().any(|ty| {
10612            matches!(
10613                ty,
10614                TypeRef::Seq(_) | TypeRef::Option(_) | TypeRef::Map(_, _)
10615            )
10616        }) {
10617            pushln!(&mut out);
10618        }
10619        writeln!(
10620            &mut out,
10621            "MapLookup(map, key) == IF key \\in DOMAIN map THEN map[key] ELSE None"
10622        )
10623        .expect("write to string");
10624        writeln!(
10625            &mut out,
10626            "MapSet(map, key, value) == [x \\in DOMAIN map \\cup {{key}} |-> IF x = key THEN value ELSE map[x]]"
10627        )
10628        .expect("write to string");
10629        writeln!(
10630            &mut out,
10631            "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]]"
10632        )
10633        .expect("write to string");
10634        writeln!(
10635            &mut out,
10636            "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]]"
10637        )
10638        .expect("write to string");
10639        writeln!(
10640            &mut out,
10641            "MapRemove(map, key) == [x \\in DOMAIN map \\ {{key}} |-> map[x]]"
10642        )
10643        .expect("write to string");
10644        writeln!(
10645            &mut out,
10646            "StartsWith(seq, prefix) == /\\ Len(prefix) <= Len(seq) /\\ SubSeq(seq, 1, Len(prefix)) = prefix"
10647        )
10648        .expect("write to string");
10649        writeln!(
10650            &mut out,
10651            "SeqElements(seq) == {{seq[i] : i \\in 1..Len(seq)}}"
10652        )
10653        .expect("write to string");
10654        writeln!(
10655            &mut out,
10656            "Count(seq, value) == Cardinality({{i \\in DOMAIN seq : seq[i] = value}})"
10657        )
10658        .expect("write to string");
10659        if !self.schema.tlc_representative_inputs.is_empty() {
10660            writeln!(
10661                &mut out,
10662                "{TLC_REPRESENTATIVE_DOMAIN_HELPER}(values) == IF values = {{}} THEN {{}} ELSE {{CHOOSE value \\in values : TRUE}}"
10663            )
10664            .expect("write to string");
10665        }
10666        writeln!(
10667            &mut out,
10668            "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)"
10669        )
10670        .expect("write to string");
10671        writeln!(
10672            &mut out,
10673            "RECURSIVE SeqRemoveAll(_, _)\nSeqRemoveAll(seq, values) == IF Len(values) = 0 THEN seq ELSE SeqRemoveAll(SeqRemove(seq, Head(values)), Tail(values))"
10674        )
10675        .expect("write to string");
10676        pushln!(&mut out);
10677
10678        let variable_list = std::iter::once("phase".to_string())
10679            .chain(std::iter::once("model_step_count".to_string()))
10680            .chain(
10681                self.schema
10682                    .state
10683                    .fields
10684                    .iter()
10685                    .map(|field| field.name.as_str().to_owned()),
10686            )
10687            .collect::<Vec<_>>()
10688            .join(", ");
10689        pushln!(&mut out, "VARIABLES {variable_list}");
10690        pushln!(&mut out);
10691        let vars = std::iter::once("phase".to_string())
10692            .chain(std::iter::once("model_step_count".to_string()))
10693            .chain(
10694                self.schema
10695                    .state
10696                    .fields
10697                    .iter()
10698                    .map(|field| field.name.as_str().to_owned()),
10699            )
10700            .collect::<Vec<_>>();
10701        pushln!(&mut out, "vars == << {} >>", vars.join(", "));
10702        pushln!(&mut out);
10703
10704        for helper in helper_dependency_order(self.schema)? {
10705            self.render_helper(&mut out, helper);
10706        }
10707        if self.schema.machine.as_str() == "MobMachine" {
10708            self.render_mob_machine_native_helpers(&mut out);
10709        }
10710        if self.schema.machine.as_str() == "MeerkatMachine" {
10711            self.render_meerkat_machine_native_helpers(&mut out);
10712        }
10713        if self.schema.machine.as_str() == "RuntimeDeliveryMachine" {
10714            self.render_runtime_delivery_native_helpers(&mut out);
10715        }
10716        if self.schema.machine.as_str() == "SessionDocumentMachine" {
10717            self.render_session_document_native_helpers(&mut out);
10718        }
10719        if !self.schema.helpers.is_empty() || !self.schema.derived.is_empty() {
10720            pushln!(&mut out);
10721        }
10722
10723        pushln!(&mut out, "Init ==");
10724        writeln!(
10725            &mut out,
10726            "    /\\ phase = {}",
10727            tla_string(&self.schema.state.init.phase)
10728        )
10729        .expect("write to string");
10730        pushln!(&mut out, "    /\\ model_step_count = 0");
10731        for field in &self.schema.state.fields {
10732            let init_expr = self
10733                .schema
10734                .state
10735                .init
10736                .fields
10737                .iter()
10738                .find(|item| item.field == field.name)
10739                .map(|item| self.render_expr(&item.expr, &BTreeMap::new(), &BTreeMap::new()))
10740                .unwrap_or_else(|| default_state_init_expr(&field.ty));
10741            pushln!(&mut out, "    /\\ {} = {}", field.name, init_expr);
10742        }
10743        pushln!(&mut out);
10744
10745        let mut rendered_transitions = Vec::new();
10746        for transition in &self.schema.transitions {
10747            let mut rendered = String::new();
10748            self.render_transition(&mut rendered, transition);
10749            rendered_transitions.push(rendered);
10750        }
10751
10752        if !self.schema.state.terminal_phases.is_empty() {
10753            let terminal_guard = if self.schema.state.terminal_phases.len() == 1 {
10754                format!(
10755                    "phase = {}",
10756                    tla_string(&self.schema.state.terminal_phases[0])
10757                )
10758            } else {
10759                self.schema
10760                    .state
10761                    .terminal_phases
10762                    .iter()
10763                    .map(|phase| format!("phase = {}", tla_string(phase)))
10764                    .collect::<Vec<_>>()
10765                    .join(" \\/ ")
10766            };
10767            pushln!(&mut out, "TerminalStutter ==");
10768            pushln!(&mut out, "    /\\ {}", terminal_guard);
10769            pushln!(&mut out, "    /\\ UNCHANGED vars");
10770            pushln!(&mut out);
10771        }
10772
10773        // Fail closed on a frame-name collision: the rendered transitions
10774        // already reference one name for two different frames, so returning the
10775        // module would silently give an action the wrong frame condition.
10776        if let Some(collision) = self.unchanged_frames.collision() {
10777            return Err(CompositionTlaError::MachineUnchangedFrameCollision {
10778                machine: self.schema.machine.as_str().to_owned(),
10779                collision: collision.clone(),
10780            });
10781        }
10782        // Every frame variable is in scope from the VARIABLES declaration
10783        // above, and every reference is in the transition bodies below.
10784        out.push_str(&self.unchanged_frames.definitions_block());
10785
10786        if !self.helper_defs.is_empty() {
10787            for helper in &self.helper_defs {
10788                pushln!(&mut out, "{helper}");
10789                pushln!(&mut out);
10790            }
10791        }
10792
10793        for transition in &rendered_transitions {
10794            pushln!(&mut out, "{transition}");
10795            pushln!(&mut out);
10796        }
10797
10798        pushln!(&mut out, "Next ==");
10799        for transition in &self.schema.transitions {
10800            let call = if transition.on.bindings().is_empty() {
10801                transition.name.as_str().to_owned()
10802            } else {
10803                let binding_types = self.binding_type_map(transition);
10804                let forced_bool_literals =
10805                    transition_forced_bool_literals(transition, &binding_types);
10806                let binding_env = transition
10807                    .on
10808                    .bindings()
10809                    .iter()
10810                    .map(|binding| {
10811                        (
10812                            binding.as_str().to_owned(),
10813                            self.local_binding_name(binding.as_str()),
10814                        )
10815                    })
10816                    .collect::<BTreeMap<_, _>>();
10817                let mut prefix = String::new();
10818                for binding in transition.on.bindings() {
10819                    if forced_bool_literals.contains_key(binding.as_str()) {
10820                        continue;
10821                    }
10822                    let Some(ty) = binding_types.get(binding.as_str()) else {
10823                        return Ok(String::new());
10824                    };
10825                    let domain = self.binding_domain_for_binding(
10826                        trigger_input_variant(transition),
10827                        binding.as_str(),
10828                        ty,
10829                    );
10830                    let domain =
10831                        if transition_uses_tlc_representative_payload(self.schema, transition) {
10832                            tlc_representative_domain(domain)
10833                        } else {
10834                            domain
10835                        };
10836                    let local = binding_env
10837                        .get(binding.as_str())
10838                        .cloned()
10839                        .unwrap_or_else(|| binding.as_str().to_owned());
10840                    prefix.push_str(&format!("\\E {local} \\in {domain} : "));
10841                }
10842                let args = transition
10843                    .on
10844                    .bindings()
10845                    .iter()
10846                    .map(|binding| {
10847                        forced_bool_literals
10848                            .get(binding.as_str())
10849                            .map(|value| tla_bool_literal(*value).to_owned())
10850                            .unwrap_or_else(|| {
10851                                binding_env
10852                                    .get(binding.as_str())
10853                                    .cloned()
10854                                    .unwrap_or_else(|| binding.as_str().to_owned())
10855                            })
10856                    })
10857                    .collect::<Vec<_>>()
10858                    .join(", ");
10859                // Hoist the source-phase guard ahead of the parameter
10860                // quantifiers. The guard is the first conjunct of the action
10861                // body too, so the disjunct is unchanged in meaning, but TLC
10862                // no longer splits it into one action per parameter tuple
10863                // that it must enumerate in every state: states outside the
10864                // source phase reject the whole disjunct at once.
10865                let from_guard = transition
10866                    .from
10867                    .iter()
10868                    .map(|phase| format!("phase = {}", tla_string(phase)))
10869                    .collect::<Vec<_>>()
10870                    .join(" \\/ ");
10871                if prefix.is_empty() || from_guard.is_empty() {
10872                    format!("{prefix}{}({})", transition.name, args)
10873                } else {
10874                    format!("({from_guard}) /\\ {prefix}{}({})", transition.name, args)
10875                }
10876            };
10877            pushln!(&mut out, "    \\/ {}", call);
10878        }
10879        if !self.schema.state.terminal_phases.is_empty() {
10880            pushln!(&mut out, "    \\/ TerminalStutter");
10881        }
10882        pushln!(&mut out);
10883
10884        for invariant in &self.schema.invariants {
10885            writeln!(
10886                &mut out,
10887                "{} == {}",
10888                invariant.name,
10889                self.render_expr(&invariant.expr, &BTreeMap::new(), &BTreeMap::new())
10890            )
10891            .expect("write to string");
10892        }
10893        pushln!(&mut out);
10894
10895        writeln!(
10896            &mut out,
10897            "CiStateConstraint == {}",
10898            render_machine_state_constraint(self.schema, false)
10899        )
10900        .expect("write to string");
10901        writeln!(
10902            &mut out,
10903            "DeepStateConstraint == {}",
10904            render_machine_state_constraint(self.schema, true)
10905        )
10906        .expect("write to string");
10907        pushln!(&mut out);
10908
10909        pushln!(&mut out, "Spec == Init /\\ [][Next]_vars");
10910        pushln!(&mut out);
10911        for invariant in &self.schema.invariants {
10912            pushln!(&mut out, "THEOREM Spec => []{}", invariant.name);
10913        }
10914        pushln!(&mut out);
10915        writeln!(
10916            &mut out,
10917            "============================================================================="
10918        )
10919        .expect("write to string");
10920
10921        if self.option_order_used.get() {
10922            out.insert_str(option_order_anchor, TLA_OPTION_ORDER_DEFINITIONS);
10923        }
10924        Ok(out)
10925    }
10926
10927    fn render_helper(&self, out: &mut String, helper: &HelperSchema) {
10928        let params = helper
10929            .params
10930            .iter()
10931            .map(|field| self.local_binding_name(field.name.as_str()))
10932            .collect::<Vec<_>>()
10933            .join(", ");
10934        let binding_env = helper
10935            .params
10936            .iter()
10937            .map(|field| {
10938                (
10939                    field.name.as_str().to_owned(),
10940                    self.local_binding_name(field.name.as_str()),
10941                )
10942            })
10943            .collect::<BTreeMap<String, _>>();
10944        let field_env = self.field_env_override.clone().unwrap_or_else(|| {
10945            self.schema
10946                .state
10947                .fields
10948                .iter()
10949                .map(|field| {
10950                    (
10951                        field.name.as_str().to_owned(),
10952                        field.name.as_str().to_owned(),
10953                    )
10954                })
10955                .collect::<BTreeMap<String, _>>()
10956        });
10957        let binding_types = helper
10958            .params
10959            .iter()
10960            .map(|field| (field.name.as_str().to_owned(), field.ty.clone()))
10961            .collect::<BTreeMap<String, _>>();
10962        if helper.params.is_empty() {
10963            writeln!(
10964                out,
10965                "{} == {}",
10966                self.scoped_helper_name(&helper.name),
10967                self.render_expr_with_types(&helper.body, &field_env, &binding_env, &binding_types)
10968            )
10969            .expect("write to string");
10970        } else {
10971            writeln!(
10972                out,
10973                "{}({}) == {}",
10974                self.scoped_helper_name(&helper.name),
10975                params,
10976                self.render_expr_with_types(&helper.body, &field_env, &binding_env, &binding_types)
10977            )
10978            .expect("write to string");
10979        }
10980    }
10981
10982    fn render_runtime_delivery_native_helpers(&self, out: &mut String) {
10983        writeln!(
10984            out,
10985            "{}(current, recipient, outcome) ==",
10986            self.scoped_helper_name("runtime_delivery_recipient_outcomes_after_set")
10987        )
10988        .expect("write to string");
10989        pushln!(out, "    MapSet(current, recipient, outcome)");
10990    }
10991
10992    fn render_session_document_native_helpers(&self, out: &mut String) {
10993        writeln!(
10994            out,
10995            "{}(current, slot, value) ==",
10996            self.scoped_helper_name("session_document_instruction_slot_after_set")
10997        )
10998        .expect("write to string");
10999        pushln!(out, "    MapSet(current, slot, value)");
11000        // The body bytes of the Active slots; a slot the bytes map does not
11001        // name counts nothing (the Rust authorities agree).
11002        writeln!(
11003            out,
11004            "{}(slot_effect, slot_bytes) ==",
11005            self.scoped_helper_name("session_document_instruction_active_bytes")
11006        )
11007        .expect("write to string");
11008        pushln!(
11009            out,
11010            "    LET RECURSIVE SessionDocumentInstructionActiveBytesOver(_)"
11011        );
11012        pushln!(
11013            out,
11014            "        SessionDocumentInstructionActiveBytesOver(instruction_slots) =="
11015        );
11016        pushln!(out, "            IF instruction_slots = {{}} THEN 0");
11017        pushln!(
11018            out,
11019            "            ELSE LET instruction_slot == CHOOSE candidate_slot \\in instruction_slots : TRUE"
11020        );
11021        pushln!(
11022            out,
11023            "                 IN (IF slot_effect[instruction_slot] = \"Active\" /\\ instruction_slot \\in DOMAIN slot_bytes"
11024        );
11025        pushln!(
11026            out,
11027            "                     THEN slot_bytes[instruction_slot] ELSE 0)"
11028        );
11029        pushln!(
11030            out,
11031            "                    + SessionDocumentInstructionActiveBytesOver(instruction_slots \\ {{instruction_slot}})"
11032        );
11033        pushln!(
11034            out,
11035            "    IN SessionDocumentInstructionActiveBytesOver(DOMAIN slot_effect)"
11036        );
11037        // The entries of a slot map whose slot is Active: what an
11038        // application puts in effect (the Rust authorities agree).
11039        writeln!(
11040            out,
11041            "{}(slot_effect, slot_values) ==",
11042            self.scoped_helper_name("session_document_instruction_active_slots")
11043        )
11044        .expect("write to string");
11045        pushln!(
11046            out,
11047            "    [instruction_slot \\in {{candidate_slot \\in DOMAIN slot_values :"
11048        );
11049        pushln!(
11050            out,
11051            "            candidate_slot \\in DOMAIN slot_effect /\\ slot_effect[candidate_slot] = \"Active\"}}"
11052        );
11053        pushln!(out, "        |-> slot_values[instruction_slot]]");
11054        // Per activation key, the rows a retirement leaves retired: every
11055        // row but the newest, or the recovered count when that is more; a
11056        // key the retired map does not name counts none (the Rust
11057        // authorities agree).
11058        writeln!(
11059            out,
11060            "{}(activation_rows, activation_retired) ==",
11061            self.scoped_helper_name("session_document_activation_retired_after")
11062        )
11063        .expect("write to string");
11064        pushln!(out, "    [activation_key \\in DOMAIN activation_rows |->");
11065        pushln!(
11066            out,
11067            "        LET retired_count == IF activation_key \\in DOMAIN activation_retired THEN activation_retired[activation_key] ELSE 0"
11068        );
11069        pushln!(
11070            out,
11071            "            superseded_count == IF activation_rows[activation_key] > 0 THEN activation_rows[activation_key] - 1 ELSE 0"
11072        );
11073        pushln!(
11074            out,
11075            "        IN IF retired_count >= superseded_count THEN retired_count ELSE superseded_count]"
11076        );
11077    }
11078
11079    fn render_meerkat_machine_native_helpers(&self, out: &mut String) {
11080        let prefix = |name: &str| self.scoped_helper_name(name);
11081        writeln!(
11082            out,
11083            "{}(current, candidate) ==",
11084            prefix("meerkat_machine_session_id_matches_string")
11085        )
11086        .expect("write to string");
11087        pushln!(out, "    current # None /\\ current.value = candidate");
11088        writeln!(
11089            out,
11090            "{}(endpoints, endpoint_count) ==",
11091            prefix("meerkat_peer_endpoint_set_cardinality_matches")
11092        )
11093        .expect("write to string");
11094        pushln!(out, "    Cardinality(endpoints) = endpoint_count");
11095        writeln!(
11096            out,
11097            "{}(endpoints, peer_id) ==",
11098            prefix("meerkat_peer_endpoint_set_contains_peer_id")
11099        )
11100        .expect("write to string");
11101        pushln!(
11102            out,
11103            "    \\E endpoint \\in endpoints: endpoint.peer_id = peer_id"
11104        );
11105        writeln!(
11106            out,
11107            "{}(endpoint, peer_id) ==",
11108            prefix("meerkat_peer_endpoint_option_peer_id_matches")
11109        )
11110        .expect("write to string");
11111        pushln!(
11112            out,
11113            "    endpoint # None /\\ endpoint.value.peer_id = peer_id"
11114        );
11115        writeln!(
11116            out,
11117            "{}(endpoint, peer_id) ==",
11118            prefix("meerkat_peer_endpoint_peer_id_matches")
11119        )
11120        .expect("write to string");
11121        pushln!(out, "    endpoint.peer_id = peer_id");
11122        writeln!(
11123            out,
11124            "{}(endpoints) ==",
11125            prefix("meerkat_peer_endpoint_set_peer_ids_unique")
11126        )
11127        .expect("write to string");
11128        pushln!(
11129            out,
11130            "    Cardinality(endpoints) = Cardinality({{ endpoint.peer_id : endpoint \\in endpoints }})"
11131        );
11132        writeln!(
11133            out,
11134            "{}(rows, operation_by_authority, operation_id) ==",
11135            prefix("meerkat_machine_live_bridge_authority_rows_without_operation")
11136        )
11137        .expect("write to string");
11138        pushln!(
11139            out,
11140            "    [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]]"
11141        );
11142        writeln!(
11143            out,
11144            "{}(authorities, operation_by_authority, operation_id) ==",
11145            prefix("meerkat_machine_live_bridge_authorities_without_operation")
11146        )
11147        .expect("write to string");
11148        pushln!(
11149            out,
11150            "    {{ authority_id \\in authorities : IF authority_id \\in DOMAIN operation_by_authority THEN operation_by_authority[authority_id] # operation_id ELSE TRUE }}"
11151        );
11152        // The inputs still bound to one run: its batch and its durable joins,
11153        // staged or, in a resumed run, applied by a committed round. The
11154        // parameters are prefixed: TLA+ forbids a parameter named like a
11155        // state variable (`input_phases`).
11156        writeln!(
11157            out,
11158            "{}(arg_run_associations, arg_input_phases, arg_run_id) ==",
11159            prefix("meerkat_machine_run_contributor_count")
11160        )
11161        .expect("write to string");
11162        pushln!(
11163            out,
11164            "    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 }})"
11165        );
11166        // The most contributors one run's commit names. A defined operator,
11167        // not a literal in the guard, so a bounded audit can substitute a
11168        // small bound (`meerkat_machine_run_contributor_limit <- ...`) and
11169        // explore the refused join.
11170        writeln!(
11171            out,
11172            "{} == {}",
11173            prefix("meerkat_machine_run_contributor_limit"),
11174            meerkat_machine_schema::catalog::dsl::meerkat_machine::command_capabilities::RUNTIME_LOOP_BATCH_MAX_INPUTS
11175        )
11176        .expect("write to string");
11177    }
11178
11179    fn render_mob_machine_native_helpers(&self, out: &mut String) {
11180        let prefix = |name: &str| self.scoped_helper_name(name);
11181        let local = |name: &str| self.local_binding_name(name);
11182        // Row #181: compute the next monotone respawn generation for an
11183        // identity. Missing identity starts at generation zero. A retained
11184        // u64::MAX generation has no successor and must never wrap to zero.
11185        writeln!(
11186            out,
11187            "{}(arg_identity_runtime_generations, arg_agent_identity) ==",
11188            prefix("mob_machine_next_respawn_generation")
11189        )
11190        .expect("write to string");
11191        pushln!(
11192            out,
11193            "    IF arg_agent_identity \\notin DOMAIN arg_identity_runtime_generations"
11194        );
11195        pushln!(out, "    THEN Some(0)");
11196        pushln!(
11197            out,
11198            "    ELSE IF arg_identity_runtime_generations[arg_agent_identity] = {TLA_RUST_U64_MAX_CONSTANT}"
11199        );
11200        pushln!(out, "         THEN None");
11201        pushln!(
11202            out,
11203            "         ELSE Some(arg_identity_runtime_generations[arg_agent_identity] + 1)"
11204        );
11205        // The generation a new incarnation mints: one past the larger of the
11206        // retained generation and the recovered high-water, zero for an
11207        // identity in neither map, and no successor past the Rust u64
11208        // ceiling. Recovery replay keeps the operator above, which reads the
11209        // retained map only.
11210        writeln!(
11211            out,
11212            "{}(arg_identity_runtime_generations, arg_identity_generation_highwater, arg_agent_identity) ==",
11213            prefix("mob_machine_next_minted_generation")
11214        )
11215        .expect("write to string");
11216        pushln!(
11217            out,
11218            "    LET retained == IF arg_agent_identity \\in DOMAIN arg_identity_runtime_generations"
11219        );
11220        pushln!(
11221            out,
11222            "                    THEN arg_identity_runtime_generations[arg_agent_identity] ELSE 0"
11223        );
11224        pushln!(
11225            out,
11226            "        highwater == IF arg_agent_identity \\in DOMAIN arg_identity_generation_highwater"
11227        );
11228        pushln!(
11229            out,
11230            "                     THEN arg_identity_generation_highwater[arg_agent_identity] ELSE 0"
11231        );
11232        pushln!(
11233            out,
11234            "        base == IF retained >= highwater THEN retained ELSE highwater"
11235        );
11236        pushln!(
11237            out,
11238            "    IN IF arg_agent_identity \\notin DOMAIN arg_identity_runtime_generations /\\ arg_agent_identity \\notin DOMAIN arg_identity_generation_highwater"
11239        );
11240        pushln!(out, "       THEN Some(0)");
11241        pushln!(
11242            out,
11243            "       ELSE IF base = {TLA_RUST_U64_MAX_CONSTANT} THEN None ELSE Some(base + 1)"
11244        );
11245        // Supervisor epochs use the same non-wrapping u64 successor relation
11246        // in both plain and Option-valued recovered tuples. These operators
11247        // deliberately mention the Rust u64 ceiling so TLC cannot admit
11248        // MAX -> 0 as a successor through unbounded integer arithmetic.
11249        writeln!(
11250            out,
11251            "{}(arg_current, arg_next) ==",
11252            prefix("mob_machine_u64_is_exact_successor")
11253        )
11254        .expect("write to string");
11255        pushln!(out, "    /\\ arg_current # {TLA_RUST_U64_MAX_CONSTANT}");
11256        pushln!(out, "    /\\ arg_next = arg_current + 1");
11257        writeln!(
11258            out,
11259            "{}(arg_current, arg_next) ==",
11260            prefix("mob_machine_optional_u64_is_exact_successor")
11261        )
11262        .expect("write to string");
11263        pushln!(out, "    /\\ arg_current # {TLA_RUST_U64_MAX_CONSTANT}");
11264        pushln!(out, "    /\\ arg_next = Some(arg_current + 1)");
11265        // Remote-turn custody admission is a native MobMachine reducer because
11266        // it enforces aggregate cardinality and correlation-key uniqueness
11267        // across all three custody sets. Keep this operator structurally
11268        // equivalent to the Rust helper in the canonical MobMachine catalog.
11269        writeln!(
11270            out,
11271            "{}(pending, committed, resolved, candidate) ==",
11272            prefix("mob_machine_remote_turn_custody_admits")
11273        )
11274        .expect("write to string");
11275        pushln!(
11276            out,
11277            "    LET same_member_host_count == Cardinality({{ row \\in pending : /\\ row.agent_identity = candidate.agent_identity /\\ row.host_id = candidate.host_id }})"
11278        );
11279        pushln!(
11280            out,
11281            "            + Cardinality({{ row \\in committed : /\\ row.agent_identity = candidate.agent_identity /\\ row.host_id = candidate.host_id }})"
11282        );
11283        pushln!(
11284            out,
11285            "            + Cardinality({{ row \\in resolved : /\\ row.agent_identity = candidate.agent_identity /\\ row.host_id = candidate.host_id }})"
11286        );
11287        pushln!(
11288            out,
11289            "    IN /\\ Cardinality(pending) + Cardinality(committed) + Cardinality(resolved) < 4096"
11290        );
11291        pushln!(out, "       /\\ candidate.dispatch_sequence > 0");
11292        pushln!(out, "       /\\ candidate.input_id # \"\"");
11293        pushln!(out, "       /\\ candidate.run_id # \"\"");
11294        pushln!(out, "       /\\ candidate.step_id # \"\"");
11295        pushln!(out, "       /\\ candidate.host_id # \"\"");
11296        pushln!(out, "       /\\ candidate.member_session_id # \"\"");
11297        for rows in ["pending", "committed", "resolved"] {
11298            pushln!(
11299                out,
11300                "       /\\ \\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)"
11301            );
11302        }
11303        pushln!(out, "       /\\ same_member_host_count < 256");
11304        // Placed completion/kickoff helpers. TLC treats canonical UUID lexical
11305        // shape as an abstract non-empty string property; Rust performs the
11306        // stricter parse-and-roundtrip check at the executable boundary.
11307        writeln!(
11308            out,
11309            "{}(candidate) ==",
11310            prefix("mob_machine_placed_completion_obligation_well_formed")
11311        )
11312        .expect("write to string");
11313        pushln!(out, "    /\\ candidate.agent_identity # \"\"");
11314        pushln!(out, "    /\\ candidate.host_id # \"\"");
11315        pushln!(out, "    /\\ candidate.host_binding_generation > 0");
11316        pushln!(out, "    /\\ candidate.member_session_id # \"\"");
11317        pushln!(out, "    /\\ candidate.dispatch_sequence > 0");
11318        pushln!(out, "    /\\ candidate.input_id # \"\"");
11319        writeln!(
11320            out,
11321            "{}(pending, resolved, candidate) ==",
11322            prefix("mob_machine_placed_completion_custody_admits")
11323        )
11324        .expect("write to string");
11325        pushln!(out, "    LET rows == pending \\cup resolved");
11326        pushln!(
11327            out,
11328            "        same_member_host == Cardinality({{ row \\in rows : /\\ row.agent_identity = candidate.agent_identity /\\ row.host_id = candidate.host_id }})"
11329        );
11330        pushln!(out, "    IN /\\ Cardinality(rows) < 4096");
11331        pushln!(
11332            out,
11333            "       /\\ \\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)"
11334        );
11335        pushln!(out, "       /\\ same_member_host < 256");
11336        writeln!(
11337            out,
11338            "{}(active_run, active_layer, active_members, layer_phases, layer_dispositions) ==",
11339            prefix("mob_machine_adaptive_lifecycle_drained")
11340        )
11341        .expect("write to string");
11342        pushln!(out, "    /\\ active_run = None");
11343        pushln!(out, "    /\\ DOMAIN active_layer = {{}}");
11344        pushln!(
11345            out,
11346            "    /\\ \\A run_id \\in DOMAIN active_members : active_members[run_id] = 0"
11347        );
11348        pushln!(out, "    /\\ \\A layer_id \\in DOMAIN layer_phases :");
11349        pushln!(
11350            out,
11351            "           \\/ layer_phases[layer_id] = \"Validating\""
11352        );
11353        pushln!(
11354            out,
11355            "           \\/ /\\ layer_id \\in DOMAIN layer_dispositions"
11356        );
11357        pushln!(
11358            out,
11359            "              /\\ layer_phases[layer_id] \\in {{\"Completed\", \"SetupFailed\", \"RunFailed\", \"ResultInvalid\", \"Canceled\"}}"
11360        );
11361        writeln!(
11362            out,
11363            "{}(adaptive_run_id, active_layer, active_members, layer_run, layer_phases, layer_dispositions) ==",
11364            prefix("mob_machine_adaptive_run_custody_drained")
11365        )
11366        .expect("write to string");
11367        pushln!(out, "    /\\ adaptive_run_id \\notin DOMAIN active_layer");
11368        pushln!(
11369            out,
11370            "    /\\ (IF adaptive_run_id \\in DOMAIN active_members THEN active_members[adaptive_run_id] ELSE 0) = 0"
11371        );
11372        pushln!(out, "    /\\ \\A layer_id \\in DOMAIN layer_run :");
11373        pushln!(out, "           \\/ layer_run[layer_id] # adaptive_run_id");
11374        pushln!(
11375            out,
11376            "           \\/ /\\ layer_id \\in DOMAIN layer_dispositions"
11377        );
11378        pushln!(out, "              /\\ layer_id \\in DOMAIN layer_phases");
11379        pushln!(
11380            out,
11381            "              /\\ layer_phases[layer_id] \\in {{\"Completed\", \"SetupFailed\", \"RunFailed\", \"ResultInvalid\", \"Canceled\"}}"
11382        );
11383        writeln!(
11384            out,
11385            "{}(started, callback_pending, failed, cancelled, kickoff_errors, identity, outcome_kind, outcome_error, closure_kind) ==",
11386            prefix("mob_machine_finalized_placed_kickoff_recovery_well_formed")
11387        )
11388        .expect("write to string");
11389        pushln!(
11390            out,
11391            "    /\\ Cardinality({{ kickoff_phase \\in {{\"Started\", \"CallbackPending\", \"Failed\", \"Cancelled\"}} :"
11392        );
11393        pushln!(
11394            out,
11395            "           CASE kickoff_phase = \"Started\" -> identity \\in started"
11396        );
11397        pushln!(
11398            out,
11399            "             [] kickoff_phase = \"CallbackPending\" -> identity \\in callback_pending"
11400        );
11401        pushln!(
11402            out,
11403            "             [] kickoff_phase = \"Failed\" -> identity \\in failed"
11404        );
11405        pushln!(
11406            out,
11407            "             [] OTHER -> identity \\in cancelled }}) = 1"
11408        );
11409        pushln!(
11410            out,
11411            "    /\\ CASE outcome_kind = \"Failed\" -> outcome_error # None"
11412        );
11413        pushln!(
11414            out,
11415            "          [] outcome_kind = \"RejectedNoEffect\" -> /\\ outcome_error # None /\\ outcome_error.value # \"\""
11416        );
11417        pushln!(out, "          [] OTHER -> outcome_error = None");
11418        pushln!(
11419            out,
11420            "    /\\ CASE closure_kind = \"Acknowledged\" -> /\\ outcome_kind # \"RejectedNoEffect\" /\\ outcome_kind # \"Disposed\""
11421        );
11422        pushln!(
11423            out,
11424            "          [] closure_kind = \"RejectedNoEffect\" -> outcome_kind = \"RejectedNoEffect\""
11425        );
11426        pushln!(
11427            out,
11428            "          [] OTHER -> outcome_kind # \"RejectedNoEffect\""
11429        );
11430        pushln!(
11431            out,
11432            "    /\\ CASE identity \\in cancelled -> identity \\notin DOMAIN kickoff_errors"
11433        );
11434        pushln!(
11435            out,
11436            "          [] identity \\in started -> /\\ outcome_kind = \"Started\" /\\ identity \\notin DOMAIN kickoff_errors"
11437        );
11438        pushln!(
11439            out,
11440            "          [] identity \\in callback_pending -> /\\ outcome_kind = \"CallbackPending\" /\\ identity \\notin DOMAIN kickoff_errors"
11441        );
11442        pushln!(
11443            out,
11444            "          [] OTHER -> /\\ outcome_kind \\in {{\"Failed\", \"RejectedNoEffect\"}} /\\ identity \\in DOMAIN kickoff_errors /\\ outcome_error = Some(kickoff_errors[identity])"
11445        );
11446        writeln!(
11447            out,
11448            "{}(candidate) ==",
11449            prefix("mob_machine_placed_kickoff_obligation_well_formed")
11450        )
11451        .expect("write to string");
11452        pushln!(out, "    /\\ candidate.agent_identity # \"\"");
11453        pushln!(out, "    /\\ candidate.host_id # \"\"");
11454        pushln!(out, "    /\\ candidate.host_binding_generation > 0");
11455        pushln!(out, "    /\\ candidate.member_session_id # \"\"");
11456        pushln!(out, "    /\\ candidate.input_id # \"\"");
11457        pushln!(out, "    /\\ candidate.objective_id # \"\"");
11458        writeln!(
11459            out,
11460            "{}(pending_kickoffs, resolved_kickoffs, retained_kickoffs, pending_turns, committed_turns, resolved_turns, pending_completions, resolved_completions, candidate) ==",
11461            prefix("mob_machine_placed_kickoff_correlation_available")
11462        )
11463        .expect("write to string");
11464        pushln!(
11465            out,
11466            "    /\\ \\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)"
11467        );
11468        pushln!(
11469            out,
11470            "    /\\ \\A identity \\in DOMAIN retained_kickoffs : retained_kickoffs[identity].agent_identity # candidate.agent_identity"
11471        );
11472        pushln!(
11473            out,
11474            "    /\\ \\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)"
11475        );
11476        pushln!(
11477            out,
11478            "    /\\ \\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)"
11479        );
11480        writeln!(
11481            out,
11482            "{}(pending, resolved, agent_identity) ==",
11483            prefix("mob_machine_placed_kickoff_custody_absent_for_identity")
11484        )
11485        .expect("write to string");
11486        pushln!(
11487            out,
11488            "    \\A row \\in pending \\cup resolved : row.agent_identity # agent_identity"
11489        );
11490        writeln!(
11491            out,
11492            "{}(pending, resolved, host_id) ==",
11493            prefix("mob_machine_placed_kickoff_custody_absent_for_host")
11494        )
11495        .expect("write to string");
11496        pushln!(
11497            out,
11498            "    \\A row \\in pending \\cup resolved : row.host_id # host_id"
11499        );
11500        writeln!(
11501            out,
11502            "{}(pending, resolved, retained, candidate) ==",
11503            prefix("mob_machine_remote_turn_input_id_available_to_kickoff")
11504        )
11505        .expect("write to string");
11506        pushln!(
11507            out,
11508            "    /\\ \\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)"
11509        );
11510        pushln!(
11511            out,
11512            "    /\\ \\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)"
11513        );
11514        // Retirement atomically prunes every local wiring edge incident to
11515        // the retiring identity. This mirrors the catalog-native Rust helper
11516        // and keeps cold replay from resurrecting topology to an absent member.
11517        writeln!(
11518            out,
11519            "{}(arg_wiring_edges, arg_agent_identity) ==",
11520            prefix("mob_machine_wiring_edges_without_identity")
11521        )
11522        .expect("write to string");
11523        pushln!(
11524            out,
11525            "    {{ edge \\in arg_wiring_edges : /\\ edge.a # arg_agent_identity /\\ edge.b # arg_agent_identity }}"
11526        );
11527        writeln!(
11528            out,
11529            "{}(arg_external_peer_edges, arg_agent_identity) ==",
11530            prefix("mob_machine_external_peer_edges_without_identity")
11531        )
11532        .expect("write to string");
11533        pushln!(
11534            out,
11535            "    {{ edge \\in arg_external_peer_edges : edge.local # arg_agent_identity }}"
11536        );
11537        writeln!(
11538            out,
11539            "{}(arg_external_peer_edges_by_key, arg_agent_identity) ==",
11540            prefix("mob_machine_external_peer_edges_by_key_without_identity")
11541        )
11542        .expect("write to string");
11543        pushln!(
11544            out,
11545            "    [key \\in {{ key \\in DOMAIN arg_external_peer_edges_by_key : key.local # arg_agent_identity }} |-> arg_external_peer_edges_by_key[key]]"
11546        );
11547        // The next sessions of the pending FreshSession rotations, which a
11548        // destroy's admission abandons. A SameSession rotation names its
11549        // member's own session, which the destroy's retirement of that member
11550        // disposes of. Mirror of the catalog-native Rust helper.
11551        writeln!(
11552            out,
11553            "{}(arg_member_rotation_session_ids, arg_member_rotation_targets) ==",
11554            prefix("mob_machine_fresh_rotation_sessions")
11555        )
11556        .expect("write to string");
11557        pushln!(
11558            out,
11559            "    [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]]"
11560        );
11561        // Row #351: reconcile-membership spawn/retire set helpers. The DSL
11562        // ReconcileMembership effect emits calls to these, but they had no TLA+
11563        // operator definitions, so TLC reported "Unknown operator" for
11564        // MobMachine (and any composition embedding it). Mirror of the Rust
11565        // helpers in `catalog::dsl::mob_machine`: spawn = desired identities not
11566        // yet bound to a runtime; retire = currently-bound identities that are
11567        // no longer desired, gated on `retire_stale` (empty set otherwise).
11568        // `identity_to_runtime` is the bound-identity function (DOMAIN = the
11569        // currently-bound identities); `desired` is the target identity set.
11570        // Both range over workers only: an identity entry (DOMAIN of
11571        // `identity_entry_origins`) is never spawned or retired by them, and
11572        // neither is a reserved name (`identity_entry_tombstones`, never
11573        // seated, is never spawned; `identity_entry_unreadable` is neither
11574        // spawned nor retired).
11575        writeln!(
11576            out,
11577            "{}(arg_identity_to_runtime, arg_identity_entry_origins, arg_identity_entry_tombstones, arg_identity_entry_unreadable, arg_desired) ==",
11578            prefix("mob_machine_members_to_spawn")
11579        )
11580        .expect("write to string");
11581        pushln!(
11582            out,
11583            "    {{ 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 }}"
11584        );
11585        writeln!(
11586            out,
11587            "{}(arg_identity_to_runtime, arg_identity_entry_origins, arg_identity_entry_unreadable, arg_desired, arg_retire_stale) ==",
11588            prefix("mob_machine_members_to_retire")
11589        )
11590        .expect("write to string");
11591        pushln!(out, "    IF arg_retire_stale");
11592        pushln!(
11593            out,
11594            "    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 }}"
11595        );
11596        pushln!(out, "    ELSE {{}}");
11597        // Placed-carrier cleanup is identity-exclusive and carries the exact
11598        // durable operation tuple. Both operators are native Rust helpers in
11599        // the catalog, so every standalone/composition TLA namespace must
11600        // define their semantic twins explicitly.
11601        writeln!(
11602            out,
11603            "{}(arg_obligations, arg_agent_identity) ==",
11604            prefix("mob_machine_placed_cleanup_absent_for_identity")
11605        )
11606        .expect("write to string");
11607        pushln!(
11608            out,
11609            "    \\A obligation \\in arg_obligations : obligation.agent_identity # arg_agent_identity"
11610        );
11611        writeln!(
11612            out,
11613            "{}(arg_agent_identity, arg_spawn_id, arg_generation, arg_fence_token, arg_provision_operation_id, arg_operation_owner_session_id, arg_expected_phase) ==",
11614            prefix("mob_machine_placed_cleanup_obligation")
11615        )
11616        .expect("write to string");
11617        pushln!(
11618            out,
11619            "    [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]"
11620        );
11621        // A placed carrier is live only at the exact currently bound host
11622        // generation. Keep every partial-map read behind a TLA IF so sampled
11623        // malformed/partial states evaluate to FALSE instead of indexing an
11624        // absent function key.
11625        writeln!(
11626            out,
11627            "{}(arg_member_placement, arg_current_binding_generations, arg_host_bind_phase, arg_host_binding_generations, arg_agent_identity) ==",
11628            prefix("mob_machine_placed_carrier_binding_active")
11629        )
11630        .expect("write to string");
11631        pushln!(
11632            out,
11633            "    IF arg_agent_identity \\notin DOMAIN arg_member_placement"
11634        );
11635        pushln!(out, "    THEN FALSE");
11636        pushln!(
11637            out,
11638            "    ELSE LET host == arg_member_placement[arg_agent_identity]"
11639        );
11640        pushln!(
11641            out,
11642            "         IN IF host \\notin DOMAIN arg_host_bind_phase"
11643        );
11644        pushln!(out, "            THEN FALSE");
11645        pushln!(
11646            out,
11647            "            ELSE IF arg_host_bind_phase[host] # \"Bound\""
11648        );
11649        pushln!(out, "                 THEN FALSE");
11650        pushln!(
11651            out,
11652            "                 ELSE IF arg_agent_identity \\notin DOMAIN arg_current_binding_generations"
11653        );
11654        pushln!(out, "                      THEN FALSE");
11655        pushln!(
11656            out,
11657            "                      ELSE LET generation == arg_current_binding_generations[arg_agent_identity]"
11658        );
11659        pushln!(out, "                           IN /\\ generation > 0");
11660        pushln!(
11661            out,
11662            "                              /\\ host \\in DOMAIN arg_host_binding_generations"
11663        );
11664        pushln!(
11665            out,
11666            "                              /\\ arg_host_binding_generations[host] = generation"
11667        );
11668        writeln!(
11669            out,
11670            "{}(arg_host_id, arg_binding_generation) ==",
11671            prefix("mob_machine_host_binding_generation_tombstone")
11672        )
11673        .expect("write to string");
11674        pushln!(
11675            out,
11676            "    [host_id |-> arg_host_id, binding_generation |-> arg_binding_generation]"
11677        );
11678        // Cleanup after a revoke is authorized only when the exact retained
11679        // carrier generation has a durable revocation tombstone and that host
11680        // is no longer Bound.
11681        writeln!(
11682            out,
11683            "{}(arg_member_placement, arg_current_binding_generations, arg_host_bind_phase, arg_confirmed_revocations, arg_agent_identity) ==",
11684            prefix("mob_machine_placed_carrier_binding_confirmed_revoked")
11685        )
11686        .expect("write to string");
11687        pushln!(
11688            out,
11689            "    IF arg_agent_identity \\notin DOMAIN arg_member_placement"
11690        );
11691        pushln!(out, "    THEN FALSE");
11692        pushln!(
11693            out,
11694            "    ELSE LET host == arg_member_placement[arg_agent_identity]"
11695        );
11696        pushln!(
11697            out,
11698            "         IN IF arg_agent_identity \\notin DOMAIN arg_current_binding_generations"
11699        );
11700        pushln!(out, "            THEN FALSE");
11701        pushln!(
11702            out,
11703            "            ELSE LET generation == arg_current_binding_generations[arg_agent_identity]"
11704        );
11705        pushln!(out, "                 IN /\\ generation > 0");
11706        pushln!(
11707            out,
11708            "                    /\\ (IF host \\in DOMAIN arg_host_bind_phase THEN arg_host_bind_phase[host] # \"Bound\" ELSE TRUE)"
11709        );
11710        pushln!(
11711            out,
11712            "                    /\\ [host_id |-> host, binding_generation |-> generation] \\in arg_confirmed_revocations"
11713        );
11714        // Mob-coordination temporal predicates (work-intent / resource-claim
11715        // expiry). The DSL emits calls to these guards but they had no TLA+
11716        // definitions, so TLC reported "Unknown operator" for MobMachine (and
11717        // for any composition embedding it). The expires-at argument is the
11718        // stored `Option<u64>` (`Some(ms)`/`None`) and `now_ms` is a raw value;
11719        // `e # None /\ e.value <= now_ms` short-circuits when there is no expiry.
11720        // Resource-claim status arrives as the raw status string.
11721        writeln!(
11722            out,
11723            "{}(expires_at_ms, now_ms) ==",
11724            prefix("mob_coordination_expired_at")
11725        )
11726        .expect("write to string");
11727        pushln!(out, "    /\\ expires_at_ms # None");
11728        pushln!(out, "    /\\ expires_at_ms.value <= now_ms");
11729        writeln!(
11730            out,
11731            "{}(expires_at_ms, now_ms) == ~{}(expires_at_ms, now_ms)",
11732            prefix("mob_coordination_work_intent_unexpired"),
11733            prefix("mob_coordination_expired_at")
11734        )
11735        .expect("write to string");
11736        writeln!(
11737            out,
11738            "{}(expires_at_ms, now_ms) == ~{}(expires_at_ms, now_ms)",
11739            prefix("mob_coordination_resource_claim_unexpired"),
11740            prefix("mob_coordination_expired_at")
11741        )
11742        .expect("write to string");
11743        writeln!(
11744            out,
11745            "{}(status, expires_at_ms, now_ms) ==",
11746            prefix("mob_coordination_resource_claim_active_at")
11747        )
11748        .expect("write to string");
11749        pushln!(out, "    /\\ status = \"Active\"");
11750        writeln!(
11751            out,
11752            "    /\\ ~{}(expires_at_ms, now_ms)",
11753            prefix("mob_coordination_expired_at")
11754        )
11755        .expect("write to string");
11756        writeln!(
11757            out,
11758            "{}(status, expires_at_ms, now_ms) == ~{}(status, expires_at_ms, now_ms)",
11759            prefix("mob_coordination_resource_claim_inactive_at"),
11760            prefix("mob_coordination_resource_claim_active_at")
11761        )
11762        .expect("write to string");
11763        writeln!(
11764            out,
11765            "{}(edges_by_key, edge) ==",
11766            prefix("mob_machine_external_peer_edge_has_matching_key")
11767        )
11768        .expect("write to string");
11769        pushln!(
11770            out,
11771            "    LET key == [local |-> edge.local, name |-> edge.endpoint.name]"
11772        );
11773        pushln!(out, "    IN /\\ key \\in DOMAIN edges_by_key");
11774        pushln!(out, "       /\\ edges_by_key[key] = edge");
11775        writeln!(
11776            out,
11777            "{}(edge) == edge.local",
11778            prefix("mob_machine_external_peer_edge_local")
11779        )
11780        .expect("write to string");
11781        writeln!(
11782            out,
11783            "{}(edge) == edge.endpoint.peer_id",
11784            prefix("mob_machine_external_peer_edge_peer_id")
11785        )
11786        .expect("write to string");
11787        writeln!(
11788            out,
11789            "{}(key, edge) ==",
11790            prefix("mob_machine_external_peer_key_matches_edge")
11791        )
11792        .expect("write to string");
11793        pushln!(out, "    /\\ key.local = edge.local");
11794        pushln!(out, "    /\\ key.name = edge.endpoint.name");
11795        writeln!(
11796            out,
11797            "{}(key, agent_identity) == key.local = agent_identity",
11798            prefix("mob_machine_external_peer_key_matches_local")
11799        )
11800        .expect("write to string");
11801        writeln!(
11802            out,
11803            "{}(edges, agent_identity) ==",
11804            prefix("mob_machine_external_peer_identity_absent")
11805        )
11806        .expect("write to string");
11807        pushln!(
11808            out,
11809            "    \\A edge \\in edges : edge.endpoint.name /= agent_identity"
11810        );
11811        writeln!(
11812            out,
11813            "{}({}, agent_identity) ==",
11814            prefix("mob_machine_identity_has_session_binding"),
11815            local("member_session_bindings")
11816        )
11817        .expect("write to string");
11818        pushln!(
11819            out,
11820            "    /\\ agent_identity \\in DOMAIN {}",
11821            local("member_session_bindings")
11822        );
11823        pushln!(
11824            out,
11825            "    /\\ {}[agent_identity] /= \"\"",
11826            local("member_session_bindings")
11827        );
11828        writeln!(
11829            out,
11830            "{}({}, {}, {}, expected_runtime_ids) ==",
11831            prefix("mob_machine_session_bound_live_runtime_ids_match"),
11832            local("identity_to_runtime"),
11833            local("member_session_bindings"),
11834            local("live_runtime_ids")
11835        )
11836        .expect("write to string");
11837        pushln!(
11838            out,
11839            "    LET eligible_ids == {{ candidate \\in DOMAIN {} : {}[candidate] /= \"\" /\\ candidate \\in DOMAIN {} /\\ {}[candidate] \\in {} }}",
11840            local("member_session_bindings"),
11841            local("member_session_bindings"),
11842            local("identity_to_runtime"),
11843            local("identity_to_runtime"),
11844            local("live_runtime_ids")
11845        );
11846        pushln!(
11847            out,
11848            "    IN expected_runtime_ids = {{ {}[id] : id \\in eligible_ids }}",
11849            local("identity_to_runtime")
11850        );
11851        writeln!(
11852            out,
11853            "{}(endpoint) == endpoint.peer_id",
11854            prefix("mob_machine_member_peer_endpoint_peer_id")
11855        )
11856        .expect("write to string");
11857        writeln!(
11858            out,
11859            "{}(host_id, peer_id) == host_id = peer_id",
11860            prefix("mob_machine_host_id_matches_peer_id")
11861        )
11862        .expect("write to string");
11863        writeln!(
11864            out,
11865            "{}(current_endpoints, prior_endpoints, agent_identity, candidate_endpoint) ==",
11866            prefix("mob_machine_member_peer_id_available_for_identity")
11867        )
11868        .expect("write to string");
11869        pushln!(
11870            out,
11871            "    /\\ \\A other_identity \\in DOMAIN current_endpoints : other_identity = agent_identity \\/ current_endpoints[other_identity].peer_id /= candidate_endpoint.peer_id"
11872        );
11873        pushln!(
11874            out,
11875            "    /\\ \\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"
11876        );
11877        writeln!(
11878            out,
11879            "{}(edges, agent_identity) ==",
11880            prefix("mob_machine_member_has_no_external_peer_edges")
11881        )
11882        .expect("write to string");
11883        pushln!(
11884            out,
11885            "    \\A edge \\in edges : edge.local /= agent_identity"
11886        );
11887        writeln!(
11888            out,
11889            "{}(all_prior_endpoints, agent_identity, current_endpoint, next_endpoint) ==",
11890            prefix("mob_machine_member_prior_peer_endpoints_after_migration")
11891        )
11892        .expect("write to string");
11893        pushln!(
11894            out,
11895            "    LET prior == IF agent_identity \\in DOMAIN all_prior_endpoints THEN all_prior_endpoints[agent_identity] ELSE {{}}"
11896        );
11897        pushln!(
11898            out,
11899            "        retained == {{ endpoint \\in (prior \\cup {{current_endpoint}}) : endpoint.peer_id /= next_endpoint.peer_id }}"
11900        );
11901        pushln!(out, "    IN IF retained = {{}}");
11902        pushln!(
11903            out,
11904            "       THEN [id \\in (DOMAIN all_prior_endpoints \\ {{agent_identity}}) |-> all_prior_endpoints[id]]"
11905        );
11906        pushln!(
11907            out,
11908            "       ELSE [id \\in (DOMAIN all_prior_endpoints \\cup {{agent_identity}}) |-> IF id = agent_identity THEN retained ELSE all_prior_endpoints[id]]"
11909        );
11910        writeln!(
11911            out,
11912            "{}(endpoint_identity, migrated_identity, retained_peer_endpoint, current_peer_ids) ==",
11913            prefix("mob_machine_member_endpoint_migration_cleanup_peer_id")
11914        )
11915        .expect("write to string");
11916        pushln!(
11917            out,
11918            "    IF endpoint_identity = migrated_identity THEN retained_peer_endpoint.peer_id ELSE current_peer_ids[endpoint_identity]"
11919        );
11920        writeln!(
11921            out,
11922            "{}(edge) == edge.a",
11923            prefix("mob_machine_wiring_edge_a")
11924        )
11925        .expect("write to string");
11926        writeln!(
11927            out,
11928            "{}(edge) == edge.b",
11929            prefix("mob_machine_wiring_edge_b")
11930        )
11931        .expect("write to string");
11932        writeln!(
11933            out,
11934            "{}(edge, agent_identity) == edge.a = agent_identity \\/ edge.b = agent_identity",
11935            prefix("mob_machine_wiring_edge_contains_identity")
11936        )
11937        .expect("write to string");
11938        writeln!(
11939            out,
11940            "{}({}, {}, agent_identity) ==",
11941            prefix("mob_machine_member_peer_overlay_complete"),
11942            local("wiring_edges"),
11943            local("member_peer_endpoints")
11944        )
11945        .expect("write to string");
11946        pushln!(
11947            out,
11948            "    \\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",
11949            local("wiring_edges"),
11950            local("member_peer_endpoints"),
11951            local("member_peer_endpoints")
11952        );
11953        writeln!(
11954            out,
11955            "{}({}, {}, {}, agent_identity) ==",
11956            prefix("mob_machine_member_peer_overlay"),
11957            local("wiring_edges"),
11958            local("member_peer_endpoints"),
11959            local("external_peer_edges")
11960        )
11961        .expect("write to string");
11962        pushln!(
11963            out,
11964            "    LET outgoing_edges == {{ edge \\in {} : edge.a = agent_identity /\\ edge.b \\in DOMAIN {} }}",
11965            local("wiring_edges"),
11966            local("member_peer_endpoints")
11967        );
11968        pushln!(
11969            out,
11970            "        incoming_edges == {{ edge \\in {} : edge.b = agent_identity /\\ edge.a \\in DOMAIN {} }}",
11971            local("wiring_edges"),
11972            local("member_peer_endpoints")
11973        );
11974        pushln!(
11975            out,
11976            "        local_external_edges == {{ edge \\in {} : edge.local = agent_identity }}",
11977            local("external_peer_edges")
11978        );
11979        pushln!(
11980            out,
11981            "    IN {{ {}[edge.b] : edge \\in outgoing_edges }}",
11982            local("member_peer_endpoints")
11983        );
11984        pushln!(
11985            out,
11986            "       \\cup {{ {}[edge.a] : edge \\in incoming_edges }}",
11987            local("member_peer_endpoints")
11988        );
11989        pushln!(
11990            out,
11991            "       \\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 }}"
11992        );
11993        writeln!(
11994            out,
11995            "{}({}, a_identity, b_identity) == \\E edge \\in {}: (edge.a = a_identity /\\ edge.b = b_identity) \\/ (edge.a = b_identity /\\ edge.b = a_identity)",
11996            prefix("mob_machine_wiring_contains_pair"),
11997            local("wiring_edges"),
11998            local("wiring_edges")
11999        )
12000        .expect("write to string");
12001        writeln!(
12002            out,
12003            "{}({}, {}, agent_identity, excluded_identity) ==",
12004            prefix("mob_machine_member_peer_overlay_without_identity_complete"),
12005            local("wiring_edges"),
12006            local("member_peer_endpoints")
12007        )
12008        .expect("write to string");
12009        pushln!(
12010            out,
12011            "    \\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",
12012            local("wiring_edges"),
12013            local("member_peer_endpoints"),
12014            local("member_peer_endpoints")
12015        );
12016        writeln!(
12017            out,
12018            "{}({}, {}, {}, agent_identity, excluded_identity) ==",
12019            prefix("mob_machine_member_peer_overlay_without_identity"),
12020            local("wiring_edges"),
12021            local("member_peer_endpoints"),
12022            local("external_peer_edges")
12023        )
12024        .expect("write to string");
12025        pushln!(
12026            out,
12027            "    LET outgoing_edges == {{ edge \\in {} : edge.a = agent_identity /\\ edge.b # excluded_identity /\\ edge.b \\in DOMAIN {} }}",
12028            local("wiring_edges"),
12029            local("member_peer_endpoints")
12030        );
12031        pushln!(
12032            out,
12033            "        incoming_edges == {{ edge \\in {} : edge.b = agent_identity /\\ edge.a # excluded_identity /\\ edge.a \\in DOMAIN {} }}",
12034            local("wiring_edges"),
12035            local("member_peer_endpoints")
12036        );
12037        pushln!(
12038            out,
12039            "        local_external_edges == {{ edge \\in {} : edge.local = agent_identity }}",
12040            local("external_peer_edges")
12041        );
12042        pushln!(
12043            out,
12044            "    IN {{ {}[edge.b] : edge \\in outgoing_edges }}",
12045            local("member_peer_endpoints")
12046        );
12047        pushln!(
12048            out,
12049            "       \\cup {{ {}[edge.a] : edge \\in incoming_edges }}",
12050            local("member_peer_endpoints")
12051        );
12052        pushln!(
12053            out,
12054            "       \\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 }}"
12055        );
12056        writeln!(
12057            out,
12058            "{}({}, {}, {}, agent_identity, excluded_identity) ==",
12059            prefix("mob_machine_member_peer_overlay_without_identity_peer_ids_unique"),
12060            local("wiring_edges"),
12061            local("member_peer_endpoints"),
12062            local("external_peer_edges")
12063        )
12064        .expect("write to string");
12065        writeln!(
12066            out,
12067            "    LET overlay == {}({}, {}, {}, agent_identity, excluded_identity) IN Cardinality(overlay) = Cardinality({{endpoint.peer_id : endpoint \\in overlay}})",
12068            prefix("mob_machine_member_peer_overlay_without_identity"),
12069            local("wiring_edges"),
12070            local("member_peer_endpoints"),
12071            local("external_peer_edges")
12072        )
12073        .expect("write to string");
12074        writeln!(
12075            out,
12076            "{}({}, {}, {}, agent_identity) ==",
12077            prefix("mob_machine_member_peer_overlay_peer_ids_unique"),
12078            local("wiring_edges"),
12079            local("member_peer_endpoints"),
12080            local("external_peer_edges")
12081        )
12082        .expect("write to string");
12083        writeln!(
12084            out,
12085            "    LET overlay == {}({}, {}, {}, agent_identity) IN Cardinality(overlay) = Cardinality({{endpoint.peer_id : endpoint \\in overlay}})",
12086            prefix("mob_machine_member_peer_overlay"),
12087            local("wiring_edges"),
12088            local("member_peer_endpoints"),
12089            local("external_peer_edges")
12090        )
12091        .expect("write to string");
12092        writeln!(
12093            out,
12094            "{}(edge, a_identity, b_identity) ==",
12095            prefix("mob_machine_wiring_edge_matches_members")
12096        )
12097        .expect("write to string");
12098        pushln!(out, "    /\\ edge.a = a_identity");
12099        pushln!(out, "    /\\ edge.b = b_identity");
12100        writeln!(
12101            out,
12102            "{}(all_statuses, run_id, step_id, status) ==",
12103            prefix("mob_machine_run_step_status_after_set")
12104        )
12105        .expect("write to string");
12106        pushln!(
12107            out,
12108            "    LET current == IF run_id \\in DOMAIN all_statuses THEN all_statuses[run_id] ELSE [x \\in {{}} |-> None]"
12109        );
12110        pushln!(
12111            out,
12112            "    IN MapSet(all_statuses, run_id, MapSet(current, step_id, Some(status)))"
12113        );
12114        writeln!(
12115            out,
12116            "{}(all_statuses, run_id) ==",
12117            prefix("mob_machine_run_step_status_after_cancel_unfinished")
12118        )
12119        .expect("write to string");
12120        pushln!(
12121            out,
12122            "    LET current == IF run_id \\in DOMAIN all_statuses THEN all_statuses[run_id] ELSE [x \\in {{}} |-> None]"
12123        );
12124        pushln!(
12125            out,
12126            "        folded == [step_id \\in DOMAIN current |-> IF current[step_id] = None \\/ current[step_id] = Some(\"Dispatched\") THEN Some(\"Canceled\") ELSE current[step_id]]"
12127        );
12128        pushln!(out, "    IN MapSet(all_statuses, run_id, folded)");
12129        writeln!(
12130            out,
12131            "{}(all_values, run_id, step_id, value) ==",
12132            prefix("mob_machine_run_step_bool_after_set")
12133        )
12134        .expect("write to string");
12135        pushln!(
12136            out,
12137            "    LET current == IF run_id \\in DOMAIN all_values THEN all_values[run_id] ELSE [x \\in {{}} |-> FALSE]"
12138        );
12139        pushln!(
12140            out,
12141            "    IN MapSet(all_values, run_id, MapSet(current, step_id, value))"
12142        );
12143        writeln!(
12144            out,
12145            "{}(all_results, run_id, step_id, result) ==",
12146            prefix("mob_machine_run_step_condition_result_after_set")
12147        )
12148        .expect("write to string");
12149        pushln!(
12150            out,
12151            "    LET current == IF run_id \\in DOMAIN all_results THEN all_results[run_id] ELSE [x \\in {{}} |-> None]"
12152        );
12153        pushln!(
12154            out,
12155            "    IN MapSet(all_results, run_id, MapSet(current, step_id, Some(result)))"
12156        );
12157        writeln!(
12158            out,
12159            "{}(all_counts, run_id, step_id, value) ==",
12160            prefix("mob_machine_run_step_u64_after_set")
12161        )
12162        .expect("write to string");
12163        pushln!(
12164            out,
12165            "    LET current == IF run_id \\in DOMAIN all_counts THEN all_counts[run_id] ELSE [x \\in {{}} |-> 0]"
12166        );
12167        pushln!(
12168            out,
12169            "    IN MapSet(all_counts, run_id, MapSet(current, step_id, value))"
12170        );
12171        writeln!(
12172            out,
12173            "{}(all_counts, run_id, step_id, delta) ==",
12174            prefix("mob_machine_run_step_u64_after_increment")
12175        )
12176        .expect("write to string");
12177        pushln!(
12178            out,
12179            "    LET current == IF run_id \\in DOMAIN all_counts THEN all_counts[run_id] ELSE [x \\in {{}} |-> 0]"
12180        );
12181        pushln!(
12182            out,
12183            "        current_value == IF step_id \\in DOMAIN current THEN current[step_id] ELSE 0"
12184        );
12185        pushln!(
12186            out,
12187            "    IN MapSet(all_counts, run_id, MapSet(current, step_id, current_value + delta))"
12188        );
12189        writeln!(
12190            out,
12191            "{}(all_counts, run_id, retry_key, delta) ==",
12192            prefix("mob_machine_run_retry_count_after_increment")
12193        )
12194        .expect("write to string");
12195        pushln!(
12196            out,
12197            "    LET current == IF run_id \\in DOMAIN all_counts THEN all_counts[run_id] ELSE [x \\in {{}} |-> 0]"
12198        );
12199        pushln!(
12200            out,
12201            "        current_value == IF retry_key \\in DOMAIN current THEN current[retry_key] ELSE 0"
12202        );
12203        pushln!(
12204            out,
12205            "    IN MapSet(all_counts, run_id, MapSet(current, retry_key, current_value + delta))"
12206        );
12207        writeln!(
12208            out,
12209            "{}(all_values, frame_id, node_id, value) ==",
12210            prefix("mob_machine_frame_node_bool_after_set")
12211        )
12212        .expect("write to string");
12213        pushln!(
12214            out,
12215            "    LET current == IF frame_id \\in DOMAIN all_values THEN all_values[frame_id] ELSE [x \\in {{}} |-> FALSE]"
12216        );
12217        pushln!(
12218            out,
12219            "    IN MapSet(all_values, frame_id, MapSet(current, node_id, value))"
12220        );
12221        writeln!(
12222            out,
12223            "{}(status) == status \\in {{\"Completed\", \"Failed\", \"Skipped\", \"Canceled\"}}",
12224            prefix("mob_machine_node_terminal")
12225        )
12226        .expect("write to string");
12227        writeln!(
12228            out,
12229            "{}(status) ==",
12230            prefix("mob_machine_step_status_from_frame_node_status")
12231        )
12232        .expect("write to string");
12233        pushln!(out, "    IF status = \"Completed\" THEN \"Completed\"");
12234        pushln!(out, "    ELSE IF status = \"Skipped\" THEN \"Skipped\"");
12235        pushln!(out, "    ELSE IF status = \"Failed\" THEN \"Failed\"");
12236        pushln!(out, "    ELSE IF status = \"Canceled\" THEN \"Canceled\"");
12237        pushln!(out, "    ELSE \"Dispatched\"");
12238        writeln!(
12239            out,
12240            "{}(all_statuses, frame_branches, ordered_nodes_by_frame, frame_id, node_id) ==",
12241            prefix("mob_machine_frame_node_status_after_admit")
12242        )
12243        .expect("write to string");
12244        pushln!(
12245            out,
12246            "    LET current == IF frame_id \\in DOMAIN all_statuses THEN all_statuses[frame_id] ELSE [x \\in {{}} |-> None]"
12247        );
12248        pushln!(
12249            out,
12250            "        branches == IF frame_id \\in DOMAIN frame_branches THEN frame_branches[frame_id] ELSE [x \\in {{}} |-> None]"
12251        );
12252        pushln!(
12253            out,
12254            "        admitted_branch == IF node_id \\in DOMAIN branches THEN branches[node_id] ELSE None"
12255        );
12256        pushln!(
12257            out,
12258            "        after_branch_reservation == [candidate \\in DOMAIN current |->"
12259        );
12260        pushln!(out, "            IF admitted_branch # None");
12261        pushln!(out, "                /\\ candidate # node_id");
12262        pushln!(out, "                /\\ candidate \\in DOMAIN branches");
12263        pushln!(
12264            out,
12265            "                /\\ branches[candidate] = admitted_branch"
12266        );
12267        pushln!(out, "                /\\ current[candidate] = \"Ready\"");
12268        pushln!(out, "            THEN \"Pending\" ELSE current[candidate]]");
12269        pushln!(
12270            out,
12271            "        after_admit == MapSet(after_branch_reservation, node_id, \"Running\")"
12272        );
12273        pushln!(out, "    IN MapSet(all_statuses, frame_id, after_admit)");
12274        writeln!(
12275            out,
12276            "{}(all_ready_queues, all_statuses, ordered_nodes_by_frame, frame_id) ==",
12277            prefix("mob_machine_frame_ready_queue_after_terminal")
12278        )
12279        .expect("write to string");
12280        pushln!(
12281            out,
12282            "    LET statuses == IF frame_id \\in DOMAIN all_statuses THEN all_statuses[frame_id] ELSE [x \\in {{}} |-> None]"
12283        );
12284        pushln!(
12285            out,
12286            "        ordered == IF frame_id \\in DOMAIN ordered_nodes_by_frame THEN ordered_nodes_by_frame[frame_id] ELSE <<>>"
12287        );
12288        pushln!(
12289            out,
12290            "    IN MapSet(all_ready_queues, frame_id, SelectSeq(ordered, LAMBDA candidate: candidate \\in DOMAIN statuses /\\ statuses[candidate] = \"Ready\"))"
12291        );
12292        writeln!(
12293            out,
12294            "{}(all_ready_queues, all_statuses, ordered_nodes_by_frame, frame_id) ==",
12295            prefix("mob_machine_frame_ready_queue_after_admit")
12296        )
12297        .expect("write to string");
12298        writeln!(
12299            out,
12300            "    {}(all_ready_queues, all_statuses, ordered_nodes_by_frame, frame_id)",
12301            prefix("mob_machine_frame_ready_queue_after_terminal")
12302        )
12303        .expect("write to string");
12304        writeln!(
12305            out,
12306            "{}(current, branches, node_id, terminal_status) ==",
12307            prefix("mob_machine_frame_node_status_after_terminal_branch")
12308        )
12309        .expect("write to string");
12310        pushln!(
12311            out,
12312            "    LET after_terminal == MapSet(current, node_id, terminal_status)"
12313        );
12314        pushln!(out, "    IN [candidate \\in DOMAIN after_terminal |->");
12315        pushln!(
12316            out,
12317            "        IF terminal_status = \"Completed\" /\\ candidate # node_id"
12318        );
12319        pushln!(
12320            out,
12321            "            /\\ candidate \\in DOMAIN branches /\\ node_id \\in DOMAIN branches"
12322        );
12323        pushln!(out, "            /\\ branches[node_id] # None");
12324        pushln!(
12325            out,
12326            "            /\\ branches[candidate] = branches[node_id]"
12327        );
12328        writeln!(
12329            out,
12330            "            /\\ ~{}(after_terminal[candidate])",
12331            prefix("mob_machine_node_terminal")
12332        )
12333        .expect("write to string");
12334        pushln!(
12335            out,
12336            "            /\\ after_terminal[candidate] # \"Running\""
12337        );
12338        pushln!(
12339            out,
12340            "        THEN \"Skipped\" ELSE after_terminal[candidate]]"
12341        );
12342        writeln!(
12343            out,
12344            "{}(after_branch, dependencies, dependency_modes) ==",
12345            prefix("mob_machine_frame_node_status_after_terminal_dependencies")
12346        )
12347        .expect("write to string");
12348        pushln!(out, "    [candidate \\in DOMAIN after_branch |->");
12349        pushln!(
12350            out,
12351            "        IF after_branch[candidate] # \"Pending\" THEN after_branch[candidate]"
12352        );
12353        pushln!(
12354            out,
12355            "        ELSE LET deps == IF candidate \\in DOMAIN dependencies THEN dependencies[candidate] ELSE <<>>"
12356        );
12357        pushln!(
12358            out,
12359            "                 mode == IF candidate \\in DOMAIN dependency_modes THEN dependency_modes[candidate] ELSE \"All\""
12360        );
12361        pushln!(out, "                 failed == Len(deps) # 0");
12362        pushln!(
12363            out,
12364            "                     /\\ ((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\"}})"
12365        );
12366        pushln!(
12367            out,
12368            "                         \\/ (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\"}}))"
12369        );
12370        pushln!(out, "                 satisfied == Len(deps) = 0");
12371        pushln!(
12372            out,
12373            "                     \\/ (mode = \"All\" /\\ \\A dep_index \\in DOMAIN deps: LET dep == deps[dep_index] IN dep \\in DOMAIN after_branch /\\ after_branch[dep] = \"Completed\")"
12374        );
12375        pushln!(
12376            out,
12377            "                     \\/ (mode = \"Any\" /\\ \\E dep_index \\in DOMAIN deps: LET dep == deps[dep_index] IN dep \\in DOMAIN after_branch /\\ after_branch[dep] = \"Completed\")"
12378        );
12379        pushln!(
12380            out,
12381            "             IN IF failed THEN \"Skipped\" ELSE IF satisfied THEN \"Ready\" ELSE after_branch[candidate]]"
12382        );
12383        writeln!(
12384            out,
12385            "{}(all_statuses, frame_branches, ordered_nodes_by_frame, dependencies_by_frame, dependency_modes_by_frame, frame_id, node_id, terminal_status) ==",
12386            prefix("mob_machine_frame_node_status_after_terminal")
12387        )
12388        .expect("write to string");
12389        pushln!(
12390            out,
12391            "    LET current == IF frame_id \\in DOMAIN all_statuses THEN all_statuses[frame_id] ELSE [x \\in {{}} |-> None]"
12392        );
12393        pushln!(
12394            out,
12395            "        branches == IF frame_id \\in DOMAIN frame_branches THEN frame_branches[frame_id] ELSE [x \\in {{}} |-> None]"
12396        );
12397        pushln!(
12398            out,
12399            "        dependencies == IF frame_id \\in DOMAIN dependencies_by_frame THEN dependencies_by_frame[frame_id] ELSE [x \\in {{}} |-> <<>>]"
12400        );
12401        pushln!(
12402            out,
12403            "        dependency_modes == IF frame_id \\in DOMAIN dependency_modes_by_frame THEN dependency_modes_by_frame[frame_id] ELSE [x \\in {{}} |-> \"All\"]"
12404        );
12405        writeln!(
12406            out,
12407            "        after_branch == {}(current, branches, node_id, terminal_status)",
12408            prefix("mob_machine_frame_node_status_after_terminal_branch")
12409        )
12410        .expect("write to string");
12411        writeln!(
12412            out,
12413            "        after_dependencies == {}(after_branch, dependencies, dependency_modes)",
12414            prefix("mob_machine_frame_node_status_after_terminal_dependencies")
12415        )
12416        .expect("write to string");
12417        pushln!(
12418            out,
12419            "    IN MapSet(all_statuses, frame_id, after_dependencies)"
12420        );
12421        // Operator instructions: the machine's records reuse the session
12422        // document's slot-set natives (one slot set, and the body bytes of
12423        // the Active slots).
12424        self.render_session_document_native_helpers(out);
12425    }
12426
12427    fn render_transition(&mut self, out: &mut String, transition: &TransitionSchema) {
12428        let binding_types = self.binding_type_map(transition);
12429        let binding_env = transition
12430            .on
12431            .bindings()
12432            .iter()
12433            .map(|binding| {
12434                (
12435                    binding.as_str().to_owned(),
12436                    self.local_binding_name(binding.as_str()),
12437                )
12438            })
12439            .collect::<BTreeMap<String, _>>();
12440        let params = transition
12441            .on
12442            .bindings()
12443            .iter()
12444            .map(|binding| {
12445                binding_env
12446                    .get(binding.as_str())
12447                    .cloned()
12448                    .unwrap_or_else(|| binding.as_str().to_owned())
12449            })
12450            .collect::<Vec<_>>()
12451            .join(", ");
12452        if params.is_empty() {
12453            writeln!(out, "{} ==", transition.name);
12454        } else {
12455            pushln!(out, "{}({}) ==", transition.name, params);
12456        }
12457
12458        let from_guard = if transition.from.len() == 1 {
12459            format!("phase = {}", tla_string(&transition.from[0]))
12460        } else {
12461            transition
12462                .from
12463                .iter()
12464                .map(|phase| format!("phase = {}", tla_string(phase)))
12465                .collect::<Vec<_>>()
12466                .join(" \\/ ")
12467        };
12468        pushln!(out, "    /\\ {}", from_guard);
12469
12470        let mut env = self
12471            .schema
12472            .state
12473            .fields
12474            .iter()
12475            .map(|field| {
12476                (
12477                    field.name.as_str().to_owned(),
12478                    field.name.as_str().to_owned(),
12479                )
12480            })
12481            .collect::<BTreeMap<String, _>>();
12482
12483        for guard in &transition.guards {
12484            writeln!(
12485                out,
12486                "    /\\ {}",
12487                self.render_guard(guard, &env, &binding_env, &binding_types)
12488            )
12489            .expect("write to string");
12490        }
12491
12492        env = self.compile_updates(
12493            transition.name.as_str(),
12494            &env,
12495            &binding_env,
12496            &binding_types,
12497            &transition.updates,
12498        );
12499
12500        pushln!(out, "    /\\ phase' = {}", tla_string(&transition.to));
12501        pushln!(out, "    /\\ model_step_count' = model_step_count + 1");
12502        let touched = self
12503            .schema
12504            .state
12505            .fields
12506            .iter()
12507            .filter_map(|field| {
12508                let next = env.get(field.name.as_str())?;
12509                if next != field.name.as_str() {
12510                    Some((field.name.as_str(), next.as_str()))
12511                } else {
12512                    None
12513                }
12514            })
12515            .collect::<Vec<_>>();
12516
12517        for (field, expr) in &touched {
12518            pushln!(out, "    /\\ {}' = {}", field, expr);
12519        }
12520
12521        let unchanged = self
12522            .schema
12523            .state
12524            .fields
12525            .iter()
12526            .filter(|field| !touched.iter().any(|(name, _)| *name == field.name.as_str()))
12527            .map(|field| field.name.as_str().to_owned())
12528            .collect::<Vec<_>>();
12529        if !unchanged.is_empty() {
12530            // Machine frames are never chunked: the split policy is a
12531            // composition-scale TLC mitigation, and applying it here would
12532            // change the emitted formula for wide machines.
12533            let name = self
12534                .unchanged_frames
12535                .intern(unchanged_frame_body(&unchanged, None));
12536            pushln!(out, "    /\\ {name}");
12537        }
12538    }
12539
12540    fn render_guard(
12541        &self,
12542        guard: &Guard,
12543        env: &BTreeMap<String, String>,
12544        binding_env: &BTreeMap<String, String>,
12545        binding_types: &BTreeMap<String, TypeRef>,
12546    ) -> String {
12547        self.render_expr_with_types(&guard.expr, env, binding_env, binding_types)
12548    }
12549
12550    fn binding_type_map(&self, transition: &TransitionSchema) -> BTreeMap<String, TypeRef> {
12551        let mut map = BTreeMap::new();
12552        if let Some(variant) = transition_trigger_variant(self.schema, transition) {
12553            for binding in transition.on.bindings() {
12554                if let Some(field) = variant.fields.iter().find(|field| field.name == *binding) {
12555                    map.insert(binding.as_str().to_owned(), field.ty.clone());
12556                }
12557            }
12558        }
12559        map
12560    }
12561
12562    fn local_binding_name(&self, name: impl AsRef<str>) -> String {
12563        let name = name.as_ref();
12564        let candidate = tla_ident(name);
12565        if candidate == "phase"
12566            || self
12567                .schema
12568                .state
12569                .fields
12570                .iter()
12571                .any(|field| field.name.as_str() == name)
12572        {
12573            format!("arg_{candidate}")
12574        } else {
12575            candidate
12576        }
12577    }
12578
12579    fn binding_domain_for_type(&self, ty: &TypeRef) -> String {
12580        match ty {
12581            TypeRef::Bool => "BOOLEAN".into(),
12582            TypeRef::U32 | TypeRef::U64 => "0..2".into(),
12583            TypeRef::String => "StringValues".into(),
12584            TypeRef::Named(_)
12585            | TypeRef::Enum(_)
12586            | TypeRef::Seq(_)
12587            | TypeRef::Set(_)
12588            | TypeRef::Option(_)
12589            | TypeRef::Map(_, _) => domain_constant_name(ty),
12590        }
12591    }
12592
12593    /// Payload domain for one bound field of `input`: the declared input
12594    /// field domain if the schema has one, otherwise the type's default.
12595    fn binding_domain_for_binding(
12596        &self,
12597        input: Option<&str>,
12598        binding: &str,
12599        ty: &TypeRef,
12600    ) -> String {
12601        let declared = input.and_then(|input| {
12602            self.schema
12603                .input_field_domain(input, binding)
12604                .map(|domain| (input, domain))
12605        });
12606        match declared {
12607            Some((_, meerkat_machine_schema::InputFieldDomainKind::StateField(state_field))) => {
12608                format!("{{{}}}", state_field.as_str())
12609            }
12610            Some((_, meerkat_machine_schema::InputFieldDomainKind::AdditionalValues(values))) => {
12611                additional_values_domain(&self.binding_domain_for_type(ty), values)
12612            }
12613            // A model constant that each profile's config assigns: the CI
12614            // profile the declared values, the Deep profile those and `0..2`.
12615            Some((input, meerkat_machine_schema::InputFieldDomainKind::CiValues(_))) => {
12616                input_samples_constant_name(input, binding)
12617            }
12618            None => self.binding_domain_for_type(ty),
12619        }
12620    }
12621
12622    fn compile_updates(
12623        &mut self,
12624        transition_name: &str,
12625        env: &BTreeMap<String, String>,
12626        binding_env: &BTreeMap<String, String>,
12627        binding_types: &BTreeMap<String, TypeRef>,
12628        updates: &[Update],
12629    ) -> BTreeMap<String, String> {
12630        let mut current = env.clone();
12631        for update in updates {
12632            self.apply_update(
12633                transition_name,
12634                &mut current,
12635                binding_env,
12636                binding_types,
12637                update,
12638            );
12639        }
12640        current
12641    }
12642
12643    fn apply_update(
12644        &mut self,
12645        transition_name: &str,
12646        env: &mut BTreeMap<String, String>,
12647        binding_env: &BTreeMap<String, String>,
12648        binding_types: &BTreeMap<String, TypeRef>,
12649        update: &Update,
12650    ) {
12651        match update {
12652            Update::Assign { field, expr } => {
12653                let value = self.render_expr_with_types(expr, env, binding_env, binding_types);
12654                env.insert(field.as_str().to_owned(), value);
12655            }
12656            Update::Increment { field, amount } => {
12657                let current = env
12658                    .get(field.as_str())
12659                    .cloned()
12660                    .unwrap_or_else(|| field.as_str().to_owned());
12661                env.insert(field.as_str().to_owned(), format!("({current}) + {amount}"));
12662            }
12663            Update::Decrement { field, amount } => {
12664                let current = env
12665                    .get(field.as_str())
12666                    .cloned()
12667                    .unwrap_or_else(|| field.as_str().to_owned());
12668                env.insert(field.as_str().to_owned(), format!("({current}) - {amount}"));
12669            }
12670            Update::MapInsert { field, key, value } => {
12671                let current = env
12672                    .get(field.as_str())
12673                    .cloned()
12674                    .unwrap_or_else(|| field.as_str().to_owned());
12675                let key_expr = self.render_expr_with_types(key, env, binding_env, binding_types);
12676                let value_expr =
12677                    self.render_expr_with_types(value, env, binding_env, binding_types);
12678                env.insert(
12679                    field.as_str().to_owned(),
12680                    format!("MapSet({current}, {key_expr}, {value_expr})"),
12681                );
12682            }
12683            Update::MapRemove { field, key } => {
12684                let current = env
12685                    .get(field.as_str())
12686                    .cloned()
12687                    .unwrap_or_else(|| field.as_str().to_owned());
12688                let key_expr = self.render_expr_with_types(key, env, binding_env, binding_types);
12689                env.insert(
12690                    field.as_str().to_owned(),
12691                    format!("MapRemove({current}, {key_expr})"),
12692                );
12693            }
12694            Update::MapIncrement { field, key, amount } => {
12695                let current = env
12696                    .get(field.as_str())
12697                    .cloned()
12698                    .unwrap_or_else(|| field.as_str().to_owned());
12699                let key_expr = self.render_expr_with_types(key, env, binding_env, binding_types);
12700                env.insert(
12701                    field.as_str().to_owned(),
12702                    format!("MapIncrement({current}, {key_expr}, {amount})"),
12703                );
12704            }
12705            Update::MapDecrement { field, key, amount } => {
12706                let current = env
12707                    .get(field.as_str())
12708                    .cloned()
12709                    .unwrap_or_else(|| field.as_str().to_owned());
12710                let key_expr = self.render_expr_with_types(key, env, binding_env, binding_types);
12711                env.insert(
12712                    field.as_str().to_owned(),
12713                    format!("MapDecrement({current}, {key_expr}, {amount})"),
12714                );
12715            }
12716            Update::SetInsert { field, value } => {
12717                // The field's pending value may be an unparenthesized
12718                // conditional (`IF c THEN a ELSE b`); spliced bare as the left
12719                // operand, the ELSE branch would capture the set operator.
12720                let current = env
12721                    .get(field.as_str())
12722                    .map(|value| tla_delimited(value))
12723                    .unwrap_or_else(|| field.as_str().to_owned());
12724                let value_expr =
12725                    self.render_expr_with_types(value, env, binding_env, binding_types);
12726                env.insert(
12727                    field.as_str().to_owned(),
12728                    format!("({current} \\cup {{{value_expr}}})"),
12729                );
12730            }
12731            Update::SetRemove { field, value } => {
12732                // The field's pending value may be an unparenthesized
12733                // conditional (`IF c THEN a ELSE b`); spliced bare as the left
12734                // operand, the ELSE branch would capture the set operator.
12735                let current = env
12736                    .get(field.as_str())
12737                    .map(|value| tla_delimited(value))
12738                    .unwrap_or_else(|| field.as_str().to_owned());
12739                let value_expr =
12740                    self.render_expr_with_types(value, env, binding_env, binding_types);
12741                env.insert(
12742                    field.as_str().to_owned(),
12743                    format!("({current} \\ {{{value_expr}}})"),
12744                );
12745            }
12746            Update::SeqAppend { field, value } => {
12747                let current = env
12748                    .get(field.as_str())
12749                    .cloned()
12750                    .unwrap_or_else(|| field.as_str().to_owned());
12751                let value_expr =
12752                    self.render_expr_with_types(value, env, binding_env, binding_types);
12753                env.insert(
12754                    field.as_str().to_owned(),
12755                    format!("Append({current}, {value_expr})"),
12756                );
12757            }
12758            Update::SeqPrepend { field, values } => {
12759                let current = env
12760                    .get(field.as_str())
12761                    .cloned()
12762                    .unwrap_or_else(|| field.as_str().to_owned());
12763                let value_expr =
12764                    self.render_expr_with_types(values, env, binding_env, binding_types);
12765                env.insert(
12766                    field.as_str().to_owned(),
12767                    format!("({value_expr} \\o {current})"),
12768                );
12769            }
12770            Update::SeqPopFront { field } => {
12771                let current = env
12772                    .get(field.as_str())
12773                    .cloned()
12774                    .unwrap_or_else(|| field.as_str().to_owned());
12775                env.insert(field.as_str().to_owned(), format!("Tail({current})"));
12776            }
12777            Update::SeqRemoveValue { field, value } => {
12778                let current = env
12779                    .get(field.as_str())
12780                    .cloned()
12781                    .unwrap_or_else(|| field.as_str().to_owned());
12782                let value_expr =
12783                    self.render_expr_with_types(value, env, binding_env, binding_types);
12784                env.insert(
12785                    field.as_str().to_owned(),
12786                    format!("SeqRemove({current}, {value_expr})"),
12787                );
12788            }
12789            Update::SeqRemoveAll { field, values } => {
12790                let current = env
12791                    .get(field.as_str())
12792                    .cloned()
12793                    .unwrap_or_else(|| field.as_str().to_owned());
12794                let value_expr =
12795                    self.render_expr_with_types(values, env, binding_env, binding_types);
12796                env.insert(
12797                    field.as_str().to_owned(),
12798                    format!("SeqRemoveAll({current}, {value_expr})"),
12799                );
12800            }
12801            Update::Conditional {
12802                condition,
12803                then_updates,
12804                else_updates,
12805            } => {
12806                let base = env.clone();
12807                let mut then_env = base.clone();
12808                for update in then_updates {
12809                    self.apply_update(
12810                        transition_name,
12811                        &mut then_env,
12812                        binding_env,
12813                        binding_types,
12814                        update,
12815                    );
12816                }
12817                let mut else_env = base.clone();
12818                for update in else_updates {
12819                    self.apply_update(
12820                        transition_name,
12821                        &mut else_env,
12822                        binding_env,
12823                        binding_types,
12824                        update,
12825                    );
12826                }
12827                let condition_expr =
12828                    self.render_expr_with_types(condition, &base, binding_env, binding_types);
12829                let touched = union_touched_fields(&base, &then_env, &else_env);
12830                for field in touched {
12831                    let then_expr = then_env
12832                        .get(&field)
12833                        .cloned()
12834                        .unwrap_or_else(|| field.clone());
12835                    let else_expr = else_env
12836                        .get(&field)
12837                        .cloned()
12838                        .unwrap_or_else(|| field.clone());
12839                    env.insert(
12840                        field.clone(),
12841                        format!("IF {condition_expr} THEN {then_expr} ELSE {else_expr}"),
12842                    );
12843                }
12844            }
12845            Update::ForEach {
12846                binding,
12847                over,
12848                updates,
12849            } => {
12850                let helper_index = self.helper_counter;
12851                self.helper_counter += 1;
12852                let over_expr = self.render_expr_with_types(over, env, binding_env, binding_types);
12853                let touched = collect_update_fields(updates);
12854                // Every touched field's fold reads the other fields as they
12855                // were BEFORE the loop: the loop below writes each fold back
12856                // into `env` as it goes, so reading `env` there would hand a
12857                // later field the earlier field's post-loop value (all of its
12858                // iterations already applied), not the value an iteration
12859                // reads in the sequential kernel.
12860                let base_env = env.clone();
12861                let referenced_bindings = collect_update_bindings(updates)
12862                    .into_iter()
12863                    .filter(|item| item != binding)
12864                    .collect::<BTreeSet<_>>();
12865                let referenced_fields = collect_update_fields_exprs(updates)
12866                    .into_iter()
12867                    .filter(|field| {
12868                        touched.contains(field) || base_env.get(field.as_str()) != Some(field)
12869                    })
12870                    .collect::<BTreeSet<_>>();
12871
12872                for field in touched {
12873                    let current = base_env
12874                        .get(&field)
12875                        .cloned()
12876                        .unwrap_or_else(|| field.clone());
12877                    let helper_name = format!(
12878                        "{}_ForEach{}_{}",
12879                        tla_ident(transition_name),
12880                        helper_index,
12881                        tla_ident(&field)
12882                    );
12883                    let collection_kind = infer_collection_kind(over, self.schema, binding_types);
12884
12885                    let mut param_defs = Vec::new();
12886                    let mut call_args = vec![current.clone(), over_expr.clone()];
12887                    let mut helper_binding_env = binding_env.clone();
12888                    helper_binding_env.insert(binding.clone(), binding.clone());
12889                    let mut helper_field_env = self
12890                        .schema
12891                        .state
12892                        .fields
12893                        .iter()
12894                        .map(|item| (item.name.as_str().to_owned(), item.name.as_str().to_owned()))
12895                        .collect::<BTreeMap<String, _>>();
12896                    helper_field_env.insert(field.clone(), "acc".into());
12897
12898                    for outer_binding in &referenced_bindings {
12899                        let param = format!("outer_{}", tla_ident(outer_binding));
12900                        param_defs.push(param.clone());
12901                        call_args.push(
12902                            binding_env
12903                                .get(outer_binding)
12904                                .cloned()
12905                                .unwrap_or_else(|| outer_binding.clone()),
12906                        );
12907                        helper_binding_env.insert(outer_binding.clone(), param);
12908                    }
12909
12910                    for ref_field in &referenced_fields {
12911                        if *ref_field == field {
12912                            continue;
12913                        }
12914                        let current_expr = base_env
12915                            .get(ref_field)
12916                            .cloned()
12917                            .unwrap_or_else(|| ref_field.clone());
12918                        if current_expr != *ref_field {
12919                            let param = format!("captured_{}", tla_ident(ref_field));
12920                            param_defs.push(param.clone());
12921                            call_args.push(current_expr);
12922                            helper_field_env.insert(ref_field.clone(), param);
12923                        }
12924                    }
12925
12926                    let body_expr = self.compile_for_each_field_body(
12927                        &field,
12928                        &helper_field_env,
12929                        &helper_binding_env,
12930                        binding_types,
12931                        updates,
12932                    );
12933
12934                    let helper_def = match collection_kind {
12935                        CollectionKind::Sequence => render_sequence_foreach_helper(
12936                            &helper_name,
12937                            binding,
12938                            &param_defs,
12939                            &body_expr,
12940                        ),
12941                        CollectionKind::Set => render_set_foreach_helper(
12942                            &helper_name,
12943                            binding,
12944                            &param_defs,
12945                            &body_expr,
12946                        ),
12947                    };
12948                    self.helper_defs.push(helper_def);
12949                    env.insert(
12950                        field.clone(),
12951                        format!("{}({})", helper_name, call_args.join(", ")),
12952                    );
12953                }
12954            }
12955        }
12956    }
12957
12958    fn compile_for_each_field_body(
12959        &mut self,
12960        target_field: &str,
12961        env: &BTreeMap<String, String>,
12962        binding_env: &BTreeMap<String, String>,
12963        binding_types: &BTreeMap<String, TypeRef>,
12964        updates: &[Update],
12965    ) -> String {
12966        let mut current = env.clone();
12967        for update in updates {
12968            self.apply_update_for_target(
12969                target_field,
12970                &mut current,
12971                binding_env,
12972                binding_types,
12973                update,
12974            );
12975        }
12976        current
12977            .get(target_field)
12978            .cloned()
12979            .unwrap_or_else(|| target_field.to_owned())
12980    }
12981
12982    fn apply_update_for_target(
12983        &mut self,
12984        target_field: &str,
12985        env: &mut BTreeMap<String, String>,
12986        binding_env: &BTreeMap<String, String>,
12987        binding_types: &BTreeMap<String, TypeRef>,
12988        update: &Update,
12989    ) {
12990        match update {
12991            Update::Conditional {
12992                condition,
12993                then_updates,
12994                else_updates,
12995            } => {
12996                let base = env.clone();
12997                let mut then_env = base.clone();
12998                for update in then_updates {
12999                    self.apply_update_for_target(
13000                        target_field,
13001                        &mut then_env,
13002                        binding_env,
13003                        binding_types,
13004                        update,
13005                    );
13006                }
13007                let mut else_env = base.clone();
13008                for update in else_updates {
13009                    self.apply_update_for_target(
13010                        target_field,
13011                        &mut else_env,
13012                        binding_env,
13013                        binding_types,
13014                        update,
13015                    );
13016                }
13017                let base_expr = base
13018                    .get(target_field)
13019                    .cloned()
13020                    .unwrap_or_else(|| target_field.to_owned());
13021                let then_expr = then_env
13022                    .get(target_field)
13023                    .cloned()
13024                    .unwrap_or_else(|| base_expr.clone());
13025                let else_expr = else_env
13026                    .get(target_field)
13027                    .cloned()
13028                    .unwrap_or_else(|| base_expr.clone());
13029                if then_expr != base_expr || else_expr != base_expr {
13030                    let condition_expr =
13031                        self.render_expr_with_types(condition, &base, binding_env, binding_types);
13032                    env.insert(
13033                        target_field.to_owned(),
13034                        format!("IF {condition_expr} THEN {then_expr} ELSE {else_expr}"),
13035                    );
13036                }
13037            }
13038            Update::ForEach {
13039                binding,
13040                over,
13041                updates,
13042            } => {
13043                let helper_index = self.helper_counter;
13044                self.helper_counter += 1;
13045                let over_expr = self.render_expr_with_types(over, env, binding_env, binding_types);
13046                let helper_name = format!(
13047                    "{}_NestedForEach{}_{}",
13048                    tla_ident(target_field),
13049                    helper_index,
13050                    tla_ident(binding)
13051                );
13052                let collection_kind = infer_collection_kind(over, self.schema, binding_types);
13053                let mut nested_binding_env = binding_env.clone();
13054                nested_binding_env.insert(binding.clone(), binding.clone());
13055                let mut nested_env = env.clone();
13056                nested_env.insert(target_field.to_owned(), "acc".into());
13057                let body_expr = self.compile_for_each_field_body(
13058                    target_field,
13059                    &nested_env,
13060                    &nested_binding_env,
13061                    binding_types,
13062                    updates,
13063                );
13064                let helper_def = match collection_kind {
13065                    CollectionKind::Sequence => {
13066                        render_sequence_foreach_helper(&helper_name, binding, &[], &body_expr)
13067                    }
13068                    CollectionKind::Set => {
13069                        render_set_foreach_helper(&helper_name, binding, &[], &body_expr)
13070                    }
13071                };
13072                self.helper_defs.push(helper_def);
13073                let current = env
13074                    .get(target_field)
13075                    .cloned()
13076                    .unwrap_or_else(|| target_field.to_owned());
13077                env.insert(
13078                    target_field.to_owned(),
13079                    format!("{}({}, {})", helper_name, current, over_expr),
13080                );
13081            }
13082            _ => {
13083                let before = env
13084                    .get(target_field)
13085                    .cloned()
13086                    .unwrap_or_else(|| target_field.to_owned());
13087                self.apply_update(
13088                    &format!("Target{}", target_field),
13089                    env,
13090                    binding_env,
13091                    binding_types,
13092                    update,
13093                );
13094                let after = env
13095                    .get(target_field)
13096                    .cloned()
13097                    .unwrap_or_else(|| target_field.to_owned());
13098                if after == before {
13099                    env.insert(target_field.to_owned(), before);
13100                }
13101            }
13102        }
13103    }
13104
13105    fn render_expr(
13106        &self,
13107        expr: &Expr,
13108        env: &BTreeMap<String, String>,
13109        binding_env: &BTreeMap<String, String>,
13110    ) -> String {
13111        self.render_expr_with_types(expr, env, binding_env, &BTreeMap::new())
13112    }
13113
13114    fn scoped_helper_name(&self, helper: &str) -> String {
13115        match &self.helper_prefix {
13116            Some(prefix) => format!("{prefix}{}", tla_ident(helper)),
13117            None => helper.to_owned(),
13118        }
13119    }
13120
13121    fn render_expr_with_types(
13122        &self,
13123        expr: &Expr,
13124        env: &BTreeMap<String, String>,
13125        binding_env: &BTreeMap<String, String>,
13126        binding_types: &BTreeMap<String, TypeRef>,
13127    ) -> String {
13128        match expr {
13129            Expr::Bool(value) => {
13130                if *value {
13131                    "TRUE".into()
13132                } else {
13133                    "FALSE".into()
13134                }
13135            }
13136            Expr::U64(value) => value.to_string(),
13137            Expr::U64Max => TLA_RUST_U64_MAX_CONSTANT.to_owned(),
13138            Expr::String(value) => tla_string(value),
13139            Expr::NamedVariant { enum_name, variant } => render_named_variant_value(
13140                enum_name.as_str(),
13141                variant.as_str(),
13142                &self.named_bindings,
13143            ),
13144            Expr::FieldAccess { base, field } => format!(
13145                "{}.{}",
13146                self.render_expr_with_types(base, env, binding_env, binding_types),
13147                tla_ident(field.as_str())
13148            ),
13149            Expr::EnumVariantIs { value, variant, .. } => format!(
13150                "({}.tag = {})",
13151                self.render_expr_with_types(value, env, binding_env, binding_types),
13152                tla_string(variant.as_str())
13153            ),
13154            Expr::EnumStringSetPayload {
13155                value,
13156                variant,
13157                field,
13158                ..
13159            } => {
13160                let rendered = self.render_expr_with_types(value, env, binding_env, binding_types);
13161                let tag = tla_string(variant.as_str());
13162                let field = tla_ident(field.as_str());
13163                format!("(IF {rendered}.tag = {tag} THEN {rendered}.{field} ELSE {{}})")
13164            }
13165            Expr::EmptySet => "{}".into(),
13166            Expr::EmptyMap => "[x \\in {} |-> None]".into(),
13167            Expr::SeqLiteral(items) => format!(
13168                "<<{}>>",
13169                items
13170                    .iter()
13171                    .map(|item| self.render_expr_with_types(item, env, binding_env, binding_types))
13172                    .collect::<Vec<_>>()
13173                    .join(", ")
13174            ),
13175            Expr::CurrentPhase => self.phase_symbol.clone().unwrap_or_else(|| "phase".into()),
13176            Expr::Phase(value) => tla_string(value),
13177            // A field already assigned earlier in the same update block reads
13178            // its pending value, which may be an unparenthesized compound
13179            // (a conditional update renders `IF c THEN a ELSE b`). Spliced bare
13180            // into a larger expression, TLA+ precedence would capture the
13181            // surrounding operator: `IF c THEN a ELSE b = x` parses as
13182            // `IF c THEN a ELSE (b = x)`. Delimit every substituted value.
13183            Expr::Field(name) => match env.get(name.as_str()) {
13184                Some(value) if value != name.as_str() => tla_delimited(value),
13185                Some(value) => value.clone(),
13186                None => name.as_str().to_owned(),
13187            },
13188            Expr::Binding(name) => binding_env
13189                .get(name)
13190                .cloned()
13191                .unwrap_or_else(|| name.clone()),
13192            Expr::Variant(name) => tla_string(name),
13193            Expr::None => "None".into(),
13194            Expr::IfElse {
13195                condition,
13196                then_expr,
13197                else_expr,
13198            } => format!(
13199                "(IF {} THEN {} ELSE {})",
13200                self.render_expr_with_types(condition, env, binding_env, binding_types),
13201                self.render_expr_with_types(then_expr, env, binding_env, binding_types),
13202                self.render_expr_with_types(else_expr, env, binding_env, binding_types)
13203            ),
13204            Expr::Not(inner) => format!(
13205                "~({})",
13206                self.render_expr_with_types(inner, env, binding_env, binding_types)
13207            ),
13208            Expr::And(items) => join_exprs(
13209                &items
13210                    .iter()
13211                    .map(|item| self.render_expr_with_types(item, env, binding_env, binding_types))
13212                    .collect::<Vec<_>>(),
13213                " /\\ ",
13214            ),
13215            Expr::Or(items) => render_or_short_circuit(
13216                &items
13217                    .iter()
13218                    .map(|item| self.render_expr_with_types(item, env, binding_env, binding_types))
13219                    .collect::<Vec<_>>(),
13220            ),
13221            Expr::Eq(left, right) => format!(
13222                "({} = {})",
13223                self.render_expr_with_types(left, env, binding_env, binding_types),
13224                self.render_expr_with_types(right, env, binding_env, binding_types)
13225            ),
13226            Expr::Neq(left, right) => format!(
13227                "({} # {})",
13228                self.render_expr_with_types(left, env, binding_env, binding_types),
13229                self.render_expr_with_types(right, env, binding_env, binding_types)
13230            ),
13231            Expr::Add(left, right) => format!(
13232                "({} + {})",
13233                self.render_expr_with_types(left, env, binding_env, binding_types),
13234                self.render_expr_with_types(right, env, binding_env, binding_types)
13235            ),
13236            Expr::Sub(left, right) => format!(
13237                "({} - {})",
13238                self.render_expr_with_types(left, env, binding_env, binding_types),
13239                self.render_expr_with_types(right, env, binding_env, binding_types)
13240            ),
13241            Expr::Gt(left, right) => self.render_ordering(
13242                OrderingOperator::Gt,
13243                left,
13244                right,
13245                env,
13246                binding_env,
13247                binding_types,
13248            ),
13249            Expr::Gte(left, right) => self.render_ordering(
13250                OrderingOperator::Gte,
13251                left,
13252                right,
13253                env,
13254                binding_env,
13255                binding_types,
13256            ),
13257            Expr::Lt(left, right) => self.render_ordering(
13258                OrderingOperator::Lt,
13259                left,
13260                right,
13261                env,
13262                binding_env,
13263                binding_types,
13264            ),
13265            Expr::Lte(left, right) => self.render_ordering(
13266                OrderingOperator::Lte,
13267                left,
13268                right,
13269                env,
13270                binding_env,
13271                binding_types,
13272            ),
13273            Expr::Contains { collection, value } => format!(
13274                "({} \\in {})",
13275                self.render_expr_with_types(value, env, binding_env, binding_types),
13276                self.render_collection_domain(collection, env, binding_env, binding_types)
13277            ),
13278            Expr::MapContainsKey { map, key } => format!(
13279                "({} \\in DOMAIN {})",
13280                self.render_expr_with_types(key, env, binding_env, binding_types),
13281                self.render_expr_with_types(map, env, binding_env, binding_types)
13282            ),
13283            Expr::SeqStartsWith { seq, prefix } => format!(
13284                "StartsWith({}, {})",
13285                self.render_expr_with_types(seq, env, binding_env, binding_types),
13286                self.render_expr_with_types(prefix, env, binding_env, binding_types)
13287            ),
13288            Expr::SeqElements(inner) => format!(
13289                "SeqElements({})",
13290                self.render_expr_with_types(inner, env, binding_env, binding_types)
13291            ),
13292            Expr::Len(inner) => {
13293                // The kernel counts the entries of a sequence, set or map
13294                // alike; TLA+ `Len` is defined only on sequences.
13295                let rendered = self.render_expr_with_types(inner, env, binding_env, binding_types);
13296                match self.infer_expr_type_for_render(inner, binding_types) {
13297                    Some(TypeRef::Map(_, _)) => format!("Cardinality(DOMAIN {rendered})"),
13298                    Some(ty) if self.type_renders_as_set(&ty) => {
13299                        format!("Cardinality({rendered})")
13300                    }
13301                    _ => format!("Len({rendered})"),
13302                }
13303            }
13304            Expr::Count { collection, value } => format!(
13305                "Count({}, {})",
13306                self.render_expr_with_types(collection, env, binding_env, binding_types),
13307                self.render_expr_with_types(value, env, binding_env, binding_types)
13308            ),
13309            Expr::Head(inner) => format!(
13310                "Head({})",
13311                self.render_expr_with_types(inner, env, binding_env, binding_types)
13312            ),
13313            Expr::MapKeys(inner) => format!(
13314                "DOMAIN {}",
13315                self.render_expr_with_types(inner, env, binding_env, binding_types)
13316            ),
13317            Expr::MapGet { map, key } => format!(
13318                "{}",
13319                if self.is_scalar_value_projection(map, key, binding_types) {
13320                    self.render_expr_with_types(map, env, binding_env, binding_types)
13321                } else {
13322                    format!(
13323                        "(IF {} \\in DOMAIN {} THEN {}[{}] ELSE {})",
13324                        self.render_expr_with_types(key, env, binding_env, binding_types),
13325                        self.render_expr_with_types(map, env, binding_env, binding_types),
13326                        self.render_expr_with_types(map, env, binding_env, binding_types),
13327                        self.render_expr_with_types(key, env, binding_env, binding_types),
13328                        self.map_absent_value_expr(map, binding_types)
13329                    )
13330                }
13331            ),
13332            // A populated map literal as a TLC function: `k1 :> v1 @@ k2 :> v2`
13333            // (the TLC module every generated model extends).
13334            Expr::MapLiteral(entries) => format!(
13335                "({})",
13336                entries
13337                    .iter()
13338                    .map(|(key, value)| format!(
13339                        "{} :> {}",
13340                        self.render_expr_with_types(key, env, binding_env, binding_types),
13341                        self.render_expr_with_types(value, env, binding_env, binding_types)
13342                    ))
13343                    .collect::<Vec<_>>()
13344                    .join(" @@ ")
13345            ),
13346            // Strict read: plain function application, so TLC reports an
13347            // error if a reachable state reads a key outside DOMAIN (#1811).
13348            Expr::MapValue { map, key } => format!(
13349                "({})[{}]",
13350                self.render_expr_with_types(map, env, binding_env, binding_types),
13351                self.render_expr_with_types(key, env, binding_env, binding_types)
13352            ),
13353            Expr::Some(inner) => format!(
13354                "Some({})",
13355                self.render_expr_with_types(inner, env, binding_env, binding_types)
13356            ),
13357            Expr::Call { helper, args } => format!(
13358                "{}",
13359                if args.is_empty() {
13360                    self.scoped_helper_name(helper)
13361                } else {
13362                    format!(
13363                        "{}({})",
13364                        self.scoped_helper_name(helper),
13365                        args.iter()
13366                            .map(|arg| self.render_expr_with_types(
13367                                arg,
13368                                env,
13369                                binding_env,
13370                                binding_types
13371                            ))
13372                            .collect::<Vec<_>>()
13373                            .join(", ")
13374                    )
13375                }
13376            ),
13377            Expr::Quantified {
13378                quantifier,
13379                binding,
13380                over,
13381                body,
13382            } => {
13383                let keyword = match quantifier {
13384                    Quantifier::Any => "\\E",
13385                    Quantifier::All => "\\A",
13386                };
13387                let mut nested_bindings = binding_env.clone();
13388                nested_bindings.insert(binding.clone(), binding.clone());
13389                let mut nested_binding_types = binding_types.clone();
13390                if let Some(item_ty) = self.collection_item_type(over, binding_types) {
13391                    nested_binding_types.insert(binding.clone(), item_ty);
13392                }
13393                format!(
13394                    "({} {} \\in {} : {})",
13395                    keyword,
13396                    binding,
13397                    self.render_collection_domain(over, env, binding_env, binding_types),
13398                    self.render_expr_with_types(body, env, &nested_bindings, &nested_binding_types)
13399                )
13400            }
13401        }
13402    }
13403
13404    /// `left op right` for an ordering comparison. With an `Option` operand
13405    /// it takes Rust's order through `OptionLt` / `OptionLe` (see
13406    /// [`TLA_OPTION_ORDER_DEFINITIONS`]); otherwise the TLA+ operator.
13407    fn render_ordering(
13408        &self,
13409        operator: OrderingOperator,
13410        left: &Expr,
13411        right: &Expr,
13412        env: &BTreeMap<String, String>,
13413        binding_env: &BTreeMap<String, String>,
13414        binding_types: &BTreeMap<String, TypeRef>,
13415    ) -> String {
13416        let left_tla = self.render_expr_with_types(left, env, binding_env, binding_types);
13417        let right_tla = self.render_expr_with_types(right, env, binding_env, binding_types);
13418        if !self.is_option_operand(left, binding_types)
13419            && !self.is_option_operand(right, binding_types)
13420        {
13421            let symbol = match operator {
13422                OrderingOperator::Lt => "<",
13423                OrderingOperator::Lte => "<=",
13424                OrderingOperator::Gt => ">",
13425                OrderingOperator::Gte => ">=",
13426            };
13427            return format!("({left_tla} {symbol} {right_tla})");
13428        }
13429        self.option_order_used.set(true);
13430        match operator {
13431            OrderingOperator::Lt => format!("OptionLt({left_tla}, {right_tla})"),
13432            OrderingOperator::Lte => format!("OptionLe({left_tla}, {right_tla})"),
13433            OrderingOperator::Gt => format!("OptionLt({right_tla}, {left_tla})"),
13434            OrderingOperator::Gte => format!("OptionLe({right_tla}, {left_tla})"),
13435        }
13436    }
13437
13438    /// Whether `expr` is an `Option` value: a `None` / `Some` literal, or an
13439    /// operand whose type is `Option<_>` (a field, a trigger binding or helper
13440    /// parameter, a helper call, a map read, the `get_copied` / `get_cloned`
13441    /// lowering).
13442    fn is_option_operand(&self, expr: &Expr, binding_types: &BTreeMap<String, TypeRef>) -> bool {
13443        matches!(expr, Expr::None | Expr::Some(_))
13444            || matches!(
13445                self.infer_expr_type_for_render(expr, binding_types),
13446                Some(TypeRef::Option(_))
13447            )
13448    }
13449
13450    fn infer_expr_type_for_render(
13451        &self,
13452        expr: &Expr,
13453        binding_types: &BTreeMap<String, TypeRef>,
13454    ) -> Option<TypeRef> {
13455        // A projection into a structural record (`restrictions.lifetime.unresolved`)
13456        // takes the declared type of the record field, so `.len()` on a
13457        // field-presence set reached through one renders as `Cardinality`.
13458        if let Expr::FieldAccess { base, field } = expr {
13459            let TypeRef::Named(record) = self.infer_expr_type_for_render(base, binding_types)?
13460            else {
13461                return None;
13462            };
13463            let meerkat_machine_schema::RustTypeAtom::TypePathStruct { fields, .. } =
13464                self.named_bindings.get(record.as_str())?
13465            else {
13466                return None;
13467            };
13468            return match &fields
13469                .iter()
13470                .find(|candidate| candidate.name == *field)?
13471                .atom
13472            {
13473                meerkat_machine_schema::TypePathStructFieldAtom::String => Some(TypeRef::String),
13474                meerkat_machine_schema::TypePathStructFieldAtom::Named(name) => {
13475                    Some(TypeRef::Named(name.clone()))
13476                }
13477                meerkat_machine_schema::TypePathStructFieldAtom::OptionalNamed(name) => {
13478                    Some(TypeRef::Option(Box::new(TypeRef::Named(name.clone()))))
13479                }
13480            };
13481        }
13482        let field_types = self
13483            .schema
13484            .state
13485            .fields
13486            .iter()
13487            .map(|field| (field.name.as_str().to_owned(), field.ty.clone()))
13488            .collect::<BTreeMap<String, _>>();
13489        let helper_returns = self
13490            .schema
13491            .helpers
13492            .iter()
13493            .chain(self.schema.derived.iter())
13494            .map(|helper| (helper.name.clone(), helper.returns.clone()))
13495            .collect::<BTreeMap<String, _>>();
13496        infer_expr_type(expr, &field_types, &helper_returns, binding_types)
13497    }
13498
13499    fn type_renders_as_set(&self, ty: &TypeRef) -> bool {
13500        match ty {
13501            TypeRef::Set(_) => true,
13502            TypeRef::Named(name) => matches!(
13503                self.named_bindings.get(name.as_str()),
13504                Some(meerkat_machine_schema::RustTypeAtom::TypePathFieldPresenceSet { .. })
13505            ),
13506            TypeRef::Enum(name) => matches!(
13507                self.named_bindings.get(name.as_str()),
13508                Some(meerkat_machine_schema::RustTypeAtom::TypePathFieldPresenceSet { .. })
13509            ),
13510            _ => false,
13511        }
13512    }
13513
13514    fn render_collection_domain(
13515        &self,
13516        over: &Expr,
13517        env: &BTreeMap<String, String>,
13518        binding_env: &BTreeMap<String, String>,
13519        binding_types: &BTreeMap<String, TypeRef>,
13520    ) -> String {
13521        let rendered = self.render_expr_with_types(over, env, binding_env, binding_types);
13522        match self.collection_item_type(over, binding_types) {
13523            Some(_) if self.is_sequence_expr(over, binding_types) => {
13524                format!("SeqElements({rendered})")
13525            }
13526            _ => rendered,
13527        }
13528    }
13529
13530    fn collection_item_type(
13531        &self,
13532        expr: &Expr,
13533        binding_types: &BTreeMap<String, TypeRef>,
13534    ) -> Option<TypeRef> {
13535        match expr {
13536            Expr::Field(name) => self
13537                .schema
13538                .state
13539                .fields
13540                .iter()
13541                .find(|field| field.name == *name)
13542                .and_then(|field| match &field.ty {
13543                    TypeRef::Seq(inner) | TypeRef::Set(inner) => Some((**inner).clone()),
13544                    _ => None,
13545                }),
13546            Expr::Binding(name) => binding_types.get(name).and_then(|ty| match ty {
13547                TypeRef::Seq(inner) | TypeRef::Set(inner) => Some((**inner).clone()),
13548                _ => None,
13549            }),
13550            Expr::EnumStringSetPayload { .. } => Some(TypeRef::String),
13551            Expr::SeqLiteral(items) => {
13552                if let Some(first) = items.first() {
13553                    self.scalar_expr_type(first, binding_types)
13554                } else {
13555                    Some(TypeRef::String)
13556                }
13557            }
13558            Expr::MapKeys(_) | Expr::EmptySet => Some(TypeRef::String),
13559            _ => None,
13560        }
13561    }
13562
13563    fn scalar_expr_type(
13564        &self,
13565        expr: &Expr,
13566        binding_types: &BTreeMap<String, TypeRef>,
13567    ) -> Option<TypeRef> {
13568        match expr {
13569            Expr::Bool(_) => Some(TypeRef::Bool),
13570            Expr::U64(_) | Expr::U64Max => Some(TypeRef::U64),
13571            Expr::String(_) | Expr::Phase(_) | Expr::Variant(_) => Some(TypeRef::String),
13572            Expr::NamedVariant { enum_name, .. } => Some(TypeRef::Enum(enum_name.clone())),
13573            Expr::FieldAccess { .. } => None,
13574            Expr::EnumVariantIs { .. } => Some(TypeRef::Bool),
13575            Expr::EnumStringSetPayload { .. } => Some(TypeRef::Set(Box::new(TypeRef::String))),
13576            Expr::MapGet { map, .. } | Expr::MapValue { map, .. } => {
13577                self.map_value_type(map, binding_types)
13578            }
13579            Expr::Field(name) => self
13580                .schema
13581                .state
13582                .fields
13583                .iter()
13584                .find(|field| field.name == *name)
13585                .map(|field| &field.ty)
13586                .cloned(),
13587            Expr::Binding(name) => binding_types.get(name).cloned(),
13588            _ => None,
13589        }
13590    }
13591
13592    fn is_scalar_value_projection(
13593        &self,
13594        map: &Expr,
13595        key: &Expr,
13596        binding_types: &BTreeMap<String, TypeRef>,
13597    ) -> bool {
13598        matches!(key, Expr::String(value) if value == "value")
13599            && matches!(
13600                self.scalar_expr_type(map, binding_types),
13601                Some(
13602                    TypeRef::Bool
13603                        | TypeRef::U32
13604                        | TypeRef::U64
13605                        | TypeRef::String
13606                        | TypeRef::Enum(_)
13607                        | TypeRef::Named(_)
13608                )
13609            )
13610    }
13611
13612    fn map_value_type(
13613        &self,
13614        expr: &Expr,
13615        binding_types: &BTreeMap<String, TypeRef>,
13616    ) -> Option<TypeRef> {
13617        match expr {
13618            Expr::Field(name) => self
13619                .schema
13620                .state
13621                .fields
13622                .iter()
13623                .find(|field| field.name == *name)
13624                .and_then(|field| match &field.ty {
13625                    TypeRef::Map(_, value) => Some((**value).clone()),
13626                    _ => None,
13627                }),
13628            Expr::Binding(name) => binding_types.get(name).and_then(|ty| match ty {
13629                TypeRef::Map(_, value) => Some((**value).clone()),
13630                _ => None,
13631            }),
13632            _ => None,
13633        }
13634    }
13635
13636    fn map_absent_value_expr(
13637        &self,
13638        expr: &Expr,
13639        binding_types: &BTreeMap<String, TypeRef>,
13640    ) -> String {
13641        self.map_value_type(expr, binding_types)
13642            .map(|ty| default_absent_map_value_expr(&ty))
13643            .unwrap_or_else(|| "None".into())
13644    }
13645
13646    fn is_sequence_expr(&self, expr: &Expr, binding_types: &BTreeMap<String, TypeRef>) -> bool {
13647        match expr {
13648            Expr::Field(name) => self
13649                .schema
13650                .state
13651                .fields
13652                .iter()
13653                .find(|field| field.name == *name)
13654                .is_some_and(|field| matches!(field.ty, TypeRef::Seq(_))),
13655            Expr::Binding(name) => binding_types
13656                .get(name)
13657                .is_some_and(|ty| matches!(ty, TypeRef::Seq(_))),
13658            Expr::SeqLiteral(_) => true,
13659            _ => false,
13660        }
13661    }
13662}
13663
13664#[derive(Copy, Clone)]
13665enum CollectionKind {
13666    Sequence,
13667    Set,
13668}
13669
13670fn infer_collection_kind(
13671    expr: &Expr,
13672    schema: &MachineSchema,
13673    binding_types: &BTreeMap<String, TypeRef>,
13674) -> CollectionKind {
13675    match expr {
13676        Expr::Field(name) => schema
13677            .state
13678            .fields
13679            .iter()
13680            .find(|field| field.name == *name)
13681            .map(|field| match field.ty {
13682                TypeRef::Set(_) => CollectionKind::Set,
13683                _ => CollectionKind::Sequence,
13684            })
13685            .unwrap_or(CollectionKind::Sequence),
13686        Expr::Binding(name) => binding_types
13687            .get(name)
13688            .map(|ty| match ty {
13689                TypeRef::Set(_) => CollectionKind::Set,
13690                _ => CollectionKind::Sequence,
13691            })
13692            .unwrap_or(CollectionKind::Sequence),
13693        Expr::MapKeys(_) | Expr::EmptySet | Expr::EnumStringSetPayload { .. } => {
13694            CollectionKind::Set
13695        }
13696        _ => CollectionKind::Sequence,
13697    }
13698}
13699
13700fn render_sequence_foreach_helper(
13701    name: &str,
13702    binding: &str,
13703    extra_params: &[String],
13704    body_expr: &str,
13705) -> String {
13706    let mut params = vec!["acc".to_owned(), "items".to_owned()];
13707    params.extend(extra_params.iter().cloned());
13708    let params_str = params.join(", ");
13709    let recurse_args = std::iter::once("next_acc".to_owned())
13710        .chain(std::iter::once("Tail(items)".to_owned()))
13711        .chain(extra_params.iter().cloned())
13712        .collect::<Vec<_>>()
13713        .join(", ");
13714    let recursive_args = std::iter::repeat_n("_", params.len())
13715        .collect::<Vec<_>>()
13716        .join(", ");
13717
13718    format!(
13719        "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})"
13720    )
13721}
13722
13723fn render_set_foreach_helper(
13724    name: &str,
13725    binding: &str,
13726    extra_params: &[String],
13727    body_expr: &str,
13728) -> String {
13729    let mut params = vec!["acc".to_owned(), "remaining".to_owned()];
13730    params.extend(extra_params.iter().cloned());
13731    let params_str = params.join(", ");
13732    let recurse_args = std::iter::once("next_acc".to_owned())
13733        .chain(std::iter::once("remaining \\ {item}".to_owned()))
13734        .chain(extra_params.iter().cloned())
13735        .collect::<Vec<_>>()
13736        .join(", ");
13737    let recursive_args = std::iter::repeat_n("_", params.len())
13738        .collect::<Vec<_>>()
13739        .join(", ");
13740
13741    format!(
13742        "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})"
13743    )
13744}
13745
13746fn collect_update_fields(updates: &[Update]) -> BTreeSet<String> {
13747    let mut fields = BTreeSet::new();
13748    for update in updates {
13749        match update {
13750            Update::Assign { field, .. }
13751            | Update::Increment { field, .. }
13752            | Update::Decrement { field, .. }
13753            | Update::MapInsert { field, .. }
13754            | Update::MapIncrement { field, .. }
13755            | Update::MapDecrement { field, .. }
13756            | Update::MapRemove { field, .. }
13757            | Update::SetInsert { field, .. }
13758            | Update::SetRemove { field, .. }
13759            | Update::SeqAppend { field, .. }
13760            | Update::SeqPrepend { field, .. }
13761            | Update::SeqPopFront { field }
13762            | Update::SeqRemoveValue { field, .. }
13763            | Update::SeqRemoveAll { field, .. } => {
13764                fields.insert(field.as_str().to_owned());
13765            }
13766            Update::Conditional {
13767                then_updates,
13768                else_updates,
13769                ..
13770            } => {
13771                fields.extend(collect_update_fields(then_updates));
13772                fields.extend(collect_update_fields(else_updates));
13773            }
13774            Update::ForEach { updates, .. } => {
13775                fields.extend(collect_update_fields(updates));
13776            }
13777        }
13778    }
13779    fields
13780}
13781
13782fn collect_update_bindings(updates: &[Update]) -> BTreeSet<String> {
13783    let mut bindings = BTreeSet::new();
13784    for update in updates {
13785        match update {
13786            Update::Assign { expr, .. } => collect_expr_bindings(expr, &mut bindings),
13787            Update::MapInsert { key, value, .. } => {
13788                collect_expr_bindings(key, &mut bindings);
13789                collect_expr_bindings(value, &mut bindings);
13790            }
13791            Update::MapRemove { key, .. } => {
13792                collect_expr_bindings(key, &mut bindings);
13793            }
13794            Update::MapIncrement { key, .. } | Update::MapDecrement { key, .. } => {
13795                collect_expr_bindings(key, &mut bindings);
13796            }
13797            Update::SetInsert { value, .. }
13798            | Update::SetRemove { value, .. }
13799            | Update::SeqAppend { value, .. }
13800            | Update::SeqRemoveValue { value, .. }
13801            | Update::SeqPrepend { values: value, .. }
13802            | Update::SeqRemoveAll { values: value, .. } => {
13803                collect_expr_bindings(value, &mut bindings);
13804            }
13805            Update::Conditional {
13806                condition,
13807                then_updates,
13808                else_updates,
13809            } => {
13810                collect_expr_bindings(condition, &mut bindings);
13811                bindings.extend(collect_update_bindings(then_updates));
13812                bindings.extend(collect_update_bindings(else_updates));
13813            }
13814            Update::ForEach {
13815                binding,
13816                over,
13817                updates,
13818            } => {
13819                bindings.insert(binding.clone());
13820                collect_expr_bindings(over, &mut bindings);
13821                bindings.extend(collect_update_bindings(updates));
13822            }
13823            Update::Increment { .. } | Update::Decrement { .. } | Update::SeqPopFront { .. } => {}
13824        }
13825    }
13826    bindings
13827}
13828
13829fn collect_update_fields_exprs(updates: &[Update]) -> BTreeSet<String> {
13830    let mut fields = BTreeSet::new();
13831    for update in updates {
13832        match update {
13833            Update::Assign { expr, .. } => collect_expr_fields(expr, &mut fields),
13834            Update::MapInsert { key, value, .. } => {
13835                collect_expr_fields(key, &mut fields);
13836                collect_expr_fields(value, &mut fields);
13837            }
13838            Update::MapRemove { key, .. } => {
13839                collect_expr_fields(key, &mut fields);
13840            }
13841            Update::MapIncrement { key, .. } | Update::MapDecrement { key, .. } => {
13842                collect_expr_fields(key, &mut fields);
13843            }
13844            Update::SetInsert { value, .. }
13845            | Update::SetRemove { value, .. }
13846            | Update::SeqAppend { value, .. }
13847            | Update::SeqRemoveValue { value, .. }
13848            | Update::SeqPrepend { values: value, .. }
13849            | Update::SeqRemoveAll { values: value, .. } => {
13850                collect_expr_fields(value, &mut fields);
13851            }
13852            Update::Conditional {
13853                condition,
13854                then_updates,
13855                else_updates,
13856            } => {
13857                collect_expr_fields(condition, &mut fields);
13858                fields.extend(collect_update_fields_exprs(then_updates));
13859                fields.extend(collect_update_fields_exprs(else_updates));
13860            }
13861            Update::ForEach { over, updates, .. } => {
13862                collect_expr_fields(over, &mut fields);
13863                fields.extend(collect_update_fields_exprs(updates));
13864            }
13865            Update::Increment { .. } | Update::Decrement { .. } | Update::SeqPopFront { .. } => {}
13866        }
13867    }
13868    fields
13869}
13870
13871fn collect_expr_bindings(expr: &Expr, bindings: &mut BTreeSet<String>) {
13872    match expr {
13873        Expr::Binding(name) => {
13874            bindings.insert(name.clone());
13875        }
13876        Expr::SeqLiteral(items) | Expr::And(items) | Expr::Or(items) => {
13877            for item in items {
13878                collect_expr_bindings(item, bindings);
13879            }
13880        }
13881        Expr::IfElse {
13882            condition,
13883            then_expr,
13884            else_expr,
13885        } => {
13886            collect_expr_bindings(condition, bindings);
13887            collect_expr_bindings(then_expr, bindings);
13888            collect_expr_bindings(else_expr, bindings);
13889        }
13890        Expr::Not(inner)
13891        | Expr::SeqElements(inner)
13892        | Expr::Len(inner)
13893        | Expr::Head(inner)
13894        | Expr::MapKeys(inner)
13895        | Expr::Some(inner)
13896        | Expr::FieldAccess { base: inner, .. }
13897        | Expr::EnumVariantIs { value: inner, .. }
13898        | Expr::EnumStringSetPayload { value: inner, .. } => collect_expr_bindings(inner, bindings),
13899        Expr::Eq(left, right)
13900        | Expr::Neq(left, right)
13901        | Expr::Add(left, right)
13902        | Expr::Sub(left, right)
13903        | Expr::Gt(left, right)
13904        | Expr::Gte(left, right)
13905        | Expr::Lt(left, right)
13906        | Expr::Lte(left, right) => {
13907            collect_expr_bindings(left, bindings);
13908            collect_expr_bindings(right, bindings);
13909        }
13910        Expr::Contains { collection, value } => {
13911            collect_expr_bindings(collection, bindings);
13912            collect_expr_bindings(value, bindings);
13913        }
13914        Expr::Count { collection, value } => {
13915            collect_expr_bindings(collection, bindings);
13916            collect_expr_bindings(value, bindings);
13917        }
13918        Expr::MapContainsKey { map, key } => {
13919            collect_expr_bindings(map, bindings);
13920            collect_expr_bindings(key, bindings);
13921        }
13922        Expr::SeqStartsWith { seq, prefix } => {
13923            collect_expr_bindings(seq, bindings);
13924            collect_expr_bindings(prefix, bindings);
13925        }
13926        Expr::MapGet { map, key } | Expr::MapValue { map, key } => {
13927            collect_expr_bindings(map, bindings);
13928            collect_expr_bindings(key, bindings);
13929        }
13930        Expr::MapLiteral(entries) => {
13931            for (key, value) in entries {
13932                collect_expr_bindings(key, bindings);
13933                collect_expr_bindings(value, bindings);
13934            }
13935        }
13936        Expr::Call { args, .. } => {
13937            for arg in args {
13938                collect_expr_bindings(arg, bindings);
13939            }
13940        }
13941        Expr::Quantified {
13942            binding,
13943            over,
13944            body,
13945            ..
13946        } => {
13947            bindings.insert(binding.clone());
13948            collect_expr_bindings(over, bindings);
13949            collect_expr_bindings(body, bindings);
13950        }
13951        Expr::Bool(_)
13952        | Expr::U64(_)
13953        | Expr::U64Max
13954        | Expr::String(_)
13955        | Expr::NamedVariant { .. }
13956        | Expr::EmptySet
13957        | Expr::EmptyMap
13958        | Expr::CurrentPhase
13959        | Expr::Phase(_)
13960        | Expr::Field(_)
13961        | Expr::Variant(_)
13962        | Expr::None => {}
13963    }
13964}
13965
13966fn collect_expr_fields(expr: &Expr, fields: &mut BTreeSet<String>) {
13967    match expr {
13968        Expr::Field(name) => {
13969            fields.insert(name.as_str().to_owned());
13970        }
13971        Expr::SeqLiteral(items) | Expr::And(items) | Expr::Or(items) => {
13972            for item in items {
13973                collect_expr_fields(item, fields);
13974            }
13975        }
13976        Expr::IfElse {
13977            condition,
13978            then_expr,
13979            else_expr,
13980        } => {
13981            collect_expr_fields(condition, fields);
13982            collect_expr_fields(then_expr, fields);
13983            collect_expr_fields(else_expr, fields);
13984        }
13985        Expr::Not(inner)
13986        | Expr::SeqElements(inner)
13987        | Expr::Len(inner)
13988        | Expr::Head(inner)
13989        | Expr::MapKeys(inner)
13990        | Expr::Some(inner)
13991        | Expr::FieldAccess { base: inner, .. }
13992        | Expr::EnumVariantIs { value: inner, .. }
13993        | Expr::EnumStringSetPayload { value: inner, .. } => collect_expr_fields(inner, fields),
13994        Expr::Eq(left, right)
13995        | Expr::Neq(left, right)
13996        | Expr::Add(left, right)
13997        | Expr::Sub(left, right)
13998        | Expr::Gt(left, right)
13999        | Expr::Gte(left, right)
14000        | Expr::Lt(left, right)
14001        | Expr::Lte(left, right) => {
14002            collect_expr_fields(left, fields);
14003            collect_expr_fields(right, fields);
14004        }
14005        Expr::Contains { collection, value } => {
14006            collect_expr_fields(collection, fields);
14007            collect_expr_fields(value, fields);
14008        }
14009        Expr::Count { collection, value } => {
14010            collect_expr_fields(collection, fields);
14011            collect_expr_fields(value, fields);
14012        }
14013        Expr::MapContainsKey { map, key } => {
14014            collect_expr_fields(map, fields);
14015            collect_expr_fields(key, fields);
14016        }
14017        Expr::SeqStartsWith { seq, prefix } => {
14018            collect_expr_fields(seq, fields);
14019            collect_expr_fields(prefix, fields);
14020        }
14021        Expr::MapGet { map, key } | Expr::MapValue { map, key } => {
14022            collect_expr_fields(map, fields);
14023            collect_expr_fields(key, fields);
14024        }
14025        Expr::MapLiteral(entries) => {
14026            for (key, value) in entries {
14027                collect_expr_fields(key, fields);
14028                collect_expr_fields(value, fields);
14029            }
14030        }
14031        Expr::Call { args, .. } => {
14032            for arg in args {
14033                collect_expr_fields(arg, fields);
14034            }
14035        }
14036        Expr::Quantified { over, body, .. } => {
14037            collect_expr_fields(over, fields);
14038            collect_expr_fields(body, fields);
14039        }
14040        Expr::Bool(_)
14041        | Expr::U64(_)
14042        | Expr::U64Max
14043        | Expr::String(_)
14044        | Expr::NamedVariant { .. }
14045        | Expr::EmptySet
14046        | Expr::EmptyMap
14047        | Expr::CurrentPhase
14048        | Expr::Phase(_)
14049        | Expr::Binding(_)
14050        | Expr::Variant(_)
14051        | Expr::None => {}
14052    }
14053}
14054
14055fn union_touched_fields(
14056    base: &BTreeMap<String, String>,
14057    then_env: &BTreeMap<String, String>,
14058    else_env: &BTreeMap<String, String>,
14059) -> BTreeSet<String> {
14060    base.keys()
14061        .filter(|field| {
14062            then_env.get(*field) != base.get(*field) || else_env.get(*field) != base.get(*field)
14063        })
14064        .cloned()
14065        .collect()
14066}
14067
14068fn join_exprs(items: &[String], separator: &str) -> String {
14069    if items.is_empty() {
14070        return "TRUE".into();
14071    }
14072    if items.len() == 1 {
14073        items[0].clone()
14074    } else {
14075        format!("({})", items.join(separator))
14076    }
14077}
14078
14079/// Render a boolean disjunction as a short-circuiting `IF a THEN TRUE ELSE …`
14080/// chain instead of `a \/ b`.
14081///
14082/// TLC expands an action-level `\/` into a tableau and evaluates *every*
14083/// disjunct independently to enumerate successor states. That breaks the
14084/// idiomatic optional guard `opt = None \/ opt.value > now`: the second
14085/// disjunct's `opt.value > now` is evaluated even when `opt = None`
14086/// (`None` still has a `"value"` field equal to the string `"none"`), so TLC
14087/// raises `first argument of > should be an integer, but instead it is "none"`.
14088/// `IF a THEN TRUE ELSE b` is boolean-equivalent to `a \/ b` but is evaluated
14089/// as a single function: the `ELSE` branch is only evaluated when `a` is false,
14090/// matching the short-circuit that `/\` already gives conjunctive guards. State
14091/// space and enabledness are unchanged. Empty/single disjunctions preserve the
14092/// prior `join_exprs` behavior.
14093fn render_or_short_circuit(items: &[String]) -> String {
14094    match items {
14095        [] => "TRUE".into(),
14096        [single] => single.clone(),
14097        [first, rest @ ..] => {
14098            format!(
14099                "(IF {first} THEN TRUE ELSE {})",
14100                render_or_short_circuit(rest)
14101            )
14102        }
14103    }
14104}
14105
14106fn default_state_init_expr(ty: &TypeRef) -> String {
14107    match ty {
14108        TypeRef::Bool => "FALSE".into(),
14109        TypeRef::U32 | TypeRef::U64 => "0".into(),
14110        TypeRef::String => tla_string(""),
14111        TypeRef::Named(name) => tla_string(format!("{}_default", tla_ident(name).to_lowercase())),
14112        TypeRef::Enum(name) => tla_string(format!("{}_default", tla_ident(name).to_lowercase())),
14113        TypeRef::Option(_) => "None".into(),
14114        TypeRef::Set(_) => "{}".into(),
14115        TypeRef::Seq(_) => "<<>>".into(),
14116        TypeRef::Map(_, _) => "[x \\in {} |-> None]".into(),
14117    }
14118}
14119
14120fn default_absent_map_value_expr(ty: &TypeRef) -> String {
14121    match ty {
14122        TypeRef::Bool => "FALSE".into(),
14123        TypeRef::U32 | TypeRef::U64 => "0".into(),
14124        TypeRef::String | TypeRef::Named(_) | TypeRef::Enum(_) => tla_string("None"),
14125        TypeRef::Option(_) => "None".into(),
14126        TypeRef::Set(_) => "{}".into(),
14127        TypeRef::Seq(_) => "<<>>".into(),
14128        TypeRef::Map(_, _) => "[x \\in {} |-> None]".into(),
14129    }
14130}
14131
14132fn render_type_ref(ty: &TypeRef) -> String {
14133    match ty {
14134        TypeRef::Bool => "Bool".into(),
14135        TypeRef::U32 => "u32".into(),
14136        TypeRef::U64 => "u64".into(),
14137        TypeRef::String => "String".into(),
14138        TypeRef::Named(name) => name.as_str().to_owned(),
14139        TypeRef::Enum(name) => name.as_str().to_owned(),
14140        TypeRef::Option(inner) => format!("Option<{}>", render_type_ref(inner)),
14141        TypeRef::Set(inner) => format!("Set<{}>", render_type_ref(inner)),
14142        TypeRef::Seq(inner) => format!("Seq<{}>", render_type_ref(inner)),
14143        TypeRef::Map(key, value) => {
14144            format!("Map<{}, {}>", render_type_ref(key), render_type_ref(value))
14145        }
14146    }
14147}
14148
14149fn render_route_delivery(route: &meerkat_machine_schema::Route) -> &'static str {
14150    match route.delivery {
14151        RouteDelivery::Immediate => "Immediate",
14152        RouteDelivery::Enqueue => "Enqueue",
14153    }
14154}
14155
14156fn render_scheduler_rule(rule: &SchedulerRule) -> String {
14157    match rule {
14158        SchedulerRule::PreemptWhenReady { higher, lower } => {
14159            format!("PreemptWhenReady({higher}, {lower})")
14160        }
14161    }
14162}
14163
14164fn render_scheduler_rule_tuple(rule: &SchedulerRule) -> String {
14165    match rule {
14166        SchedulerRule::PreemptWhenReady { higher, lower } => {
14167            format!(
14168                "<<{}, {}, {}>>",
14169                tla_string("PreemptWhenReady"),
14170                tla_string(higher),
14171                tla_string(lower)
14172            )
14173        }
14174    }
14175}
14176
14177fn render_scheduler_trigger_formula(rule: &SchedulerRule) -> String {
14178    match rule {
14179        SchedulerRule::PreemptWhenReady { higher, lower } => format!(
14180            "/\\ {} \\in PendingActors /\\ {} \\in PendingActors",
14181            tla_string(higher),
14182            tla_string(lower)
14183        ),
14184    }
14185}
14186
14187fn render_composition_invariant_formula(
14188    schema: &CompositionSchema,
14189    kind: &CompositionInvariantKind,
14190) -> String {
14191    match kind {
14192        CompositionInvariantKind::RoutePresent {
14193            from_machine,
14194            effect_variant,
14195            to_machine,
14196            input_variant,
14197        } => format!(
14198            "\\E route_name \\in RouteNames : /\\ RouteSource(route_name) = {} /\\ RouteEffect(route_name) = {} /\\ RouteTargetMachine(route_name) = {} /\\ RouteTargetInput(route_name) = {}",
14199            tla_string(from_machine),
14200            tla_string(effect_variant),
14201            tla_string(to_machine),
14202            tla_string(input_variant)
14203        ),
14204        CompositionInvariantKind::ObservedInputOriginatesFromEffect {
14205            to_machine,
14206            input_variant,
14207            from_machine,
14208            effect_variant,
14209        } => format!(
14210            "\\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))",
14211            tla_string(to_machine),
14212            tla_string(input_variant),
14213            tla_string(from_machine),
14214            tla_string(effect_variant),
14215            tla_string(from_machine),
14216            tla_string(effect_variant),
14217            tla_string(from_machine),
14218            tla_string(effect_variant),
14219            tla_string(to_machine),
14220            tla_string(input_variant)
14221        ),
14222        CompositionInvariantKind::ObservedRouteInputOriginatesFromEffect {
14223            route_name,
14224            to_machine,
14225            input_variant,
14226            from_machine,
14227            effect_variant,
14228        } => format!(
14229            "\\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))",
14230            tla_string(to_machine),
14231            tla_string(input_variant),
14232            tla_string(route_name),
14233            tla_string(from_machine),
14234            tla_string(effect_variant),
14235            tla_string(from_machine),
14236            tla_string(effect_variant),
14237            tla_string(route_name),
14238            tla_string(from_machine),
14239            tla_string(effect_variant),
14240            tla_string(to_machine),
14241            tla_string(input_variant)
14242        ),
14243        CompositionInvariantKind::ActorPriorityPresent { higher, lower } => format!(
14244            "<<{}, {}>> \\in ActorPriorities",
14245            tla_string(higher),
14246            tla_string(lower)
14247        ),
14248        CompositionInvariantKind::SchedulerRulePresent { rule } => {
14249            format!("{} \\in SchedulerRules", render_scheduler_rule_tuple(rule))
14250        }
14251        CompositionInvariantKind::OutcomeHandled {
14252            from_machine,
14253            effect_variant,
14254            required_targets,
14255        } => {
14256            let required = required_targets
14257                .iter()
14258                .enumerate()
14259                .map(|(idx, target)| {
14260                    let binding = format!("route_packet_{idx}");
14261                    let input_binding = format!("input_packet_{idx}");
14262                    format!(
14263                        "\\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",
14264                        tla_string(from_machine),
14265                        tla_string(effect_variant),
14266                        tla_string(&target.machine),
14267                        tla_string(&target.input_variant)
14268                        ,
14269                        tla_string(&target.machine),
14270                        tla_string(&target.input_variant),
14271                        tla_string(from_machine),
14272                        tla_string(effect_variant)
14273                    )
14274                })
14275                .collect::<Vec<_>>()
14276                .join(" /\\ ");
14277            let fallback = schema
14278                .routes
14279                .iter()
14280                .filter(|route| {
14281                    route.from_machine == *from_machine && route.effect_variant == *effect_variant
14282                })
14283                .count();
14284            if fallback == 0 {
14285                "FALSE".into()
14286            } else {
14287                format!(
14288                    "\\A effect_packet \\in emitted_effects : ((effect_packet.machine = {} /\\ effect_packet.variant = {}) => ({}))",
14289                    tla_string(from_machine),
14290                    tla_string(effect_variant),
14291                    required
14292                )
14293            }
14294        }
14295        CompositionInvariantKind::HandoffProtocolCovered { .. } => {
14296            // Structural invariant — validated at schema level, always TRUE in TLA+.
14297            "TRUE".into()
14298        }
14299    }
14300}
14301
14302fn render_composition_state_constraint(
14303    schema: &CompositionSchema,
14304    limits: &CompositionStateLimits,
14305    compiler: &CompositionTlaCompiler<'_>,
14306) -> String {
14307    let limits = effective_composition_state_limits(limits, None);
14308    let mut clauses = vec![
14309        format!("model_step_count <= {}", limits.step_limit),
14310        format!("Len(pending_inputs) <= {}", limits.pending_input_limit),
14311        format!(
14312            "Cardinality(observed_inputs) <= {}",
14313            limits.pending_input_limit + limits.delivered_route_limit + 2
14314        ),
14315        format!("Len(pending_routes) <= {}", limits.pending_route_limit),
14316        format!(
14317            "Cardinality(delivered_routes) <= {}",
14318            limits.delivered_route_limit
14319        ),
14320        format!(
14321            "Cardinality(emitted_effects) <= {}",
14322            limits.emitted_effect_limit
14323        ),
14324        format!("Cardinality(observed_transitions) <= {}", limits.step_limit),
14325    ];
14326
14327    for instance in &schema.machines {
14328        let machine = compiler.machine(instance.instance_id.as_str());
14329        for field in &machine.state.fields {
14330            let field_var = compiler.field_var(instance.instance_id.as_str(), field.name.as_str());
14331            match &field.ty {
14332                TypeRef::Seq(_) => {
14333                    clauses.push(format!("Len({field_var}) <= {}", limits.seq_limit))
14334                }
14335                TypeRef::Set(_) => {
14336                    clauses.push(format!("Cardinality({field_var}) <= {}", limits.set_limit))
14337                }
14338                TypeRef::Map(_, _) => clauses.push(format!(
14339                    "Cardinality(DOMAIN {field_var}) <= {}",
14340                    limits.map_limit
14341                )),
14342                _ => {}
14343            }
14344        }
14345    }
14346
14347    format!("/\\ {}", clauses.join(" /\\ "))
14348}
14349
14350fn effective_composition_state_limits(
14351    limits: &CompositionStateLimits,
14352    witness: Option<&CompositionWitness>,
14353) -> CompositionStateLimits {
14354    let mut effective = limits.clone();
14355    if let Some(witness) = witness {
14356        let minimum_step_limit =
14357            (witness.preload_inputs.len() + witness.expected_transitions.len()) as u32;
14358        effective.step_limit = effective.step_limit.max(minimum_step_limit);
14359        effective.delivered_route_limit = effective
14360            .delivered_route_limit
14361            .max(witness.expected_routes.len() as u32);
14362        effective.emitted_effect_limit = effective
14363            .emitted_effect_limit
14364            .max(witness.expected_transitions.len() as u32);
14365        effective.pending_input_limit = effective.pending_input_limit.max(1);
14366    }
14367    effective
14368}
14369
14370fn composition_deep_state_limits(schema: &CompositionSchema) -> CompositionStateLimits {
14371    let mut deep = CompositionStateLimits::deep_defaults();
14372    if let Some(ci) = &schema.ci_limits {
14373        deep.step_limit = deep.step_limit.max(ci.step_limit);
14374        deep.pending_input_limit = deep.pending_input_limit.max(ci.pending_input_limit);
14375        deep.pending_route_limit = deep.pending_route_limit.max(ci.pending_route_limit);
14376        deep.delivered_route_limit = deep.delivered_route_limit.max(ci.delivered_route_limit);
14377        deep.emitted_effect_limit = deep.emitted_effect_limit.max(ci.emitted_effect_limit);
14378        deep.seq_limit = deep.seq_limit.max(ci.seq_limit);
14379        deep.set_limit = deep.set_limit.max(ci.set_limit);
14380        deep.map_limit = deep.map_limit.max(ci.map_limit);
14381    }
14382    deep
14383}
14384
14385fn render_machine_state_constraint(schema: &MachineSchema, deep: bool) -> String {
14386    let step_limit = if deep {
14387        8
14388    } else {
14389        schema.ci_step_limit.unwrap_or(6) as usize
14390    };
14391    let seq_limit = if deep { 2 } else { 1 };
14392    let set_limit = if deep { 2 } else { 1 };
14393    let map_limit = if deep { 2 } else { 1 };
14394    let (step_limit, seq_limit, set_limit, map_limit) =
14395        if !deep && let Some(model) = &schema.tlc_model {
14396            let limits = &model.ci_limits;
14397            (
14398                limits.step_limit as usize,
14399                limits.seq_limit as usize,
14400                limits.set_limit as usize,
14401                limits.map_limit as usize,
14402            )
14403        } else {
14404            (step_limit, seq_limit, set_limit, map_limit)
14405        };
14406    let mut clauses = vec![format!("model_step_count <= {step_limit}")];
14407
14408    for field in &schema.state.fields {
14409        match &field.ty {
14410            TypeRef::Seq(_) => {
14411                clauses.push(format!("Len({}) <= {seq_limit}", tla_ident(&field.name)))
14412            }
14413            TypeRef::Set(_) => clauses.push(format!(
14414                "Cardinality({}) <= {set_limit}",
14415                tla_ident(&field.name)
14416            )),
14417            TypeRef::Map(_, _) => clauses.push(format!(
14418                "Cardinality(DOMAIN {}) <= {map_limit}",
14419                tla_ident(&field.name)
14420            )),
14421            _ => {}
14422        }
14423    }
14424
14425    if clauses.is_empty() {
14426        "TRUE".into()
14427    } else {
14428        format!("/\\ {}", clauses.join(" /\\ "))
14429    }
14430}
14431
14432/// Default arm for a generated composition `CASE` operator.
14433///
14434/// Route-component lookups (`RouteSource`, `RouteEffect`, …) are validated
14435/// up-front by [`CompositionTlaCompiler::validate_routes`], so the historical
14436/// `OTHER -> "unknown_*"` arm is provably unreachable for any real route name.
14437/// Emitting that sentinel was a silent catch-all that could launder an
14438/// undeclared route component into a passing model. Such lookups now use
14439/// [`CaseDefault::FailClosed`]: the `OTHER` arm is dropped entirely so an
14440/// unmatched route name surfaces as a TLC error instead of a fabricated value,
14441/// and the renderer fails closed at codegen time if a route component cannot
14442/// be resolved.
14443///
14444/// Genuinely closed enumerations (`RouteTargetKind`, `RouteDeliveryKind`) keep
14445/// a total literal fallback via [`CaseDefault::ClosedEnum`]; every input maps
14446/// to a finite, exhaustive enum, so the literal is a sound total default rather
14447/// than a sentinel standing in for an undeclared component.
14448enum CaseDefault {
14449    /// Total literal fallback over a closed enumeration domain.
14450    ClosedEnum(String),
14451    /// Fail-closed route-component lookup: no `OTHER` sentinel is emitted.
14452    ///
14453    /// `require_mapping` is `true` for operators whose domain must be
14454    /// non-empty for a well-formed composition (e.g. `ActorOfMachine`, which
14455    /// maps over declared machine instances): an empty mapping is then a hard
14456    /// codegen error. It is `false` for operators keyed on routes, since a
14457    /// protocol-only composition legitimately declares zero routes — the
14458    /// operator is structurally defined but never evaluated.
14459    FailClosed {
14460        component: &'static str,
14461        require_mapping: bool,
14462    },
14463}
14464
14465fn render_composition_case_fn(
14466    out: &mut String,
14467    composition: &str,
14468    fn_name: &str,
14469    param: &str,
14470    mappings: Vec<(&str, String)>,
14471    default: CaseDefault,
14472) -> std::result::Result<(), CompositionTlaError> {
14473    writeln!(out, "{fn_name}({param}) ==");
14474    if mappings.is_empty() {
14475        // No keys to map. For a closed-enum operator the literal fallback is
14476        // the operator body. For a fail-closed route-component operator the
14477        // composition declares no routes, so the operator is structurally
14478        // defined but unreachable; emitting the bare error label as a string
14479        // makes any accidental evaluation explode in TLC rather than yield a
14480        // plausible-looking value.
14481        let body = match &default {
14482            CaseDefault::ClosedEnum(expr) => expr.clone(),
14483            CaseDefault::FailClosed {
14484                component,
14485                require_mapping,
14486            } => {
14487                if *require_mapping {
14488                    return Err(CompositionTlaError::UnknownRouteComponent {
14489                        composition: composition.to_owned(),
14490                        component,
14491                    });
14492                }
14493                tla_string(format!("unresolved_{component}"))
14494            }
14495        };
14496        pushln!(out, "    {}", body);
14497        pushln!(out);
14498        return Ok(());
14499    }
14500
14501    let mut first = true;
14502    for (key, value) in mappings {
14503        if first {
14504            pushln!(out, "    CASE {} = {} -> {}", param, tla_string(key), value);
14505            first = false;
14506        } else {
14507            writeln!(out, "      [] {} = {} -> {}", param, tla_string(key), value);
14508        }
14509    }
14510    match default {
14511        CaseDefault::ClosedEnum(expr) => {
14512            writeln!(out, "      [] OTHER -> {}", expr);
14513        }
14514        CaseDefault::FailClosed { .. } => {
14515            // validate_routes() guarantees the CASE arms cover every declared
14516            // route, so an OTHER arm here would be a silent catch-all over an
14517            // undeclared route component. Drop it: an unmatched route name now
14518            // becomes a TLC evaluation error (fail closed) instead of a
14519            // fabricated sentinel.
14520        }
14521    }
14522    pushln!(out);
14523    Ok(())
14524}
14525
14526fn tla_ident(value: impl AsRef<str>) -> String {
14527    value
14528        .as_ref()
14529        .chars()
14530        .map(|ch| if ch.is_ascii_alphanumeric() { ch } else { '_' })
14531        .collect()
14532}
14533
14534fn tla_string(value: impl AsRef<str>) -> String {
14535    format!("\"{}\"", value.as_ref().replace('"', "\\\""))
14536}
14537
14538/// Wrap a rendered TLA+ expression in parentheses unless it is already an
14539/// atom (an identifier, field path, number or string, optionally applied with balanced
14540/// `(...)`/`[...]` suffixes, or one parenthesized group), so it can be spliced
14541/// as an operand without TLA+ operator precedence reaching into it.
14542fn tla_delimited(expr: &str) -> String {
14543    if tla_is_atom(expr) {
14544        expr.to_owned()
14545    } else {
14546        format!("({expr})")
14547    }
14548}
14549
14550fn tla_is_atom(expr: &str) -> bool {
14551    let bytes = expr.as_bytes();
14552    let mut index = 0;
14553    match bytes.first() {
14554        Some(b'(') => {}
14555        Some(b'"') => {
14556            index = 1;
14557            while index < bytes.len() && bytes[index] != b'"' {
14558                index += 1;
14559            }
14560            if index >= bytes.len() {
14561                return false;
14562            }
14563            index += 1;
14564        }
14565        Some(byte) if byte.is_ascii_alphanumeric() || *byte == b'_' => {
14566            // Identifiers and record field paths (`packet.payload.run_id`):
14567            // field access binds tighter than every operator.
14568            while index < bytes.len()
14569                && (bytes[index].is_ascii_alphanumeric()
14570                    || bytes[index] == b'_'
14571                    || bytes[index] == b'.')
14572            {
14573                index += 1;
14574            }
14575        }
14576        _ => return false,
14577    }
14578    // Zero or more balanced `(...)` / `[...]` groups, with nothing between.
14579    while index < bytes.len() {
14580        let (open, close) = match bytes[index] {
14581            b'(' => (b'(', b')'),
14582            b'[' => (b'[', b']'),
14583            _ => return false,
14584        };
14585        let mut depth = 0usize;
14586        let mut in_string = false;
14587        let mut end = None;
14588        for (offset, byte) in bytes[index..].iter().enumerate() {
14589            match *byte {
14590                b'"' => in_string = !in_string,
14591                b if b == open && !in_string => depth += 1,
14592                b if b == close && !in_string => {
14593                    depth -= 1;
14594                    if depth == 0 {
14595                        end = Some(index + offset);
14596                        break;
14597                    }
14598                }
14599                _ => {}
14600            }
14601        }
14602        match end {
14603            Some(end) => index = end + 1,
14604            None => return false,
14605        }
14606    }
14607    true
14608}
14609
14610/// The input variant a transition is triggered by, if it is input-triggered.
14611fn trigger_input_variant(transition: &TransitionSchema) -> Option<&str> {
14612    match &transition.on {
14613        TriggerMatch::Input { variant, .. } => Some(variant.as_str()),
14614        _ => None,
14615    }
14616}
14617
14618/// The default unsigned domain extended with declared additional values.
14619fn additional_values_domain(default: &str, values: &BTreeSet<u64>) -> String {
14620    let values = values
14621        .iter()
14622        .map(u64::to_string)
14623        .collect::<Vec<_>>()
14624        .join(", ");
14625    format!("({default} \\cup {{{values}}})")
14626}
14627
14628/// The model constant that a `CiValues` input field ranges over in the
14629/// generated model; each profile's config assigns it.
14630fn input_samples_constant_name(input: &str, field: &str) -> String {
14631    format!("InputSamples_{}_{}", tla_ident(input), tla_ident(field))
14632}
14633
14634/// The samples a `CiValues` input field keeps outside the CI profile (the
14635/// Deep profile and every composition): the declared values together with the
14636/// default unsigned domain (`0..2`).
14637fn broad_input_samples(ci_values: &BTreeSet<u64>) -> BTreeSet<u64> {
14638    (0..=2).chain(ci_values.iter().copied()).collect()
14639}
14640
14641fn render_u64_set(values: &BTreeSet<u64>) -> String {
14642    let values = values
14643        .iter()
14644        .map(u64::to_string)
14645        .collect::<Vec<_>>()
14646        .join(", ");
14647    format!("{{{values}}}")
14648}
14649
14650/// Every `CiValues` input field of a machine, in declaration order: the model
14651/// constant the field ranges over and the values the CI profile assigns it.
14652fn machine_input_sample_constants(schema: &MachineSchema) -> Vec<(String, &BTreeSet<u64>)> {
14653    schema
14654        .input_field_domains
14655        .iter()
14656        .filter_map(|declaration| match &declaration.domain {
14657            meerkat_machine_schema::InputFieldDomainKind::CiValues(values) => Some((
14658                input_samples_constant_name(declaration.input.as_str(), declaration.field.as_str()),
14659                values,
14660            )),
14661            meerkat_machine_schema::InputFieldDomainKind::AdditionalValues(_)
14662            | meerkat_machine_schema::InputFieldDomainKind::StateField(_) => None,
14663        })
14664        .collect()
14665}