Skip to main content

logicaffeine_kernel/
recheck.rs

1//! An independent proof-term re-checker (the de Bruijn criterion taken seriously).
2//!
3//! The kernel's [`infer_type`](crate::infer_type) is the entire trust base. This module
4//! is a SECOND, deliberately separate implementation of the CIC type checker: trust then
5//! rests on two small independent kernels agreeing, not on one. For the independence to
6//! be meaningful the two must not share their checking logic — so this re-checker uses a
7//! DIFFERENT term representation (de Bruijn indices, no names) with its own reduction and
8//! its own cumulative conversion. A variable-capture or substitution bug in the main
9//! kernel's name-based machinery would surface here as a type error rather than slipping
10//! through identically — Logos's analog of `lean4checker`/`nanoda`.
11//!
12//! Scope: the CIC logical core — `Sort`/`Var`/`Global`/`Pi`/`Lambda`/`App`/`Lit` (incl.
13//! `BigInt`/`Nat` literal arithmetic and the Nat↔Peano bridge) with β/ι/ζ/δ-reduction and
14//! cumulative conversion — PLUS the inductive eliminator `Match` (coverage, per-constructor
15//! case typing via de Bruijn telescope instantiation, ι-reduction, large-elimination
16//! restriction) AND both single (`Fix`) and MUTUAL (`MutualFix`) fixpoints, each with an
17//! INDEPENDENT structural-termination guard. Transparent definitions ARE δ-unfolded during
18//! whnf; only axioms/constructors/inductives stay opaque. The only fragment reported
19//! HONESTLY as [`ReCheckError::Unsupported`] — rather than silently passed — is `Hole`
20//! (an unelaborated metavariable) and a `match` on an inductive this checker cannot
21//! resolve: such a proof is single-checked by the main kernel and [`double_check`] says so.
22//! The re-checker never reports a term as independently verified unless it actually
23//! verified every part of it.
24
25use std::collections::HashMap;
26
27use crate::term::{int_lit, lit_bigint, Literal, Term, Universe};
28use crate::Context;
29#[path = "recheck_equality.rs"]
30mod equality;
31#[path = "recheck_storage.rs"]
32mod storage;
33use storage::DbBox;
34#[path = "recheck_definitions.rs"]
35mod definitions;
36
37/// Why the re-checker could not produce a verdict, split by soundness meaning.
38#[derive(Debug, Clone, PartialEq)]
39pub enum ReCheckError {
40    /// No verdict: the re-checker did not finish checking the term. NOT a soundness signal: the
41    /// term is still fully checked by the main kernel, and [`double_check`] flags it as
42    /// single-checked rather than claiming agreement. [`Incomplete::kind`] says why — a construct
43    /// outside the covered fragment, or a resource bound that stopped the check.
44    Unsupported(Incomplete),
45    /// A genuine ill-typedness the re-checker is confident about (a non-function in
46    /// application position, a sort/type mismatch, wrong case count, unbound variable).
47    /// If the main kernel accepted the same term, the two kernels DISAGREE — an alarm.
48    Ill(String),
49}
50
51impl ReCheckError {
52    fn ill(msg: impl Into<String>) -> Self {
53        ReCheckError::Ill(msg.into())
54    }
55    fn unsupported(msg: impl Into<String>) -> Self {
56        ReCheckError::Unsupported(Incomplete {
57            kind: IncompleteKind::Unsupported,
58            message: msg.into(),
59        })
60    }
61    /// The check was stopped by one of this kernel's resource bounds.
62    fn resource_limit(msg: impl Into<String>) -> Self {
63        ReCheckError::Unsupported(Incomplete {
64            kind: IncompleteKind::ResourceLimit {
65                steps: MAX_RECHECK_STEPS,
66                depth: MAX_RECHECK_WHNF_DEPTH,
67                nodes: MAX_RECHECK_TERM_NODES,
68            },
69            message: msg.into(),
70        })
71    }
72    /// The incompleteness, when this is not a refutation.
73    pub fn incomplete(&self) -> Option<&Incomplete> {
74        match self {
75            ReCheckError::Unsupported(incomplete) => Some(incomplete),
76            ReCheckError::Ill(_) => None,
77        }
78    }
79}
80
81/// Why the independent kernel reached no verdict, and its account of the stop.
82///
83/// It reads as the message it carries (`Deref<Target = str>`, and `Debug` prints the message as a
84/// string), so every existing reading of an incompleteness as text is unchanged; the typed
85/// [`IncompleteKind`] is what a consumer decides on.
86#[derive(Clone, PartialEq, Eq)]
87pub struct Incomplete {
88    kind: IncompleteKind,
89    message: String,
90}
91
92/// What stopped the independent kernel.
93#[derive(Debug, Clone, Copy, PartialEq, Eq)]
94pub enum IncompleteKind {
95    /// A construct outside the covered fragment: a `Hole` (an unelaborated metavariable), a
96    /// `match` on an inductive whose head this kernel does not recognize, or a reduction rule of
97    /// the first kernel that this one does not compute. More resources cannot decide it.
98    Unsupported,
99    /// One of this kernel's resource bounds stopped the check before it decided: its reduction
100    /// step budget, its nesting depth, its term size, its share of the native stack, or its input
101    /// admission bounds. The bounds in force are recorded; more of the resource could decide it.
102    ResourceLimit {
103        steps: usize,
104        depth: usize,
105        nodes: usize,
106    },
107}
108
109impl Incomplete {
110    fn unsupported(message: impl Into<String>) -> Self {
111        Incomplete {
112            kind: IncompleteKind::Unsupported,
113            message: message.into(),
114        }
115    }
116    /// The same stop, its account prefixed with where it surfaced.
117    fn prefixed(&self, prefix: impl std::fmt::Display) -> Self {
118        Incomplete {
119            kind: self.kind,
120            message: format!("{prefix}: {}", self.message),
121        }
122    }
123    pub fn kind(&self) -> IncompleteKind {
124        self.kind
125    }
126    pub fn message(&self) -> &str {
127        &self.message
128    }
129    pub fn is_resource_limit(&self) -> bool {
130        matches!(self.kind, IncompleteKind::ResourceLimit { .. })
131    }
132}
133
134impl std::ops::Deref for Incomplete {
135    type Target = str;
136    fn deref(&self) -> &str {
137        &self.message
138    }
139}
140
141impl std::fmt::Display for Incomplete {
142    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
143        f.write_str(&self.message)
144    }
145}
146
147impl std::fmt::Debug for Incomplete {
148    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
149        std::fmt::Debug::fmt(&self.message, f)
150    }
151}
152
153impl From<Incomplete> for String {
154    fn from(incomplete: Incomplete) -> String {
155        incomplete.message
156    }
157}
158
159type RResult<T> = Result<T, ReCheckError>;
160
161/// A locally-nameless term: every bound variable is a de Bruijn INDEX (0 = innermost
162/// binder), so α-equivalence is syntactic identity and there are no names to capture.
163/// This is the independence-bearing representation — distinct from the main kernel's
164/// named [`Term`].
165#[derive(Debug, Clone, PartialEq)]
166enum Db {
167    Sort(Universe),
168    /// de Bruijn index of a `λ`/`Π`-bound variable (0 = nearest enclosing binder).
169    Var(usize),
170    /// A reference into the global environment (inductive, constructor, definition,
171    /// or declaration) — kept opaque.
172    Global(String),
173    /// A universe-polymorphic global at explicit levels — `name.{ℓ…}`.
174    Const {
175        name: String,
176        levels: Vec<Universe>,
177    },
178    /// `Π(_:dom). body` — `body` is one binder deeper than `dom`.
179    Pi(DbBox, DbBox),
180    /// `λ(_:dom). body`.
181    Lam(DbBox, DbBox),
182    App(DbBox, DbBox),
183    /// `match disc return motive with cases` — the node binds nothing itself; each case
184    /// and the motive are `λ`s that introduce their own binders.
185    Match {
186        disc: DbBox,
187        motive: DbBox,
188        cases: Vec<Db>,
189    },
190    /// `fix rec. body` — binds the recursive self-reference (index 0 inside `body`).
191    Fix(FixBody),
192    /// `mutualfix { b₀, …, b_{n-1} }.index` — a block of `n` mutually-recursive bodies.
193    /// ALL `n` names bind in EVERY body: entering a body pushes `n` levels, with def `j`
194    /// at level `base + j` (`base` = enclosing depth). The node reduces to the
195    /// `index`-th body once an argument is constructor-headed.
196    MutualFix {
197        defs: Vec<Db>,
198        index: usize,
199    },
200    /// `let _:ty := value in body` — `body` is one binder deeper than `ty`/`value`.
201    Let(DbBox, DbBox, DbBox),
202    Lit(Literal),
203}
204
205// Optional immutable Fix bodies. No semantic reduction or typing certificate.
206#[derive(Clone, Copy, Default)]
207struct FixFactory {
208    scope: usize,
209    started: bool,
210    remaining: usize,
211    spent: usize,
212}
213thread_local! {
214    static FIX_FACTORY:std::cell::Cell<FixFactory> = const {
215        std::cell::Cell::new(FixFactory {scope:0,started:false,remaining:0,spent:0})
216    };
217    // This ledger is NEVER restored/reset with a prefix scope: Rc owners may escape it.
218    static FIX_SHARED_LIVE:std::cell::Cell<usize> = const {std::cell::Cell::new(0)};
219}
220#[cfg(test)]
221thread_local! {static FIX_BODY_STATS:std::cell::Cell<[usize;6]> = const {std::cell::Cell::new([0;6])};}
222fn fix_body_stat(i: usize) {
223    #[cfg(test)]
224    FIX_BODY_STATS.with(|s| {
225        let mut v = s.get();
226        v[i] += 1;
227        s.set(v);
228    });
229    #[cfg(not(test))]
230    let _ = i;
231}
232fn prefix_combined_fits(prefix: usize) -> bool {
233    FIX_SHARED_LIVE.with(|s| {
234        prefix
235            .checked_add(s.get())
236            .is_some_and(|n| n <= PREFIX_LIVE_BYTES)
237    })
238}
239fn fix_factory_begin() -> bool {
240    FIX_FACTORY.with(|s| {
241        let mut f = s.get();
242        if f.scope == 0 || f.started {
243            return false;
244        }
245        f.started = true;
246        f.remaining = PREFIX_ADMISSION_WORK;
247        f.spent = 0;
248        s.set(f);
249        true
250    })
251}
252fn fix_factory_spend(n: usize) -> Option<()> {
253    let f = FIX_FACTORY.with(|s| s.get());
254    if !f.started || f.scope == 0 || f.remaining < n {
255        return None;
256    }
257    if recheck_budget_active() {
258        if !prefix_work_available(n) || !nat_order_spend(n) {
259            return None;
260        }
261    }
262    FIX_FACTORY.with(|s| {
263        let mut current = s.get();
264        if current.scope != f.scope || !current.started {
265            return None;
266        }
267        current.remaining = current.remaining.checked_sub(n)?;
268        current.spent = current.spent.checked_add(n)?;
269        s.set(current);
270        Some(())
271    })
272}
273struct FixSharedTicket {
274    bytes: usize,
275}
276impl FixSharedTicket {
277    fn new(bytes: usize) -> Option<Self> {
278        FIX_SHARED_LIVE.with(|s| {
279            let live = s.get().checked_add(bytes)?;
280            let prefix = PREFIX_MEMORY.with(|p| p.get().live);
281            if live.checked_add(prefix)? > PREFIX_LIVE_BYTES {
282                return None;
283            }
284            s.set(live);
285            Some(Self { bytes })
286        })
287    }
288}
289impl Drop for FixSharedTicket {
290    fn drop(&mut self) {
291        FIX_SHARED_LIVE.with(|s| {
292            s.set(
293                s.get()
294                    .checked_sub(self.bytes)
295                    .expect("each shared allocation releases its own reservation once"),
296            )
297        });
298    }
299}
300#[derive(Clone, Copy, Debug)]
301struct FixFacts {
302    metrics: PrefixMetrics,
303    required: usize,
304}
305struct AdmittedFixBody {
306    body: Db,
307    facts: FixFacts,
308    generation: usize,
309    _memory: FixSharedTicket,
310}
311enum FixBody {
312    Owned(Box<Db>),
313    Shared(std::rc::Rc<AdmittedFixBody>),
314}
315impl std::fmt::Debug for FixBody {
316    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
317        self.as_ref().fmt(f)
318    }
319}
320#[cfg(test)]
321thread_local! {
322    static OWNED_FIX_CLONES: std::cell::Cell<Option<usize>> = const { std::cell::Cell::new(None) };
323}
324impl Clone for FixBody {
325    fn clone(&self) -> Self {
326        match self {
327            Self::Owned(b) => {
328                #[cfg(test)]
329                OWNED_FIX_CLONES.with(|c| {
330                    if let Some(n) = c.get() {
331                        c.set(Some(n + 1));
332                    }
333                });
334                Self::Owned(b.clone())
335            }
336            Self::Shared(b) => {
337                fix_body_stat(1);
338                Self::Shared(b.clone())
339            }
340        }
341    }
342}
343impl PartialEq for FixBody {
344    fn eq(&self, other: &Self) -> bool {
345        self.same_current(other) || self.as_ref() == other.as_ref()
346    }
347}
348impl std::ops::Deref for FixBody {
349    type Target = Db;
350    fn deref(&self) -> &Db {
351        self.as_ref()
352    }
353}
354impl AsRef<Db> for FixBody {
355    fn as_ref(&self) -> &Db {
356        match self {
357            Self::Owned(b) => b,
358            Self::Shared(b) => &b.body,
359        }
360    }
361}
362impl FixBody {
363    fn into_db(self) -> Db {
364        match self {
365            Self::Owned(body) => *body,
366            Self::Shared(body) => match std::rc::Rc::try_unwrap(body) {
367                Ok(body) => body.body,
368                Err(body) => body.body.clone(),
369            },
370        }
371    }
372    fn owned(body: Box<Db>) -> Self {
373        Self::Owned(body)
374    }
375    fn new(body: Db) -> Self {
376        let Some(facts) = fix_facts(&body) else {
377            return Self::Owned(Box::new(body));
378        };
379        if facts.required > 1 {
380            return Self::Owned(Box::new(body));
381        }
382        // Each immutable allocation reserves only its exclusive storage;
383        // nested shared children keep their own persistent reservations.
384        let memory =
385            storage::exclusive_retained_bytes(&body, std::mem::size_of::<AdmittedFixBody>())
386                .and_then(FixSharedTicket::new);
387        let Some(memory) = memory else {
388            return Self::Owned(Box::new(body));
389        };
390        let generation = FIX_FACTORY.with(|s| s.get().scope);
391        fix_body_stat(0);
392        Self::Shared(std::rc::Rc::new(AdmittedFixBody {
393            body,
394            facts,
395            generation,
396            _memory: memory,
397        }))
398    }
399    fn facts(&self) -> Option<FixFacts> {
400        let Self::Shared(b) = self else {
401            return None;
402        };
403        let f = FIX_FACTORY.with(|s| s.get());
404        (f.started && f.scope != 0 && f.scope == b.generation).then_some(b.facts)
405    }
406    fn same_current(&self, other: &Self) -> bool {
407        match (self, other) {
408            (Self::Shared(a), Self::Shared(b)) => {
409                std::rc::Rc::ptr_eq(a, b) && self.facts().is_some()
410            }
411            _ => false,
412        }
413    }
414    fn shifted(&self, delta: isize, cutoff: usize) -> Self {
415        // Zero shift is unconditional syntax identity, including after the
416        // admission generation expires. It needs no new admission facts.
417        if delta == 0 {
418            #[cfg(test)]
419            if let Self::Owned(body) = self {
420                beta_count_clone(body);
421            }
422            return self.clone();
423        }
424        if self.facts().is_some_and(|s| s.required <= cutoff) {
425            return self.clone();
426        }
427        Self::new(shift(self, delta, cutoff))
428    }
429    fn opened(&self, arg: &Db, depth: usize) -> Self {
430        if self.facts().is_some_and(|s| s.required <= depth) {
431            return self.clone();
432        }
433        Self::new(beta_open_at(self, arg, depth))
434    }
435}
436fn fix_facts(t: &Db) -> Option<FixFacts> {
437    fn bounded(s: &FixFacts) -> bool {
438        let m = s.metrics;
439        m.nodes <= PREFIX_NODES
440            && m.levels <= PREFIX_NODES
441            && m.depth <= PREFIX_DEPTH
442            && m.payload <= 16384
443            && m.bytes <= PREFIX_TREE_BYTES
444    }
445    fn payload(m: &mut PrefixMetrics, s: &String) -> Option<()> {
446        if s.len() > 256 {
447            return None;
448        }
449        fix_factory_spend(s.len().checked_add(1)?)?;
450        m.payload = m.payload.checked_add(s.len())?;
451        m.bytes = m.bytes.checked_add(s.capacity())?;
452        Some(())
453    }
454    fn level(m: &mut PrefixMetrics, u: &Universe, depth: usize) -> Option<()> {
455        fix_factory_spend(1)?;
456        if depth > PREFIX_DEPTH {
457            return None;
458        }
459        m.levels = m.levels.checked_add(1)?;
460        if m.levels > PREFIX_NODES {
461            return None;
462        }
463        m.depth = m.depth.max(depth);
464        match u {
465            Universe::SProp | Universe::Prop | Universe::Type(_) => {}
466            Universe::Var(n) => payload(m, n)?,
467            Universe::Succ(a) => {
468                m.bytes = m.bytes.checked_add(std::mem::size_of::<Universe>())?;
469                level(m, a, depth + 1)?;
470            }
471            Universe::Max(a, b) | Universe::IMax(a, b) => {
472                m.bytes = m.bytes.checked_add(2 * std::mem::size_of::<Universe>())?;
473                level(m, a, depth + 1)?;
474                level(m, b, depth + 1)?;
475            }
476        }
477        (m.payload <= 16384 && m.bytes <= PREFIX_TREE_BYTES).then_some(())
478    }
479    fn merge(out: &mut FixFacts, c: FixFacts, binders: usize, boxed: bool) -> Option<()> {
480        out.metrics.nodes = out.metrics.nodes.checked_add(c.metrics.nodes)?;
481        out.metrics.levels = out.metrics.levels.checked_add(c.metrics.levels)?;
482        out.metrics.depth = out.metrics.depth.max(c.metrics.depth.checked_add(1)?);
483        out.metrics.payload = out.metrics.payload.checked_add(c.metrics.payload)?;
484        let bytes = if boxed {
485            c.metrics.bytes
486        } else {
487            c.metrics.bytes.checked_sub(std::mem::size_of::<Db>())?
488        };
489        out.metrics.bytes = out.metrics.bytes.checked_add(bytes)?;
490        out.required = out.required.max(c.required.saturating_sub(binders));
491        bounded(out).then_some(())
492    }
493    fn child(t: &DbBox, depth: usize) -> Option<FixFacts> {
494        if let Some(facts) = t.facts() {
495            fix_factory_spend(1)?;
496            if depth.checked_sub(1)?.checked_add(facts.metrics.depth)? > PREFIX_DEPTH {
497                return None;
498            }
499            Some(facts)
500        } else {
501            walk(t, depth)
502        }
503    }
504    fn walk(t: &Db, depth: usize) -> Option<FixFacts> {
505        fix_factory_spend(1)?;
506        fix_body_stat(4);
507        if depth > PREFIX_DEPTH {
508            return None;
509        }
510        let mut out = FixFacts {
511            metrics: PrefixMetrics {
512                nodes: 1,
513                depth: 1,
514                bytes: std::mem::size_of::<Db>(),
515                ..PrefixMetrics::default()
516            },
517            required: 0,
518        };
519        match t {
520            Db::Var(i) => out.required = i.checked_add(1)?,
521            Db::Global(n) => payload(&mut out.metrics, n)?,
522            Db::Const { name, levels } => {
523                if levels.len() > PREFIX_NODES {
524                    return None;
525                }
526                payload(&mut out.metrics, name)?;
527                out.metrics.bytes = out.metrics.bytes.checked_add(
528                    levels
529                        .capacity()
530                        .checked_mul(std::mem::size_of::<Universe>())?,
531                )?;
532                for u in levels {
533                    level(&mut out.metrics, u, 2)?;
534                }
535            }
536            Db::Sort(u) => level(&mut out.metrics, u, 2)?,
537            Db::Lit(Literal::Float(_)) => return None,
538            Db::Lit(Literal::Text(s)) => payload(&mut out.metrics, s)?,
539            Db::Lit(Literal::Nat(n)) => {
540                if n.is_negative() || n.to_i64().is_none() {
541                    return None;
542                }
543            }
544            Db::Lit(Literal::BigInt(n)) => {
545                n.to_i64()?;
546            }
547            Db::Lit(_) => {}
548            Db::Pi(a, b) | Db::Lam(a, b) => {
549                merge(&mut out, child(a, depth + 1)?, 0, true)?;
550                merge(&mut out, child(b, depth + 1)?, 1, true)?;
551            }
552            Db::App(a, b) => {
553                merge(&mut out, child(a, depth + 1)?, 0, true)?;
554                merge(&mut out, child(b, depth + 1)?, 0, true)?;
555            }
556            Db::Fix(b) => {
557                let facts = if let Some(f) = b.facts() {
558                    fix_factory_spend(1)?;
559                    f
560                } else {
561                    walk(b, depth + 1)?
562                };
563                merge(&mut out, facts, 1, true)?;
564            }
565            Db::Let(a, b, c) => {
566                merge(&mut out, child(a, depth + 1)?, 0, true)?;
567                merge(&mut out, child(b, depth + 1)?, 0, true)?;
568                merge(&mut out, child(c, depth + 1)?, 1, true)?;
569            }
570            Db::Match {
571                disc,
572                motive,
573                cases,
574            } => {
575                if cases.len() > PREFIX_NODES {
576                    return None;
577                }
578                out.metrics.bytes = out
579                    .metrics
580                    .bytes
581                    .checked_add(cases.capacity().checked_mul(std::mem::size_of::<Db>())?)?;
582                merge(&mut out, child(disc, depth + 1)?, 0, true)?;
583                merge(&mut out, child(motive, depth + 1)?, 0, true)?;
584                for c in cases {
585                    merge(&mut out, walk(c, depth + 1)?, 0, false)?;
586                }
587            }
588            Db::MutualFix { defs, .. } => {
589                if defs.len() > PREFIX_NODES {
590                    return None;
591                }
592                out.metrics.bytes = out
593                    .metrics
594                    .bytes
595                    .checked_add(defs.capacity().checked_mul(std::mem::size_of::<Db>())?)?;
596                for c in defs {
597                    merge(&mut out, walk(c, depth + 1)?, defs.len(), false)?;
598                }
599            }
600        }
601        if !bounded(&out) {
602            return None;
603        }
604        out.metrics.closed = out.required == 0;
605        Some(out)
606    }
607    walk(t, 1)
608}
609
610// ---------------------------------------------------------------------------
611// Named `Term` ⟷ de Bruijn `Db`
612// ---------------------------------------------------------------------------
613
614/// Lower a named [`Term`] to a de Bruijn [`Db`], resolving each `Var` to the index of
615/// its nearest enclosing binder. `scope` holds the binder names, innermost LAST. A
616/// `Var` with no matching binder is a free local — illegal in a closed certificate
617/// term, so it is rejected. `Fix`/`Hole` are outside the covered fragment.
618fn to_db(term: &Term, scope: &mut Vec<String>) -> RResult<Db> {
619    match term {
620        Term::Sort(u) => Ok(Db::Sort(u.clone())),
621        Term::Var(name) => {
622            for (depth_from_inner, bound) in scope.iter().rev().enumerate() {
623                if bound == name {
624                    return Ok(Db::Var(depth_from_inner));
625                }
626            }
627            // A `?`-named free variable is an elaborator METAVARIABLE that was never solved, not
628            // a typo — a different event needing a different repair. The second kernel reaches
629            // the same diagnosis independently (from the shared convention, not from the first
630            // kernel's answer), so `double_check` still reports agreement on the REJECTION.
631            Err(ReCheckError::ill(
632                crate::type_checker::unbound_diagnosis(name)
633                    .unwrap_or_else(|| format!("unbound local variable '{}'", name)),
634            ))
635        }
636        Term::Global(name) => Ok(Db::Global(name.clone())),
637        Term::Const { name, levels } => Ok(Db::Const {
638            name: name.clone(),
639            levels: levels.clone(),
640        }),
641        Term::Pi {
642            param,
643            param_type,
644            body_type,
645        } => {
646            let dom = to_db(param_type, scope)?;
647            scope.push(param.clone());
648            let body = to_db(body_type, scope);
649            scope.pop();
650            Ok(Db::Pi(DbBox::new(dom), DbBox::new(body?)))
651        }
652        Term::Lambda {
653            param,
654            param_type,
655            body,
656        } => {
657            let dom = to_db(param_type, scope)?;
658            scope.push(param.clone());
659            let inner = to_db(body, scope);
660            scope.pop();
661            Ok(Db::Lam(DbBox::new(dom), DbBox::new(inner?)))
662        }
663        Term::App(f, a) => Ok(Db::App(
664            DbBox::new(to_db(f, scope)?),
665            DbBox::new(to_db(a, scope)?),
666        )),
667        Term::Match {
668            discriminant,
669            motive,
670            cases,
671        } => {
672            let disc = to_db(discriminant, scope)?;
673            let mot = to_db(motive, scope)?;
674            let cs = cases
675                .iter()
676                .map(|c| to_db(c, scope))
677                .collect::<RResult<Vec<_>>>()?;
678            Ok(Db::Match {
679                disc: DbBox::new(disc),
680                motive: DbBox::new(mot),
681                cases: cs,
682            })
683        }
684        Term::Fix { name, body } => {
685            scope.push(name.clone());
686            let b = to_db(body, scope);
687            scope.pop();
688            Ok(Db::Fix(FixBody::new(b?)))
689        }
690        // Mutual fixpoint: all `n` names bind in every body, so push all `n` before
691        // converting any body (innermost-last, so def `j` sits at level `base + j`).
692        Term::MutualFix { defs, index } => {
693            let names: Vec<String> = defs.iter().map(|(n, _)| n.clone()).collect();
694            for n in &names {
695                scope.push(n.clone());
696            }
697            let mut dbs = Vec::with_capacity(defs.len());
698            let mut err = None;
699            for (_, body) in defs {
700                match to_db(body, scope) {
701                    Ok(d) => dbs.push(d),
702                    Err(e) => {
703                        err = Some(e);
704                        break;
705                    }
706                }
707            }
708            for _ in &names {
709                scope.pop();
710            }
711            match err {
712                Some(e) => Err(e),
713                None => Ok(Db::MutualFix {
714                    defs: dbs,
715                    index: *index,
716                }),
717            }
718        }
719        Term::Let {
720            name,
721            ty,
722            value,
723            body,
724        } => {
725            let d_ty = to_db(ty, scope)?;
726            let d_val = to_db(value, scope)?;
727            scope.push(name.clone());
728            let d_body = to_db(body, scope);
729            scope.pop();
730            Ok(Db::Let(
731                DbBox::new(d_ty),
732                DbBox::new(d_val),
733                DbBox::new(d_body?),
734            ))
735        }
736        Term::Lit(l) => Ok(Db::Lit(l.clone())),
737        Term::Hole => Err(ReCheckError::unsupported("Hole (unelaborated implicit)")),
738        // `Db` is kernel meaning and has no annotation: this kernel erases its own, at the one
739        // boundary every term it checks crosses.
740        Term::Annotated { term, .. } => to_db(term, scope),
741    }
742}
743
744/// Raise a de Bruijn [`Db`] back to a named [`Term`], naming binders `v{depth}` by their
745/// binding depth (used only to report an inferred type back; comparisons stay in
746/// de Bruijn).
747fn from_db(t: &Db, depth: usize) -> Term {
748    from_db_with_external(t, depth, &[])
749}
750
751// External levels retain their exact names. Internal names use the existing vN
752// spelling unless it could capture an external local; distinct levels still
753// have distinct numeric stems. Own domains are raised before entering a binder.
754fn raised_name(level: usize, external: &[String]) -> String {
755    if let Some(name) = external.get(level) {
756        return name.clone();
757    }
758    let mut name = format!("v{level}");
759    while external.iter().any(|outer| outer == &name) {
760        name.push('_');
761    }
762    name
763}
764
765#[cfg(test)]
766thread_local! {
767    static RAISED_DB_NODES: std::cell::Cell<Option<usize>> = const { std::cell::Cell::new(None) };
768}
769fn from_db_with_external(t: &Db, depth: usize, external: &[String]) -> Term {
770    #[cfg(test)]
771    RAISED_DB_NODES.with(|c| {
772        if let Some(n) = c.get() {
773            c.set(Some(n + 1));
774        }
775    });
776    match t {
777        Db::Sort(u) => Term::Sort(u.clone()),
778        Db::Var(k) => {
779            let binder = depth.saturating_sub(1).saturating_sub(*k);
780            Term::Var(raised_name(binder, external))
781        }
782        Db::Global(n) => Term::Global(n.clone()),
783        Db::Const { name, levels } => Term::Const {
784            name: name.clone(),
785            levels: levels.clone(),
786        },
787        Db::Pi(a, b) => Term::Pi {
788            param: raised_name(depth, external),
789            param_type: Box::new(from_db_with_external(a, depth, external)),
790            body_type: Box::new(from_db_with_external(b, depth + 1, external)),
791        },
792        Db::Lam(a, b) => Term::Lambda {
793            param: raised_name(depth, external),
794            param_type: Box::new(from_db_with_external(a, depth, external)),
795            body: Box::new(from_db_with_external(b, depth + 1, external)),
796        },
797        Db::App(f, a) => Term::App(
798            Box::new(from_db_with_external(f, depth, external)),
799            Box::new(from_db_with_external(a, depth, external)),
800        ),
801        Db::Match {
802            disc,
803            motive,
804            cases,
805        } => Term::Match {
806            discriminant: Box::new(from_db_with_external(disc, depth, external)),
807            motive: Box::new(from_db_with_external(motive, depth, external)),
808            cases: cases
809                .iter()
810                .map(|c| from_db_with_external(c, depth, external))
811                .collect(),
812        },
813        // A `Fix` binder occupies ONE de Bruijn level, exactly as a `λ` does — `to_db` pushes
814        // its name onto the same scope stack — so it must be named by the SAME scheme its own
815        // bound occurrences get. Naming it anything else (it used to be `rec{depth}`) leaves
816        // the recursive self-reference reconstructed as `v{depth}`, a variable NOTHING binds:
817        // `to_db` then refuses the round trip, and `double_check` reports "inferred type
818        // outside re-checker fragment" for every type that mentions a fixpoint.
819        Db::Fix(body) => Term::Fix {
820            name: raised_name(depth, external),
821            body: Box::new(from_db_with_external(body, depth + 1, external)),
822        },
823        // The same rule for a mutual block: all `n` names bind in every body, innermost-LAST,
824        // so def `j` sits at level `depth + j` and its occurrences reconstruct as `v{depth+j}`.
825        Db::MutualFix { defs, index } => {
826            let n = defs.len();
827            Term::MutualFix {
828                defs: defs
829                    .iter()
830                    .enumerate()
831                    .map(|(j, b)| {
832                        (
833                            raised_name(depth + j, external),
834                            from_db_with_external(b, depth + n, external),
835                        )
836                    })
837                    .collect(),
838                index: *index,
839            }
840        }
841        Db::Let(ty, value, body) => Term::Let {
842            name: raised_name(depth, external),
843            ty: Box::new(from_db_with_external(ty, depth, external)),
844            value: Box::new(from_db_with_external(value, depth, external)),
845            body: Box::new(from_db_with_external(body, depth + 1, external)),
846        },
847        Db::Lit(l) => Term::Lit(l.clone()),
848    }
849}
850
851// ---------------------------------------------------------------------------
852// de Bruijn shifting and substitution (the capture-free core)
853// ---------------------------------------------------------------------------
854
855#[cfg(test)]
856thread_local! {
857    // Counts visited source nodes and constructed output Db nodes, including subtree clones.
858    static BETA_WORK: std::cell::Cell<Option<(usize, usize)>> = const {
859        std::cell::Cell::new(None)
860    };
861    static MOTIVE_CHECKS: std::cell::Cell<Option<usize>> = const {
862        std::cell::Cell::new(None)
863    };
864    static K_PROBE_ATTEMPTS: std::cell::Cell<Option<usize>> = const {
865        std::cell::Cell::new(None)
866    };
867}
868
869#[cfg(test)]
870fn beta_count_work(constructed: usize) {
871    BETA_WORK.with(|work| {
872        if let Some((visits, copies)) = work.get() {
873            work.set(Some((visits + 1, copies + constructed)));
874        }
875    });
876}
877
878/// Account for actual Db construction by Clone, not unfolded logical size.
879/// This extra walk exists only while a test explicitly enables BETA_WORK.
880#[cfg(test)]
881fn beta_count_clone(t: &Db) {
882    fn edge(t: &DbBox) -> usize {
883        match t {
884            DbBox::Owned(t) => count(t),
885            DbBox::Shared(_) => 0,
886        }
887    }
888    fn count(t: &Db) -> usize {
889        1 + match t {
890            Db::Pi(a, b) | Db::Lam(a, b) | Db::App(a, b) => edge(a) + edge(b),
891            Db::Let(a, b, c) => edge(a) + edge(b) + edge(c),
892            Db::Match {
893                disc,
894                motive,
895                cases,
896            } => edge(disc) + edge(motive) + cases.iter().map(count).sum::<usize>(),
897            Db::Fix(body) => match body {
898                FixBody::Owned(t) => count(t),
899                FixBody::Shared(_) => 0,
900            },
901            Db::MutualFix { defs, .. } => defs.iter().map(count).sum(),
902            _ => 0,
903        }
904    }
905    BETA_WORK.with(|work| {
906        if let Some((visits, copies)) = work.get() {
907            let nodes = count(t);
908            work.set(Some((visits + nodes, copies + nodes)));
909        }
910    });
911}
912
913#[cfg(test)]
914fn db_node_count(t: &Db) -> usize {
915    match t {
916        Db::Pi(a, b) | Db::Lam(a, b) | Db::App(a, b) => 1 + db_node_count(a) + db_node_count(b),
917        Db::Let(a, b, c) => 1 + db_node_count(a) + db_node_count(b) + db_node_count(c),
918        Db::Fix(b) => 1 + db_node_count(b),
919        Db::MutualFix { defs, .. } => 1 + defs.iter().map(db_node_count).sum::<usize>(),
920        Db::Match {
921            disc,
922            motive,
923            cases,
924        } => {
925            1 + db_node_count(disc)
926                + db_node_count(motive)
927                + cases.iter().map(db_node_count).sum::<usize>()
928        }
929        _ => 1,
930    }
931}
932
933/// Shift every free index `≥ cutoff` by `d` (which may be negative). Binders raise the
934/// cutoff so bound indices are untouched (the classic TAPL shift).
935fn shift(t: &Db, d: isize, cutoff: usize) -> Db {
936    // No binder or index can change when the offset is zero. Clone retains
937    // immutable child allocations without consulting their admission epoch.
938    if d == 0 {
939        #[cfg(test)]
940        beta_count_clone(t);
941        return t.clone();
942    }
943    #[cfg(test)]
944    beta_count_work(1);
945    match t {
946        Db::Var(k) => {
947            if *k >= cutoff {
948                Db::Var((*k as isize + d) as usize)
949            } else {
950                Db::Var(*k)
951            }
952        }
953        Db::Pi(a, b) => Db::Pi(a.shifted(d, cutoff), b.shifted(d, cutoff + 1)),
954        Db::Lam(a, b) => Db::Lam(a.shifted(d, cutoff), b.shifted(d, cutoff + 1)),
955        Db::App(f, a) => Db::App(f.shifted(d, cutoff), a.shifted(d, cutoff)),
956        Db::Match {
957            disc,
958            motive,
959            cases,
960        } => Db::Match {
961            disc: disc.shifted(d, cutoff),
962            motive: motive.shifted(d, cutoff),
963            cases: cases.iter().map(|c| shift(c, d, cutoff)).collect(),
964        },
965        Db::Fix(body) => Db::Fix(body.shifted(d, cutoff + 1)),
966        Db::MutualFix { defs, index } => Db::MutualFix {
967            // Every body lives beneath ALL `n` mutual binders, so the cutoff rises by `n`.
968            defs: defs
969                .iter()
970                .map(|b| shift(b, d, cutoff + defs.len()))
971                .collect(),
972            index: *index,
973        },
974        Db::Let(ty, value, body) => Db::Let(
975            ty.shifted(d, cutoff),
976            value.shifted(d, cutoff),
977            body.shifted(d, cutoff + 1),
978        ),
979        Db::Sort(_) | Db::Global(_) | Db::Const { .. } | Db::Lit(_) => t.clone(),
980    }
981}
982
983/// Substitute the variable with index `j` by `s` (capture-free: `s` is shifted as it
984/// descends under binders, `j` rises in step).
985#[cfg(test)]
986fn subst(t: &Db, j: usize, s: &Db) -> Db {
987    #[cfg(test)]
988    beta_count_work(if matches!(t, Db::Var(k) if *k == j) {
989        db_node_count(s)
990    } else {
991        1
992    });
993    match t {
994        Db::Var(k) => {
995            if *k == j {
996                s.clone()
997            } else {
998                Db::Var(*k)
999            }
1000        }
1001        Db::Pi(a, b) => Db::Pi(
1002            DbBox::new(subst(a, j, s)),
1003            DbBox::new(subst(b, j + 1, &shift(s, 1, 0))),
1004        ),
1005        Db::Lam(a, b) => Db::Lam(
1006            DbBox::new(subst(a, j, s)),
1007            DbBox::new(subst(b, j + 1, &shift(s, 1, 0))),
1008        ),
1009        Db::App(f, a) => Db::App(DbBox::new(subst(f, j, s)), DbBox::new(subst(a, j, s))),
1010        Db::Match {
1011            disc,
1012            motive,
1013            cases,
1014        } => Db::Match {
1015            disc: DbBox::new(subst(disc, j, s)),
1016            motive: DbBox::new(subst(motive, j, s)),
1017            cases: cases.iter().map(|c| subst(c, j, s)).collect(),
1018        },
1019        Db::Fix(body) => Db::Fix(FixBody::new(subst(body, j + 1, &shift(s, 1, 0)))),
1020        Db::MutualFix { defs, index } => {
1021            // Under `n` mutual binders: the substituted index rises by `n` and `s` is
1022            // shifted by `n` to keep its free variables aligned.
1023            let n = defs.len();
1024            Db::MutualFix {
1025                defs: defs
1026                    .iter()
1027                    .map(|b| subst(b, j + n, &shift(s, n as isize, 0)))
1028                    .collect(),
1029                index: *index,
1030            }
1031        }
1032        Db::Let(ty, value, body) => Db::Let(
1033            DbBox::new(subst(ty, j, s)),
1034            DbBox::new(subst(value, j, s)),
1035            DbBox::new(subst(body, j + 1, &shift(s, 1, 0))),
1036        ),
1037        Db::Sort(_) | Db::Global(_) | Db::Const { .. } | Db::Lit(_) => t.clone(),
1038    }
1039}
1040
1041/// β-substitution of the argument into a binder body: `(λ. body) arg ⤳ body[0 := arg]`.
1042fn beta_open(body: &Db, arg: &Db) -> Db {
1043    beta_open_at(body, arg, 0)
1044}
1045
1046/// Fuse the initial argument shift, substitution, and final binder removal.
1047/// At depth d, index d names the opened binder; larger indices lose that binder,
1048/// while smaller indices belong to binders encountered inside the body. Shift
1049/// the argument only at occurrences, so unused arguments require no traversal.
1050fn beta_open_at(body: &Db, arg: &Db, depth: usize) -> Db {
1051    #[cfg(test)]
1052    beta_count_work(usize::from(!matches!(body, Db::Var(k) if *k == depth)));
1053    match body {
1054        Db::Var(k) if *k == depth => shift(arg, depth as isize, 0),
1055        Db::Var(k) if *k > depth => Db::Var(k - 1),
1056        Db::Var(k) => Db::Var(*k),
1057        Db::Pi(a, b) => Db::Pi(a.opened(arg, depth), b.opened(arg, depth + 1)),
1058        Db::Lam(a, b) => Db::Lam(a.opened(arg, depth), b.opened(arg, depth + 1)),
1059        Db::App(f, a) => Db::App(f.opened(arg, depth), a.opened(arg, depth)),
1060        Db::Match {
1061            disc,
1062            motive,
1063            cases,
1064        } => Db::Match {
1065            disc: disc.opened(arg, depth),
1066            motive: motive.opened(arg, depth),
1067            cases: cases.iter().map(|c| beta_open_at(c, arg, depth)).collect(),
1068        },
1069        Db::Fix(body) => Db::Fix(body.opened(arg, depth + 1)),
1070        Db::MutualFix { defs, index } => Db::MutualFix {
1071            defs: defs
1072                .iter()
1073                .map(|b| beta_open_at(b, arg, depth + defs.len()))
1074                .collect(),
1075            index: *index,
1076        },
1077        Db::Let(ty, value, body) => Db::Let(
1078            ty.opened(arg, depth),
1079            value.opened(arg, depth),
1080            body.opened(arg, depth + 1),
1081        ),
1082        Db::Sort(_) | Db::Global(_) | Db::Const { .. } | Db::Lit(_) => body.clone(),
1083    }
1084}
1085
1086/// Unfold the `index`-th body of a mutual block: replace each of the `n` mutual names by
1087/// its own `MutualFix` projection and drop the `n` binders. The mutual analog of
1088/// `beta_open` — the innermost binder (index 0) is name `n-1`, so it receives projection
1089/// `n-1`, down to name `0`.
1090///
1091/// A projection is NOT closed in general: a recursor applied to motives and minors that
1092/// mention local variables yields a block whose bodies refer to them. The projection lives
1093/// in the block's OUTER context, while the binder opened at step `k` still sits under the
1094/// `n-1-k` mutual binders not yet opened, so the projection is shifted over exactly those
1095/// before it is substituted. Without the shift its free variables would name the wrong
1096/// binders.
1097fn open_mutual(defs: &[Db], index: usize) -> Db {
1098    let n = defs.len();
1099    let mut result = defs[index].clone();
1100    for k in 0..n {
1101        let proj = Db::MutualFix {
1102            defs: defs.to_vec(),
1103            index: n - 1 - k,
1104        };
1105        result = beta_open(&result, &shift(&proj, (n - 1 - k) as isize, 0));
1106    }
1107    result
1108}
1109
1110/// Decompose an application spine into its head and arguments (in source order).
1111fn spine(t: &Db) -> (Db, Vec<Db>) {
1112    let mut args = Vec::new();
1113    let mut cur = t.clone();
1114    while let Db::App(f, a) = cur {
1115        args.push(a.into_db());
1116        cur = f.into_db();
1117    }
1118    args.reverse();
1119    (cur, args)
1120}
1121
1122/// Whether `t` reduces to an application headed by a constructor — the guard that lets a
1123/// fixpoint unfold (its decreasing argument is a value) without risking a loop.
1124/// Whether the re-checker's fix-unfolding guard sees a constructor application.
1125///
1126/// A `Nat` LITERAL is morally one — `Nat(0)` IS `Zero` and `Nat(n)` IS `Succ (n-1)`, and this
1127/// kernel's `Match` arm already expands it that way — so admitting it here closes a real
1128/// `double_check` disagreement: a structural recursion over a literal is stuck HERE while it
1129/// computes in the main kernel, which leaves proofs resting on `decide (2 = 2) ⤳ true`
1130/// single-kernel-verified. The one-clause fix is written out below and is NOT enabled, because
1131/// it trades a safe-direction disagreement for an UNSAFE one: once the guard lets go, the
1132/// re-checker actually runs the recursion, and a string-as-character-list recursion over a
1133/// literal overflows the native stack and ABORTS THE PROCESS. It is blocked on the same stack
1134/// residue as the depth door in `type_checker.rs` — a larger kernel stack, not a clause here.
1135///
1136/// ```text
1137/// if matches!(whnf(genv, t), Db::Lit(Literal::Nat(_))) { return true; }
1138/// ```
1139fn ctor_headed(genv: &Context, t: &Db) -> bool {
1140    constructor_value(genv, &whnf(genv, t))
1141}
1142
1143/// Constructor admission on an already computed independent weak-head value.
1144fn constructor_value(genv: &Context, reduced: &Db) -> bool {
1145    if db_int_constructor(genv, reduced).is_some() {
1146        return true;
1147    }
1148    // A `Nat` LITERAL is a constructor application: `Nat(0)` IS `Zero` and `Nat(n)` IS
1149    // `Succ (n-1)`. This kernel's `Match` arm and `def_eq` already bridge the two, so refusing
1150    // it HERE is the one place the bridge was missing — and it made every structural recursion
1151    // over a literal stuck in this kernel while it computed in the main one, which reports as a
1152    // `double_check` DISAGREEMENT on a term the main kernel is right to accept. Enabling it is
1153    // safe only because `whnf` is now BOUNDED (step budget + depth door, the same discipline
1154    // `reduction::normalize_checked` gives the main kernel): the guard letting go means the
1155    // recursion actually runs, and an unbounded reducer running it aborts the process.
1156    if matches!(reduced, Db::Lit(Literal::Nat(_))) {
1157        return true;
1158    }
1159    matches!(spine_head(reduced), Db::Global(n) | Db::Const { name: n, .. } if genv.is_constructor(n))
1160}
1161
1162// ---------------------------------------------------------------------------
1163// Universe-polymorphic references — this kernel's own lookup over the SHARED spec
1164// ---------------------------------------------------------------------------
1165
1166/// A name's DECLARED universe parameters (present only where a declaration STATED one) and its
1167/// stored type. The registries are consulted in order, never merged: `get_global` must not see a
1168/// universe-polymorphic definition.
1169///
1170/// [`Context::poly_declaration`] answers for a polymorphic TYPE declaration (a body-less
1171/// inductive, structure or class) and for a polymorphic DEFINITION alike, so this kernel and the
1172/// main one cannot come to disagree about which constants carry a level telescope. The stated
1173/// list is what gets zipped: see the main kernel's `lookup_const` for why a telescope DERIVED
1174/// from the stored type silently exchanges the parameters of a declaration whose arity mentions
1175/// them out of order — a wrong answer both kernels reach identically, which is the one shape
1176/// `double_check` cannot see.
1177fn const_declaration<'a>(
1178    genv: &'a Context,
1179    name: &str,
1180) -> Option<(Option<&'a [String]>, &'a Term)> {
1181    if let Some((params, ty)) = genv.poly_declaration(name) {
1182        return Some((Some(params), ty));
1183    }
1184    // A monomorphic declaration has no level telescope, so `name.{}` is NOT a second spelling of
1185    // `Global(name)` — see the main kernel's `lookup_const` for the argument and the lock.
1186    let ty = genv.get_global(name)?;
1187    if !db_mentions_level_term(ty) {
1188        return None;
1189    }
1190    Some((None, ty))
1191}
1192
1193/// Whether a named type mentions a free universe variable — the telescope test `const_declaration`
1194/// gates on, written over `Term` because that is what the environment stores.
1195fn db_mentions_level_term(ty: &Term) -> bool {
1196    crate::term::mentions_level_var(ty)
1197}
1198
1199#[cfg(test)]
1200thread_local! {
1201    static DEFINITION_LOWERINGS:std::cell::Cell<Option<usize>> = const {std::cell::Cell::new(None)};
1202}
1203fn definition_lowered() {
1204    #[cfg(test)]
1205    DEFINITION_LOWERINGS.with(|s| {
1206        if let Some(n) = s.get() {
1207            s.set(Some(n + 1));
1208        }
1209    });
1210}
1211/// The δ-reduct of `name.{levels}` — its body with the universe parameters instantiated — or
1212/// `None` when there is no body (a polymorphic inductive, constructor or axiom is a VALUE) or
1213/// the reference is ill-formed (in which case it is inert here and refused by `infer`).
1214fn definition_body(genv: &Context, name: &str) -> Option<Db> {
1215    let body = genv.get_definition_body(name)?;
1216    definitions::lower(genv, body, None, || {
1217        definition_lowered();
1218        to_db(body, &mut Vec::new()).ok()
1219    })
1220}
1221
1222fn const_body(genv: &Context, name: &str, levels: &[Universe]) -> Option<Db> {
1223    let (declared, ty, body) = match genv.get_universe_poly(name) {
1224        Some((params, ty, body)) => (Some(params.as_slice()), ty, body),
1225        None => {
1226            let ty = genv.get_global(name)?;
1227            if !db_mentions_level_term(ty) {
1228                return None;
1229            }
1230            (None, ty, genv.get_definition_body(name)?)
1231        }
1232    };
1233    let subst = crate::term::resolve_const_levels(name, declared, ty, levels).ok()?;
1234    definitions::lower(genv, body, Some(levels), || {
1235        definition_lowered();
1236        to_db(
1237            &crate::term::instantiate_universes(body, &subst),
1238            &mut Vec::new(),
1239        )
1240        .ok()
1241    })
1242}
1243
1244/// The free universe variables of a de Bruijn term, first-occurrence order — this kernel's own
1245/// walk, over the same definition `term::free_level_vars` states.
1246fn db_level_vars(t: &Db, out: &mut Vec<String>) {
1247    let push = |u: &Universe, out: &mut Vec<String>| {
1248        for v in crate::term::free_level_vars(&Term::Sort(u.clone())) {
1249            if !out.iter().any(|x| *x == v) {
1250                out.push(v);
1251            }
1252        }
1253    };
1254    match t {
1255        Db::Sort(u) => push(u, out),
1256        Db::Var(_) | Db::Global(_) | Db::Lit(_) => {}
1257        Db::Const { levels, .. } => {
1258            for l in levels {
1259                push(l, out);
1260            }
1261        }
1262        Db::Pi(a, b) | Db::Lam(a, b) | Db::App(a, b) => {
1263            db_level_vars(a, out);
1264            db_level_vars(b, out);
1265        }
1266        Db::Match {
1267            disc,
1268            motive,
1269            cases,
1270        } => {
1271            db_level_vars(disc, out);
1272            db_level_vars(motive, out);
1273            for c in cases {
1274                db_level_vars(c, out);
1275            }
1276        }
1277        Db::Fix(b) => db_level_vars(b, out),
1278        Db::MutualFix { defs, .. } => {
1279            for d in defs {
1280                db_level_vars(d, out);
1281            }
1282        }
1283        Db::Let(a, b, c) => {
1284            db_level_vars(a, out);
1285            db_level_vars(b, out);
1286            db_level_vars(c, out);
1287        }
1288    }
1289}
1290
1291/// Whether a de Bruijn term mentions a universe variable satisfying `pred` — recursive,
1292/// short-circuiting and ALLOCATION-FREE. The guard in front of `db_level_params`: the application
1293/// rule asks this at every node, almost always about a monomorphic declaration, so learning "no"
1294/// must cost nothing — not a `Vec`, and certainly not a cloned `Universe` per `Sort`.
1295fn db_mentions_level(t: &Db, pred: &dyn Fn(&str) -> bool) -> bool {
1296    match t {
1297        Db::Sort(u) => crate::term::universe_mentions(u, pred),
1298        Db::Var(_) | Db::Global(_) | Db::Lit(_) => false,
1299        Db::Const { levels, .. } => levels
1300            .iter()
1301            .any(|l| crate::term::universe_mentions(l, pred)),
1302        Db::Pi(a, b) | Db::Lam(a, b) | Db::App(a, b) => {
1303            db_mentions_level(a, pred) || db_mentions_level(b, pred)
1304        }
1305        Db::Match {
1306            disc,
1307            motive,
1308            cases,
1309        } => {
1310            db_mentions_level(disc, pred)
1311                || db_mentions_level(motive, pred)
1312                || cases.iter().any(|c| db_mentions_level(c, pred))
1313        }
1314        Db::Fix(b) => db_mentions_level(b, pred),
1315        Db::MutualFix { defs, .. } => defs.iter().any(|d| db_mentions_level(d, pred)),
1316        Db::Let(a, b, c) => {
1317            db_mentions_level(a, pred) || db_mentions_level(b, pred) || db_mentions_level(c, pred)
1318        }
1319    }
1320}
1321
1322/// The free universe variables of a de Bruijn term, first-occurrence order.
1323fn db_level_params(t: &Db) -> Vec<String> {
1324    let mut out = Vec::new();
1325    db_level_vars(t, &mut out);
1326    out
1327}
1328
1329/// Substitute universe variables throughout a de Bruijn term.
1330fn db_instantiate_universes(t: &Db, subst: &HashMap<String, Universe>) -> Db {
1331    match t {
1332        Db::Sort(u) => Db::Sort(u.substitute(subst)),
1333        Db::Var(k) => Db::Var(*k),
1334        Db::Global(n) => Db::Global(n.clone()),
1335        Db::Lit(l) => Db::Lit(l.clone()),
1336        Db::Const { name, levels } => Db::Const {
1337            name: name.clone(),
1338            levels: levels.iter().map(|l| l.substitute(subst)).collect(),
1339        },
1340        Db::Pi(a, b) => Db::Pi(
1341            DbBox::new(db_instantiate_universes(a, subst)),
1342            DbBox::new(db_instantiate_universes(b, subst)),
1343        ),
1344        Db::Lam(a, b) => Db::Lam(
1345            DbBox::new(db_instantiate_universes(a, subst)),
1346            DbBox::new(db_instantiate_universes(b, subst)),
1347        ),
1348        Db::App(a, b) => Db::App(
1349            DbBox::new(db_instantiate_universes(a, subst)),
1350            DbBox::new(db_instantiate_universes(b, subst)),
1351        ),
1352        Db::Match {
1353            disc,
1354            motive,
1355            cases,
1356        } => Db::Match {
1357            disc: DbBox::new(db_instantiate_universes(disc, subst)),
1358            motive: DbBox::new(db_instantiate_universes(motive, subst)),
1359            cases: cases
1360                .iter()
1361                .map(|c| db_instantiate_universes(c, subst))
1362                .collect(),
1363        },
1364        Db::Fix(b) => Db::Fix(FixBody::new(db_instantiate_universes(b, subst))),
1365        Db::MutualFix { defs, index } => Db::MutualFix {
1366            defs: defs
1367                .iter()
1368                .map(|d| db_instantiate_universes(d, subst))
1369                .collect(),
1370            index: *index,
1371        },
1372        Db::Let(a, b, c) => Db::Let(
1373            DbBox::new(db_instantiate_universes(a, subst)),
1374            DbBox::new(db_instantiate_universes(b, subst)),
1375            DbBox::new(db_instantiate_universes(c, subst)),
1376        ),
1377    }
1378}
1379
1380/// Solve the level metavariables of an application's domain from the argument's actual type
1381/// (the shared specification's rule 4), and propagate the solution into the codomain.
1382///
1383/// A domain with no metavariables is returned untouched, so the ordinary path never pays for
1384/// this. Choosing an instantiation is not accepting one: `check` still runs afterwards.
1385fn solve_domain_levels(
1386    genv: &Context,
1387    lctx: &dyn LocalTypes,
1388    dom: &Db,
1389    body: &Db,
1390    arg: &Db,
1391) -> (Db, Db) {
1392    match db_domain_level_solution(genv, lctx, dom, arg) {
1393        Some(subst) => (
1394            db_instantiate_universes(dom, &subst),
1395            db_instantiate_universes(body, &subst),
1396        ),
1397        None => (dom.clone(), body.clone()),
1398    }
1399}
1400
1401/// The levels `arg` solves for the metavariables of the domain `dom` — this kernel's application
1402/// rule's one decision, applied by [`solve_domain_levels_owned`] and recorded by
1403/// `db_implicit_instance_levels`. `None` when the domain has no metavariables, the argument has
1404/// no type, or nothing was solved.
1405fn db_domain_level_solution(
1406    genv: &Context,
1407    lctx: &dyn LocalTypes,
1408    dom: &Db,
1409    arg: &Db,
1410) -> Option<HashMap<String, Universe>> {
1411    if !db_mentions_level(dom, &|v| crate::term::is_level_meta(v)) {
1412        return None;
1413    }
1414    let arg_ty = whnf_in(genv, lctx, &infer(genv, lctx, arg).ok()?);
1415    let mut subst = HashMap::new();
1416    db_unify_levels(dom, &arg_ty, &mut subst);
1417    (!subst.is_empty()).then_some(subst)
1418}
1419
1420/// A bare reference to a universe-polymorphic declaration carries no levels, so at its
1421/// application they become fresh metavariables — the one place with an argument to solve them
1422/// from. Restricted to a bare `Db::Global` head for the same reason as in the main kernel: a
1423/// level variable anywhere else is bound by its own declaration.
1424fn db_implicit_levels_for_head(f: &Db, f_ty: Db) -> Db {
1425    match f {
1426        Db::Global(name) if db_mentions_level(&f_ty, &|_| true) => {
1427            let params = db_level_params(&f_ty);
1428            if params.is_empty() {
1429                f_ty
1430            } else {
1431                db_instantiate_universes(&f_ty, &crate::term::fresh_level_metas(name, &params))
1432            }
1433        }
1434        _ => f_ty,
1435    }
1436}
1437
1438/// The de Bruijn half of level unification: match a pattern type (which may carry
1439/// metavariables) against an actual one, solving bare metavariables only.
1440fn db_unify_levels(pattern: &Db, actual: &Db, subst: &mut HashMap<String, Universe>) {
1441    match (pattern, actual) {
1442        (Db::Sort(p), Db::Sort(a)) => {
1443            crate::term::unify_levels(&Term::Sort(p.clone()), &Term::Sort(a.clone()), subst);
1444        }
1445        (Db::Pi(p1, p2), Db::Pi(a1, a2))
1446        | (Db::Lam(p1, p2), Db::Lam(a1, a2))
1447        | (Db::App(p1, p2), Db::App(a1, a2)) => {
1448            db_unify_levels(p1, a1, subst);
1449            db_unify_levels(p2, a2, subst);
1450        }
1451        (
1452            Db::Const {
1453                name: n1,
1454                levels: l1,
1455            },
1456            Db::Const {
1457                name: n2,
1458                levels: l2,
1459            },
1460        ) if n1 == n2 && l1.len() == l2.len() => {
1461            for (p, a) in l1.iter().zip(l2.iter()) {
1462                crate::term::unify_levels(&Term::Sort(p.clone()), &Term::Sort(a.clone()), subst);
1463            }
1464        }
1465        _ => {}
1466    }
1467}
1468
1469/// An application spine's HEAD alone — no vector, no clones. The cheapest possible question, and
1470/// the one the fix guard asks at every reduction step.
1471fn spine_head(t: &Db) -> &Db {
1472    let mut cur = t;
1473    while let Db::App(f, _) = cur {
1474        cur = f.as_ref();
1475    }
1476    cur
1477}
1478
1479/// An application spine's head and arguments BY REFERENCE, in source order — the non-cloning
1480/// counterpart of [`spine`], for the hot pre-checks that only need to look.
1481fn spine_ref(t: &Db) -> (&Db, Vec<&Db>) {
1482    let mut args = Vec::new();
1483    let mut cur = t;
1484    while let Db::App(f, a) = cur {
1485        args.push(a.as_ref());
1486        cur = f.as_ref();
1487    }
1488    args.reverse();
1489    (cur, args)
1490}
1491
1492// Optional per-check sharing of independently observed closed Nat prefixes.
1493// No evaluator result or Context state is shared with the main checker.
1494const PREFIX_SLOTS: usize = 4;
1495const PREFIX_NODES: usize = 2048;
1496const PREFIX_DEPTH: usize = 64;
1497const PREFIX_TREE_BYTES: usize = 128 * 1024;
1498const PREFIX_LIVE_BYTES: usize = 512 * 1024;
1499const PREFIX_PENDING: usize = 196;
1500fn prefix_reuse_enabled() -> bool {
1501    true
1502}
1503// Bounds cover every node/level/payload operation in the optional helpers.
1504// They are availability guards, not debits/refunds: actual operations debit fuel.
1505const PREFIX_ADMISSION_WORK: usize = 8 * (2 * PREFIX_NODES) + 16384 + 2;
1506const PREFIX_COPY_WORK: usize = 3 * (2 * PREFIX_NODES) + 16384;
1507fn prefix_work_available(work: usize) -> bool {
1508    !WHNF_EXHAUSTED.with(|v| v.get()) && WHNF_FUEL.with(|v| v.get()) >= work
1509}
1510
1511#[derive(Clone, Copy, Default, Debug)]
1512struct PrefixMetrics {
1513    nodes: usize,
1514    levels: usize,
1515    depth: usize,
1516    payload: usize,
1517    bytes: usize,
1518    closed: bool,
1519}
1520impl PrefixMetrics {
1521    fn comparison_cost(self) -> usize {
1522        2 * (self.nodes + self.levels + self.payload) + 1
1523    }
1524}
1525#[derive(Clone, Copy, Default)]
1526struct PrefixMemory {
1527    scope: usize,
1528    live: usize,
1529    peak: usize,
1530}
1531thread_local! {
1532    static PREFIX_MEMORY: std::cell::Cell<PrefixMemory> =
1533        const { std::cell::Cell::new(PrefixMemory { scope:0,live:0,peak:0 }) };
1534    // Tickets released while a nested table is active debit their original
1535    // ledger when that table is restored. Until then the aggregate overcounts.
1536    static PREFIX_RELEASES: std::cell::RefCell<Option<std::rc::Rc<std::cell::Cell<usize>>>> =
1537        const { std::cell::RefCell::new(None) };
1538    static PREFIX_GENERATION: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1539    static PREFIX_TABLE: std::cell::RefCell<PrefixTable> =
1540        std::cell::RefCell::new(PrefixTable::default());
1541}
1542#[cfg(test)]
1543thread_local! {
1544    static PREFIX_METRICS_NODES: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1545    static PREFIX_STATS: std::cell::Cell<[usize;5]> = const { std::cell::Cell::new([0;5]) };
1546}
1547fn prefix_stat(index: usize) {
1548    #[cfg(test)]
1549    PREFIX_STATS.with(|v| {
1550        let mut a = v.get();
1551        a[index] += 1;
1552        v.set(a);
1553    });
1554    #[cfg(not(test))]
1555    let _ = index;
1556}
1557struct PrefixTicket {
1558    scope: usize,
1559    bytes: usize,
1560    releases: std::rc::Rc<std::cell::Cell<usize>>,
1561}
1562impl PrefixTicket {
1563    fn new(bytes: usize) -> Option<Self> {
1564        let releases = PREFIX_RELEASES.with(|v| v.borrow().clone())?;
1565        let mut ticket = Self {
1566            scope: PREFIX_MEMORY.with(|m| m.get().scope),
1567            bytes: 0,
1568            releases,
1569        };
1570        if ticket.scope == 0 {
1571            return None;
1572        }
1573        ticket.add(bytes)?;
1574        Some(ticket)
1575    }
1576    fn add(&mut self, bytes: usize) -> Option<()> {
1577        PREFIX_MEMORY.with(|m| {
1578            let mut state = m.get();
1579            if state.scope != self.scope {
1580                return None;
1581            }
1582            let live = state.live.checked_add(bytes)?;
1583            if !prefix_combined_fits(live) {
1584                return None;
1585            }
1586            state.live = live;
1587            state.peak = state.peak.max(live);
1588            self.bytes = self.bytes.checked_add(bytes)?;
1589            m.set(state);
1590            Some(())
1591        })
1592    }
1593}
1594impl Drop for PrefixTicket {
1595    fn drop(&mut self) {
1596        PREFIX_MEMORY.with(|m| {
1597            let mut state = m.get();
1598            if state.scope == self.scope {
1599                state.live = state.live.saturating_sub(self.bytes);
1600                m.set(state);
1601            } else {
1602                // Each ticket releases once; total reservations are bounded.
1603                self.releases.set(
1604                    self.releases
1605                        .get()
1606                        .checked_add(self.bytes)
1607                        .expect("bounded outstanding prefix reservations"),
1608                );
1609            }
1610        });
1611    }
1612}
1613#[derive(Clone, Copy, PartialEq, Eq)]
1614enum PrefixStatus {
1615    Available,
1616    Busy,
1617    Vacant,
1618}
1619struct PrefixEntry {
1620    key: Db,
1621    key_metrics: PrefixMetrics,
1622    _key_memory: PrefixTicket,
1623    observed: usize,
1624    tail: Option<Db>,
1625    tail_memory: Option<PrefixTicket>,
1626    tail_metrics: Option<PrefixMetrics>,
1627    status: std::rc::Rc<std::cell::Cell<PrefixStatus>>,
1628    _status_memory: PrefixTicket,
1629}
1630struct PrefixTable {
1631    context: usize,
1632    scope: usize,
1633    entries: [Option<PrefixEntry>; PREFIX_SLOTS],
1634    definitions: definitions::Cache,
1635}
1636impl Default for PrefixTable {
1637    fn default() -> Self {
1638        Self {
1639            context: 0,
1640            scope: 0,
1641            entries: std::array::from_fn(|_| None),
1642            definitions: definitions::Cache::default(),
1643        }
1644    }
1645}
1646#[must_use]
1647struct PrefixScope<'ctx> {
1648    previous: Option<PrefixTable>,
1649    memory: PrefixMemory,
1650    previous_factory: FixFactory,
1651    releases: Option<std::rc::Rc<std::cell::Cell<usize>>>,
1652    // The check's own positive conversion evidence (`conversion_memo`), for this context only.
1653    _evidence: conversion_memo::Scope,
1654    context: std::marker::PhantomData<&'ctx Context>,
1655    not_send: std::marker::PhantomData<*const ()>,
1656}
1657fn prefix_table_bytes() -> usize {
1658    std::mem::size_of::<PrefixTable>()
1659        + std::mem::size_of::<FixFactory>()
1660        + std::mem::size_of::<std::cell::Cell<usize>>()
1661        + 2 * std::mem::size_of::<usize>()
1662}
1663impl<'ctx> PrefixScope<'ctx> {
1664    fn enter(ctx: &'ctx Context) -> Self {
1665        let memory = PREFIX_MEMORY.with(|v| v.get());
1666        let scope = PREFIX_GENERATION.with(|v| {
1667            let next = v.get().checked_add(1)?;
1668            v.set(next);
1669            Some(next)
1670        });
1671        let scope = scope
1672            .filter(|_| {
1673                memory
1674                    .live
1675                    .checked_add(prefix_table_bytes())
1676                    .is_some_and(prefix_combined_fits)
1677            })
1678            .unwrap_or(0);
1679        // A failed nested admission suppresses the outer cache, including for
1680        // the very same Context. The previous scope is restored by Drop.
1681        let previous = PREFIX_TABLE.with(|v| {
1682            v.replace(PrefixTable {
1683                context: if scope == 0 {
1684                    0
1685                } else {
1686                    ctx as *const Context as usize
1687                },
1688                scope,
1689                ..PrefixTable::default()
1690            })
1691        });
1692        let releases = PREFIX_RELEASES.with(|v| {
1693            v.replace(if scope == 0 {
1694                None
1695            } else {
1696                Some(std::rc::Rc::new(std::cell::Cell::new(0)))
1697            })
1698        });
1699        let fixed = if scope == 0 { 0 } else { prefix_table_bytes() };
1700        let previous_factory = FIX_FACTORY.with(|f| {
1701            f.replace(FixFactory {
1702                scope,
1703                ..FixFactory::default()
1704            })
1705        });
1706        PREFIX_MEMORY.with(|v| {
1707            v.set(PrefixMemory {
1708                scope,
1709                live: memory.live + fixed,
1710                peak: memory.peak.max(memory.live + fixed),
1711            })
1712        });
1713        Self {
1714            previous: Some(previous),
1715            memory,
1716            previous_factory,
1717            releases,
1718            _evidence: conversion_memo::Scope::enter(ctx),
1719            context: std::marker::PhantomData,
1720            not_send: std::marker::PhantomData,
1721        }
1722    }
1723}
1724impl Drop for PrefixScope<'_> {
1725    fn drop(&mut self) {
1726        if let Some(previous) = self.previous.take() {
1727            let completed = PREFIX_TABLE.with(|v| v.replace(previous));
1728            drop(completed); // release this scope's tickets before restoring the outer ledger
1729            FIX_FACTORY.with(|f| f.set(self.previous_factory));
1730            let releases = self.releases.take();
1731            let deferred = releases.as_ref().map_or(0, |r| r.replace(0));
1732            PREFIX_RELEASES.with(|v| {
1733                v.replace(releases);
1734            });
1735            PREFIX_MEMORY.with(|v| {
1736                let peak = v.get().peak;
1737                let mut old = self.memory;
1738                old.live = old
1739                    .live
1740                    .checked_sub(deferred)
1741                    .expect("original scope owns released tickets");
1742                if old.scope != 0 {
1743                    old.peak = old.peak.max(peak);
1744                }
1745                v.set(old);
1746            });
1747        }
1748    }
1749}
1750
1751/// Bounded, equality-faithful closure/capacity admission. Wide children are
1752/// visited through slices; no frontier proportional to an untrusted width.
1753fn prefix_metrics(t: &Db) -> Option<PrefixMetrics> {
1754    enum Visit<'a> {
1755        Node(&'a Db, usize, usize),
1756        Slice(&'a [Db], usize, usize),
1757        Level(&'a Universe, usize),
1758        Levels(&'a [Universe], usize),
1759    }
1760    fn push<'a>(v: &mut Vec<Visit<'a>>, x: Visit<'a>) -> Option<()> {
1761        if !nat_order_tick() || v.len() == PREFIX_PENDING {
1762            return None;
1763        }
1764        v.push(x);
1765        Some(())
1766    }
1767    fn payload(m: &mut PrefixMetrics, s: &str, capacity: usize) -> Option<()> {
1768        if s.len() > 256 {
1769            return None;
1770        }
1771        m.payload = m.payload.checked_add(s.len())?;
1772        m.bytes = m.bytes.checked_add(capacity)?;
1773        if m.payload > 16384 || !nat_order_spend(s.len()) {
1774            return None;
1775        }
1776        Some(())
1777    }
1778    let requested = PREFIX_PENDING.checked_mul(std::mem::size_of::<Visit<'_>>())?;
1779    let mut memory = PrefixTicket::new(requested)?;
1780    if !nat_order_tick() {
1781        return None;
1782    }
1783    let mut pending = Vec::with_capacity(PREFIX_PENDING);
1784    let actual = pending
1785        .capacity()
1786        .checked_mul(std::mem::size_of::<Visit<'_>>())?;
1787    if actual > requested {
1788        memory.add(actual - requested)?;
1789    }
1790    let mut m = PrefixMetrics {
1791        closed: true,
1792        bytes: std::mem::size_of::<Db>(),
1793        ..PrefixMetrics::default()
1794    };
1795    push(&mut pending, Visit::Node(t, 1, 0))?;
1796    while let Some(item) = pending.pop() {
1797        if !nat_order_tick() {
1798            return None;
1799        }
1800        match item {
1801            Visit::Slice(a, d, b) => {
1802                if let Some((head, rest)) = a.split_first() {
1803                    push(&mut pending, Visit::Slice(rest, d, b))?;
1804                    push(&mut pending, Visit::Node(head, d, b))?;
1805                }
1806            }
1807            Visit::Levels(a, d) => {
1808                if let Some((head, rest)) = a.split_first() {
1809                    push(&mut pending, Visit::Levels(rest, d))?;
1810                    push(&mut pending, Visit::Level(head, d))?;
1811                }
1812            }
1813            Visit::Level(u, d) => {
1814                m.levels += 1;
1815                m.depth = m.depth.max(d);
1816                if d > PREFIX_DEPTH || m.levels > PREFIX_NODES {
1817                    return None;
1818                }
1819                match u {
1820                    Universe::SProp | Universe::Prop | Universe::Type(_) => {}
1821                    Universe::Var(n) => payload(&mut m, n, n.capacity())?,
1822                    Universe::Succ(a) => {
1823                        m.bytes = m.bytes.checked_add(std::mem::size_of::<Universe>())?;
1824                        push(&mut pending, Visit::Level(a, d + 1))?;
1825                    }
1826                    Universe::Max(a, b) | Universe::IMax(a, b) => {
1827                        m.bytes = m.bytes.checked_add(2 * std::mem::size_of::<Universe>())?;
1828                        push(&mut pending, Visit::Level(b, d + 1))?;
1829                        push(&mut pending, Visit::Level(a, d + 1))?;
1830                    }
1831                }
1832            }
1833            Visit::Node(t, d, b) => {
1834                #[cfg(test)]
1835                PREFIX_METRICS_NODES.with(|v| v.set(v.get() + 1));
1836                m.nodes += 1;
1837                m.depth = m.depth.max(d);
1838                if d > PREFIX_DEPTH || m.nodes > PREFIX_NODES {
1839                    return None;
1840                }
1841                match t {
1842                    Db::Var(i) => m.closed &= *i < b,
1843                    Db::Global(n) => payload(&mut m, n, n.capacity())?,
1844                    Db::Const { name, levels } => {
1845                        payload(&mut m, name, name.capacity())?;
1846                        if levels.len() > PREFIX_NODES {
1847                            return None;
1848                        }
1849                        m.bytes = m.bytes.checked_add(
1850                            levels
1851                                .capacity()
1852                                .checked_mul(std::mem::size_of::<Universe>())?,
1853                        )?;
1854                        push(&mut pending, Visit::Levels(levels, d + 1))?;
1855                    }
1856                    Db::Sort(u) => push(&mut pending, Visit::Level(u, d + 1))?,
1857                    Db::Lit(Literal::Float(_)) => return None,
1858                    Db::Lit(Literal::Text(s)) => payload(&mut m, s, s.capacity())?,
1859                    Db::Lit(Literal::Nat(n)) => {
1860                        if n.to_i64().is_none() || n.is_negative() {
1861                            return None;
1862                        }
1863                    }
1864                    Db::Lit(Literal::BigInt(n)) => {
1865                        n.to_i64()?;
1866                    }
1867                    Db::Lit(_) => {}
1868                    Db::Pi(a, c) | Db::Lam(a, c) => {
1869                        m.bytes = m.bytes.checked_add(2 * std::mem::size_of::<Db>())?;
1870                        push(&mut pending, Visit::Node(c, d + 1, b.checked_add(1)?))?;
1871                        push(&mut pending, Visit::Node(a, d + 1, b))?;
1872                    }
1873                    Db::App(a, c) => {
1874                        m.bytes = m.bytes.checked_add(2 * std::mem::size_of::<Db>())?;
1875                        push(&mut pending, Visit::Node(c, d + 1, b))?;
1876                        push(&mut pending, Visit::Node(a, d + 1, b))?;
1877                    }
1878                    Db::Fix(c) => {
1879                        if let Some(facts) = c.facts() {
1880                            if !nat_order_tick() {
1881                                return None;
1882                            }
1883                            fix_body_stat(2);
1884                            m.nodes = m.nodes.checked_add(facts.metrics.nodes)?;
1885                            m.levels = m.levels.checked_add(facts.metrics.levels)?;
1886                            m.depth = m.depth.max(d.checked_add(facts.metrics.depth)?);
1887                            m.payload = m.payload.checked_add(facts.metrics.payload)?;
1888                            m.bytes = m.bytes.checked_add(facts.metrics.bytes)?;
1889                            m.closed &= facts.required <= b.checked_add(1)?;
1890                            if m.nodes > PREFIX_NODES
1891                                || m.levels > PREFIX_NODES
1892                                || m.depth > PREFIX_DEPTH
1893                                || m.payload > 16384
1894                            {
1895                                return None;
1896                            }
1897                        } else {
1898                            m.bytes = m.bytes.checked_add(std::mem::size_of::<Db>())?;
1899                            push(&mut pending, Visit::Node(c, d + 1, b.checked_add(1)?))?;
1900                        }
1901                    }
1902                    Db::Let(a, c, e) => {
1903                        m.bytes = m.bytes.checked_add(3 * std::mem::size_of::<Db>())?;
1904                        push(&mut pending, Visit::Node(e, d + 1, b.checked_add(1)?))?;
1905                        push(&mut pending, Visit::Node(c, d + 1, b))?;
1906                        push(&mut pending, Visit::Node(a, d + 1, b))?;
1907                    }
1908                    Db::Match {
1909                        disc,
1910                        motive,
1911                        cases,
1912                    } => {
1913                        if cases.len() > PREFIX_NODES {
1914                            return None;
1915                        }
1916                        m.bytes = m
1917                            .bytes
1918                            .checked_add(2 * std::mem::size_of::<Db>())?
1919                            .checked_add(
1920                                cases.capacity().checked_mul(std::mem::size_of::<Db>())?,
1921                            )?;
1922                        push(&mut pending, Visit::Slice(cases, d + 1, b))?;
1923                        push(&mut pending, Visit::Node(motive, d + 1, b))?;
1924                        push(&mut pending, Visit::Node(disc, d + 1, b))?;
1925                    }
1926                    Db::MutualFix { defs, .. } => {
1927                        if defs.len() > PREFIX_NODES {
1928                            return None;
1929                        }
1930                        m.bytes = m
1931                            .bytes
1932                            .checked_add(defs.capacity().checked_mul(std::mem::size_of::<Db>())?)?;
1933                        push(
1934                            &mut pending,
1935                            Visit::Slice(defs, d + 1, b.checked_add(defs.len())?),
1936                        )?;
1937                    }
1938                }
1939            }
1940        }
1941        if m.bytes > PREFIX_TREE_BYTES {
1942            return None;
1943        }
1944    }
1945    Some(m)
1946}
1947
1948// Explicit copying only after prefix_metrics admission. Each allocation request
1949// is reserved before construction; any actual excess capacity is charged before
1950// filling. Tickets release on every failed partial construction.
1951fn prefix_string(s: &str, m: &mut PrefixTicket) -> Option<String> {
1952    if !nat_order_spend(s.len() + 1) {
1953        return None;
1954    }
1955    m.add(s.len())?;
1956    let mut out = String::with_capacity(s.len());
1957    if out.capacity() > s.len() {
1958        m.add(out.capacity() - s.len())?;
1959    }
1960    out.push_str(s);
1961    Some(out)
1962}
1963fn prefix_vec<T>(len: usize, m: &mut PrefixTicket) -> Option<Vec<T>> {
1964    if !nat_order_tick() {
1965        return None;
1966    }
1967    let bytes = len.checked_mul(std::mem::size_of::<T>())?;
1968    m.add(bytes)?;
1969    let out = Vec::with_capacity(len);
1970    let actual = out.capacity().checked_mul(std::mem::size_of::<T>())?;
1971    if actual > bytes {
1972        m.add(actual - bytes)?;
1973    }
1974    Some(out)
1975}
1976fn prefix_level(u: &Universe, m: &mut PrefixTicket) -> Option<Universe> {
1977    if !nat_order_tick() {
1978        return None;
1979    }
1980    fn boxed(u: &Universe, m: &mut PrefixTicket) -> Option<Box<Universe>> {
1981        m.add(std::mem::size_of::<Universe>())?;
1982        Some(Box::new(prefix_level(u, m)?))
1983    }
1984    Some(match u {
1985        Universe::SProp => Universe::SProp,
1986        Universe::Prop => Universe::Prop,
1987        Universe::Type(n) => Universe::Type(*n),
1988        Universe::Var(n) => Universe::Var(prefix_string(n, m)?),
1989        Universe::Succ(a) => Universe::Succ(boxed(a, m)?),
1990        Universe::Max(a, b) => Universe::Max(boxed(a, m)?, boxed(b, m)?),
1991        Universe::IMax(a, b) => Universe::IMax(boxed(a, m)?, boxed(b, m)?),
1992    })
1993}
1994fn prefix_copy_node(t: &Db, m: &mut PrefixTicket) -> Option<Db> {
1995    if !nat_order_tick() {
1996        return None;
1997    }
1998    prefix_stat(2); // actual Db nodes copied, not reserved copies
1999    fn boxed(t: &Db, m: &mut PrefixTicket) -> Option<DbBox> {
2000        m.add(std::mem::size_of::<Db>())?;
2001        Some(DbBox::owned(Box::new(prefix_copy_node(t, m)?)))
2002    }
2003    Some(match t {
2004        Db::Var(i) => Db::Var(*i),
2005        Db::Global(n) => Db::Global(prefix_string(n, m)?),
2006        Db::Sort(u) => Db::Sort(prefix_level(u, m)?),
2007        Db::Const { name, levels } => {
2008            let name = prefix_string(name, m)?;
2009            let mut out = prefix_vec(levels.len(), m)?;
2010            for u in levels {
2011                out.push(prefix_level(u, m)?);
2012            }
2013            Db::Const { name, levels: out }
2014        }
2015        Db::Pi(a, b) => Db::Pi(boxed(a, m)?, boxed(b, m)?),
2016        Db::Lam(a, b) => Db::Lam(boxed(a, m)?, boxed(b, m)?),
2017        Db::App(a, b) => Db::App(boxed(a, m)?, boxed(b, m)?),
2018        Db::Fix(b) => Db::Fix(match b {
2019            FixBody::Shared(_) => b.clone(), // existing persistent ticket owns the immutable body
2020            FixBody::Owned(_) => FixBody::owned(boxed(b, m)?.into_box()),
2021        }),
2022        Db::Let(a, b, c) => Db::Let(boxed(a, m)?, boxed(b, m)?, boxed(c, m)?),
2023        Db::Match {
2024            disc,
2025            motive,
2026            cases,
2027        } => {
2028            let disc = boxed(disc, m)?;
2029            let motive = boxed(motive, m)?;
2030            let mut out = prefix_vec(cases.len(), m)?;
2031            for c in cases {
2032                out.push(prefix_copy_node(c, m)?);
2033            }
2034            Db::Match {
2035                disc,
2036                motive,
2037                cases: out,
2038            }
2039        }
2040        Db::MutualFix { defs, index } => {
2041            let mut out = prefix_vec(defs.len(), m)?;
2042            for d in defs {
2043                out.push(prefix_copy_node(d, m)?);
2044            }
2045            Db::MutualFix {
2046                defs: out,
2047                index: *index,
2048            }
2049        }
2050        Db::Lit(l) => Db::Lit(match l {
2051            Literal::Int(n) => Literal::Int(*n),
2052            Literal::Duration(n) => Literal::Duration(*n),
2053            Literal::Date(n) => Literal::Date(*n),
2054            Literal::Moment(n) => Literal::Moment(*n),
2055            Literal::Text(s) => Literal::Text(prefix_string(s, m)?),
2056            Literal::Nat(n) => Literal::Nat(n.to_i64()?.into()),
2057            Literal::BigInt(n) => Literal::BigInt(n.to_i64()?.into()),
2058            Literal::Float(_) => return None,
2059        }),
2060    })
2061}
2062fn prefix_copy(t: &Db) -> Option<(Db, PrefixTicket)> {
2063    let mut memory = PrefixTicket::new(std::mem::size_of::<Db>())?;
2064    let copy = prefix_copy_node(t, &mut memory)?;
2065    Some((copy, memory))
2066}
2067
2068// The cursor owns the tail first and this ticket last, so abandoning a cursor
2069// destroys its owned syntax before releasing its auxiliary capacity reservation.
2070struct PrefixOwned {
2071    metrics: Option<PrefixMetrics>,
2072    memory: PrefixTicket,
2073    clean: bool,
2074}
2075struct PrefixSeed<'a> {
2076    key: &'a Db,
2077    metrics: PrefixMetrics,
2078    slot: Option<usize>,
2079    scope: usize,
2080    observed: usize,
2081    publishable: bool,
2082    lease: Option<std::rc::Rc<std::cell::Cell<PrefixStatus>>>,
2083}
2084impl Drop for PrefixSeed<'_> {
2085    fn drop(&mut self) {
2086        // This exact slot's shared state survives an inner table being active.
2087        // No table borrow, lookup, allocation, or evaluator call occurs here.
2088        if let Some(status) = self.lease.take() {
2089            if status.get() == PrefixStatus::Busy {
2090                status.set(PrefixStatus::Vacant);
2091            }
2092        }
2093    }
2094}
2095fn prefix_move_enabled() -> bool {
2096    true
2097}
2098// Exact, metered structural comparison. Shared identity skips only immutable bytes
2099// actually owned by both operands; no historical pointer/hash table is consulted.
2100fn prefix_exact_equal(a: &Db, b: &Db) -> Option<bool> {
2101    fn text(a: &str, b: &str) -> Option<bool> {
2102        if a.len() != b.len() {
2103            return Some(false);
2104        }
2105        if !nat_order_spend(a.len().checked_mul(2)?) {
2106            return None;
2107        }
2108        Some(a == b)
2109    }
2110    fn level(a: &Universe, b: &Universe, depth: usize) -> Option<bool> {
2111        if depth > PREFIX_DEPTH || !nat_order_spend(2) {
2112            return None;
2113        }
2114        Some(match (a, b) {
2115            (Universe::SProp, Universe::SProp) | (Universe::Prop, Universe::Prop) => true,
2116            (Universe::Type(x), Universe::Type(y)) => x == y,
2117            (Universe::Var(x), Universe::Var(y)) => text(x, y)?,
2118            (Universe::Succ(x), Universe::Succ(y)) => level(x, y, depth + 1)?,
2119            (Universe::Max(a, b), Universe::Max(c, d))
2120            | (Universe::IMax(a, b), Universe::IMax(c, d)) => {
2121                level(a, c, depth + 1)? && level(b, d, depth + 1)?
2122            }
2123            _ => false,
2124        })
2125    }
2126    fn visit(a: &Db, b: &Db, depth: usize) -> Option<bool> {
2127        if depth > PREFIX_DEPTH || !nat_order_spend(2) {
2128            return None;
2129        }
2130        fix_body_stat(5);
2131        Some(match (a, b) {
2132            (Db::Var(x), Db::Var(y)) => x == y,
2133            (Db::Global(x), Db::Global(y)) => text(x, y)?,
2134            (Db::Sort(x), Db::Sort(y)) => level(x, y, depth + 1)?,
2135            (Db::Const { name: a, levels: x }, Db::Const { name: b, levels: y }) => {
2136                if x.len() != y.len() || !text(a, b)? {
2137                    false
2138                } else {
2139                    let mut same = true;
2140                    for (a, b) in x.iter().zip(y) {
2141                        if !level(a, b, depth + 1)? {
2142                            same = false;
2143                            break;
2144                        }
2145                    }
2146                    same
2147                }
2148            }
2149            (Db::Pi(a, b), Db::Pi(c, d))
2150            | (Db::Lam(a, b), Db::Lam(c, d))
2151            | (Db::App(a, b), Db::App(c, d)) => visit(a, c, depth + 1)? && visit(b, d, depth + 1)?,
2152            (Db::Fix(a), Db::Fix(b)) => {
2153                if a.same_current(b) {
2154                    if !nat_order_spend(2) {
2155                        return None;
2156                    }
2157                    fix_body_stat(3);
2158                    true
2159                } else {
2160                    visit(a, b, depth + 1)?
2161                }
2162            }
2163            (Db::Let(a, b, c), Db::Let(d, e, f)) => {
2164                visit(a, d, depth + 1)? && visit(b, e, depth + 1)? && visit(c, f, depth + 1)?
2165            }
2166            (
2167                Db::Match {
2168                    disc: a,
2169                    motive: b,
2170                    cases: x,
2171                },
2172                Db::Match {
2173                    disc: c,
2174                    motive: d,
2175                    cases: y,
2176                },
2177            ) => {
2178                if x.len() != y.len() || !visit(a, c, depth + 1)? || !visit(b, d, depth + 1)? {
2179                    false
2180                } else {
2181                    let mut same = true;
2182                    for (a, b) in x.iter().zip(y) {
2183                        if !visit(a, b, depth + 1)? {
2184                            same = false;
2185                            break;
2186                        }
2187                    }
2188                    same
2189                }
2190            }
2191            (Db::MutualFix { defs: x, index: i }, Db::MutualFix { defs: y, index: j }) => {
2192                if i != j || x.len() != y.len() {
2193                    false
2194                } else {
2195                    let mut same = true;
2196                    for (a, b) in x.iter().zip(y) {
2197                        if !visit(a, b, depth + 1)? {
2198                            same = false;
2199                            break;
2200                        }
2201                    }
2202                    same
2203                }
2204            }
2205            (Db::Lit(a), Db::Lit(b)) => match (a, b) {
2206                (Literal::Int(a), Literal::Int(b))
2207                | (Literal::Duration(a), Literal::Duration(b))
2208                | (Literal::Moment(a), Literal::Moment(b)) => a == b,
2209                (Literal::Date(a), Literal::Date(b)) => a == b,
2210                (Literal::Text(a), Literal::Text(b)) => text(a, b)?,
2211                (Literal::Nat(a), Literal::Nat(b)) | (Literal::BigInt(a), Literal::BigInt(b)) => {
2212                    a.to_i64()? == b.to_i64()?
2213                }
2214                // An admitted stored key cannot contain Float.
2215                (Literal::Float(_), _) => return None,
2216                _ => false,
2217            },
2218            _ => false,
2219        })
2220    }
2221    if !nat_order_tick() {
2222        return None;
2223    }
2224    visit(a, b, 1)
2225}
2226
2227fn prefix_lookup<'a>(
2228    ctx: &Context,
2229    key: &'a Db,
2230) -> Option<(PrefixSeed<'a>, Option<NatOrderCursor<'a>>)> {
2231    if !prefix_reuse_enabled() {
2232        return None;
2233    }
2234    PREFIX_TABLE.with(|state| {
2235        let mut table = state.borrow_mut();
2236        if table.scope == 0 || table.context != ctx as *const Context as usize {
2237            return None;
2238        }
2239        let scope = table.scope;
2240        let comparisons = table
2241            .entries
2242            .iter()
2243            .flatten()
2244            .map(|e| e.key_metrics.comparison_cost())
2245            .sum::<usize>();
2246        if !prefix_work_available(comparisons + PREFIX_ADMISSION_WORK + PREFIX_COPY_WORK) {
2247            return None;
2248        }
2249        for (slot, entry) in table.entries.iter_mut().enumerate() {
2250            let Some(entry) = entry else {
2251                continue;
2252            };
2253            prefix_stat(0);
2254            if !prefix_exact_equal(&entry.key, key)? {
2255                continue;
2256            }
2257            if entry.status.get() == PrefixStatus::Busy {
2258                return None;
2259            }
2260            if entry.status.get() == PrefixStatus::Vacant {
2261                entry.status.set(PrefixStatus::Busy);
2262                return Some((
2263                    PrefixSeed {
2264                        key,
2265                        metrics: entry.key_metrics,
2266                        slot: Some(slot),
2267                        scope,
2268                        observed: 0,
2269                        publishable: true,
2270                        lease: Some(entry.status.clone()),
2271                    },
2272                    None,
2273                ));
2274            }
2275            // Retain the prior conservative capacity gate. A move allocates
2276            // nothing and debits no copying work; full-ledger hits still refuse.
2277            let bytes = entry.tail_memory.as_ref().map_or(0, |m| m.bytes);
2278            if PREFIX_MEMORY.with(|m| {
2279                m.get()
2280                    .live
2281                    .checked_add(bytes)
2282                    .is_none_or(|n| !prefix_combined_fits(n))
2283            }) {
2284                return None;
2285            }
2286            let (tail, owned, lease) = if prefix_move_enabled() {
2287                let memory = entry
2288                    .tail_memory
2289                    .take()
2290                    .expect("available prefix owns reservation");
2291                let tail = entry.tail.take().map(NatOrderTail::Owned);
2292                entry.status.set(PrefixStatus::Busy);
2293                (
2294                    tail,
2295                    Some(PrefixOwned {
2296                        metrics: entry.tail_metrics,
2297                        memory,
2298                        clean: true,
2299                    }),
2300                    Some(entry.status.clone()),
2301                )
2302            } else {
2303                // Compiling RED seam: preserve old copies/admission on hits.
2304                let (tail, owned) = match &entry.tail {
2305                    Some(t) => {
2306                        let (t, memory) = prefix_copy(t)?;
2307                        (
2308                            Some(NatOrderTail::Owned(t)),
2309                            Some(PrefixOwned {
2310                                metrics: None,
2311                                memory,
2312                                clean: false,
2313                            }),
2314                        )
2315                    }
2316                    None => (None, None),
2317                };
2318                (tail, owned, None)
2319            };
2320            prefix_stat(1);
2321            return Some((
2322                PrefixSeed {
2323                    key,
2324                    metrics: entry.key_metrics,
2325                    slot: Some(slot),
2326                    scope,
2327                    observed: entry.observed,
2328                    publishable: true,
2329                    lease,
2330                },
2331                Some(NatOrderCursor {
2332                    count: logicaffeine_base::BigInt::from_i64(entry.observed as i64),
2333                    tail,
2334                    prefix: owned,
2335                }),
2336            ));
2337        }
2338        if table.entries.iter().all(Option::is_some) {
2339            return None;
2340        }
2341        let metrics = prefix_metrics(key)?;
2342        if !metrics.closed {
2343            return None;
2344        }
2345        Some((
2346            PrefixSeed {
2347                key,
2348                metrics,
2349                slot: None,
2350                scope: table.scope,
2351                observed: 0,
2352                publishable: true,
2353                lease: None,
2354            },
2355            None,
2356        ))
2357    })
2358}
2359fn prefix_observe(seed: &mut Option<PrefixSeed<'_>>, count: &logicaffeine_base::BigInt) {
2360    if let Some(seed) = seed {
2361        let next = count
2362            .to_i64()
2363            .and_then(|n| usize::try_from(n).ok())
2364            .and_then(|n| seed.observed.checked_add(n));
2365        match next {
2366            Some(n) if n <= MAX_RECHECK_STEPS => seed.observed = n,
2367            _ => seed.publishable = false,
2368        }
2369    }
2370}
2371fn prefix_publish(
2372    ctx: &Context,
2373    seed: &mut Option<PrefixSeed<'_>>,
2374    cursor: &mut NatOrderCursor<'_>,
2375) {
2376    let Some(seed) = seed.as_mut().filter(|s| s.publishable) else {
2377        return;
2378    };
2379    if WHNF_EXHAUSTED.with(|e| e.get()) || matches!(cursor.tail, Some(NatOrderTail::Borrowed(_))) {
2380        return;
2381    }
2382    // Return replaced owned values so they are dropped after the table borrow.
2383    let retired = PREFIX_TABLE.with(|state| {
2384        let mut table = state.borrow_mut();
2385        if table.scope != seed.scope || table.context != ctx as *const Context as usize {
2386            return None;
2387        }
2388        let mut slot = seed.slot;
2389        let comparisons = if slot.is_some() {
2390            0
2391        } else {
2392            table
2393                .entries
2394                .iter()
2395                .flatten()
2396                .map(|e| e.key_metrics.comparison_cost())
2397                .sum()
2398        };
2399        if !prefix_work_available(comparisons + PREFIX_ADMISSION_WORK + PREFIX_COPY_WORK) {
2400            return None;
2401        }
2402        if slot.is_none() {
2403            for (i, entry) in table.entries.iter().enumerate() {
2404                let Some(entry) = entry else {
2405                    continue;
2406                };
2407                if !nat_order_spend(entry.key_metrics.comparison_cost()) {
2408                    return None;
2409                }
2410                prefix_stat(0);
2411                if entry.key == *seed.key {
2412                    slot = Some(i);
2413                    break;
2414                }
2415            }
2416        }
2417        if let Some(i) = slot {
2418            let entry = table.entries[i].as_ref()?;
2419            if let Some(lease) = &seed.lease {
2420                if !std::rc::Rc::ptr_eq(lease, &entry.status) || lease.get() != PrefixStatus::Busy {
2421                    return None;
2422                }
2423            } else if entry.status.get() == PrefixStatus::Busy
2424                || (entry.status.get() == PrefixStatus::Available
2425                    && entry.observed >= seed.observed)
2426            {
2427                return None;
2428            }
2429        }
2430        let i = slot.or_else(|| table.entries.iter().position(Option::is_none))?;
2431        let clean = cursor.prefix.as_ref().is_some_and(|p| p.clean);
2432        let tail_metrics = if clean {
2433            // Certified direct projection only removes nonbinding wrappers.
2434            // Its old capacity/depth/closedness bounds remain conservative.
2435            cursor.prefix.as_ref().and_then(|p| p.metrics)
2436        } else {
2437            match cursor.tail.as_ref() {
2438                Some(NatOrderTail::Owned(t)) => match prefix_metrics(t) {
2439                    Some(m) if m.closed => Some(m),
2440                    _ => return None,
2441                },
2442                None => None,
2443                Some(NatOrderTail::Borrowed(_)) => return None,
2444            }
2445        };
2446        let new_memory = if clean {
2447            None
2448        } else {
2449            Some(PrefixTicket::new(tail_metrics.map_or(0, |m| m.bytes))?)
2450        };
2451        let new_key = if table.entries[i].is_none() {
2452            let status_memory = PrefixTicket::new(std::mem::size_of::<(
2453                usize,
2454                usize,
2455                std::cell::Cell<PrefixStatus>,
2456            )>())?;
2457            let (key, key_memory) = prefix_copy(seed.key)?;
2458            let status = std::rc::Rc::new(std::cell::Cell::new(PrefixStatus::Available));
2459            Some((key, key_memory, status, status_memory))
2460        } else {
2461            None
2462        };
2463        if WHNF_EXHAUSTED.with(|e| e.get()) {
2464            return None;
2465        }
2466        let tail = match cursor.tail.take() {
2467            Some(NatOrderTail::Owned(t)) => Some(t),
2468            None => None,
2469            Some(NatOrderTail::Borrowed(_)) => unreachable!(),
2470        };
2471        let old_owned = cursor.prefix.take();
2472        let (tail_memory, retired_memory) = if clean {
2473            (old_owned.expect("clean owned certificate").memory, None)
2474        } else {
2475            (
2476                new_memory.expect("fresh reservation"),
2477                old_owned.map(|p| p.memory),
2478            )
2479        };
2480        let retired = if let Some((key, key_memory, status, status_memory)) = new_key {
2481            table.entries[i] = Some(PrefixEntry {
2482                key,
2483                key_metrics: seed.metrics,
2484                _key_memory: key_memory,
2485                observed: seed.observed,
2486                tail,
2487                tail_memory: Some(tail_memory),
2488                tail_metrics,
2489                status,
2490                _status_memory: status_memory,
2491            });
2492            (None, None, retired_memory)
2493        } else {
2494            let entry = table.entries[i]
2495                .as_mut()
2496                .expect("existing immutable slot key");
2497            entry.observed = seed.observed;
2498            let old_tail = std::mem::replace(&mut entry.tail, tail);
2499            let old_memory = entry.tail_memory.replace(tail_memory);
2500            entry.tail_metrics = tail_metrics;
2501            entry.status.set(PrefixStatus::Available);
2502            (old_tail, old_memory, retired_memory)
2503        };
2504        seed.lease = None;
2505        prefix_stat(3);
2506        Some(retired)
2507    });
2508    drop(retired);
2509}
2510
2511// Optional work telemetry counts executed cursor/admission/WHNF dispatches,
2512// independently of fuel reservation and the existing actual clone-node counter.
2513#[cfg(test)]
2514thread_local! {
2515    static NAT_ORDER_WORK: std::cell::Cell<Option<usize>> =
2516        const { std::cell::Cell::new(None) };
2517}
2518fn nat_order_observed_work() {
2519    #[cfg(test)]
2520    NAT_ORDER_WORK.with(|v| {
2521        if let Some(n) = v.get() {
2522            v.set(Some(n + 1));
2523        }
2524    });
2525}
2526fn nat_order_spend(n: usize) -> bool {
2527    let enough = WHNF_FUEL.with(|f| {
2528        let left = f.get();
2529        if left < n {
2530            f.set(0);
2531            false
2532        } else {
2533            f.set(left - n);
2534            true
2535        }
2536    });
2537    if !enough {
2538        WHNF_EXHAUSTED.with(|v| v.set(true));
2539    }
2540    enough
2541}
2542fn nat_order_tick() -> bool {
2543    if !nat_order_spend(1) {
2544        return false;
2545    }
2546    nat_order_observed_work();
2547    true
2548}
2549
2550/// Check a borrowed computed tail before cloning it. Slice continuations keep
2551/// wide Match/MutualFix nodes from allocating a frontier proportional to width.
2552fn nat_order_admit(t: &Db) -> Option<usize> {
2553    enum Visit<'a> {
2554        Node(&'a Db, usize),
2555        Slice(std::slice::Iter<'a, Db>, usize),
2556    }
2557    fn push<'a>(pending: &mut Vec<Visit<'a>>, v: Visit<'a>) -> Option<()> {
2558        if !nat_order_tick() {
2559            return None;
2560        }
2561        // At most two pending binary siblings per admitted depth, plus a slice
2562        // continuation. Bound auxiliary storage before Vec can grow.
2563        if pending.len() >= MAX_RECHECK_WHNF_DEPTH * 3 + 3 {
2564            WHNF_EXHAUSTED.with(|e| e.set(true));
2565            return None;
2566        }
2567        pending.push(v);
2568        Some(())
2569    }
2570    let mut pending = Vec::new();
2571    push(&mut pending, Visit::Node(t, 1))?;
2572    let mut nodes = 0usize;
2573    while let Some(item) = pending.pop() {
2574        if !nat_order_tick() {
2575            return None;
2576        }
2577        match item {
2578            Visit::Slice(mut children, depth) => {
2579                if let Some(child) = children.next() {
2580                    push(&mut pending, Visit::Slice(children, depth))?;
2581                    push(&mut pending, Visit::Node(child, depth))?;
2582                }
2583            }
2584            Visit::Node(t, depth) => {
2585                nodes += 1;
2586                if depth > MAX_RECHECK_WHNF_DEPTH || nodes > MAX_RECHECK_TERM_NODES {
2587                    WHNF_EXHAUSTED.with(|e| e.set(true));
2588                    return None;
2589                }
2590                match t {
2591                    Db::Sort(_) | Db::Var(_) | Db::Global(_) | Db::Const { .. } | Db::Lit(_) => {}
2592                    Db::Pi(a, b) | Db::Lam(a, b) | Db::App(a, b) => {
2593                        push(&mut pending, Visit::Node(b, depth + 1))?;
2594                        push(&mut pending, Visit::Node(a, depth + 1))?;
2595                    }
2596                    Db::Fix(body) => push(&mut pending, Visit::Node(body, depth + 1))?,
2597                    Db::Let(a, b, c) => {
2598                        push(&mut pending, Visit::Node(c, depth + 1))?;
2599                        push(&mut pending, Visit::Node(b, depth + 1))?;
2600                        push(&mut pending, Visit::Node(a, depth + 1))?;
2601                    }
2602                    Db::MutualFix { defs, .. } => {
2603                        push(&mut pending, Visit::Slice(defs.iter(), depth + 1))?
2604                    }
2605                    Db::Match {
2606                        disc,
2607                        motive,
2608                        cases,
2609                    } => {
2610                        push(&mut pending, Visit::Slice(cases.iter(), depth + 1))?;
2611                        push(&mut pending, Visit::Node(motive, depth + 1))?;
2612                        push(&mut pending, Visit::Node(disc, depth + 1))?;
2613                    }
2614                }
2615            }
2616        }
2617    }
2618    Some(nodes)
2619}
2620
2621enum NatOrderTail<'a> {
2622    Borrowed(&'a Db),
2623    Owned(Db),
2624}
2625struct NatOrderCursor<'a> {
2626    count: logicaffeine_base::BigInt,
2627    tail: Option<NatOrderTail<'a>>,
2628    prefix: Option<PrefixOwned>,
2629}
2630impl<'a> NatOrderCursor<'a> {
2631    fn new(t: &'a Db, strict: bool) -> Self {
2632        Self {
2633            count: if strict { 1.into() } else { 0.into() },
2634            tail: Some(NatOrderTail::Borrowed(t)),
2635            prefix: None,
2636        }
2637    }
2638    fn recognize(t: NatOrderTail<'a>) -> Result<Self, NatOrderTail<'a>> {
2639        use NatOrderTail::{Borrowed, Owned};
2640        match t {
2641            Borrowed(Db::Global(n)) if n == "Zero" => Ok(Self {
2642                count: 0.into(),
2643                tail: None,
2644                prefix: None,
2645            }),
2646            Borrowed(Db::Lit(Literal::Nat(n))) => Ok(Self {
2647                count: if n.is_negative() { 0.into() } else { n.clone() },
2648                tail: None,
2649                prefix: None,
2650            }),
2651            Borrowed(Db::App(f, a)) if matches!(f.as_ref(),Db::Global(n) if n=="Succ") => {
2652                Ok(Self {
2653                    count: 1.into(),
2654                    tail: Some(Borrowed(a)),
2655                    prefix: None,
2656                })
2657            }
2658            Owned(Db::Global(n)) if n == "Zero" => Ok(Self {
2659                count: 0.into(),
2660                tail: None,
2661                prefix: None,
2662            }),
2663            Owned(Db::Lit(Literal::Nat(n))) => Ok(Self {
2664                count: if n.is_negative() { 0.into() } else { n },
2665                tail: None,
2666                prefix: None,
2667            }),
2668            Owned(Db::App(f, a)) if matches!(f.as_ref(),Db::Global(n) if n=="Succ") => Ok(Self {
2669                count: 1.into(),
2670                tail: Some(Owned(a.into_db())),
2671                prefix: None,
2672            }),
2673            other => Err(other),
2674        }
2675    }
2676    fn expose(&mut self, genv: &Context, lctx: &dyn LocalTypes) -> Option<()> {
2677        if !nat_order_tick() {
2678            return None;
2679        }
2680        let Some(tail) = self.tail.take() else {
2681            return Some(());
2682        };
2683        let mut next = match Self::recognize(tail) {
2684            Ok(next) => next,
2685            Err(tail) => {
2686                // Every computed exposure invalidates the certificate, even
2687                // when WHNF returns syntactically unchanged syntax.
2688                if let Some(owned) = self.prefix.as_mut() {
2689                    owned.clean = false;
2690                }
2691                let reduced = match tail {
2692                    NatOrderTail::Borrowed(t) => {
2693                        let nodes = nat_order_admit(t)?;
2694                        // Reserve actual clone work before taking ownership.
2695                        // Keep a dispatch available before invoking WHNF.
2696                        if !nat_order_spend(nodes.checked_add(1)?) {
2697                            return None;
2698                        }
2699                        whnf_in(genv, lctx, t)
2700                    }
2701                    NatOrderTail::Owned(t) => {
2702                        if !nat_order_tick() {
2703                            return None;
2704                        }
2705                        whnf_in_owned(genv, lctx, t)
2706                    }
2707                };
2708                if WHNF_EXHAUSTED.with(|e| e.get()) {
2709                    return None;
2710                }
2711                Self::recognize(NatOrderTail::Owned(reduced)).ok()?
2712            }
2713        };
2714        next.prefix = self.prefix.take();
2715        *self = next;
2716        Some(())
2717    }
2718}
2719
2720/// An independent lazy prefix decision for the exactly attested Nat order
2721/// program. Unknown tails retain ordinary reduction; no proof fields are erased.
2722fn try_nat_order_db_in(genv: &Context, lctx: &dyn LocalTypes, t: &Db) -> Option<Db> {
2723    let Db::App(f1, right) = t else {
2724        return None;
2725    };
2726    let Db::App(f0, left) = f1.as_ref() else {
2727        return None;
2728    };
2729    let Db::Global(name) = f0.as_ref() else {
2730        return None;
2731    };
2732    let strict = match name.as_str() {
2733        "natLe" => false,
2734        "natLt" => true,
2735        _ => return None,
2736    };
2737    if WHNF_EXHAUSTED.with(|e| e.get()) {
2738        return None;
2739    }
2740    if !nat_order_tick() {
2741        return None;
2742    }
2743    let parent = WHNF_DEPTH.with(|d| d.get());
2744    if parent == 0 || parent >= MAX_RECHECK_WHNF_DEPTH {
2745        WHNF_EXHAUSTED.with(|e| e.set(true));
2746        return None;
2747    }
2748    let _depth_guard = WhnfDepthGuard(parent);
2749    WHNF_DEPTH.with(|d| d.set(parent + 1));
2750    if !genv.simp_rules().is_empty()
2751        || genv.constructor_inventory_upper_bound("Nat") > 4096
2752        || genv.constructor_inventory_upper_bound("Bool") > 4096
2753    {
2754        return None;
2755    }
2756    let names: &[&str] = if strict {
2757        &["natLe", "natLt"]
2758    } else {
2759        &["natLe"]
2760    };
2761    let admitted = |t: &Term| {
2762        matches!(crate::reduction::bounded_conversion_metrics(t),
2763        Some((_,depth,true)) if depth<=crate::type_checker::MAX_TERM_DEPTH)
2764    };
2765    if !names.iter().all(|name| {
2766        genv.poly_declaration(name).is_none()
2767            && !genv.is_constructor(name)
2768            && !genv.is_inductive(name)
2769            && genv.get_global(name) == genv.get_definition_type(name)
2770            && genv.get_definition_type(name).is_some_and(admitted)
2771            && genv.get_definition_body(name).is_some_and(admitted)
2772    }) || !crate::reduction::accelerates_nat_order(genv, name)
2773    {
2774        return None;
2775    }
2776    run_nat_order_db(
2777        genv,
2778        lctx,
2779        left,
2780        right,
2781        strict,
2782        ZeroCase::Uniform,
2783        "true",
2784        "false",
2785    )
2786}
2787
2788/// How a certified order answers once its left operand is exhausted. `Uniform`: its equation
2789/// `f 0 n = yes` was proved for a free `n`, so it holds by reduction whatever the right operand
2790/// is. `Split`: only `f 0 0 = yes` and `f 0 (n+1) = yes` were proved (Lean's `Nat.ble` matches on
2791/// both operands), so the answer holds by reduction only once the right operand is observed to be
2792/// `Zero` or a successor — for a right operand stuck on a local variable the program is stuck too.
2793#[derive(Clone, Copy, PartialEq)]
2794enum ZeroCase {
2795    Uniform,
2796    Split,
2797}
2798
2799fn run_nat_order_db(
2800    genv: &Context,
2801    lctx: &dyn LocalTypes,
2802    left: &Db,
2803    right: &Db,
2804    strict: bool,
2805    zero_case: ZeroCase,
2806    yes: &str,
2807    no: &str,
2808) -> Option<Db> {
2809    let mut a = NatOrderCursor::new(left, false);
2810    if strict {
2811        a.count = 1.into();
2812    }
2813    let mut b = NatOrderCursor::new(right, false);
2814    let mut prefix_started = false;
2815    let mut prefix_seed = None;
2816    loop {
2817        if !nat_order_tick() {
2818            return None;
2819        }
2820        let left_exhausted = |a: &NatOrderCursor| a.count == 0.into() && a.tail.is_none();
2821        if a.count == 0.into() {
2822            if a.tail.is_some() {
2823                a.expose(genv, lctx)?;
2824            }
2825            let right_observed =
2826                zero_case == ZeroCase::Uniform || b.count > 0.into() || b.tail.is_none();
2827            if left_exhausted(&a) && right_observed {
2828                prefix_publish(genv, &mut prefix_seed, &mut b);
2829                if WHNF_EXHAUSTED.with(|e| e.get()) {
2830                    return None;
2831                }
2832                return Some(Db::Global(yes.into()));
2833            }
2834        }
2835        if b.count == 0.into() {
2836            // Lookup only when the original left-first machine demands right.
2837            if !prefix_started {
2838                prefix_started = true;
2839                if let Some((seed, cached)) = prefix_lookup(genv, right) {
2840                    prefix_seed = Some(seed);
2841                    if let Some(cursor) = cached {
2842                        b = cursor;
2843                    }
2844                }
2845                if WHNF_EXHAUSTED.with(|e| e.get()) {
2846                    return None;
2847                }
2848            }
2849            if b.count == 0.into() && b.tail.is_some() {
2850                b.expose(genv, lctx)?;
2851                prefix_observe(&mut prefix_seed, &b.count);
2852            }
2853            // An exhausted left operand answers from the observed right one: `f 0 0` is `yes`.
2854            if left_exhausted(&a) {
2855                continue;
2856            }
2857            if b.count == 0.into() && b.tail.is_none() {
2858                prefix_publish(genv, &mut prefix_seed, &mut b);
2859                if WHNF_EXHAUSTED.with(|e| e.get()) {
2860                    return None;
2861                }
2862                return Some(Db::Global(no.into()));
2863            }
2864        }
2865        let common = std::cmp::min(a.count.clone(), b.count.clone());
2866        a.count = a.count.sub(&common);
2867        b.count = b.count.sub(&common);
2868    }
2869}
2870
2871// This kernel earns its own certificate. The three recurrence equations are
2872// checked with de Bruijn conversion, under the existing shared fuel budget;
2873// neither the named kernel's equality function nor its certificate is used.
2874fn try_certified_nat_order_db_in(genv: &Context, lctx: &dyn LocalTypes, t: &Db) -> Option<Db> {
2875    if genv.checking_order_recurrence
2876        || !genv.simp_rules().is_empty()
2877        || WHNF_EXHAUSTED.with(|e| e.get())
2878    {
2879        return None;
2880    }
2881    let Db::App(f, right) = t else {
2882        return None;
2883    };
2884    let Db::App(head, left) = f.as_ref() else {
2885        return None;
2886    };
2887    let Db::Global(name) = head.as_ref() else {
2888        return None;
2889    };
2890    if genv.poly_declaration(name).is_some() || genv.is_inductive(name) || genv.is_constructor(name)
2891    {
2892        return None;
2893    }
2894    let signature = genv.get_definition_type(name)?;
2895    if genv.get_global(name) != Some(signature) {
2896        return None;
2897    }
2898    let mut result = signature;
2899    for _ in 0..2 {
2900        let Term::Pi {
2901            param_type,
2902            body_type,
2903            ..
2904        } = result
2905        else {
2906            return None;
2907        };
2908        if !matches!(&**param_type,Term::Global(n) if n=="Nat") {
2909            return None;
2910        }
2911        result = body_type;
2912    }
2913    let Term::Global(carrier) = result else {
2914        return None;
2915    };
2916    if genv.constructor_inventory_upper_bound("Nat") > 4096
2917        || !crate::int_inductive::canonical_nat_environment(genv)
2918        || !genv.is_inductive(carrier)
2919        || genv.get_global(carrier) != Some(&Term::Sort(Universe::Type(0)))
2920        || genv.get_definition_body(carrier).is_some()
2921        || genv.poly_declaration(carrier).is_some()
2922        || genv.inductive_num_params(carrier) != 0
2923        || genv.constructor_inventory_upper_bound(carrier) != 2
2924    {
2925        return None;
2926    }
2927    let constructors = genv.get_constructors(carrier);
2928    if constructors.len() != 2
2929        || constructors.iter().any(|(n, ty)| {
2930            *ty != result
2931                || genv.get_global(n) != Some(result)
2932                || genv.constructor_inductive(n) != Some(carrier.as_str())
2933                || genv.poly_declaration(n).is_some()
2934                || genv.get_definition_body(n).is_some()
2935        })
2936    {
2937        return None;
2938    }
2939    let body = genv.get_definition_body(name)?;
2940    // Bound annotations and universe trees before recursive de Bruijn lowering.
2941    // Admission spends the caller's fuel even when the optional probe refuses.
2942    let limit = WHNF_FUEL.with(|fuel| fuel.get().min(4096));
2943    let mut admission = LocalAdmission::new(limit);
2944    let admitted = admission.free_names(body);
2945    if !nat_order_spend(limit - admission.remaining + 1) {
2946        return None;
2947    }
2948    if admission.max_depth > MAX_RECHECK_WHNF_DEPTH || !admitted.ok()?.is_empty() {
2949        return None;
2950    }
2951    // Independent lowering rejects free variables and holes before a program
2952    // can be considered closed. Retain no body across calls or context changes.
2953    to_db(body, &mut Vec::new()).ok()?;
2954    let parent = WHNF_DEPTH.with(|d| d.get());
2955    if parent == 0 || parent >= MAX_RECHECK_WHNF_DEPTH {
2956        return None;
2957    }
2958    let _depth = WhnfDepthGuard(parent);
2959    WHNF_DEPTH.with(|d| d.set(parent + 1));
2960    let probe = genv.order_recurrence_context();
2961    let variables = vec![Db::Global("Nat".into()), Db::Global("Nat".into())];
2962    let apply = |f: Db, a: Db| Db::App(DbBox::new(f), DbBox::new(a));
2963    let call = |a: Db, b: Db| apply(apply(Db::Global(name.clone()), a), b);
2964    let succ = |a: Db| apply(Db::Global("Succ".into()), a);
2965    let base = call(Db::Global("Zero".into()), Db::Var(0));
2966    // `f 0 n = yes` for every n, or, for a program matching on both arguments (Lean's
2967    // `Nat.ble`), its two cases `f 0 0 = yes` and `f 0 (n+1) = yes`.
2968    let (yes, zero_case) = match constructors
2969        .iter()
2970        .position(|(n, _)| def_eq(&probe, &variables, &base, &Db::Global((*n).into())))
2971    {
2972        Some(yes) => (yes, ZeroCase::Uniform),
2973        None => {
2974            let at_zero = call(Db::Global("Zero".into()), Db::Global("Zero".into()));
2975            let at_successor = call(Db::Global("Zero".into()), succ(Db::Var(0)));
2976            (
2977                constructors.iter().position(|(n, _)| {
2978                    def_eq(&probe, &variables, &at_zero, &Db::Global((*n).into()))
2979                        && def_eq(&probe, &variables, &at_successor, &Db::Global((*n).into()))
2980                })?,
2981                ZeroCase::Split,
2982            )
2983        }
2984    };
2985    let no = 1 - yes;
2986    if !def_eq(
2987        &probe,
2988        &variables,
2989        &call(succ(Db::Var(1)), Db::Global("Zero".into())),
2990        &Db::Global(constructors[no].0.into()),
2991    ) || !def_eq(
2992        &probe,
2993        &variables,
2994        &call(succ(Db::Var(1)), succ(Db::Var(0))),
2995        &call(Db::Var(1), Db::Var(0)),
2996    ) || WHNF_EXHAUSTED.with(|e| e.get())
2997    {
2998        return None;
2999    }
3000    run_nat_order_db(
3001        genv,
3002        lctx,
3003        left,
3004        right,
3005        false,
3006        zero_case,
3007        constructors[yes].0,
3008        constructors[no].0,
3009    )
3010}
3011
3012/// The EUCLIDEAN division pair on `i64` — this kernel's own implementation of the shared
3013/// specification, written from the rule rather than copied from `reduction::ediv_emod_i64`.
3014///
3015/// **The specification, restated.** For a dividend `a` and a divisor `b ≠ 0`, `div a b` and
3016/// `mod a b` are the unique `q` and `r` with
3017///
3018/// * `a = b·q + r`, and
3019/// * `0 ≤ r < |b|` — the remainder is NEVER negative, whatever the sign of either operand.
3020///
3021/// That second clause is the whole content: truncating division (Rust's `/` and `%`, and
3022/// `BigInt::div_rem`) instead gives the remainder the DIVIDEND's sign, so the two conventions
3023/// agree on every non-negative dividend and part company on every negative one
3024/// (`-7 / 2` is `-4` here and `-3` there). Lean totalises the rule at a zero divisor with
3025/// `a / 0 = 0` and `a % 0 = a`, which is the only pair that keeps `b·q + r = a` when `b` is
3026/// zero — and the reason a zero divisor computes here rather than sticking.
3027///
3028/// **Why this is not the main kernel's function.** `reduction::ediv_emod_i64` reaches the pair
3029/// by taking the TRUNCATED quotient and correcting it by one when the remainder came out
3030/// negative. This one reaches it from the other end: it takes the residue of `a` against the
3031/// divisor's MAGNITUDE — the `0 ≤ r < |b|` clause read literally — and then recovers `q` by an
3032/// exact division of `a - r`, a quantity that is divisible by `b` by construction and so rounds
3033/// nowhere and needs no correction. Two routes to one specification is the entire point of a
3034/// second kernel; a copied function would make one wrong correction wrong in both, which is the
3035/// failure mode this campaign has already hit seven times.
3036///
3037/// `None` means the narrow type cannot hold an intermediate (`|i64::MIN|`, or the `a - r` it
3038/// would need), and the caller redoes the operation exactly in `BigInt` — so the narrow path
3039/// and the wide path answer identically on every value both can represent.
3040fn euclidean_pair_i64(a: i64, b: i64) -> Option<(i64, i64)> {
3041    if b == 0 {
3042        return Some((0, a));
3043    }
3044    let magnitude = b.checked_abs()?;
3045    // `a % magnitude` lands in `(-magnitude, magnitude)`; one addition moves a negative
3046    // residue into `[0, magnitude)` and a non-negative one is already there.
3047    let residue = a % magnitude;
3048    let r = if residue < 0 {
3049        residue.checked_add(magnitude)?
3050    } else {
3051        residue
3052    };
3053    let q = a.checked_sub(r)?.checked_div(b)?;
3054    Some((q, r))
3055}
3056
3057/// The arbitrary-precision half of the SAME specification, by the same residue-first route, so
3058/// the two widths cannot disagree about a value both can represent. Total at a zero divisor in
3059/// exactly the way the narrow path is.
3060fn euclidean_pair_big(
3061    a: &logicaffeine_base::BigInt,
3062    b: &logicaffeine_base::BigInt,
3063) -> Option<(logicaffeine_base::BigInt, logicaffeine_base::BigInt)> {
3064    use logicaffeine_base::BigInt;
3065    if b.is_zero() {
3066        return Some((BigInt::zero(), a.clone()));
3067    }
3068    let magnitude = b.abs();
3069    let (_, residue) = a.div_rem(&magnitude)?;
3070    let r = if residue.is_negative() {
3071        residue.add(&magnitude)
3072    } else {
3073        residue
3074    };
3075    let (q, _) = a.sub(&r).div_rem(b)?;
3076    Some((q, r))
3077}
3078
3079/// A `Bool` constructor as this kernel spells it.
3080fn db_bool(b: bool) -> Db {
3081    Db::Global(if b { "true" } else { "false" }.to_string())
3082}
3083
3084/// Whether `op` names a rule in the BINARY primitive table.
3085///
3086/// This question is asked at every application node of every reduction step and the answer is
3087/// almost always "no", so it must be one name test and no allocation.
3088fn is_binary_primitive(op: &str) -> bool {
3089    matches!(
3090        op,
3091        "add"
3092            | "sub"
3093            | "mul"
3094            | "div"
3095            | "mod"
3096            | "le"
3097            | "lt"
3098            | "ge"
3099            | "gt"
3100            | "Text_append"
3101            | "Text_beq"
3102            | "Text_isPrefixOf"
3103    )
3104}
3105
3106/// Whether `op` names a rule in the UNARY primitive table.
3107fn is_unary_primitive(op: &str) -> bool {
3108    matches!(op, "Text_length")
3109}
3110
3111/// Whether a DEFINITION of `op` outranks the primitive rule of the same name.
3112///
3113/// A primitive fires on a NAME, so it must never beat a body the term was type-checked against:
3114/// a context that defines `Text_append` has to be reduced by what it defined, or the checker
3115/// disagrees with the very declaration it accepted. The question is asked only once a name has
3116/// already matched the table, so the common path never pays for it.
3117fn shadowed_by_a_definition(genv: &Context, op: &str) -> bool {
3118    genv.get_definition_body(op).is_some()
3119}
3120
3121/// Whether the context's DECLARATION of `op` agrees with the type the rule's answer inhabits.
3122///
3123/// SUBJECT REDUCTION, the other half of the same gate. A rule fires on a NAME and a pair of
3124/// literal kinds; nothing here used to look at the declared TYPE. So a context declaring
3125/// `Text_append : Text → Text → Nat` got a kernel where `infer` answered `Nat` and `whnf`
3126/// produced a `Text` literal — a term and its reduct with different types, which is precisely
3127/// what a conversion check may not have, since every use of a reduct in place of its term
3128/// assumes the two are interchangeable.
3129///
3130/// The DECISION is shared with the first kernel on purpose — `reduction::declaration_agrees_with_the_rule`
3131/// reads the same signature table — for the same reason `term::resolve_const_levels` is shared:
3132/// whether a rule APPLIES is a fact about the context, and two kernels that answered it
3133/// differently would be computing two different programs for one closed term. The arithmetic
3134/// each rule then performs stays this kernel's own, which is where independence buys something.
3135fn declaration_agrees_with_the_rule(genv: &Context, op: &str) -> bool {
3136    crate::reduction::declaration_agrees_with_the_rule(genv, op)
3137}
3138
3139/// The `Int` computation rules: a machine fast path that PROMOTES on overflow rather than
3140/// wrapping, and order decided directly. `None` means "no rule for this name at these literal
3141/// kinds", which is how a `Nat`, `Text` or `Float` operand leaves the term stuck instead of
3142/// being silently read as an integer.
3143fn int_binary_db(op: &str, xl: &Literal, yl: &Literal) -> Option<Db> {
3144    if let (Literal::Int(x), Literal::Int(y)) = (xl, yl) {
3145        let fast = match op {
3146            "add" => x.checked_add(*y),
3147            "sub" => x.checked_sub(*y),
3148            "mul" => x.checked_mul(*y),
3149            "div" => euclidean_pair_i64(*x, *y).map(|(q, _)| q),
3150            "mod" => euclidean_pair_i64(*x, *y).map(|(_, r)| r),
3151            _ => None,
3152        };
3153        if let Some(r) = fast {
3154            return Some(Db::Lit(Literal::Int(r)));
3155        }
3156        match op {
3157            "le" => return Some(db_bool(*x <= *y)),
3158            "lt" => return Some(db_bool(*x < *y)),
3159            "ge" => return Some(db_bool(*x >= *y)),
3160            "gt" => return Some(db_bool(*x > *y)),
3161            _ => {}
3162        }
3163    }
3164    // EXACT PATH: arbitrary precision, reached when an operand is a `BigInt` or an `i64` op
3165    // overflowed. Canonicalised by `int_lit` (demoted to `Int` when it fits), so a value has ONE
3166    // literal and definitional equality of literals stays sound.
3167    let (xb, yb) = (lit_bigint(xl)?, lit_bigint(yl)?);
3168    let big = match op {
3169        "add" => Some(xb.add(&yb)),
3170        "sub" => Some(xb.sub(&yb)),
3171        "mul" => Some(xb.mul(&yb)),
3172        "div" => euclidean_pair_big(&xb, &yb).map(|(q, _)| q),
3173        "mod" => euclidean_pair_big(&xb, &yb).map(|(_, r)| r),
3174        _ => None,
3175    };
3176    if let Some(r) = big {
3177        return Some(Db::Lit(int_lit(r)));
3178    }
3179    match op {
3180        "le" => Some(db_bool(xb <= yb)),
3181        "lt" => Some(db_bool(xb < yb)),
3182        "ge" => Some(db_bool(xb >= yb)),
3183        "gt" => Some(db_bool(xb > yb)),
3184        _ => None,
3185    }
3186}
3187
3188/// The `Text` computation rules, from the same specification the main kernel implements:
3189/// `Text_append` concatenates, `Text_beq` decides equality of the two strings, and
3190/// `Text_isPrefixOf a b` holds exactly when `a` is an initial segment of `b`. Anything that is
3191/// not two `Text` literals has no rule at all, so an `Int` operand leaves the term stuck rather
3192/// than being read as text.
3193fn text_binary_db(op: &str, xl: &Literal, yl: &Literal) -> Option<Db> {
3194    let (Literal::Text(a), Literal::Text(b)) = (xl, yl) else {
3195        return None;
3196    };
3197    match op {
3198        "Text_append" => Some(Db::Lit(Literal::Text(format!("{a}{b}")))),
3199        "Text_beq" => Some(db_bool(a == b)),
3200        "Text_isPrefixOf" => Some(db_bool(b.starts_with(a.as_str()))),
3201        _ => None,
3202    }
3203}
3204
3205/// `Text_length` counts CHARACTERS, as Lean's `String.length` does — not bytes, so one
3206/// multi-byte character counts once. The only unary rule in either kernel's table.
3207fn text_unary_db(op: &str, xl: &Literal) -> Option<Db> {
3208    match (op, xl) {
3209        ("Text_length", Literal::Text(s)) => Some(Db::Lit(Literal::Nat(
3210            logicaffeine_base::BigInt::from_u64(s.chars().count() as u64),
3211        ))),
3212        _ => None,
3213    }
3214}
3215
3216/// Reduce a fully-applied primitive on literal arguments — the main kernel's built-in
3217/// computation rules, implemented here INDEPENDENTLY so the re-checker reaches the same value
3218/// by its own arithmetic (`le 2 3 ⤳ true`, `add 2 4 ⤳ 6`, `Text_append "ab" "cd" ⤳ "abcd"`).
3219/// The arguments are themselves reduced first, so `le (add 1 1) 3` works. `None` if `t` is not
3220/// such an application — the answer at almost every node, reached by one pointer walk and one
3221/// name test.
3222///
3223/// **The table is part of the shared specification, not a per-kernel convenience.** A rule the
3224/// main kernel has and this one does not is NOT a safe shortfall: the term stays stuck here, the
3225/// conversion check fails on one side only, and `double_check` reports `Disagree` — a soundness
3226/// alarm — about a proof that is perfectly valid. That is the same argument `MAX_RECHECK_STEPS`
3227/// makes about the step budget, and it applies to every row of this table: a new primitive in
3228/// one engine is a new row in ALL of them, each written from the rule rather than copied.
3229fn try_builtin(genv: &Context, t: &Db) -> Option<Db> {
3230    // The SHAPE and the operation NAME are checked by reference first, before any argument is
3231    // reduced and before any map is consulted.
3232    let Db::App(head, last) = t else { return None };
3233    match head.as_ref() {
3234        // Binary: `(op x) y`.
3235        Db::App(f0, first) => {
3236            let Db::Global(name) = f0.as_ref() else {
3237                return None;
3238            };
3239            let op = name.as_str();
3240            if !is_binary_primitive(op)
3241                || (shadowed_by_a_definition(genv, op)
3242                    && !crate::int_inductive::accelerates_integer_alias(genv, op))
3243                || !declaration_agrees_with_the_rule(genv, op)
3244            {
3245                return None;
3246            }
3247            let operand = |t: &Db| match whnf(genv, t) {
3248                Db::Lit(literal) => Some(literal),
3249                constructor => db_int_literal(genv, &constructor),
3250            };
3251            let (x, y) = (operand(first)?, operand(last)?);
3252            int_binary_db(op, &x, &y).or_else(|| text_binary_db(op, &x, &y))
3253        }
3254        // Unary: `op x`.
3255        Db::Global(name) => {
3256            let op = name.as_str();
3257            if !is_unary_primitive(op)
3258                || shadowed_by_a_definition(genv, op)
3259                || !declaration_agrees_with_the_rule(genv, op)
3260            {
3261                return None;
3262            }
3263            let Db::Lit(x) = whnf(genv, last.as_ref()) else {
3264                return None;
3265            };
3266            text_unary_db(op, &x)
3267        }
3268        _ => None,
3269    }
3270}
3271
3272/// ι for a fixpoint, asked of the WHOLE spine: `(fix f. λx₀ … λxₙ. e) a₀ … aₙ` unrolls when the
3273/// argument at the STRUCTURAL column is constructor-headed.
3274///
3275/// Both the inner Fix application and the restored outer application spine
3276/// ask this helper. An inner application may not yet supply the recursive
3277/// column; a constructor in another position must not unfold a neutral fixpoint.
3278/// This preserves the defining recursion boundary while later arguments arrive.
3279///
3280/// WHICH COLUMN is a shared DECISION, not shared arithmetic: `termination::structural_position`
3281/// is the guard's own answer about this body, and its doc comment names `reduction.rs` and this
3282/// module as its two callers for exactly this reason. Two kernels that picked different columns
3283/// would unroll different fixpoints — one of them past its guard, which is how a normaliser
3284/// diverges. The unrolling below is this kernel's own, over de Bruijn levels.
3285///
3286/// No demand exists when the head is not a `Fix`, the guard admits no column,
3287/// or a partial application has not supplied that column. Constructor admission
3288/// occurs only after the scheduled argument has independently reached weak head.
3289fn fix_structural_column(genv: &Context, t: &Db) -> Option<usize> {
3290    let Db::Fix(body) = spine_head(t) else {
3291        return None;
3292    };
3293    let mut domains = Vec::new();
3294    let mut core = body.as_ref();
3295    while let Db::Lam(domain, inner) = core {
3296        domains.push(domain.as_ref());
3297        core = inner;
3298    }
3299    // The fix binder precedes the lambda telescope. An index outside that
3300    // telescope names the recursive binder or an external local, never a column.
3301    // The innermost `match` is read through an application spine, as the guard reads it.
3302    let preferred = match spine_head(core) {
3303        Db::Match { disc, .. } => match disc.as_ref() {
3304            Db::Var(index) => index
3305                .checked_add(1)
3306                .and_then(|i| domains.len().checked_sub(i)),
3307            _ => None,
3308        },
3309        _ => None,
3310    };
3311    let candidates = domains.iter().enumerate().map(|(position, domain)| {
3312        let inductive = matches!(spine_head(domain),
3313            Db::Global(name) | Db::Const { name, .. } if genv.is_inductive(name));
3314        (position, inductive)
3315    });
3316    let column = crate::termination::select_structural_position(candidates, preferred)?;
3317    let mut supplied = 0usize;
3318    let mut head = t;
3319    while let Db::App(function, _) = head {
3320        supplied += 1;
3321        head = function;
3322    }
3323    (column < supplied).then_some(column)
3324}
3325
3326/// The quotient computation rule in de Bruijn form: `Quot_lift A r B f h (Quot_mk A r a) ⤳
3327/// f a`, and `Quot.ind`'s. Returns the reduct when `t` is exactly that spine, else `None`. The
3328/// major premise is weak-head normalized in `t`'s own local context, so a representative that
3329/// only δ exposes (`Quotient.mk s a := Quot.mk Setoid.r a`) is recognized.
3330fn try_quot_lift_db(genv: &Context, lctx: &dyn LocalTypes, t: &Db) -> Option<Db> {
3331    let (arity, universe) = match spine_head(t) {
3332        Db::Global(n) => {
3333            let arity = match crate::quotient::prelude_kind(genv, n)? {
3334                crate::quotient::PreludeKind::Lift => 6,
3335                crate::quotient::PreludeKind::Induction => 5,
3336                _ => return None,
3337            };
3338            (arity, None)
3339        }
3340        Db::Const { name, levels } => {
3341            let arity = match crate::quotient::kind(genv, name, levels)? {
3342                crate::quotient::Kind::Lift => 6,
3343                crate::quotient::Kind::Induction => 5,
3344                _ => return None,
3345            };
3346            (arity, Some(&levels[0]))
3347        }
3348        _ => return None,
3349    };
3350    let (_, args) = spine_ref(t);
3351    if args.len() != arity {
3352        return None;
3353    }
3354    let q = whnf_in(genv, lctx, args[arity - 1]);
3355    let constructor = match (spine_head(&q), universe) {
3356        (Db::Global(n), None) => {
3357            crate::quotient::prelude_kind(genv, n)
3358                == Some(crate::quotient::PreludeKind::Constructor)
3359        }
3360        (Db::Const { name, levels }, Some(u)) => {
3361            crate::quotient::kind(genv, name, levels) == Some(crate::quotient::Kind::Constructor)
3362                && levels[0].equiv(u)
3363        }
3364        _ => false,
3365    };
3366    let (_, qa) = spine_ref(&q);
3367    if !constructor || qa.len() != 3 {
3368        return None;
3369    }
3370    Some(Db::App(
3371        DbBox::new(args[3].clone()),
3372        DbBox::new(qa[2].clone()),
3373    ))
3374}
3375
3376// ---------------------------------------------------------------------------
3377// THE PRIMITIVE RULE TABLE
3378// ---------------------------------------------------------------------------
3379
3380/// What THIS kernel does with one of the first kernel's registered reduction rules.
3381///
3382/// The prelude DECLARES the reflection and tactic primitives, so they are inside the trusted
3383/// base and a proof may cite what they compute. A rule the main kernel computes and this one
3384/// walks past is NOT a safe shortfall: the redex stays a value here, the conversion check fails
3385/// on one side only, and [`double_check`] reports `Disagree` — a SOUNDNESS ALARM — about a proof
3386/// that is perfectly valid. An alarm that fires on valid proofs is an alarm nobody reads.
3387///
3388/// There are exactly TWO honest answers for a primitive this kernel is handed, and this table
3389/// says which one each rule gets. "Quietly treat it as stuck and then disagree" is neither.
3390#[derive(Clone, Copy, PartialEq, Eq, Debug)]
3391enum RuleKind {
3392    /// This kernel computes the rule ITSELF, from the written specification, over its own de
3393    /// Bruijn representation — so an agreement is corroboration rather than an echo.
3394    Checked,
3395    /// This kernel does NOT compute the rule, and says so: reaching one sets the exhaustion
3396    /// flag, exactly as a spent step budget does, so a later rejection is reported as
3397    /// [`ReCheckError::Unsupported`] — honestly single-checked — instead of as a disagreement.
3398    ///
3399    /// Every row marked this way runs an ENGINE in the first kernel (ring normalisation,
3400    /// Fourier–Motzkin, congruence closure, a derivation checker). A second kernel that
3401    /// transcribed one of those would be the same implementation twice, which corroborates
3402    /// nothing while looking exactly like corroboration — the failure mode this campaign found
3403    /// six times in the universe algebra, where both kernels call one function.
3404    Unchecked,
3405}
3406
3407/// Every reduction rule the FIRST kernel dispatches on, with the number of arguments it
3408/// consumes and what this kernel does with it.
3409///
3410/// `U_universes_extra::the_second_kernels_primitive_table_names_every_primitive_the_first_kernel_dispatches_on`
3411/// reads `reduction.rs`'s own dispatcher and fails if a name is missing here, so a rule added to
3412/// one kernel cannot stay silently absent from the other.
3413const PRIMITIVE_RULES: &[(&str, usize, RuleKind)] = &[
3414    // THE REFLECTION ALGEBRA's evaluator — a recursion over the `Syntax` grammar, so its
3415    // specification is written down in full and this kernel implements it independently. The
3416    // operations `reflection` defines are not rules here: this kernel computes them by their
3417    // definitions, which checks the first kernel's accelerators of them.
3418    ("syn_step", 1, RuleKind::Checked),
3419    ("syn_eval", 2, RuleKind::Checked),
3420    // Certificate-backed successes are checked independently. Unsupported goal/derivation
3421    // shapes still return Unchecked, including the remaining derivation constructors.
3422    ("concludes", 1, RuleKind::Checked),
3423    ("try_refl", 1, RuleKind::Unchecked),
3424    ("try_compute", 1, RuleKind::Unchecked),
3425    ("try_ring", 1, RuleKind::Checked),
3426    ("try_lia", 1, RuleKind::Checked),
3427    ("try_cc", 1, RuleKind::Checked),
3428    ("try_simp", 1, RuleKind::Unchecked),
3429    ("try_omega", 1, RuleKind::Unchecked),
3430    ("try_auto", 1, RuleKind::Unchecked),
3431    ("try_decide", 1, RuleKind::Unchecked),
3432    ("try_assumption", 1, RuleKind::Unchecked),
3433    ("try_split", 1, RuleKind::Unchecked),
3434    ("try_left", 1, RuleKind::Unchecked),
3435    ("try_right", 1, RuleKind::Unchecked),
3436    ("try_bitblast", 1, RuleKind::Unchecked),
3437    ("try_tabulate", 1, RuleKind::Unchecked),
3438    ("try_hw_auto", 1, RuleKind::Unchecked),
3439    ("try_inversion", 1, RuleKind::Unchecked),
3440    ("tact_fail", 1, RuleKind::Unchecked),
3441    ("induction_num_cases", 1, RuleKind::Unchecked),
3442    ("try_cong", 2, RuleKind::Unchecked),
3443    ("try_rewrite", 2, RuleKind::Unchecked),
3444    ("try_rewrite_rev", 2, RuleKind::Unchecked),
3445    ("try_script", 2, RuleKind::Unchecked),
3446    ("induction_base_goal", 2, RuleKind::Unchecked),
3447    ("tact_try", 2, RuleKind::Unchecked),
3448    ("tact_repeat", 2, RuleKind::Unchecked),
3449    ("tact_solve", 2, RuleKind::Unchecked),
3450    ("tact_first", 2, RuleKind::Unchecked),
3451    ("tact_orelse", 3, RuleKind::Unchecked),
3452    ("tact_then", 3, RuleKind::Unchecked),
3453    ("induction_step_goal", 3, RuleKind::Unchecked),
3454    ("try_induction", 3, RuleKind::Unchecked),
3455    ("try_destruct", 3, RuleKind::Unchecked),
3456    ("try_apply", 3, RuleKind::Unchecked),
3457];
3458
3459/// The names in `PRIMITIVE_RULES` — the reading surface the cross-kernel ratchet needs, so the
3460/// table can be compared against the first kernel's dispatcher from a test rather than by eye.
3461pub fn primitive_rule_names() -> Vec<&'static str> {
3462    PRIMITIVE_RULES.iter().map(|(n, _, _)| *n).collect()
3463}
3464
3465/// The arity and treatment of a primitive rule, or `None` when the name is not one.
3466fn primitive_rule(name: &str) -> Option<(usize, RuleKind)> {
3467    PRIMITIVE_RULES
3468        .iter()
3469        .find(|(n, _, _)| *n == name)
3470        .map(|(_, arity, kind)| (*arity, *kind))
3471}
3472
3473// ---------------------------------------------------------------------------
3474// THE REFLECTION ALGEBRA, IMPLEMENTED INDEPENDENTLY
3475// ---------------------------------------------------------------------------
3476//
3477// `Syntax` is a first-order grammar — `SVar n`, `SGlobal n`, `SSort u`, `SLit n`, `SName s`,
3478// `SApp f x`, `SLam T b`, `SPi T B`. The operations `reflection` defines over it are checked
3479// definitions, which this kernel computes by unfolding; the evaluator (`syn_step`, `syn_eval`) is
3480// a rule whose answer the grammar fixes, written down in full (in `reduction.rs`'s doc comments
3481// and in this module's), so this kernel computes it from the rule rather than by transcribing a
3482// function, with its own substitution below.
3483//
3484// Tactic success cases use the independent certificate module. The remaining primitives
3485// explicitly report incomplete checking.
3486
3487/// A `Syntax` node with ONE argument: `(Ctor arg)`.
3488fn s_unary(t: &Db) -> Option<(&str, &Db)> {
3489    let Db::App(f, a) = t else { return None };
3490    let Db::Global(n) = f.as_ref() else {
3491        return None;
3492    };
3493    Some((n.as_str(), a.as_ref()))
3494}
3495
3496/// A `Syntax` node with TWO arguments: `((Ctor a) b)`.
3497fn s_binary(t: &Db) -> Option<(&str, &Db, &Db)> {
3498    let Db::App(f, b) = t else { return None };
3499    let Db::App(c, a) = f.as_ref() else {
3500        return None;
3501    };
3502    let Db::Global(n) = c.as_ref() else {
3503        return None;
3504    };
3505    Some((n.as_str(), a.as_ref(), b.as_ref()))
3506}
3507
3508/// The machine integer a reflected numeral carries — the ONLY literal kind the `Syntax` layer's
3509/// `SVar`/`SLit`/`SGlobal` indices are written at, so a `Nat` or `BigInt` operand leaves the
3510/// rule stuck instead of being read as one.
3511fn s_int(t: &Db) -> Option<i64> {
3512    match t {
3513        Db::Lit(Literal::Int(n)) => Some(*n),
3514        _ => None,
3515    }
3516}
3517
3518fn s_mk1(ctor: &str, a: Db) -> Db {
3519    Db::App(DbBox::new(Db::Global(ctor.to_string())), DbBox::new(a))
3520}
3521
3522fn s_mk2(ctor: &str, a: Db, b: Db) -> Db {
3523    Db::App(DbBox::new(s_mk1(ctor, a)), DbBox::new(b))
3524}
3525
3526fn s_lit(n: i64) -> Db {
3527    s_mk1("SLit", Db::Lit(Literal::Int(n)))
3528}
3529
3530fn s_var(n: i64) -> Db {
3531    s_mk1("SVar", Db::Lit(Literal::Int(n)))
3532}
3533
3534fn s_name(s: &str) -> Db {
3535    s_mk1("SName", Db::Lit(Literal::Text(s.to_string())))
3536}
3537
3538/// `syn_lift amount cutoff t` — shift every free index at or above `cutoff` by `amount`.
3539///
3540/// Specification: `SVar k` becomes `SVar (k + amount)` when `k >= cutoff` and is untouched
3541/// otherwise; other leaves are untouched; `SApp` lifts both children at the same cutoff;
3542/// `SLam`/`SPi` lift the annotation at `cutoff` and the body at `cutoff + 1`, because the body
3543/// is one binder deeper.
3544fn syn_lift_db(amount: i64, cutoff: i64, t: &Db) -> Option<Db> {
3545    let _nest = nest(stack_mark())?;
3546    if let Some((c, a)) = s_unary(t) {
3547        match c {
3548            "SVar" => {
3549                let k = s_int(a)?;
3550                return Some(if k >= cutoff {
3551                    s_var(k.checked_add(amount)?)
3552                } else {
3553                    t.clone()
3554                });
3555            }
3556            "SGlobal" | "SSort" | "SLit" | "SName" => return Some(t.clone()),
3557            _ => {}
3558        }
3559    }
3560    if let Some((c, a, b)) = s_binary(t) {
3561        match c {
3562            "SApp" => {
3563                return Some(s_mk2(
3564                    "SApp",
3565                    syn_lift_db(amount, cutoff, a)?,
3566                    syn_lift_db(amount, cutoff, b)?,
3567                ));
3568            }
3569            "SLam" | "SPi" => {
3570                return Some(s_mk2(
3571                    c,
3572                    syn_lift_db(amount, cutoff, a)?,
3573                    syn_lift_db(amount, cutoff + 1, b)?,
3574                ));
3575            }
3576            _ => {}
3577        }
3578    }
3579    None
3580}
3581
3582/// `t` with `replacement` written at `SVar index` and the binder `index` counted removed: the
3583/// substitution a β step of `syn_step` performs. Every surviving `SVar k` with `k > index` drops
3584/// to `k - 1`, because the binder it counted is gone; going under a binder lifts the replacement
3585/// by one at cutoff 0, so its own free variables keep pointing where they did.
3586fn syn_beta_db(replacement: &Db, index: i64, t: &Db) -> Option<Db> {
3587    let _nest = nest(stack_mark())?;
3588    if let Some((c, a)) = s_unary(t) {
3589        match c {
3590            "SVar" => {
3591                let k = s_int(a)?;
3592                return Some(if k == index {
3593                    replacement.clone()
3594                } else if k > index {
3595                    s_var(k - 1)
3596                } else {
3597                    t.clone()
3598                });
3599            }
3600            "SGlobal" | "SSort" | "SLit" | "SName" => return Some(t.clone()),
3601            _ => {}
3602        }
3603    }
3604    if let Some((c, a, b)) = s_binary(t) {
3605        match c {
3606            "SApp" => {
3607                return Some(s_mk2(
3608                    "SApp",
3609                    syn_beta_db(replacement, index, a)?,
3610                    syn_beta_db(replacement, index, b)?,
3611                ));
3612            }
3613            "SLam" | "SPi" => {
3614                let head = syn_beta_db(replacement, index, a)?;
3615                let lifted = syn_lift_db(1, 0, replacement)?;
3616                let body = syn_beta_db(&lifted, index + 1, b)?;
3617                return Some(s_mk2(c, head, body));
3618            }
3619            _ => {}
3620        }
3621    }
3622    None
3623}
3624
3625/// Arithmetic on two reflected integer literals: `SApp (SApp (SName op) (SLit n)) (SLit m)`.
3626///
3627/// The reflected object language MODELS this kernel's own arithmetic — a proof door accepts
3628/// what it computes — so `div`/`mod` are the same TOTAL Euclidean pair the primitive table
3629/// uses, reached through this module's own [`euclidean_pair_i64`]. A reflected `div` that
3630/// truncated while the kernel's rounded the other way would certify `Eq Int (div (-7) 2) (-3)`,
3631/// a false equation with a kernel-checked proof in front of it.
3632fn syn_arith_db(func: &Db, arg: &Db) -> Option<Db> {
3633    let (sapp, op_node, n_node) = s_binary(func)?;
3634    if sapp != "SApp" {
3635        return None;
3636    }
3637    let (sname, op_lit) = s_unary(op_node)?;
3638    if sname != "SName" {
3639        return None;
3640    }
3641    let Db::Lit(Literal::Text(op)) = op_lit else {
3642        return None;
3643    };
3644    let (nc, n_lit) = s_unary(n_node)?;
3645    let (mc, m_lit) = s_unary(arg)?;
3646    if nc != "SLit" || mc != "SLit" {
3647        return None;
3648    }
3649    let (n, m) = (s_int(n_lit)?, s_int(m_lit)?);
3650    let r = match op.as_str() {
3651        "add" => n.checked_add(m),
3652        "sub" => n.checked_sub(m),
3653        "mul" => n.checked_mul(m),
3654        "div" => euclidean_pair_i64(n, m).map(|(q, _)| q),
3655        "mod" => euclidean_pair_i64(n, m).map(|(_, r)| r),
3656        _ => None,
3657    }?;
3658    Some(s_lit(r))
3659}
3660
3661/// `syn_step` — ONE leftmost-outermost step of the reflected evaluator.
3662///
3663/// Specification, in order: reflected arithmetic on two literals; β on `SApp (SLam T b) a`;
3664/// δ/ι by REIFYING the application and reducing it with this kernel's own reducer; then the
3665/// congruence rules (step the function, else step the argument); and finally the term
3666/// unchanged, which is how a stuck term reports that it is a value.
3667///
3668/// The δ hop is where the two kernels could part company for a reason that is NOT a
3669/// disagreement: reduction here is metered, so a budget spent mid-way would hand back a PARTIAL
3670/// reduct and this kernel would compute a different `Syntax` value from a valid one. So the
3671/// meter is read: a hop whose reduction was cut short reports `Unchecked` instead of an answer.
3672fn syn_step_db(genv: &Context, t: &Db) -> PrimStep {
3673    let Some(_nest) = nest(stack_mark()) else {
3674        return PrimStep::Unchecked;
3675    };
3676    let Some((c, func, arg)) = s_binary(t) else {
3677        return PrimStep::Reduced(t.clone());
3678    };
3679    if c != "SApp" {
3680        return PrimStep::Reduced(t.clone());
3681    }
3682    if let Some(r) = syn_arith_db(func, arg) {
3683        return PrimStep::Reduced(r);
3684    }
3685    if let Some((lam, _annotation, body)) = s_binary(func) {
3686        if lam == "SLam" {
3687            return match syn_beta_db(arg, 0, body) {
3688                Some(r) => PrimStep::Reduced(r),
3689                None => PrimStep::Unchecked,
3690            };
3691        }
3692    }
3693    if let Some(reified) = syntax_to_db(t) {
3694        match db_normalize_checked(genv, &reified) {
3695            None => return PrimStep::Unchecked,
3696            Some(nf) if nf != reified => {
3697                if let Some(s) = db_to_syntax(&nf) {
3698                    return PrimStep::Reduced(s);
3699                }
3700            }
3701            Some(_) => {}
3702        }
3703    }
3704    match syn_step_db(genv, func) {
3705        PrimStep::Unchecked => return PrimStep::Unchecked,
3706        PrimStep::Reduced(f2) if f2 != *func => {
3707            return PrimStep::Reduced(s_mk2("SApp", f2, arg.clone()));
3708        }
3709        _ => {}
3710    }
3711    match syn_step_db(genv, arg) {
3712        PrimStep::Unchecked => return PrimStep::Unchecked,
3713        PrimStep::Reduced(a2) if a2 != *arg => {
3714            return PrimStep::Reduced(s_mk2("SApp", func.clone(), a2));
3715        }
3716        _ => {}
3717    }
3718    PrimStep::Reduced(t.clone())
3719}
3720
3721/// `syn_eval fuel t` — iterate [`syn_step_db`] until nothing changes or the fuel runs out.
3722///
3723/// The fuel is written in the TERM, so an exhausted evaluation is a legitimate answer for the
3724/// object-language expression (the caller can see the bound it asked for) and the partial
3725/// reduct is returned, exactly as the first kernel returns it.
3726fn syn_eval_db(genv: &Context, fuel: i64, t: &Db) -> PrimStep {
3727    let mut cur = t.clone();
3728    let mut left = fuel;
3729    while left > 0 {
3730        match syn_step_db(genv, &cur) {
3731            PrimStep::Reduced(next) => {
3732                if next == cur {
3733                    return PrimStep::Reduced(cur);
3734                }
3735                cur = next;
3736            }
3737            other => return other,
3738        }
3739        left -= 1;
3740    }
3741    PrimStep::Reduced(cur)
3742}
3743
3744/// Reify a reflected term into an ordinary de Bruijn term, so the δ/ι rules can run on it.
3745///
3746/// A reflected de Bruijn INDEX becomes an opaque global (`v0`, `g0`) rather than a `Db::Var`:
3747/// the index counts binders of the OBJECT language, which the reflected `SLam` does not open in
3748/// this one, so reading it as a real variable would bind it to the wrong thing. Opaque is the
3749/// faithful reading — it is exactly what the first kernel's reification does with its own named
3750/// representation, and it is why the δ hop only ever fires on variable-free reflected terms.
3751fn syntax_to_db(t: &Db) -> Option<Db> {
3752    let _nest = nest(stack_mark())?;
3753    if let Some((c, a)) = s_unary(t) {
3754        match c {
3755            "SName" => {
3756                let Db::Lit(Literal::Text(s)) = a else {
3757                    return None;
3758                };
3759                return Some(Db::Global(s.clone()));
3760            }
3761            "SLit" => return Some(Db::Lit(Literal::Int(s_int(a)?))),
3762            "SVar" => return Some(Db::Global(format!("v{}", s_int(a)?))),
3763            "SGlobal" => return Some(Db::Global(format!("g{}", s_int(a)?))),
3764            _ => {}
3765        }
3766    }
3767    if let Some((c, a, b)) = s_binary(t) {
3768        let (l, r) = (syntax_to_db(a)?, syntax_to_db(b)?);
3769        match c {
3770            "SApp" => return Some(Db::App(DbBox::new(l), DbBox::new(r))),
3771            "SLam" => return Some(Db::Lam(DbBox::new(l), DbBox::new(r))),
3772            "SPi" => return Some(Db::Pi(DbBox::new(l), DbBox::new(r))),
3773            _ => {}
3774        }
3775    }
3776    None
3777}
3778
3779/// Reflect an ordinary term back into `Syntax`. The inverse of [`syntax_to_db`] on the fragment
3780/// both cover; `None` for anything the `Syntax` grammar cannot spell, so a reduct that left the
3781/// fragment leaves the rule stuck instead of being mis-reflected.
3782fn db_to_syntax(t: &Db) -> Option<Db> {
3783    let _nest = nest(stack_mark())?;
3784    Some(match t {
3785        Db::Global(n) => s_name(n),
3786        Db::Const { name, .. } => s_name(name),
3787        Db::App(f, x) => s_mk2("SApp", db_to_syntax(f)?, db_to_syntax(x)?),
3788        Db::Pi(d, b) => s_mk2("SPi", db_to_syntax(d)?, db_to_syntax(b)?),
3789        Db::Lam(d, b) => s_mk2("SLam", db_to_syntax(d)?, db_to_syntax(b)?),
3790        Db::Sort(u) => s_mk1("SSort", univ_to_syntax_db(u)),
3791        Db::Lit(Literal::Int(n)) => s_lit(*n),
3792        Db::Lit(Literal::Text(s)) => s_name(s),
3793        _ => return None,
3794    })
3795}
3796
3797/// The reflected form of a universe. Deeply embedded and TOTAL, so a polymorphic level reflects
3798/// rather than stopping the walk.
3799fn univ_to_syntax_db(u: &Universe) -> Db {
3800    match u {
3801        Universe::SProp => Db::Global("USProp".to_string()),
3802        Universe::Prop => Db::Global("UProp".to_string()),
3803        Universe::Type(n) => s_mk1("UType", Db::Lit(Literal::Int(*n as i64))),
3804        Universe::Var(v) => s_mk1("UVar", Db::Global(v.clone())),
3805        Universe::Succ(l) => s_mk1("USucc", univ_to_syntax_db(l)),
3806        Universe::Max(a, b) => s_mk2("UMax", univ_to_syntax_db(a), univ_to_syntax_db(b)),
3807        Universe::IMax(a, b) => s_mk2("UIMax", univ_to_syntax_db(a), univ_to_syntax_db(b)),
3808    }
3809}
3810
3811/// Full normalisation by descent: weak-head-normalise, then normalise the children.
3812///
3813/// `None` only when a nesting guard tripped, which the exhaustion flag has already recorded.
3814fn db_normalize(genv: &Context, t: &Db) -> Option<Db> {
3815    let _nest = nest(stack_mark())?;
3816    Some(match whnf(genv, t) {
3817        Db::App(f, a) => Db::App(
3818            DbBox::new(db_normalize(genv, &f)?),
3819            DbBox::new(db_normalize(genv, &a)?),
3820        ),
3821        Db::Lam(d, b) => Db::Lam(
3822            DbBox::new(db_normalize(genv, &d)?),
3823            DbBox::new(db_normalize(genv, &b)?),
3824        ),
3825        Db::Pi(d, b) => Db::Pi(
3826            DbBox::new(db_normalize(genv, &d)?),
3827            DbBox::new(db_normalize(genv, &b)?),
3828        ),
3829        other => other,
3830    })
3831}
3832
3833/// [`db_normalize`], reporting whether the reduction FINISHED.
3834///
3835/// `None` means a meter tripped somewhere inside, so the answer is a partial reduct and not the
3836/// value of the expression. The caller must then report `Unchecked` rather than hand a partial
3837/// reduct to a rule whose answer a proof may cite — the same argument the step budget makes
3838/// about a rejection. The flag is saved and restored so this question does not erase an
3839/// exhaustion the surrounding reduction had already recorded.
3840fn db_normalize_checked(genv: &Context, t: &Db) -> Option<Db> {
3841    let outer = WHNF_EXHAUSTED.with(|e| e.replace(false));
3842    let out = db_normalize(genv, t);
3843    let tripped = WHNF_EXHAUSTED.with(|e| e.get());
3844    WHNF_EXHAUSTED.with(|e| e.set(outer || tripped));
3845    if tripped {
3846        None
3847    } else {
3848        out
3849    }
3850}
3851
3852/// What one primitive rule did with its operands.
3853#[derive(Debug)]
3854enum PrimStep {
3855    /// The rule fired and this is its value.
3856    Reduced(Db),
3857    /// The rule's operands are outside its grammar, so there is nothing to compute — a VALUE,
3858    /// exactly as the first kernel leaves it.
3859    Stuck,
3860    /// This kernel did not compute the rule, and has set the exhaustion flag to say so.
3861    Unchecked,
3862}
3863
3864/// Whether a name COULD be a primitive rule — a few byte comparisons, short-circuiting on the
3865/// first character. Asked at every application node of every reduction step, where the answer is
3866/// almost always "no", so it must cost nothing before the table is consulted.
3867fn looks_like_a_primitive_rule(name: &str) -> bool {
3868    name.starts_with("syn_")
3869        || name.starts_with("try_")
3870        || name.starts_with("tact_")
3871        || name.starts_with("induction_")
3872        || name == "concludes"
3873}
3874
3875/// Read the certificate grammar directly from this checker's representation.
3876fn certificate_syntax(t: &Db) -> Option<crate::tactic_cert::Syn> {
3877    use crate::tactic_cert::Syn;
3878    let (head, args) = spine_ref(t);
3879    let Db::Global(name) = head else { return None };
3880    match (name.as_str(), args.as_slice()) {
3881        ("SLit", [Db::Lit(Literal::Int(n))]) => Some(Syn::Lit(*n)),
3882        ("SVar", [Db::Lit(Literal::Int(n))]) => Some(Syn::Var(*n)),
3883        ("SName", [Db::Lit(Literal::Text(n))]) => Some(Syn::Name(n.clone())),
3884        ("SApp", [f, x]) => Some(Syn::App(
3885            Box::new(certificate_syntax(f)?),
3886            Box::new(certificate_syntax(x)?),
3887        )),
3888        _ => None,
3889    }
3890}
3891
3892/// A successful certificate corroborates a result; an absent certificate proves nothing.
3893fn apply_certificate_rule(name: &str, operand: &Db) -> PrimStep {
3894    use crate::tactic_cert::CertifiablePrimitive;
3895    let (primitive, goal) = if name == "concludes" {
3896        let (head, args) = spine_ref(operand);
3897        let Db::Global(constructor) = head else {
3898            return PrimStep::Unchecked;
3899        };
3900        let [goal] = args.as_slice() else {
3901            return PrimStep::Unchecked;
3902        };
3903        let Some(primitive) = CertifiablePrimitive::ALL
3904            .into_iter()
3905            .find(|p| p.success_constructor() == constructor)
3906        else {
3907            return PrimStep::Unchecked;
3908        };
3909        (primitive, *goal)
3910    } else {
3911        let Some(primitive) = CertifiablePrimitive::of_rule(name) else {
3912            return PrimStep::Unchecked;
3913        };
3914        (primitive, operand)
3915    };
3916    let Some(syntax) = certificate_syntax(goal) else {
3917        return PrimStep::Unchecked;
3918    };
3919    if !primitive.verify(&syntax) {
3920        return PrimStep::Unchecked;
3921    }
3922    if name == "concludes" {
3923        PrimStep::Reduced(goal.clone())
3924    } else {
3925        PrimStep::Reduced(Db::App(
3926            DbBox::new(Db::Global(primitive.success_constructor().to_string())),
3927            DbBox::new(goal.clone()),
3928        ))
3929    }
3930}
3931
3932/// Apply one rule of the reflection algebra to its ALREADY-NORMALISED operands.
3933fn apply_reflection_rule(genv: &Context, name: &str, args: &[Db]) -> PrimStep {
3934    let value = |o: Option<Db>| match o {
3935        Some(d) => PrimStep::Reduced(d),
3936        None => PrimStep::Stuck,
3937    };
3938    match name {
3939        "try_ring" | "try_lia" | "try_cc" | "concludes" => apply_certificate_rule(name, &args[0]),
3940        "syn_step" => syn_step_db(genv, &args[0]),
3941        "syn_eval" => match s_int(&args[0]) {
3942            Some(fuel) => syn_eval_db(genv, fuel, &args[1]),
3943            None => PrimStep::Stuck,
3944        },
3945        // Every `Checked` row above is handled. A `Checked` row with no arm would silently
3946        // become "stuck", i.e. exactly the cry-wolf this table exists to end, so the default
3947        // is the honest one instead.
3948        _ => PrimStep::Unchecked,
3949    }
3950}
3951
3952/// Dispatch one of the first kernel's registered reduction rules over this kernel's own
3953/// representation. `None` when `t` is not a saturated application of a table name — the answer
3954/// at almost every node, reached by one pointer walk and a few byte comparisons.
3955///
3956/// A DEFINITION of the name outranks the rule, in both kernels: a primitive fires on a NAME and
3957/// must never beat a body the term was type-checked against.
3958fn try_primitive_rule(genv: &Context, t: &Db) -> Option<PrimStep> {
3959    let Db::Global(head) = spine_head(t) else {
3960        return None;
3961    };
3962    if !looks_like_a_primitive_rule(head) {
3963        return None;
3964    }
3965    let (arity, kind) = primitive_rule(head)?;
3966    if shadowed_by_a_definition(genv, head)
3967        || !crate::reduction::reflection_declaration_agrees(genv, head)
3968    {
3969        return None;
3970    }
3971    let (_, args) = spine_ref(t);
3972    if args.len() < arity {
3973        return None;
3974    }
3975    if kind == RuleKind::Unchecked {
3976        return Some(PrimStep::Unchecked);
3977    }
3978    // The first kernel normalises each operand before walking the grammar, so this one does too
3979    // — and it reads the meter while doing it, because a rule fed a PARTIAL reduct would answer
3980    // a different question from the rule fed the value.
3981    let mut operands = Vec::with_capacity(arity);
3982    for a in &args[..arity] {
3983        match db_normalize_checked(genv, a) {
3984            Some(n) => operands.push(n),
3985            None => return Some(PrimStep::Unchecked),
3986        }
3987    }
3988    // Over-application: the rule consumes its own arguments and the surplus stays applied to the
3989    // result, which is where the first kernel's innermost-first descent leaves them too.
3990    let surplus: Vec<Db> = args[arity..].iter().map(|a| (*a).clone()).collect();
3991    Some(match apply_reflection_rule(genv, head, &operands) {
3992        PrimStep::Reduced(r) => PrimStep::Reduced(
3993            surplus
3994                .into_iter()
3995                .fold(r, |acc, x| Db::App(DbBox::new(acc), DbBox::new(x))),
3996        ),
3997        other => other,
3998    })
3999}
4000
4001/// The re-checker's reduction step budget, per outermost `whnf`.
4002///
4003/// It is deliberately the SAME constant `reduction::normalize_checked` gives the main kernel. A
4004/// second kernel with a DIFFERENT budget is worse than no second kernel on exactly the terms
4005/// that matter: one runs out of room where the other does not, the conversion check fails on one
4006/// side only, and `double_check` reports a soundness alarm about a valid proof. The budget is
4007/// part of the shared specification, not an implementation detail.
4008const MAX_RECHECK_STEPS: usize = 1 << 20;
4009
4010/// How deep the re-checker will nest NATIVE recursion inside `whnf`.
4011///
4012/// Limit on logical head-reduction demands, including suspended application,
4013/// Match and fix-argument frames. Moving these demands off the native stack
4014/// does not remove this independent resource boundary.
4015const MAX_RECHECK_WHNF_DEPTH: usize = 512;
4016
4017/// The largest term the re-checker will carry through a reduction, in nodes.
4018///
4019/// A step budget alone does NOT bound memory. Each fix-unfolding substitutes the fixpoint's whole
4020/// body at every recursive occurrence, so a reduction that does not converge grows the term
4021/// GEOMETRICALLY — measured at 11 GB of resident term inside a hundred seconds, with the step
4022/// budget nowhere near spent. A checker that dies of OOM is exactly as useless as one that dies of
4023/// `SIGABRT`, so size is metered too.
4024const MAX_RECHECK_TERM_NODES: usize = 1 << 19;
4025
4026/// Whether `t` has more than `limit` nodes — measured with an EXPLICIT stack and an early exit,
4027/// so asking the question about a pathological term neither overflows nor costs more than the
4028/// limit itself.
4029fn db_forest_size_exceeds(mut work: Vec<&Db>, limit: usize) -> bool {
4030    let mut seen = 0usize;
4031    while let Some(node) = work.pop() {
4032        seen += 1;
4033        if seen > limit {
4034            return true;
4035        }
4036        match node {
4037            Db::Sort(_) | Db::Var(_) | Db::Global(_) | Db::Const { .. } | Db::Lit(_) => {}
4038            Db::Pi(a, b) | Db::Lam(a, b) | Db::App(a, b) => {
4039                work.push(a);
4040                work.push(b);
4041            }
4042            Db::Fix(b) => work.push(b),
4043            Db::MutualFix { defs, .. } => work.extend(defs.iter()),
4044            Db::Let(a, b, c) => {
4045                work.push(a);
4046                work.push(b);
4047                work.push(c);
4048            }
4049            Db::Match {
4050                disc,
4051                motive,
4052                cases,
4053            } => {
4054                work.push(disc);
4055                work.push(motive);
4056                work.extend(cases.iter());
4057            }
4058        }
4059    }
4060    false
4061}
4062
4063/// How much of the thread's stack the re-checker will spend descending before it stops.
4064///
4065/// A DEPTH cap is a proxy for the thing that actually runs out, and a bad one: a frame of this
4066/// module's `whnf` costs kilobytes in a debug build and a few hundred bytes optimised, so any
4067/// single number is either far below what a real proof needs or far above what a 2 MiB thread can
4068/// hold. So the meter measures the stack ITSELF, by the distance from the outermost re-checker
4069/// frame — which adapts to the build, to the thread, and to how much the caller had already used.
4070/// HALF the stack this thread actually has, so the other half is left to unwind and report
4071/// through. Derived rather than fixed: the two kernels now SIZE their stack from the term's own
4072/// depth (`term_store::deepen_stack`), and a hard-coded budget would give up with tens of
4073/// megabytes unused — the second kernel answering `Unsupported` about a term the first kernel
4074/// checks happily, which is single-checking wearing a two-kernel badge. `kernel_stack_bytes()`
4075/// reports the stack the kernel arranged, or the 2 MiB default when nobody sized it, so an
4076/// un-wired call behaves byte-identically to the constant this replaced.
4077fn recheck_stack_budget() -> usize {
4078    crate::term_store::kernel_stack_bytes() / 2
4079}
4080
4081/// The address of a local in the CALLER's frame — a monotone proxy for how deep the native stack
4082/// has grown. Always inlined, so the local belongs to the guarded function rather than to this one.
4083#[inline(always)]
4084fn stack_mark() -> usize {
4085    let probe = 0u8;
4086    std::ptr::addr_of!(probe) as usize
4087}
4088
4089/// Restores the nesting count on the way out, including on a panic.
4090struct NestGuard;
4091
4092impl Drop for NestGuard {
4093    fn drop(&mut self) {
4094        RECHECK_NEST.with(|n| n.set(n.get().saturating_sub(1)));
4095    }
4096}
4097
4098/// A ticket for one native frame of the re-checker's recursion, or `None` when the stack budget
4099/// is spent — in which case the caller must return its SAFE answer (an unreduced term, "not
4100/// equal", or `Unsupported`) and the exhaustion flag makes the whole verdict honestly incomplete.
4101///
4102/// Called as `nest(stack_mark())` so the measured address is the CALLER's.
4103fn nest(here: usize) -> Option<NestGuard> {
4104    let depth = RECHECK_NEST.with(|n| n.get());
4105    if depth == 0 {
4106        RECHECK_STACK_BASE.with(|b| b.set(here));
4107    } else if RECHECK_STACK_BASE.with(|b| b.get()).abs_diff(here) > recheck_stack_budget() {
4108        WHNF_EXHAUSTED.with(|e| e.set(true));
4109        return None;
4110    }
4111    RECHECK_NEST.with(|n| n.set(depth + 1));
4112    Some(NestGuard)
4113}
4114
4115thread_local! {
4116    /// Native nesting count across every recursive function in this module.
4117    static RECHECK_NEST: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4118    /// Stack address of the outermost re-checker frame.
4119    static RECHECK_STACK_BASE: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4120    /// Logical nesting depth of `whnf`, including suspended iterative demands.
4121    static WHNF_DEPTH: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4122    /// Steps remaining for the current outermost `whnf`.
4123    static WHNF_FUEL: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4124    /// Whether the budget or the depth door stopped a reduction since the flag was cleared.
4125    /// A reduction that was CUT SHORT did not compute a normal form, and a conversion check
4126    /// that compares two abandoned reductions has certified nothing — so the re-checker reports
4127    /// `Unsupported` (honestly single-checked) rather than a verdict it did not earn.
4128    static WHNF_EXHAUSTED: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
4129}
4130
4131thread_local! {
4132    /// Whether `infer` is typing a term conversion or reduction PRODUCED — see [`infer_reduct`].
4133    static REDUCT_INFERENCE: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
4134}
4135
4136/// Types reducts until dropped, including on a panic; scopes nest.
4137struct ReductInference(bool);
4138
4139impl ReductInference {
4140    fn enter() -> Self {
4141        ReductInference(REDUCT_INFERENCE.with(|m| m.replace(true)))
4142    }
4143}
4144
4145impl Drop for ReductInference {
4146    fn drop(&mut self) {
4147        REDUCT_INFERENCE.with(|m| m.set(self.0));
4148    }
4149}
4150
4151/// The type of a term that conversion or reduction produced — a REDUCT. Its depth is set by how
4152/// far a computation ran, not by how deep the input was written, so the door at `recheck`'s entry
4153/// never measured it and the stack sized from the input need not hold it: a reduction the budget
4154/// cut short leaves exactly such a term, a tower of pending eliminations as deep as the reduction
4155/// got. Its inference is therefore metered as the reduction that made it is. Past the meter it
4156/// stops, the exhaustion flag records the stop, and the caller's "no" becomes an honest resource
4157/// limit rather than a native overflow.
4158fn infer_reduct(genv: &Context, lctx: &dyn LocalTypes, t: &Db) -> RResult<Db> {
4159    let _reduct = ReductInference::enter();
4160    infer(genv, lctx, t)
4161}
4162
4163/// Clear the exhaustion flag and report whether anything tripped it since the last clear.
4164fn take_budget_exhausted() -> bool {
4165    WHNF_EXHAUSTED.with(|e| e.replace(false))
4166}
4167
4168thread_local! {
4169    /// This check met a reduction rule of the first kernel that this one does not compute (an
4170    /// unchecked primitive, a `@[simp]` rewrite). Such a stop is not a resource limit: no amount
4171    /// of fuel decides it.
4172    static UNCHECKED_RULE: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
4173}
4174
4175/// Start a check's record: no stop and no unchecked rule yet.
4176fn begin_check() {
4177    take_budget_exhausted();
4178    UNCHECKED_RULE.with(|u| u.set(false));
4179}
4180
4181/// Stop here: this kernel does not compute the rule it has reached. Reported through the same
4182/// exhaustion channel as a spent budget, and recorded so the stop is classified as unsupported.
4183fn mark_unchecked_rule() {
4184    WHNF_EXHAUSTED.with(|e| e.set(true));
4185    UNCHECKED_RULE.with(|u| u.set(true));
4186}
4187
4188/// A stop outside any rejection: unsupported if the check met a rule this kernel does not
4189/// compute, otherwise a resource limit.
4190fn stopped(what: impl Into<String>) -> Incomplete {
4191    let what = what.into();
4192    match UNCHECKED_RULE.with(|u| u.get()) {
4193        true => Incomplete::unsupported(format!("{what}: the re-checker reached a rule it does not compute")),
4194        false => match ReCheckError::resource_limit(format!(
4195            "{what}: the re-checker's budget ({MAX_RECHECK_STEPS} steps, depth {MAX_RECHECK_WHNF_DEPTH}, \
4196             {MAX_RECHECK_TERM_NODES} nodes) ran out"
4197        )) {
4198            ReCheckError::Unsupported(incomplete) => incomplete,
4199            ReCheckError::Ill(_) => unreachable!("a resource limit is an incompleteness"),
4200        },
4201    }
4202}
4203
4204/// The honest account of a rejection reached after a stop: no verdict. An unchecked rule met
4205/// anywhere in the check makes it unsupported, since more resources could never decide it;
4206/// otherwise a resource bound stopped it.
4207fn cut_short(rejection: &ReCheckError, what: &str) -> ReCheckError {
4208    if UNCHECKED_RULE.with(|u| u.get()) {
4209        ReCheckError::unsupported(format!(
4210            "the re-checker's {what} reached a rule it does not compute, so its rejection \
4211             ({rejection:?}) is not an independent verdict"
4212        ))
4213    } else {
4214        ReCheckError::resource_limit(format!(
4215            "the re-checker's {what} was cut short by its budget ({MAX_RECHECK_STEPS} steps, \
4216             depth {MAX_RECHECK_WHNF_DEPTH}, {MAX_RECHECK_TERM_NODES} nodes), so its rejection \
4217             ({rejection:?}) is not an independent verdict"
4218        ))
4219    }
4220}
4221
4222/// Restores the nesting depth on the way out, including on a panic.
4223struct WhnfDepthGuard(usize);
4224
4225impl Drop for WhnfDepthGuard {
4226    fn drop(&mut self) {
4227        WHNF_DEPTH.with(|d| d.set(self.0));
4228    }
4229}
4230
4231fn whnf(genv: &Context, t: &Db) -> Db {
4232    whnf_in(genv, &[], t)
4233}
4234
4235#[cfg(test)]
4236thread_local! {
4237    static WHNF_INPUT_CLONES: std::cell::Cell<Option<usize>> =
4238        const { std::cell::Cell::new(None) };
4239}
4240
4241fn clone_whnf_input(t: &Db) -> Db {
4242    #[cfg(test)]
4243    WHNF_INPUT_CLONES.with(|counter| {
4244        if let Some(count) = counter.get() {
4245            counter.set(Some(count + db_node_count(t)));
4246        }
4247    });
4248    t.clone()
4249}
4250
4251fn whnf_in_owned(genv: &Context, lctx: &dyn LocalTypes, t: Db) -> Db {
4252    whnf_from(genv, lctx, || t)
4253}
4254
4255thread_local! {
4256    /// The `whnf_from` depth at which δ of the outermost spine's head is withheld; 0 for none.
4257    static CORE_DEPTH: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4258}
4259
4260/// Weak-head normal form WITHOUT δ at the head — Lean's `whnf_core` — computed by this kernel's own
4261/// weak-head machine, so every rule it applies before δ (the stuck-head rules, the certified `Nat`
4262/// order and arithmetic, the equality recurrence), its fuel, its depth door and its size check all
4263/// hold exactly as in [`whnf_in`]. Only the head constant of the result is left unexpanded.
4264fn whnf_core_in(genv: &Context, lctx: &dyn LocalTypes, t: Db) -> Db {
4265    struct Restore(usize);
4266    impl Drop for Restore {
4267        fn drop(&mut self) {
4268            CORE_DEPTH.with(|c| c.set(self.0));
4269        }
4270    }
4271    let depth = WHNF_DEPTH.with(|d| d.get()) + 1;
4272    let _restore = Restore(CORE_DEPTH.with(|c| c.replace(depth)));
4273    whnf_in_owned(genv, lctx, t)
4274}
4275
4276fn whnf_in(genv: &Context, lctx: &dyn LocalTypes, t: &Db) -> Db {
4277    whnf_from(genv, lctx, || clone_whnf_input(t))
4278}
4279
4280/// Delay ownership acquisition until the original depth/stack guard locations.
4281/// Borrowed inputs retain their existing clone/return contract; fresh owned
4282/// inputs move into precisely the same independent reduction loop.
4283fn whnf_from(genv: &Context, lctx: &dyn LocalTypes, input: impl FnOnce() -> Db) -> Db {
4284    let depth = WHNF_DEPTH.with(|d| {
4285        let next = d.get() + 1;
4286        d.set(next);
4287        next
4288    });
4289    let _depth_guard = WhnfDepthGuard(depth - 1);
4290    // The outermost call establishes the step budget; every nested one SHARES it, so the total
4291    // work of one reduction is bounded rather than the work of each frame.
4292    if depth == 1 && LOCAL_CONTEXT_BUDGET_DEPTH.with(|d| d.get() == 0) {
4293        WHNF_FUEL.with(|f| f.set(MAX_RECHECK_STEPS));
4294    }
4295    if depth > MAX_RECHECK_WHNF_DEPTH {
4296        WHNF_EXHAUSTED.with(|e| e.set(true));
4297        return input();
4298    }
4299    // Remaining recursive primitive and quotient probes still need the native-stack
4300    // guard; ordinary application, Match and structural-argument demands use frames.
4301    let Some(_nest) = nest(stack_mark()) else {
4302        return input();
4303    };
4304    let mut cur = input();
4305    let mut pending: Vec<WhnfFrame> = Vec::new();
4306    let mut steps = 0usize;
4307    let mut next_size_check = 1024usize;
4308    loop {
4309        // Explicit demands occupy the same logical depth as recursive whnf calls.
4310        // Recursive primitive/quotient probes also see this depth and shared fuel.
4311        WHNF_DEPTH.with(|d| d.set(depth + pending.len()));
4312        let spent = WHNF_FUEL.with(|f| {
4313            let left = f.get();
4314            if left == 0 {
4315                return false;
4316            }
4317            f.set(left - 1);
4318            true
4319        });
4320        if !spent {
4321            WHNF_EXHAUSTED.with(|e| e.set(true));
4322            return rebuild_whnf(cur, pending);
4323        }
4324        nat_order_observed_work();
4325        prefix_stat(4);
4326        steps += 1;
4327        if steps == next_size_check {
4328            next_size_check *= 2;
4329            if whnf_size_exceeds(&cur, &pending, MAX_RECHECK_TERM_NODES) {
4330                WHNF_EXHAUSTED.with(|e| e.set(true));
4331                return rebuild_whnf(cur, pending);
4332            }
4333        }
4334        // Head reduction without δ AT THE HEAD (`whnf_core_in`): the outermost spine's head constant
4335        // is left folded; a major premise, a structural argument and every nested reduction still
4336        // unfold as usual.
4337        let head_delta_withheld = CORE_DEPTH.with(|c| c.get()) == depth
4338            && matches!(cur, Db::Global(_) | Db::Const { .. })
4339            && pending
4340                .iter()
4341                .all(|frame| matches!(frame, WhnfFrame::Apply(_)));
4342        let mut step = if head_delta_withheld {
4343            WhnfStep::Ready(cur)
4344        } else {
4345            whnf_step(genv, lctx, cur)
4346        };
4347        loop {
4348            match step {
4349                WhnfStep::Reduce(next) => {
4350                    cur = next;
4351                    break;
4352                }
4353                WhnfStep::Ready(value) => match pending.pop() {
4354                    None => return value,
4355                    Some(frame) => {
4356                        WHNF_DEPTH.with(|d| d.set(depth + pending.len()));
4357                        step = resume_whnf(genv, lctx, frame, value);
4358                    }
4359                },
4360                WhnfStep::Demand { term, frame } => {
4361                    if depth + pending.len() + 1 > MAX_RECHECK_WHNF_DEPTH {
4362                        WHNF_EXHAUSTED.with(|e| e.set(true));
4363                        return rebuild_whnf(frame.rebuild(term), pending);
4364                    }
4365                    pending.push(frame);
4366                    cur = term;
4367                    break;
4368                }
4369            }
4370        }
4371    }
4372}
4373
4374/// Suspended independent reductions. Every frame owns only the context around
4375/// its hole, so resource refusal can reconstruct the complete outer expression.
4376enum WhnfFrame {
4377    // An undemanded argument retains its original owned/shared edge.
4378    Apply(DbBox),
4379    Match {
4380        motive: DbBox,
4381        cases: Vec<Db>,
4382    },
4383    FixArgument {
4384        head: Db,
4385        before: Vec<DbBox>,
4386        after: Vec<DbBox>,
4387    },
4388}
4389enum WhnfStep {
4390    Reduce(Db),
4391    Ready(Db),
4392    Demand { term: Db, frame: WhnfFrame },
4393}
4394fn apply_db_edges(head: Db, args: impl IntoIterator<Item = DbBox>) -> Db {
4395    args.into_iter()
4396        .fold(head, |f, a| Db::App(DbBox::new(f), a))
4397}
4398fn apply_fix_arguments(head: Db, before: Vec<DbBox>, value: Db, after: Vec<DbBox>) -> Db {
4399    let prefix = apply_db_edges(head, before);
4400    // Only the demanded result is a new argument edge. Retain the original
4401    // admission order at its application node and all undemanded side edges.
4402    let applied = Db::App(DbBox::new(prefix), DbBox::new(value));
4403    apply_db_edges(applied, after)
4404}
4405impl WhnfFrame {
4406    fn rebuild(self, term: Db) -> Db {
4407        match self {
4408            Self::Apply(a) => Db::App(DbBox::new(term), a),
4409            Self::Match { motive, cases } => Db::Match {
4410                disc: DbBox::new(term),
4411                motive,
4412                cases,
4413            },
4414            Self::FixArgument {
4415                head,
4416                before,
4417                after,
4418            } => apply_fix_arguments(head, before, term, after),
4419        }
4420    }
4421    fn size_roots<'a>(&'a self, roots: &mut Vec<&'a Db>) -> usize {
4422        match self {
4423            Self::Apply(a) => {
4424                roots.push(a);
4425                1
4426            }
4427            Self::Match { motive, cases } => {
4428                roots.push(motive);
4429                roots.extend(cases);
4430                1
4431            }
4432            Self::FixArgument {
4433                head,
4434                before,
4435                after,
4436            } => {
4437                roots.push(head);
4438                roots.extend(before.iter().map(|edge| edge.as_ref()));
4439                roots.extend(after.iter().map(|edge| edge.as_ref()));
4440                before.len() + 1 + after.len()
4441            }
4442        }
4443    }
4444}
4445fn rebuild_whnf(mut term: Db, mut pending: Vec<WhnfFrame>) -> Db {
4446    while let Some(frame) = pending.pop() {
4447        term = frame.rebuild(term);
4448    }
4449    term
4450}
4451fn whnf_size_exceeds(cur: &Db, pending: &[WhnfFrame], limit: usize) -> bool {
4452    let mut roots = vec![cur];
4453    let mut context_nodes = 0usize;
4454    for frame in pending {
4455        context_nodes += frame.size_roots(&mut roots);
4456    }
4457    context_nodes > limit || db_forest_size_exceeds(roots, limit - context_nodes)
4458}
4459fn demand_fix_argument(genv: &Context, full: Db) -> WhnfStep {
4460    if let Some(column) = fix_structural_column(genv, &full) {
4461        let mut head = full;
4462        let mut args = Vec::new();
4463        while let Db::App(f, a) = head {
4464            args.push(a);
4465            head = f.into_db();
4466        }
4467        args.reverse();
4468        let after = args.split_off(column + 1);
4469        let term = args
4470            .pop()
4471            .expect("checked structural column exists")
4472            .into_db();
4473        WhnfStep::Demand {
4474            term,
4475            frame: WhnfFrame::FixArgument {
4476                head,
4477                before: args,
4478                after,
4479            },
4480        }
4481    } else if let Some(reduced) = try_builtin(genv, &full) {
4482        WhnfStep::Reduce(reduced)
4483    } else {
4484        WhnfStep::Ready(full)
4485    }
4486}
4487fn resume_whnf(genv: &Context, lctx: &dyn LocalTypes, frame: WhnfFrame, value: Db) -> WhnfStep {
4488    match frame {
4489        WhnfFrame::Apply(a) => match value {
4490            Db::Lam(_, body) => WhnfStep::Reduce(beta_open_consuming(body.into_db(), a.into_db())),
4491            // Keep the existing mutual-fix guard and substitution semantics.
4492            Db::MutualFix { defs, index } => {
4493                if ctor_headed(genv, &a) {
4494                    WhnfStep::Reduce(Db::App(DbBox::new(open_mutual(&defs, index)), a))
4495                } else {
4496                    WhnfStep::Ready(Db::App(DbBox::new(Db::MutualFix { defs, index }), a))
4497                }
4498            }
4499            // The head is now in weak-head normal form, and this application may be a redex no
4500            // spine on the way down contained: offer it the rules of a stuck head first.
4501            other => {
4502                let full = Db::App(DbBox::new(other), a);
4503                match stuck_head_rule(genv, lctx, &full) {
4504                    Some(StuckHead::Reduce(reduced)) => WhnfStep::Reduce(reduced),
4505                    Some(StuckHead::Unchecked) => {
4506                        mark_unchecked_rule();
4507                        WhnfStep::Ready(full)
4508                    }
4509                    None => demand_fix_argument(genv, full),
4510                }
4511            }
4512        },
4513        WhnfFrame::FixArgument {
4514            head,
4515            before,
4516            after,
4517        } => {
4518            let ready = constructor_value(genv, &value);
4519            if ready {
4520                let Db::Fix(body) = head else {
4521                    unreachable!("checked Fix head")
4522                };
4523                let recursive = Db::Fix(body.clone());
4524                let unfolded = beta_open_consuming(body.into_db(), recursive);
4525                WhnfStep::Reduce(apply_fix_arguments(unfolded, before, value, after))
4526            } else {
4527                WhnfStep::Ready(apply_fix_arguments(head, before, value, after))
4528            }
4529        }
4530        WhnfFrame::Match { motive, cases } => resume_match(genv, lctx, value, motive, cases),
4531    }
4532}
4533fn db_motive_admits(genv: &Context, motive: &Db, discriminant: &Db) -> bool {
4534    let mut ctor = discriminant;
4535    while let Db::App(f, _) = ctor {
4536        ctor = f;
4537    }
4538    let Some(actual) = (match ctor {
4539        Db::Global(c) | Db::Const { name: c, .. } => genv.constructor_inductive(c),
4540        _ => None,
4541    }) else {
4542        return true;
4543    };
4544    let mut domain = None;
4545    let mut binders = 0usize;
4546    let mut current = motive;
4547    while let Db::Lam(param_type, body) = current {
4548        domain = Some(param_type.as_ref());
4549        binders += 1;
4550        current = body;
4551    }
4552    // An eta-short motive's last lambda binds an index, not the major premise.
4553    if binders <= genv.inductive_num_indices(actual) {
4554        return true;
4555    }
4556    let Some(domain) = domain else { return true };
4557    let mut head = domain;
4558    while let Db::App(f, _) = head {
4559        head = f;
4560    }
4561    let named = match head {
4562        Db::Global(n) | Db::Const { name: n, .. } if genv.is_inductive(n) => n,
4563        _ => return true,
4564    };
4565    actual == named.as_str()
4566}
4567
4568fn resume_match(
4569    genv: &Context,
4570    lctx: &dyn LocalTypes,
4571    mut d: Db,
4572    motive: DbBox,
4573    mut cases: Vec<Db>,
4574) -> WhnfStep {
4575    // Peano bridge (K6): a `Nat(n)` literal is `Zero`/`Succ(Nat(n-1))` — expand
4576    // one step so the constructor-selection below fires (the recursor computes
4577    // on Nat literals, peeling one `Succ` per match), where the literal's reading holds
4578    // (`int_inductive::reads_nat_literal`).
4579    if matches!(&d, Db::Lit(Literal::Nat(n)) if crate::int_inductive::reads_nat_literal(genv, n)) {
4580        d = db_nat_peano_step(&d);
4581    }
4582    if let Some(constructor) = db_int_constructor(genv, &d) {
4583        d = constructor;
4584    }
4585    // Inspect only the spine and registration headers before consuming it.
4586    // Preserve the constructor's field application boxes; replace just the
4587    // constructor and uniform-parameter prefix with the selected branch.
4588    let plan = {
4589        let mut head = &d;
4590        let mut arguments = 0usize;
4591        while let Db::App(function, _) = head {
4592            arguments += 1;
4593            head = function;
4594        }
4595        match head {
4596            Db::Global(name) | Db::Const { name, .. } => {
4597                genv.constructor_inductive(name).and_then(|inductive| {
4598                    let index = genv
4599                        .constructor_headers(inductive)
4600                        .position(|(constructor, _)| constructor == name)?;
4601                    if index >= cases.len() {
4602                        return None;
4603                    }
4604                    let Some(fields) = arguments.checked_sub(genv.inductive_num_params(inductive))
4605                    else {
4606                        return Some((index, None));
4607                    };
4608                    Some((index, Some(fields)))
4609                })
4610            }
4611            _ => None,
4612        }
4613    };
4614    // A recursor fires only on its own inductive's constructors: a motive whose last binder
4615    // names a different registered inductive makes this match ill-typed, and it must not compute
4616    // (the main kernel's `motive_admits`).
4617    let plan = plan.filter(|_| db_motive_admits(genv, &motive, &d));
4618    if let Some((index, fields)) = plan {
4619        let Some(fields) = fields else {
4620            return WhnfStep::Ready(Db::Match {
4621                disc: DbBox::new(d),
4622                motive,
4623                cases,
4624            });
4625        };
4626        let branch = cases.swap_remove(index);
4627        let mut prefix = &mut d;
4628        for _ in 0..fields {
4629            let Db::App(function, _) = prefix else {
4630                unreachable!("counted constructor spine")
4631            };
4632            prefix = function;
4633        }
4634        *prefix = branch;
4635        return WhnfStep::Reduce(d);
4636    }
4637    // K can select a branch only for a fieldless singleton.
4638    // Its checked full or reachable pruned inventory has one case.
4639    // Avoid re-inferring a neutral discriminant when this necessary
4640    // condition already rules out singleton reduction.
4641    if cases.len() == 1 {
4642        if let Some(constructor) = k_constructor_db(genv, lctx, &d) {
4643            return WhnfStep::Reduce(Db::Match {
4644                disc: DbBox::new(constructor),
4645                motive,
4646                cases,
4647            });
4648        }
4649    }
4650    return WhnfStep::Ready(Db::Match {
4651        disc: DbBox::new(d),
4652        motive,
4653        cases,
4654    });
4655}
4656#[path = "recheck_arithmetic.rs"]
4657mod arithmetic;
4658#[path = "recheck_conversion_memo.rs"]
4659mod conversion_memo;
4660#[path = "recheck_division.rs"]
4661mod division;
4662#[path = "recheck_lazy_delta.rs"]
4663mod lazy_delta;
4664#[path = "recheck_observational.rs"]
4665mod observational;
4666#[cfg(test)]
4667thread_local! {
4668    /// How many conversions reached the reduction-based comparison (`def_eq_by_whnf`).
4669    static WHNF_CONVERSIONS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4670}
4671
4672/// What an application headed by a constant with no δ of its own reduces by.
4673enum StuckHead {
4674    Reduce(Db),
4675    /// A primitive rule this kernel does not compute: the application is a value here, and the
4676    /// exhaustion flag says so.
4677    Unchecked,
4678}
4679
4680/// The rules of an application headed by a constant that has no δ of its own: the quotient
4681/// computation rules (mirroring the main kernel, so quotient proofs are two-kernel verified), the
4682/// first kernel's registered primitive rules, and the native-reduction hook.
4683///
4684/// Every application whose head is in weak-head normal form is offered them — the spine
4685/// [`whnf_step`] is handed, AND the spine [`resume_whnf`] rebuilds once δ and β have reduced the
4686/// head. The second is not a corner: Lean's `Quotient.lift` unfolds to the PARTIAL primitive
4687/// `Quot.lift f`, its respect proof and its major premise arrive from the enclosing application,
4688/// and the quotient redex exists only in the rebuilt spine. A rule offered only on descent leaves
4689/// that redex a value here while the main kernel computes it — a disagreement about a valid proof
4690/// (Lean core's `Quotient.lift₂._proof_2`).
4691fn stuck_head_rule(genv: &Context, lctx: &dyn LocalTypes, t: &Db) -> Option<StuckHead> {
4692    let Db::App(function, argument) = t else {
4693        return None;
4694    };
4695    if let Some(reduced) = try_quot_lift_db(genv, lctx, t) {
4696        return Some(StuckHead::Reduce(reduced));
4697    }
4698    if let Some(reduced) = observational::reduce(genv, lctx, t) {
4699        return Some(StuckHead::Reduce(reduced));
4700    }
4701    // The first kernel's registered reduction rules — the reflection algebra computed here
4702    // independently, the tactic family declared unchecked. A rule only ONE kernel has is not a
4703    // safe shortfall: the redex would stay a value here, the conversion check would fail on one
4704    // side only, and `double_check` would report `Disagree` about a proof that is perfectly valid.
4705    match try_primitive_rule(genv, t) {
4706        Some(PrimStep::Reduced(reduced)) => return Some(StuckHead::Reduce(reduced)),
4707        // Honest incompleteness, through the SAME channel a spent step budget uses: a later
4708        // rejection is reported as `Unsupported` — single-checked and labelled — instead of as a
4709        // disagreement this kernel did not earn.
4710        Some(PrimStep::Unchecked) => return Some(StuckHead::Unchecked),
4711        Some(PrimStep::Stuck) | None => {}
4712    }
4713    // Native-reduction hook: the main kernel reduces `reduceBool t` with its trusted evaluator;
4714    // the re-checker reduces `t` with its OWN machinery (δ/ι/builtins) — an independent
4715    // computation of the same value, so a `native_decide` proof is genuinely two-kernel verified.
4716    if matches!(function.as_ref(), Db::Global(n) if n == "reduceBool") {
4717        let value = whnf_in(genv, lctx, argument);
4718        if matches!(&value, Db::Global(n) if n == "true" || n == "false") {
4719            return Some(StuckHead::Reduce(value));
4720        }
4721    }
4722    None
4723}
4724
4725/// The accelerations of a DEFINED operation applied to values: each computes, with this kernel's
4726/// own arithmetic, what δ followed by ι would compute one step at a time. Every one must run BEFORE
4727/// δ, because δ erases the operation's name from the spine.
4728fn accelerated_application(genv: &Context, lctx: &dyn LocalTypes, cur: &Db) -> Option<Db> {
4729    // Checked public Int aliases must use their independently implemented
4730    // literal arithmetic before delta erases the attested alias head.
4731    if let Db::App(function, _) = cur {
4732        if let Db::App(head, _) = function.as_ref() {
4733            if let Db::Global(operation) = head.as_ref() {
4734                if crate::int_inductive::accelerates_integer_alias(genv, operation) {
4735                    if let Some(reduced) = try_builtin(genv, cur) {
4736                        return Some(reduced);
4737                    }
4738                }
4739            }
4740        }
4741    }
4742    if let Some(reduced) = arithmetic::reduce(genv, lctx, cur) {
4743        return Some(reduced);
4744    }
4745    // The `Nat` order on two closed naturals, by arithmetic rather than by `min(m, n)`
4746    // ι-steps. Runs BEFORE δ, because `natLt`'s body unfolds to `natLe (Succ m) n` and
4747    // `natLe`'s to a `Fix` — after either, the spine no longer names the operation.
4748    if let Some(reduced) = try_nat_order_db_in(genv, lctx, cur) {
4749        return Some(reduced);
4750    }
4751    if let Some(reduced) = try_certified_nat_order_db_in(genv, lctx, cur) {
4752        return Some(reduced);
4753    }
4754    if let Some(reduced) = division::reduce(genv, lctx, cur) {
4755        return Some(reduced);
4756    }
4757    equality::reduce(genv, lctx, cur)
4758}
4759
4760fn whnf_step(genv: &Context, lctx: &dyn LocalTypes, cur: Db) -> WhnfStep {
4761    if matches!(cur, Db::App(..)) {
4762        match stuck_head_rule(genv, lctx, &cur) {
4763            Some(StuckHead::Reduce(reduced)) => return WhnfStep::Reduce(reduced),
4764            Some(StuckHead::Unchecked) => {
4765                mark_unchecked_rule();
4766                return WhnfStep::Ready(cur);
4767            }
4768            None => {}
4769        }
4770        if let Some(reduced) = accelerated_application(genv, lctx, &cur) {
4771            return WhnfStep::Reduce(reduced);
4772        }
4773        // A `@[simp]` rewrite is a rule the FIRST kernel's conversion now takes and this one
4774        // does not. Making a registered PROPOSITIONAL equation DEFINITIONAL is a decision
4775        // about the trusted base, not an algorithm — a second kernel that re-took it would
4776        // be the same decision twice, which corroborates nothing while looking exactly like
4777        // corroboration. So this kernel says what is true: it did not carry that rewrite
4778        // through. The flag is set and reduction CONTINUES, so where δ/ι reach the same
4779        // normal form anyway the verdict is still `Agreed`; only where they do not does the
4780        // rejection become `Unsupported` — honestly single-checked — instead of a soundness
4781        // alarm about a proof the first kernel checked with a rule of its own.
4782        //
4783        // The `is_empty` test comes first so a context with no simp lemma — every context
4784        // until a user registers one — pays nothing at all for this at every application
4785        // node of every reduction step.
4786        if !genv.simp_rules().is_empty() {
4787            if let Db::Global(head) = spine_head(&cur) {
4788                if genv.simp_rules_for(head).next().is_some() {
4789                    mark_unchecked_rule();
4790                }
4791            }
4792        }
4793    }
4794
4795    match cur {
4796        Db::Global(name) => {
4797            if theorem_folded(genv, &name) {
4798                return WhnfStep::Ready(Db::Global(name));
4799            }
4800            if let Some(db) = definition_body(genv, &name) {
4801                return WhnfStep::Reduce(db);
4802            }
4803            WhnfStep::Ready(Db::Global(name))
4804        }
4805        Db::Const { name, levels } => {
4806            if theorem_folded(genv, &name) {
4807                return WhnfStep::Ready(Db::Const { name, levels });
4808            }
4809            if let Some(body) = const_body(genv, &name, &levels) {
4810                return WhnfStep::Reduce(body);
4811            }
4812            WhnfStep::Ready(Db::Const { name, levels })
4813        }
4814        Db::App(f, a) => WhnfStep::Demand {
4815            term: f.into_db(),
4816            frame: WhnfFrame::Apply(a),
4817        },
4818        Db::Match {
4819            disc,
4820            motive,
4821            cases,
4822        } => WhnfStep::Demand {
4823            term: disc.into_db(),
4824            frame: WhnfFrame::Match { motive, cases },
4825        },
4826        Db::Let(_ty, value, body) => {
4827            WhnfStep::Reduce(beta_open_consuming(body.into_db(), value.into_db()))
4828        }
4829        other => WhnfStep::Ready(other),
4830    }
4831}
4832
4833// ---------------------------------------------------------------------------
4834// Conversion (definitional equality + cumulativity)
4835// ---------------------------------------------------------------------------
4836
4837/// Independently reconstruct a nullary proof constructor and compare every index.
4838fn k_constructor_db(genv: &Context, lctx: &dyn LocalTypes, proof: &Db) -> Option<Db> {
4839    if definitely_fieldful_k_family(genv, lctx, proof) {
4840        return None;
4841    }
4842    #[cfg(test)]
4843    K_PROBE_ATTEMPTS.with(|n| {
4844        if let Some(count) = n.get() {
4845            n.set(Some(count + 1));
4846        }
4847    });
4848    let proof_type = whnf_in_owned(genv, lctx, infer_reduct(genv, lctx, proof).ok()?);
4849    let (head, args) = spine_ref(&proof_type);
4850    let (name, levels) = match head {
4851        Db::Global(name) => (name, None),
4852        Db::Const { name, levels } => (name, Some(levels)),
4853        _ => return None,
4854    };
4855    if !genv.is_inductive(&name)
4856        || genv
4857            .mutual_block_of(&name)
4858            .is_some_and(|block| block.len() != 1)
4859    {
4860        return None;
4861    }
4862    let parameters = genv.inductive_num_params(&name);
4863    let mut declared_sort = genv.get_global(&name)?;
4864    let mut arity = 0;
4865    while let Term::Pi { body_type, .. } = declared_sort {
4866        arity += 1;
4867        declared_sort = body_type;
4868    }
4869    if !matches!(declared_sort, Term::Sort(_)) {
4870        return None;
4871    }
4872    let unit = arity == parameters;
4873    if !unit
4874        && !matches!(declared_sort, Term::Sort(u) if *u != Universe::SProp && u.equiv(&Universe::Prop))
4875    {
4876        return None;
4877    }
4878    let constructors = genv.get_constructors(&name);
4879    if constructors.len() != 1 {
4880        return None;
4881    }
4882    let mut constructor_type = constructors[0].1;
4883    let mut fields = 0;
4884    while let Term::Pi { body_type, .. } = constructor_type {
4885        fields += 1;
4886        constructor_type = body_type;
4887    }
4888    if fields != parameters || args.len() < parameters {
4889        return None;
4890    }
4891    let sort = whnf_in_owned(genv, lctx, infer_reduct(genv, lctx, &proof_type).ok()?);
4892    if !unit && !matches!(sort, Db::Sort(u) if u != Universe::SProp && u.equiv(&Universe::Prop)) {
4893        return None;
4894    }
4895    let mut constructor = match levels {
4896        Some(levels) => Db::Const {
4897            name: constructors[0].0.into(),
4898            levels: levels.clone(),
4899        },
4900        None => Db::Global(constructors[0].0.into()),
4901    };
4902    for arg in args.into_iter().take(parameters) {
4903        constructor = Db::App(DbBox::new(constructor), DbBox::new(arg.clone()));
4904    }
4905    let constructor_type = infer_reduct(genv, lctx, &constructor).ok()?;
4906    def_eq(genv, lctx, &proof_type, &constructor_type).then_some(constructor)
4907}
4908
4909/// One Peano-unfolding step of a de Bruijn `Nat` literal: `Nat(0) → Zero`,
4910/// `Nat(n) → Succ (Nat(n-1))` (K6). Non-Nat terms are returned unchanged.
4911fn db_nat_peano_step(t: &Db) -> Db {
4912    match t {
4913        // `n ≤ 0` collapses to `Zero` so the peel TERMINATES on any (incl. malformed
4914        // negative) literal — critical here, where the re-checker consumes untrusted input.
4915        Db::Lit(Literal::Nat(n)) if *n <= logicaffeine_base::BigInt::from_i64(0) => {
4916            Db::Global("Zero".to_string())
4917        }
4918        Db::Lit(Literal::Nat(n)) => Db::App(
4919            DbBox::new(Db::Global("Succ".to_string())),
4920            DbBox::new(Db::Lit(Literal::Nat(
4921                n.sub(&logicaffeine_base::BigInt::from_i64(1)),
4922            ))),
4923        ),
4924        other => other.clone(),
4925    }
4926}
4927
4928/// True if `t` heads a `Nat` Peano value — `Zero` or `Succ _` — the shape a `Nat` literal
4929/// bridges against.
4930fn db_nat_peano_headed(t: &Db) -> bool {
4931    match t {
4932        Db::Global(n) => n == "Zero",
4933        Db::App(f, _) => matches!(f.as_ref(), Db::Global(n) if n == "Succ"),
4934        _ => false,
4935    }
4936}
4937
4938/// Positive-only conversion probe. It uses the independent de Bruijn syntax and
4939/// beta substitution, never the main checker. A failed/exhausted probe proves
4940/// nothing; the ordinary conversion path remains responsible for the verdict.
4941/// Keeping shared heads folded avoids copying and reducing a common function
4942/// just to compare two small convertible arguments.
4943#[path = "recheck_delta.rs"]
4944mod delta;
4945#[path = "recheck_folded.rs"]
4946mod folded;
4947#[path = "recheck_head_closure.rs"]
4948mod head_closure;
4949#[cfg(test)]
4950#[path = "../../logicaffeine_tests/unit/logicaffeine_kernel/recheck/proof_reference_boundary_controls.rs"]
4951mod proof_reference_boundary_controls;
4952#[cfg(test)]
4953#[path = "../../logicaffeine_tests/unit/logicaffeine_kernel/recheck/proof_reference_controls.rs"]
4954mod proof_reference_controls;
4955
4956fn borrowed_congruence(a: &Db, b: &Db, fuel: &mut usize) -> bool {
4957    borrowed_congruence_in(None, a, b, fuel)
4958}
4959
4960fn borrowed_congruence_in(ctx: Option<&Context>, a: &Db, b: &Db, fuel: &mut usize) -> bool {
4961    borrowed_congruence_with_limit(ctx, a, b, fuel, 64, *fuel)
4962}
4963
4964// A wider sequence of small reductions does not widen a single recursive
4965// substitution. Charge every attempted traversal to its enclosing allowance.
4966fn bounded_beta_zeta_probe(t: &Db, fuel: &mut usize, candidate: usize) -> Option<Db> {
4967    let allowance = if candidate > 64 {
4968        (*fuel).min(256)
4969    } else {
4970        *fuel
4971    };
4972    let mut remaining = allowance;
4973    let result = bounded_beta_zeta(t, &mut remaining);
4974    *fuel -= allowance - remaining;
4975    result
4976}
4977
4978fn borrowed_congruence_with_limit(
4979    ctx: Option<&Context>,
4980    a: &Db,
4981    b: &Db,
4982    fuel: &mut usize,
4983    candidate: usize,
4984    depth: usize,
4985) -> bool {
4986    if depth == 0 {
4987        return false;
4988    }
4989    let _nest = if candidate > 64 {
4990        let Some(guard) = nest(stack_mark()) else {
4991            return false;
4992        };
4993        Some(guard)
4994    } else {
4995        None
4996    };
4997    if *fuel == 0 {
4998        return false;
4999    }
5000    *fuel -= 1;
5001    let congruent = match (a, b) {
5002        (Db::Var(x), Db::Var(y)) => x == y,
5003        (Db::Global(x), Db::Global(y)) => x == y,
5004        (Db::Lit(x), Db::Lit(y)) => x == y,
5005        (Db::Sort(x), Db::Sort(y)) => x.equiv(y),
5006        (Db::Const { name: x, levels: u }, Db::Const { name: y, levels: v }) => {
5007            x == y && u.len() == v.len() && u.iter().zip(v).all(|(x, y)| x.equiv(y))
5008        }
5009        (Db::App(f, x), Db::App(g, y)) => {
5010            borrowed_congruence_with_limit(ctx, f, g, fuel, candidate, depth - 1)
5011                && borrowed_congruence_with_limit(ctx, x, y, fuel, candidate, depth - 1)
5012        }
5013        (Db::Pi(d, x), Db::Pi(e, y)) | (Db::Lam(d, x), Db::Lam(e, y)) => {
5014            borrowed_congruence_with_limit(ctx, d, e, fuel, candidate, depth - 1)
5015                && borrowed_congruence_with_limit(ctx, x, y, fuel, candidate, depth - 1)
5016        }
5017        _ => false,
5018    };
5019    if congruent {
5020        return true;
5021    }
5022    if let Some(reduced) = bounded_beta_zeta_probe(a, fuel, candidate) {
5023        return borrowed_congruence_with_limit(ctx, &reduced, b, fuel, candidate, depth - 1);
5024    }
5025    if let Some(reduced) = bounded_beta_zeta_probe(b, fuel, candidate) {
5026        return borrowed_congruence_with_limit(ctx, a, &reduced, fuel, candidate, depth - 1);
5027    }
5028    if let Some(ctx) = ctx {
5029        if let Some(reduced) = delta::reduce_with_limit(ctx, a, fuel, candidate) {
5030            return borrowed_congruence_with_limit(
5031                Some(ctx),
5032                &reduced,
5033                b,
5034                fuel,
5035                candidate,
5036                depth - 1,
5037            );
5038        }
5039        if let Some(reduced) = delta::reduce_with_limit(ctx, b, fuel, candidate) {
5040            return borrowed_congruence_with_limit(
5041                Some(ctx),
5042                a,
5043                &reduced,
5044                fuel,
5045                candidate,
5046                depth - 1,
5047            );
5048        }
5049    }
5050    false
5051}
5052
5053/// Count with the probe's shared work allowance. No traversal allocates a
5054/// frontier larger than the remaining allowance.
5055fn congruence_nodes(t: &Db, fuel: &mut usize) -> Option<usize> {
5056    let mut work = vec![t];
5057    let mut count = 0usize;
5058    while let Some(t) = work.pop() {
5059        if *fuel == 0 {
5060            return None;
5061        }
5062        *fuel -= 1;
5063        count += 1;
5064        let children = match t {
5065            Db::Pi(..) | Db::Lam(..) | Db::App(..) => 2,
5066            Db::Let(..) => 3,
5067            Db::Fix(..) => 1,
5068            Db::MutualFix { defs, .. } => defs.len(),
5069            Db::Match { cases, .. } => cases.len().checked_add(2)?,
5070            _ => 0,
5071        };
5072        if children > fuel.saturating_sub(work.len()) {
5073            return None;
5074        }
5075        match t {
5076            Db::Pi(a, b) | Db::Lam(a, b) | Db::App(a, b) => {
5077                work.push(a);
5078                work.push(b);
5079            }
5080            Db::Let(a, b, c) => {
5081                work.push(a);
5082                work.push(b);
5083                work.push(c);
5084            }
5085            Db::Fix(b) => work.push(b),
5086            Db::MutualFix { defs, .. } => work.extend(defs),
5087            Db::Match {
5088                disc,
5089                motive,
5090                cases,
5091            } => {
5092                work.push(disc);
5093                work.push(motive);
5094                work.extend(cases);
5095            }
5096            _ => {}
5097        }
5098    }
5099    Some(count)
5100}
5101
5102fn bounded_beta_zeta(t: &Db, fuel: &mut usize) -> Option<Db> {
5103    let (body, arg) = match t {
5104        Db::Let(_, value, body) => (body.as_ref(), value.as_ref()),
5105        Db::App(f, arg) => match f.as_ref() {
5106            Db::Lam(_, body) => (body.as_ref(), arg.as_ref()),
5107            _ => return None,
5108        },
5109        _ => return None,
5110    };
5111    let body_nodes = congruence_nodes(body, fuel)?;
5112    let arg_nodes = congruence_nodes(arg, fuel)?;
5113    // At most every body node is a substituted occurrence. This conservative
5114    // bound covers output Db nodes and index-shifting node visits before allocating.
5115    // Literal/name/universe payload sizes retain their existing representation costs.
5116    let maximum_work = body_nodes.checked_mul(arg_nodes.checked_add(1)?)?;
5117    if maximum_work > *fuel {
5118        return None;
5119    }
5120    *fuel -= maximum_work;
5121    Some(beta_open(body, arg))
5122}
5123
5124/// Result of discharging only the canonical natural constructor prefix.
5125/// Unknown tails return to the existing general conversion rules.
5126enum NatPrefixComparison {
5127    Decided(bool),
5128    Residual(Db, Db),
5129    Exhausted,
5130}
5131fn natural_prefix_value(t: &Db) -> bool {
5132    matches!(t, Db::Lit(Literal::Nat(_))) || db_nat_peano_headed(t)
5133}
5134fn compare_nat_prefix(
5135    genv: &Context,
5136    lctx: &dyn LocalTypes,
5137    mut a: Db,
5138    mut b: Db,
5139) -> NatPrefixComparison {
5140    if let (Db::Lit(Literal::Nat(x)), Db::Lit(Literal::Nat(y))) = (&a, &b) {
5141        return NatPrefixComparison::Decided(x == y);
5142    }
5143    // This is a representation-level rule, not an arithmetic operation-name hook.
5144    // The cheap shape gate avoids scanning Nat metadata in unrelated conversion.
5145    if !natural_prefix_value(&a)
5146        || !natural_prefix_value(&b)
5147        || !genv.simp_rules().is_empty()
5148        || !crate::int_inductive::canonical_nat_environment(genv)
5149    {
5150        return NatPrefixComparison::Residual(a, b);
5151    }
5152    // A discharged successor head leaves one tail obligation, not a pending
5153    // recursive call. Keep one logical ticket and share the unchanged reduction
5154    // fuel with every whnf used to expose the next constructor.
5155    let parent_depth = WHNF_DEPTH.with(|d| d.get());
5156    if parent_depth >= MAX_RECHECK_WHNF_DEPTH {
5157        WHNF_EXHAUSTED.with(|e| e.set(true));
5158        return NatPrefixComparison::Exhausted;
5159    }
5160    // A previous independent probe may already have recorded incompleteness.
5161    // Preserve that flag while distinguishing a fresh refusal in this loop.
5162    struct ExhaustionScope(bool);
5163    impl Drop for ExhaustionScope {
5164        fn drop(&mut self) {
5165            WHNF_EXHAUSTED.with(|e| e.set(self.0 || e.get()));
5166        }
5167    }
5168    let _exhaustion_scope = ExhaustionScope(WHNF_EXHAUSTED.with(|e| e.replace(false)));
5169    let _depth_guard = WhnfDepthGuard(parent_depth);
5170    WHNF_DEPTH.with(|d| d.set(parent_depth + 1));
5171    if parent_depth == 0 && LOCAL_CONTEXT_BUDGET_DEPTH.with(|d| d.get() == 0) {
5172        WHNF_FUEL.with(|f| f.set(MAX_RECHECK_STEPS));
5173    }
5174    let mut steps = 0usize;
5175    let mut next_size_check = 1024usize;
5176    loop {
5177        let spent = WHNF_FUEL.with(|f| {
5178            let n = f.get();
5179            if n == 0 {
5180                false
5181            } else {
5182                f.set(n - 1);
5183                true
5184            }
5185        });
5186        if !spent {
5187            WHNF_EXHAUSTED.with(|e| e.set(true));
5188            return NatPrefixComparison::Exhausted;
5189        }
5190        steps += 1;
5191        if steps == next_size_check {
5192            next_size_check *= 2;
5193            if db_forest_size_exceeds(vec![&a, &b], MAX_RECHECK_TERM_NODES) {
5194                WHNF_EXHAUSTED.with(|e| e.set(true));
5195                return NatPrefixComparison::Exhausted;
5196            }
5197        }
5198        if a == b {
5199            return NatPrefixComparison::Decided(true);
5200        }
5201        match (&a, &b) {
5202            (Db::Lit(Literal::Nat(x)), Db::Lit(Literal::Nat(y))) => {
5203                return NatPrefixComparison::Decided(x == y)
5204            }
5205            (Db::Lit(Literal::Nat(n)), Db::Global(z))
5206            | (Db::Global(z), Db::Lit(Literal::Nat(n)))
5207                if z == "Zero" =>
5208            {
5209                return NatPrefixComparison::Decided(*n <= 0.into())
5210            }
5211            (Db::Global(z), Db::App(f, _)) | (Db::App(f, _), Db::Global(z))
5212                if z == "Zero" && matches!(f.as_ref(), Db::Global(s) if s == "Succ") =>
5213            {
5214                return NatPrefixComparison::Decided(false)
5215            }
5216            // Use the existing independently implemented literal→Peano rule.
5217            (Db::Lit(Literal::Nat(_)), _) if db_nat_peano_headed(&b) => a = db_nat_peano_step(&a),
5218            (_, Db::Lit(Literal::Nat(_))) if db_nat_peano_headed(&a) => b = db_nat_peano_step(&b),
5219            _ => {}
5220        }
5221        // Cancel only the same registered unary constructor, after each head
5222        // has independently reached weak head. In particular neutral tails,
5223        // explicit-universe references and unrelated families are not guessed.
5224        let both_successors = matches!((&a, &b),
5225            (Db::App(f, _), Db::App(g, _))
5226                if matches!(f.as_ref(), Db::Global(s) if s == "Succ")
5227                && matches!(g.as_ref(), Db::Global(s) if s == "Succ"));
5228        if !both_successors {
5229            return NatPrefixComparison::Residual(a, b);
5230        }
5231        let (Db::App(_, x), Db::App(_, y)) = (a, b) else {
5232            unreachable!()
5233        };
5234        a = whnf_in_owned(genv, lctx, x.into_db());
5235        b = whnf_in_owned(genv, lctx, y.into_db());
5236        if WHNF_EXHAUSTED.with(|e| e.get()) {
5237            return NatPrefixComparison::Exhausted;
5238        }
5239    }
5240}
5241
5242// LAZY THEOREM DELTA, the re-checker's copy of the main kernel's rule (Lean's
5243// `lazy_delta_reduction`: a theorem has the lowest unfolding priority).
5244//
5245// While `FOLDING` is set, weak-head reduction treats a checked transparent theorem as a
5246// constant it may not unfold, and records in `FOLDED` that it declined one. That record is the
5247// whole soundness argument: a reduction that recorded nothing performed exactly the steps the
5248// unrestricted one performs, so its result IS the weak-head normal form; a reduction that
5249// recorded a refusal returned a reduct of the input, which can prove equalities but never
5250// refute them. Every conversion starts unrestricted (`def_eq` saves and clears both cells),
5251// so folding never leaks into a nested conversion or into what it infers.
5252thread_local! {
5253    /// Weak-head reduction keeps checked transparent theorems folded.
5254    static FOLDING: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
5255    /// A folded reduction declined to unfold a theorem.
5256    static FOLDED: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
5257}
5258
5259fn theorem_folded(genv: &Context, name: &str) -> bool {
5260    if !FOLDING.with(|folding| folding.get())
5261        || !crate::type_checker::is_transparent_theorem(genv, name)
5262    {
5263        return false;
5264    }
5265    FOLDED.with(|folded| folded.set(true));
5266    true
5267}
5268
5269/// Weak-head normalize with theorems folded. The flag says whether a theorem was declined, i.e.
5270/// whether the result may still reduce further under full transparency.
5271fn whnf_theorems_folded(genv: &Context, lctx: &dyn LocalTypes, t: &Db) -> (Db, bool) {
5272    FOLDING.with(|folding| folding.set(true));
5273    FOLDED.with(|folded| folded.set(false));
5274    let result = whnf_in(genv, lctx, t);
5275    FOLDING.with(|folding| folding.set(false));
5276    (result, FOLDED.with(|folded| folded.replace(false)))
5277}
5278
5279struct TheoremFoldingScope(bool, bool);
5280impl TheoremFoldingScope {
5281    fn enter() -> Self {
5282        TheoremFoldingScope(
5283            FOLDING.with(|folding| folding.replace(false)),
5284            FOLDED.with(|folded| folded.replace(false)),
5285        )
5286    }
5287}
5288impl Drop for TheoremFoldingScope {
5289    fn drop(&mut self) {
5290        FOLDING.with(|folding| folding.set(self.0));
5291        FOLDED.with(|folded| folded.set(self.1));
5292    }
5293}
5294
5295#[cfg(test)]
5296thread_local! {
5297    /// The conversions this thread has asked this kernel for, nested ones included.
5298    static DEF_EQ_CALLS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5299}
5300
5301/// Definitional equality in the independent de Bruijn kernel.
5302fn def_eq(genv: &Context, lctx: &dyn LocalTypes, a: &Db, b: &Db) -> bool {
5303    #[cfg(test)]
5304    DEF_EQ_CALLS.with(|n| n.set(n.get() + 1));
5305    if folded::exhausted() {
5306        return false;
5307    }
5308    let _folding = TheoremFoldingScope::enter();
5309    let _numeric_observation = arithmetic::ConversionScope::enter();
5310    // Syntactic identity is α-equality in de Bruijn form, and α-equal terms are definitionally
5311    // equal — so the two reductions below are not merely redundant, they are the whole cost. The
5312    // main kernel's `is_subtype` has had this door since the certified-grid work; the re-checker
5313    // did not, and it is what made the second kernel run a recursion the first one never had to.
5314    // A bound proof compares a term against ITSELF: `natLe (Succ i) 18446744073709551616` is
5315    // decided here in one comparison, or peeled one `Succ` at a time 2^64 times.
5316    if a == b {
5317        return true;
5318    }
5319    // Conversion recurses over the two terms' structure as well as reducing them, so it gets the
5320    // same stack meter. "Not equal" is the safe answer: a conversion the re-checker could not
5321    // finish must never be reported as one it decided, and the exhaustion flag turns the
5322    // resulting rejection into an honest `Unsupported`.
5323    let Some(_nest) = nest(stack_mark()) else {
5324        return false;
5325    };
5326    if borrowed_congruence(a, b, &mut 256) {
5327        return true;
5328    }
5329    if conversion_memo::known(genv, lctx, a, b) {
5330        return true;
5331    }
5332    let proved = def_eq_proved(genv, lctx, a, b);
5333    if proved {
5334        conversion_memo::record(genv, lctx, a, b);
5335    }
5336    proved
5337}
5338
5339/// [`def_eq`] past its identity, stack and borrowed-congruence doors.
5340fn def_eq_proved(genv: &Context, lctx: &dyn LocalTypes, a: &Db, b: &Db) -> bool {
5341    if folded::proof_references(genv, lctx, a, b) {
5342        return true;
5343    }
5344    if folded::equivalent(genv, lctx, a, b) {
5345        return true;
5346    }
5347    if borrowed_congruence_in(Some(genv), a, b, &mut 256) {
5348        return true;
5349    }
5350    if folded::align_definitions(genv, a, b) {
5351        return true;
5352    }
5353    // LAZY δ (Lean's `lazy_delta_reduction`, this kernel's own): reduce without unfolding the
5354    // heads, compare, and unfold one side at a time. Undecided pairs fall to the reduction-based
5355    // conversion below, unchanged.
5356    match lazy_delta::conversion(genv, lctx, a, b) {
5357        lazy_delta::Lazy::Decided(answer) => {
5358            #[cfg(debug_assertions)]
5359            lazy_delta::differential(genv, lctx, a, b, answer);
5360            answer
5361        }
5362        lazy_delta::Lazy::Open => def_eq_by_whnf(genv, lctx, a, b),
5363    }
5364}
5365
5366/// Conversion by weak-head normal forms: both sides reduced (theorems folded first), then
5367/// compared by the literal bridges, η, structure η, congruence, singleton types and proof
5368/// irrelevance. The lazy loop's fallback, and its differential oracle.
5369fn def_eq_by_whnf(genv: &Context, lctx: &dyn LocalTypes, a: &Db, b: &Db) -> bool {
5370    #[cfg(test)]
5371    WHNF_CONVERSIONS.with(|n| n.set(n.get() + 1));
5372    let (a, a_folded) = whnf_theorems_folded(genv, lctx, a);
5373    let (b, b_folded) = whnf_theorems_folded(genv, lctx, b);
5374    if a == b {
5375        return true;
5376    }
5377    // A side stuck on a folded theorem: first the comparisons that need no proof — the same
5378    // head applied to convertible arguments, then proof irrelevance — and only then unfold.
5379    let mut irrelevance_tried = false;
5380    let (a, b) = if a_folded || b_folded {
5381        if let (Db::App(f1, x1), Db::App(f2, x2)) = (&a, &b) {
5382            if def_eq(genv, lctx, f1, f2) && def_eq(genv, lctx, x1, x2) {
5383                return true;
5384            }
5385        }
5386        if proof_irrel(genv, lctx, &a, &b) {
5387            return true;
5388        }
5389        irrelevance_tried = true;
5390        let a = if a_folded { whnf_in(genv, lctx, &a) } else { a };
5391        let b = if b_folded { whnf_in(genv, lctx, &b) } else { b };
5392        if a == b {
5393            return true;
5394        }
5395        (a, b)
5396    } else {
5397        (a, b)
5398    };
5399
5400    let (a, b) = match compare_nat_prefix(genv, lctx, a, b) {
5401        NatPrefixComparison::Decided(equal) => return equal,
5402        NatPrefixComparison::Residual(a, b) => (a, b),
5403        NatPrefixComparison::Exhausted => return false,
5404    };
5405
5406    if let Some(a_ctor) = db_int_constructor(genv, &a) {
5407        let b_ctor = db_int_constructor(genv, &b);
5408        return def_eq(genv, lctx, &a_ctor, b_ctor.as_ref().unwrap_or(&b));
5409    }
5410    if let Some(b_ctor) = db_int_constructor(genv, &b) {
5411        return def_eq(genv, lctx, &a, &b_ctor);
5412    }
5413
5414    // Peano bridge (K6): a `Nat(n)` literal is definitionally `Succ^n Zero`. Two Nat
5415    // literals are equal iff their counts are; a Nat literal against a `Zero`/`Succ`-headed
5416    // term is compared by peeling one `Succ` (terminating at `Nat(0) ≡ Zero`), where the
5417    // literal's reading holds (`int_inductive::reads_nat_literal`).
5418    match (&a, &b) {
5419        (Db::Lit(Literal::Nat(x)), Db::Lit(Literal::Nat(y))) => return x == y,
5420        (Db::Lit(Literal::Nat(n)), _)
5421            if db_nat_peano_headed(&b) && crate::int_inductive::reads_nat_literal(genv, n) =>
5422        {
5423            return def_eq(genv, lctx, &db_nat_peano_step(&a), &b);
5424        }
5425        (_, Db::Lit(Literal::Nat(n)))
5426            if db_nat_peano_headed(&a) && crate::int_inductive::reads_nat_literal(genv, n) =>
5427        {
5428            return def_eq(genv, lctx, &a, &db_nat_peano_step(&b));
5429        }
5430        _ => {}
5431    }
5432
5433    // η-conversion: `λ. f (Var 0) ≡ g`. When exactly one side is a `λ`, compare its body
5434    // against the other side (shifted under the binder) applied to `Var 0`.
5435    if let Db::Lam(dom, body) = &a {
5436        if !matches!(b, Db::Lam(..)) {
5437            let mut ext = extend_local(lctx);
5438            ext.push((**dom).clone());
5439            let bx = whnf_in(
5440                genv,
5441                &ext,
5442                &Db::App(DbBox::new(shift(&b, 1, 0)), DbBox::new(Db::Var(0))),
5443            );
5444            return def_eq(genv, &ext, body, &bx);
5445        }
5446    }
5447    if let Db::Lam(dom, body) = &b {
5448        if !matches!(a, Db::Lam(..)) {
5449            let mut ext = extend_local(lctx);
5450            ext.push((**dom).clone());
5451            let ax = whnf_in(
5452                genv,
5453                &ext,
5454                &Db::App(DbBox::new(shift(&a, 1, 0)), DbBox::new(Db::Var(0))),
5455            );
5456            return def_eq(genv, &ext, &ax, body);
5457        }
5458    }
5459
5460    // Structure η (the second kernel's copy of the main kernel's rule): a
5461    // fully-applied structure constructor is convertible with any term whose
5462    // projections match it field-wise.
5463    if let Some(eq) = try_struct_eta_db(genv, lctx, &a, &b) {
5464        return eq;
5465    }
5466    if let Some(eq) = try_struct_eta_db(genv, lctx, &b, &a) {
5467        return eq;
5468    }
5469    if db_implicit_instance_conversion(genv, lctx, &a, &b) {
5470        return true;
5471    }
5472
5473    let congruent = match (&a, &b) {
5474        (Db::Sort(x), Db::Sort(y)) => x.equiv(y),
5475        (Db::Var(i), Db::Var(j)) => i == j,
5476        (Db::Global(m), Db::Global(n)) => m == n,
5477        (Db::Lit(x), Db::Lit(y)) => x == y,
5478        (Db::App(f1, a1), Db::App(f2, a2)) => {
5479            !db_bare_against_explicit(&a, &b)
5480                && def_eq(genv, lctx, f1, f2)
5481                && def_eq(genv, lctx, a1, a2)
5482        }
5483        (Db::Pi(d1, b1), Db::Pi(d2, b2)) => {
5484            def_eq(genv, lctx, d1, d2) && {
5485                let mut ext = extend_local(lctx);
5486                ext.push((**d1).clone());
5487                def_eq(genv, &ext, b1, b2)
5488            }
5489        }
5490        (Db::Lam(d1, b1), Db::Lam(d2, b2)) => {
5491            def_eq(genv, lctx, d1, d2) && {
5492                let mut ext = extend_local(lctx);
5493                ext.push((**d1).clone());
5494                def_eq(genv, &ext, b1, b2)
5495            }
5496        }
5497        (
5498            Db::Match {
5499                disc: d1,
5500                motive: m1,
5501                cases: c1,
5502            },
5503            Db::Match {
5504                disc: d2,
5505                motive: m2,
5506                cases: c2,
5507            },
5508        ) => {
5509            def_eq(genv, lctx, d1, d2)
5510                && def_eq(genv, lctx, m1, m2)
5511                && c1.len() == c2.len()
5512                && c1
5513                    .iter()
5514                    .zip(c2.iter())
5515                    .all(|(x, y)| def_eq(genv, lctx, x, y))
5516        }
5517        (Db::Fix(b1), Db::Fix(b2)) => {
5518            let mut ext = extend_local(lctx);
5519            ext.push(Db::Sort(Universe::Prop)); // `rec` placeholder (its type is never consulted)
5520            def_eq(genv, &ext, b1, b2)
5521        }
5522        (
5523            Db::MutualFix {
5524                defs: d1,
5525                index: i1,
5526            },
5527            Db::MutualFix {
5528                defs: d2,
5529                index: i2,
5530            },
5531        ) => {
5532            i1 == i2 && d1.len() == d2.len() && {
5533                let mut ext = extend_local(lctx);
5534                for _ in 0..d1.len() {
5535                    ext.push(Db::Sort(Universe::Prop)); // the `n` recursive-name placeholders
5536                }
5537                d1.iter()
5538                    .zip(d2.iter())
5539                    .all(|(a, b)| def_eq(genv, &ext, a, b))
5540            }
5541        }
5542        (
5543            Db::Const {
5544                name: n1,
5545                levels: l1,
5546            },
5547            Db::Const {
5548                name: n2,
5549                levels: l2,
5550            },
5551        ) => n1 == n2 && l1.len() == l2.len() && l1.iter().zip(l2.iter()).all(|(a, b)| a.equiv(b)),
5552        _ => false,
5553    };
5554    if congruent {
5555        return true;
5556    }
5557
5558    // Independently recognize fieldless, non-indexed singleton types.
5559    if let Ok(a_type) = infer_reduct(genv, lctx, &a) {
5560        let a_type = whnf_in(genv, lctx, &a_type);
5561        let (head, _) = spine(&a_type);
5562        if let Db::Global(name) | Db::Const { name, .. } = head {
5563            let mut arity = genv.get_global(&name);
5564            let mut count = 0;
5565            while let Some(Term::Pi { body_type, .. }) = arity {
5566                count += 1;
5567                arity = Some(body_type);
5568            }
5569            let ctors = genv.get_constructors(&name);
5570            let params = genv.inductive_num_params(&name);
5571            if genv.is_inductive(&name)
5572                && matches!(arity, Some(Term::Sort(_)))
5573                && count == params
5574                && ctors.len() == 1
5575                && genv.mutual_block_of(&name).is_none_or(|b| b.len() == 1)
5576            {
5577                let mut cty = ctors[0].1;
5578                let mut fields = 0;
5579                while let Term::Pi { body_type, .. } = cty {
5580                    fields += 1;
5581                    cty = body_type;
5582                }
5583                if fields == params {
5584                    if let Ok(b_type) = infer_reduct(genv, lctx, &b) {
5585                        if def_eq(genv, lctx, &a_type, &b_type) {
5586                            return true;
5587                        }
5588                    }
5589                }
5590            }
5591        }
5592    }
5593
5594    // Proof irrelevance: two proofs of the same proposition are equal.
5595    !irrelevance_tried && proof_irrel(genv, lctx, &a, &b)
5596}
5597
5598/// A bare reference is its own implicit instantiation — this kernel's copy of the main kernel's
5599/// `implicit_instance_conversion`, over its own application rule: `n a₁ … aₖ ≡ n.{ℓ̄} b₁ … bₖ`
5600/// exactly when the levels this kernel solves for the bare spine are equivalent to `ℓ̄`
5601/// position by position and `aᵢ ≡ bᵢ`. An unsolved level concludes nothing.
5602fn db_implicit_instance_conversion(genv: &Context, lctx: &dyn LocalTypes, a: &Db, b: &Db) -> bool {
5603    if !db_bare_against_explicit(a, b) {
5604        return false;
5605    }
5606    let (ah, aa) = spine_ref(a);
5607    let (bh, ba) = spine_ref(b);
5608    if aa.len() != ba.len() {
5609        return false;
5610    }
5611    let (name, levels, bare_args) = match (ah, bh) {
5612        (Db::Global(n), Db::Const { name, levels }) if n == name => (name, levels, &aa),
5613        (Db::Const { name, levels }, Db::Global(n)) if n == name => (name, levels, &ba),
5614        _ => return false,
5615    };
5616    // With no arguments the bare reference stands at its declaration's own levels (`term`'s
5617    // rule 4).
5618    if bare_args.is_empty() {
5619        return const_declaration(genv, name).is_some_and(|(declared, const_type)| {
5620            let own = crate::term::level_telescope(declared, const_type);
5621            own.len() == levels.len()
5622                && own
5623                    .iter()
5624                    .zip(levels.iter())
5625                    .all(|(p, l)| l.equiv(&Universe::Var(p.clone())))
5626        });
5627    }
5628    // The spine is a term conversion reached, so typing it is typing a reduct.
5629    let solved = {
5630        let _reduct = ReductInference::enter();
5631        db_implicit_instance_levels(genv, lctx, name, bare_args)
5632    };
5633    solved.is_some_and(|solved| {
5634        solved.len() == levels.len() && solved.iter().zip(levels.iter()).all(|(x, y)| x.equiv(y))
5635    }) && aa
5636        .iter()
5637        .zip(ba.iter())
5638        .all(|(x, y)| def_eq(genv, lctx, x, y))
5639}
5640
5641/// Whether the spines of `a` and `b` are headed by the same name, bare in one and explicit in the
5642/// other. Such a pair converts only by [`db_implicit_instance_conversion`]: congruence never
5643/// compares the two heads, since a bare head's levels come from its arguments.
5644fn db_bare_against_explicit(a: &Db, b: &Db) -> bool {
5645    matches!(
5646        (spine_head(a), spine_head(b)),
5647        (Db::Global(n), Db::Const { name, .. }) | (Db::Const { name, .. }, Db::Global(n))
5648            if n == name
5649    )
5650}
5651
5652/// The levels this kernel's application rule solves for the bare spine `name args`, zipped in
5653/// the positional order of a `Db::Const` reference (`term::resolve_const_levels`).
5654///
5655/// The spine is walked with this kernel's own application steps — `infer` of the head, `whnf`,
5656/// `db_implicit_levels_for_head`, and `db_domain_level_solution` per argument — so the instance
5657/// read here is the one the typing of the same spine used.
5658fn db_implicit_instance_levels(
5659    genv: &Context,
5660    lctx: &dyn LocalTypes,
5661    name: &str,
5662    args: &[&Db],
5663) -> Option<Vec<Universe>> {
5664    let (declared, const_type) = const_declaration(genv, name)?;
5665    let positional = crate::term::level_telescope(declared, const_type);
5666    let head = Db::Global(name.to_string());
5667    let mut current = infer(genv, lctx, &head).ok()?;
5668    let mut solution = HashMap::new();
5669    for (i, arg) in args.iter().enumerate() {
5670        let exposed = whnf_in_owned(genv, lctx, current);
5671        let exposed = if i == 0 {
5672            db_implicit_levels_for_head(&head, exposed)
5673        } else {
5674            exposed
5675        };
5676        let Db::Pi(dom, body) = exposed else {
5677            return None;
5678        };
5679        let body = match db_domain_level_solution(genv, lctx, &dom, arg) {
5680            Some(subst) => {
5681                let body = db_instantiate_universes(&body, &subst);
5682                solution.extend(subst);
5683                body
5684            }
5685            None => body.into_db(),
5686        };
5687        current = beta_open_owned(body, arg);
5688    }
5689    let metas = crate::term::fresh_level_metas(name, &positional);
5690    positional
5691        .iter()
5692        .map(|p| {
5693            let solved = metas.get(p)?.substitute(&solution);
5694            (!crate::term::universe_mentions(&solved, &crate::term::is_level_meta))
5695                .then_some(solved)
5696        })
5697        .collect()
5698}
5699
5700/// Structure η in the de Bruijn re-checker, ONE direction (see the main kernel's
5701/// `try_structure_eta`). `None` when `mk_term` is not a fully-applied registered
5702/// structure constructor, or `other` is the same constructor (ordinary congruence).
5703fn try_struct_eta_db(
5704    genv: &Context,
5705    lctx: &dyn LocalTypes,
5706    mk_term: &Db,
5707    other: &Db,
5708) -> Option<bool> {
5709    let (head, args) = spine_ref(mk_term);
5710    let (hname, levels) = match &head {
5711        Db::Global(n) => (n, None),
5712        Db::Const { name, levels } => (name, Some(levels)),
5713        _ => return None,
5714    };
5715    let (_sname, info) = genv.struct_of_constructor(hname)?;
5716    let nfields = info.projections.len();
5717    if args.len() != info.num_params + nfields {
5718        return None;
5719    }
5720    let ohead = spine_head(other);
5721    if matches!(&ohead, Db::Global(n) | Db::Const {name:n, ..} if n == hname) {
5722        return None;
5723    }
5724    let params = &args[..info.num_params];
5725    let field_args = &args[info.num_params..];
5726    Some(info.projections.iter().enumerate().all(|(i, proj)| {
5727        // `proj params… other` as a Db application.
5728        let mut app = match levels {
5729            Some(levels) => Db::Const {
5730                name: proj.clone(),
5731                levels: levels.clone(),
5732            },
5733            None => Db::Global(proj.clone()),
5734        };
5735        for p in params {
5736            app = Db::App(DbBox::new(app), DbBox::new((*p).clone()));
5737        }
5738        app = Db::App(DbBox::new(app), DbBox::new(other.clone()));
5739        def_eq(genv, lctx, &field_args[i], &app)
5740    }))
5741}
5742
5743/// Proof irrelevance for the re-checker, from the same specification as the main kernel's:
5744/// `a ≡ b` when `a : A`, `b : B`, `A ≡ B`, and that common type is a `Prop` (or the
5745/// definitionally-irrelevant `SProp`).
5746///
5747/// The premise is a property of the pair, not of the left element — `A ≡ B` makes one
5748/// propositional exactly when the other is — so the check is written over BOTH inferred types.
5749/// Interrogating only `a` costs nothing when both types infer and silently breaks symmetry
5750/// when one does not; conversion that depends on argument order is not conversion.
5751fn proof_irrel(genv: &Context, lctx: &dyn LocalTypes, a: &Db, b: &Db) -> bool {
5752    let (Ok(ta), Ok(tb)) = (infer_reduct(genv, lctx, a), infer_reduct(genv, lctx, b)) else {
5753        return false;
5754    };
5755    let propositional = |t: &Db| {
5756        matches!(
5757            infer_reduct(genv, lctx, t).map(|s| whnf_in_owned(genv, lctx, s)),
5758            Ok(Db::Sort(level)) if level == Universe::SProp || level.equiv(&Universe::Prop)
5759        )
5760    };
5761    if !propositional(&ta) && !propositional(&tb) {
5762        return false;
5763    }
5764    def_eq(genv, lctx, &ta, &tb)
5765}
5766
5767/// Cumulative subtyping `sub ≤ sup`: sorts follow `Prop ≤ Type i ≤ Type j`; a `Π` is
5768/// covariant in its codomain and invariant in its domain; everything else is `def_eq`.
5769fn is_sub(genv: &Context, lctx: &dyn LocalTypes, sub: &Db, sup: &Db) -> bool {
5770    if folded::exhausted() {
5771        return false;
5772    }
5773    // As in def_eq, de Bruijn identity proves reflexivity without reducing the
5774    // already inferred types. Inference still checks every term and annotation.
5775    if sub == sup {
5776        return true;
5777    }
5778    if borrowed_congruence(sub, sup, &mut 256) {
5779        return true;
5780    }
5781    if folded::equivalent(genv, lctx, sub, sup) {
5782        return true;
5783    }
5784    if borrowed_congruence_in(Some(genv), sub, sup, &mut 256) {
5785        return true;
5786    }
5787    if folded::align_definitions(genv, sub, sup) {
5788        return true;
5789    }
5790    let s = whnf_in(genv, lctx, sub);
5791    let t = whnf_in(genv, lctx, sup);
5792    match (&s, &t) {
5793        (Db::Sort(x), Db::Sort(y)) => x.is_subtype_of(y),
5794        (Db::Pi(d1, b1), Db::Pi(d2, b2)) => {
5795            def_eq(genv, lctx, d1, d2) && {
5796                let mut ext = extend_local(lctx);
5797                ext.push((**d1).clone());
5798                is_sub(genv, &ext, b1, b2)
5799            }
5800        }
5801        _ => def_eq(genv, lctx, &s, &t),
5802    }
5803}
5804
5805// ---------------------------------------------------------------------------
5806// Inference
5807// ---------------------------------------------------------------------------
5808
5809/// The type of de Bruijn variable `k`, read from `lctx` (binder types, innermost LAST,
5810/// each stored in the scope of ITS binding point) and lifted by `k+1` to current depth.
5811fn var_type(lctx: &dyn LocalTypes, k: usize) -> RResult<Db> {
5812    if k >= lctx.len() {
5813        return Err(ReCheckError::ill(format!(
5814            "de Bruijn index {} out of range",
5815            k
5816        )));
5817    }
5818    let stored = lctx
5819        .binding(lctx.len() - 1 - k)
5820        .expect("index checked against telescope length");
5821    Ok(shift(stored, (k + 1) as isize, 0))
5822}
5823
5824/// Infer the type of `t` under global env `genv` and local context `lctx`.
5825fn infer(genv: &Context, lctx: &dyn LocalTypes, t: &Db) -> RResult<Db> {
5826    // The INPUT's inference is NOT metered. It recurses over the term's own structure, whose
5827    // depth the door at `recheck`'s entry already bounds by `MAX_TERM_DEPTH`; a 500-deep Peano
5828    // numeral is legitimate work that a caller with stack to spare must be allowed to finish. The
5829    // meter guards what the door did not measure: REDUCTION — `whnf` and `def_eq` — where the
5830    // recursion is driven by how far a computation runs, and the inference of the reducts it
5831    // produces (`infer_reduct`). Metering the input as well would make the re-checker refuse work
5832    // the thread had room for, which
5833    // `kernel_core_extra::the_kernel_is_correct_at_depths_a_default_thread_cannot_afford` locks
5834    // against: the limit is the ambient stack, not the logic.
5835    let _metered = match REDUCT_INFERENCE.with(|m| m.get()) {
5836        false => None,
5837        true => match nest(stack_mark()) {
5838            Some(guard) => Some(guard),
5839            None => {
5840                return Err(ReCheckError::resource_limit(
5841                    "the type of a reduct nests past the re-checker's stack meter",
5842                ))
5843            }
5844        },
5845    };
5846    match t {
5847        Db::Sort(u) => Ok(Db::Sort(u.succ())),
5848        Db::Var(k) => var_type(lctx, *k),
5849        Db::Global(name) => {
5850            let ty = genv.get_global(name).ok_or_else(|| {
5851                ReCheckError::ill(
5852                    crate::type_checker::unbound_diagnosis(name)
5853                        .unwrap_or_else(|| format!("unknown global '{}'", name)),
5854                )
5855            })?;
5856            // The stored type is returned VERBATIM. A declaration whose type mentions level
5857            // variables is universe-polymorphic even with no levels written, but the
5858            // metavariables are introduced by the APPLICATION rule, where there is an argument
5859            // to solve them from — never here, where it would rename the level variables a
5860            // polymorphic definition's own body is checked against.
5861            to_db(ty, &mut Vec::new())
5862        }
5863        // A universe-polymorphic reference. The telescope, the closure rule and the positional
5864        // zip are the SHARED SPECIFICATION in `term::resolve_const_levels`; the lookup below is
5865        // this kernel's own, so the two kernels agree about what a polymorphic reference MEANS
5866        // without either one borrowing the other's arithmetic.
5867        Db::Const { name, levels } => {
5868            let (declared, ty) = const_declaration(genv, name).ok_or_else(|| {
5869                ReCheckError::ill(
5870                    crate::type_checker::unbound_diagnosis(name)
5871                        .unwrap_or_else(|| format!("unknown universe-poly global '{}'", name)),
5872                )
5873            })?;
5874            let subst = crate::term::resolve_const_levels(name, declared, ty, levels)
5875                .map_err(|e| ReCheckError::ill(e.to_string()))?;
5876            to_db(
5877                &crate::term::instantiate_universes(ty, &subst),
5878                &mut Vec::new(),
5879            )
5880        }
5881        Db::Lit(Literal::Nat(n)) if *n < logicaffeine_base::BigInt::from_i64(0) => Err(
5882            ReCheckError::ill("a `Nat` literal must be non-negative".to_string()),
5883        ),
5884        Db::Lit(l) => Ok(Db::Global(lit_type_name(l).to_string())),
5885        Db::Pi(dom, body) => {
5886            let dom_sort = infer_sort(genv, lctx, dom)?;
5887            let mut ext = extend_local(lctx);
5888            ext.push((**dom).clone());
5889            let body_sort = infer_sort(genv, &ext, body)?;
5890            // Impredicative product formation via `imax` (see the main kernel's
5891            // `Pi` arm) — the second kernel decides the same level algebra.
5892            let pi_sort = dom_sort.imax(&body_sort);
5893            Ok(Db::Sort(pi_sort))
5894        }
5895        Db::Lam(dom, body) => {
5896            let _ = infer_sort(genv, lctx, dom)?;
5897            let mut ext = extend_local(lctx);
5898            ext.push((**dom).clone());
5899            let body_ty = infer(genv, &ext, body)?;
5900            Ok(Db::Pi(dom.clone(), DbBox::new(body_ty)))
5901        }
5902        Db::App(f, a) => {
5903            let f_ty = whnf_in_owned(genv, lctx, infer(genv, lctx, f)?);
5904            let f_ty = db_implicit_levels_for_head(f.as_ref(), f_ty);
5905            match f_ty {
5906                Db::Pi(dom, body) => {
5907                    // LEVEL SOLVING (shared specification, independent implementation): a
5908                    // domain carrying level metavariables is solved against the argument's
5909                    // ACTUAL type before anything is checked. Choosing an instantiation is not
5910                    // accepting one — `check` still runs against the substituted domain.
5911                    let (dom, body) =
5912                        solve_domain_levels_owned(genv, lctx, dom.into_db(), body.into_db(), a);
5913                    check(genv, lctx, a, &dom)?;
5914                    // The main kernel SHARES a large argument behind a ζ-binding rather than
5915                    // copying it; this kernel substitutes eagerly. That is deliberate, not a
5916                    // divergence: `let x := a in B` and `B[x := a]` are ζ-equal and BOTH kernels
5917                    // implement ζ, so the two routes meet in `def_eq`. Sharing here would buy
5918                    // nothing — this kernel `whnf`s the function type at every application, which
5919                    // ζ-reduces the binding away immediately.
5920                    Ok(beta_open_owned(body, a))
5921                }
5922                other => Err(ReCheckError::ill(format!(
5923                    "application of a non-function (type {})",
5924                    from_db(&other, lctx.len())
5925                ))),
5926            }
5927        }
5928        Db::Match {
5929            disc,
5930            motive,
5931            cases,
5932        } => infer_match(genv, lctx, disc, motive, cases),
5933        Db::Fix(body) => infer_fix(genv, lctx, body),
5934        Db::MutualFix { defs, index } => infer_mutual_fix(genv, lctx, defs, *index),
5935        // Let: check `ty` is a sort and `value : ty`, then type the body with the
5936        // value substituted in (zeta) — exactly the main kernel's by-substitution
5937        // rule, so both kernels agree.
5938        Db::Let(ty, value, body) => {
5939            let _ = infer_sort(genv, lctx, ty)?;
5940            check(genv, lctx, value, ty)?;
5941            std::thread_local! { static LET_PROBE: std::cell::Cell<bool> = const { std::cell::Cell::new(false) }; }
5942            struct Probe(bool);
5943            impl Drop for Probe {
5944                fn drop(&mut self) {
5945                    LET_PROBE.with(|flag| flag.set(self.0));
5946                }
5947            }
5948            let probe = Probe(LET_PROBE.with(|flag| flag.replace(true)));
5949            let nested = probe.0;
5950            let mut ext = extend_local(lctx);
5951            ext.push((**ty).clone());
5952            let result = infer(genv, &ext, body);
5953            drop(probe);
5954            match result {
5955                // Independently apply the substitution lemma in de Bruijn form.
5956                Ok(body_type) => Ok(beta_open_owned(body_type, value)),
5957                Err(error) if nested => Err(error),
5958                Err(_) => infer(genv, lctx, &beta_open(body, value)),
5959            }
5960        }
5961    }
5962}
5963
5964/// The effective motive of a `match`: a function motive `λx:I.T` (checked: its domain
5965/// matches the discriminant type, its codomain is a type) is used as-is; a raw type `T`
5966/// (a `Sort`-typed motive) is wrapped as `λ_:I. T` (shifting `T` under the new binder).
5967fn effective_motive(
5968    genv: &Context,
5969    lctx: &dyn LocalTypes,
5970    motive: &Db,
5971    disc_ty: &Db,
5972) -> RResult<Db> {
5973    #[cfg(test)]
5974    MOTIVE_CHECKS.with(|n| {
5975        if let Some(count) = n.get() {
5976            n.set(Some(count + 1));
5977        }
5978    });
5979    let motive_ty = whnf_in_owned(genv, lctx, infer(genv, lctx, motive)?);
5980    match &motive_ty {
5981        Db::Pi(dom, cod) => {
5982            if !def_eq(genv, lctx, dom, disc_ty) {
5983                return Err(ReCheckError::ill(format!(
5984                    "motive domain {} does not match discriminant type {}",
5985                    from_db(dom, lctx.len()),
5986                    from_db(disc_ty, lctx.len())
5987                )));
5988            }
5989            let mut ext = extend_local(lctx);
5990            ext.push(disc_ty.clone());
5991            if !matches!(whnf_in(genv, &ext, cod), Db::Sort(_)) {
5992                return Err(ReCheckError::ill("motive type codomain is not a sort"));
5993            }
5994            Ok(motive.clone())
5995        }
5996        Db::Sort(_) => Ok(Db::Lam(
5997            DbBox::new(disc_ty.clone()),
5998            DbBox::new(shift(motive, 1, 0)),
5999        )),
6000        other => Err(ReCheckError::ill(format!(
6001            "motive is neither a function nor a type (type {})",
6002            from_db(other, lctx.len())
6003        ))),
6004    }
6005}
6006
6007/// Type a `fix rec. body`: compute its (structural) type, INDEPENDENTLY verify the
6008/// termination guard, sanity-check the body under `rec : T`, and return `T`. The guard
6009/// is the load-bearing soundness check — without it `fix f. f` inhabits every type.
6010fn infer_fix(genv: &Context, lctx: &dyn LocalTypes, body: &Db) -> RResult<Db> {
6011    let fix_level = lctx.len();
6012
6013    // 1. The fixpoint's type, read from the body's λ-telescope and its `match` codomain
6014    //    (which does not depend on `rec`). The body's indices are relative to a context
6015    //    that INCLUDES the `rec` binder, so `fix_type` must run with that slot present
6016    //    (a placeholder — its type is never consulted), or every index is off by one.
6017    let mut inner = extend_local(lctx);
6018    inner.push(Db::Sort(Universe::Prop));
6019    let fix_ty_inner = fix_type(genv, &inner, body)?;
6020    // The type may not reference `rec` (level `fix_level`, index 0 at this base); it does not, so
6021    // that slot is dropped to express the type in the enclosing context.
6022    if mentions_index(&fix_ty_inner, 0) {
6023        return Err(ReCheckError::ill(
6024            "a fixpoint's type mentions the fixpoint itself".to_string(),
6025        ));
6026    }
6027    let fix_ty = shift(&fix_ty_inner, -1, 0);
6028
6029    // 2. THE GUARDIAN — an independent structural-decrease check. The body lives one
6030    //    binder (`rec`, at level `fix_level`) beneath the current depth.
6031    check_terminates(genv, body, fix_level)?;
6032
6033    // 3. Sanity: the body type-checks with `rec : T` in scope.
6034    let mut ext = extend_local(lctx);
6035    ext.push(fix_ty.clone());
6036    let _ = infer(genv, &ext, body)?;
6037
6038    Ok(fix_ty)
6039}
6040
6041/// Type a `mutualfix { b₀ … b_{n-1} }.index` — the mutual analog of [`infer_fix`]. Each
6042/// body's structural type is read from its λ-telescope (independent of the recursive
6043/// names), the MUTUAL termination guard is verified over the whole block, the bodies are
6044/// sanity-checked with all `n` names bound, and the `index`-th type is returned.
6045fn infer_mutual_fix(
6046    genv: &Context,
6047    lctx: &dyn LocalTypes,
6048    defs: &[Db],
6049    index: usize,
6050) -> RResult<Db> {
6051    let n = defs.len();
6052    if n == 0 || index >= n {
6053        return Err(ReCheckError::ill("malformed mutual fixpoint".to_string()));
6054    }
6055    let base = lctx.len();
6056
6057    // 1. Structural type of each body, computed with `n` placeholder binders in scope
6058    //    (the bodies' indices assume all `n` mutual names are present). The types do not
6059    //    mention those names, so drop the `n` slots (shift down by `n`) into the
6060    //    enclosing context — each `types[j]` is then expressed relative to depth `base`.
6061    let mut inner = extend_local(lctx);
6062    for _ in 0..n {
6063        inner.push(Db::Sort(Universe::Prop));
6064    }
6065    let mut types: Vec<Db> = Vec::with_capacity(n);
6066    for body in defs {
6067        let ty_inner = fix_type(genv, &inner, body)?;
6068        types.push(shift(&ty_inner, -(n as isize), 0));
6069    }
6070
6071    // 2. THE GUARDIAN — the mutual structural-decrease check.
6072    check_terminates_mutual(genv, defs, base)?;
6073
6074    // 3. Sanity: every body type-checks with all `n` names bound. Binder `j` sits at level
6075    //    `base + j`, so its type must be expressed relative to depth `base + j` (shift up
6076    //    by `j` from the `base`-relative `types[j]`).
6077    let mut ext = extend_local(lctx);
6078    for (j, ty) in types.iter().enumerate() {
6079        ext.push(shift(ty, j as isize, 0));
6080    }
6081    for body in defs {
6082        let _ = infer(genv, &ext, body)?;
6083    }
6084
6085    Ok(types[index].clone())
6086}
6087
6088/// The structural type of a fixpoint body: each leading `λ(_:A). …` contributes a
6089/// `Π(_:A). …`, and the innermost `match` contributes its return type `motive(disc)`
6090/// (independent of `rec`). A non-`match` tail is typed directly.
6091fn fix_type(genv: &Context, lctx: &dyn LocalTypes, body: &Db) -> RResult<Db> {
6092    match body {
6093        Db::Lam(dom, inner) => {
6094            let _ = infer_sort(genv, lctx, dom)?;
6095            let mut ext = extend_local(lctx);
6096            ext.push((**dom).clone());
6097            let inner_ty = fix_type(genv, &ext, inner)?;
6098            Ok(Db::Pi(dom.clone(), DbBox::new(inner_ty)))
6099        }
6100        Db::Match { disc, motive, .. } => {
6101            let disc_ty = whnf_in_owned(genv, lctx, infer(genv, lctx, disc)?);
6102            match_return_type(genv, lctx, motive, disc, &disc_ty)
6103        }
6104        // A convoy: a `match` applied to further arguments, typed as the `match` is and then
6105        // applied to them.
6106        Db::App(..) if matches!(spine_head(body), Db::Match { .. }) => {
6107            let (head, args) = spine_ref(body);
6108            let mut ty = fix_type(genv, lctx, head)?;
6109            for arg in args {
6110                match whnf_in_owned(genv, lctx, ty) {
6111                    Db::Pi(_, codomain) => ty = beta_open(&codomain, arg),
6112                    other => {
6113                        return Err(ReCheckError::ill(format!(
6114                            "a convoy applies a match whose type is {:?}, not a function",
6115                            other
6116                        )))
6117                    }
6118                }
6119            }
6120            Ok(ty)
6121        }
6122        other => infer(genv, lctx, other),
6123    }
6124}
6125
6126/// Whether the de Bruijn index `k`, counted from `t`'s root, occurs in `t`.
6127fn mentions_index(t: &Db, k: usize) -> bool {
6128    match t {
6129        Db::Var(i) => *i == k,
6130        Db::Pi(a, b) | Db::Lam(a, b) => mentions_index(a, k) || mentions_index(b, k + 1),
6131        Db::App(a, b) => mentions_index(a, k) || mentions_index(b, k),
6132        Db::Let(a, b, body) => {
6133            mentions_index(a, k) || mentions_index(b, k) || mentions_index(body, k + 1)
6134        }
6135        Db::Match {
6136            disc,
6137            motive,
6138            cases,
6139        } => {
6140            mentions_index(disc, k)
6141                || mentions_index(motive, k)
6142                || cases.iter().any(|c| mentions_index(c, k))
6143        }
6144        Db::Fix(body) => mentions_index(body.as_ref(), k + 1),
6145        Db::MutualFix { defs, .. } => defs.iter().any(|d| mentions_index(d, k + defs.len())),
6146        Db::Sort(_) | Db::Global(_) | Db::Const { .. } | Db::Lit(_) => false,
6147    }
6148}
6149
6150// ---------------------------------------------------------------------------
6151// The termination guard (Giménez 1995 / the Coq guard) — independently re-derived.
6152//
6153// A fixpoint is sound only if every recursive call decreases a STRUCTURAL argument.
6154// Without this, `fix f. f` (and the higher-order escape `(λg. g Zero) f`) inhabit every
6155// type, including `False`. This is a SEPARATE implementation of the main kernel's
6156// `termination` module. Crucially, the main kernel tracks shadowing with explicit
6157// `struct_param_live`/`fix_name_live` flags because it works with NAMES; here, working
6158// in de Bruijn LEVELS, shadowing is automatic — an inner binder gets a fresh level, so a
6159// reference can never be mistaken for the recursive name or the structural parameter.
6160// That structural simplicity is the point: the two guards cannot share a shadowing bug.
6161// ---------------------------------------------------------------------------
6162
6163/// The de Bruijn LEVEL referred to by index `k` at the given `depth` (`None` if the
6164/// index is out of range). A level is absolute, so it identifies a binder independently
6165/// of how deep the reference is — which is what makes shadowing a non-issue.
6166fn level_of(depth: usize, k: usize) -> Option<usize> {
6167    depth.checked_sub(1)?.checked_sub(k)
6168}
6169
6170/// The inductive each of a (named) constructor's VALUE FIELDS is typed by, in order, skipping
6171/// the inductive's `num_type_params` leading parameter binders. The empty string where a field's
6172/// type does not head an inductive — such a field is still a structural subterm, but there is
6173/// nothing to match on it.
6174fn named_field_heads(genv: &Context, ctor_type: &Term, num_type_params: usize) -> Vec<String> {
6175    let mut heads = Vec::new();
6176    let mut cur = ctor_type;
6177    let mut i = 0usize;
6178    while let Term::Pi {
6179        param_type,
6180        body_type,
6181        ..
6182    } = cur
6183    {
6184        if i >= num_type_params {
6185            let mut head = param_type.as_ref();
6186            while let Term::App(f, _) = head {
6187                head = f;
6188            }
6189            heads.push(match head {
6190                Term::Global(n) | Term::Const { name: n, .. } if genv.is_inductive(n) => n.clone(),
6191                _ => String::new(),
6192            });
6193        }
6194        cur = body_type;
6195        i += 1;
6196    }
6197    heads
6198}
6199
6200/// Locate a fixpoint body's structural parameter: peel the λ-telescope from `base_depth`,
6201/// pick the scrutinee of the innermost `match` if inductive-typed (else the first
6202/// inductive-typed binder). Returns the parameter's LEVEL, its inductive name, the body
6203/// just past it, and its argument POSITION in the telescope.
6204fn locate_struct<'a>(
6205    genv: &Context,
6206    body: &'a Db,
6207    base_depth: usize,
6208) -> RResult<(usize, String, &'a Db, usize)> {
6209    let mut chain: Vec<(usize, Option<String>, &Db)> = Vec::new();
6210    let mut cur = body;
6211    let mut depth = base_depth;
6212    while let Db::Lam(dom, inner) = cur {
6213        let dom_h = whnf(genv, dom);
6214        chain.push((
6215            depth,
6216            extract_inductive(genv, &dom_h).map(|(n, _)| n),
6217            inner,
6218        ));
6219        cur = inner;
6220        depth += 1;
6221    }
6222    // The innermost `match`, read through an application spine: a convoy `(match v … ) w …`
6223    // recurses on `v` as a bare `match` does.
6224    let scrutinee = match spine_head(cur) {
6225        Db::Match { disc, .. } => match &**disc {
6226            Db::Var(k) => {
6227                level_of(depth, *k).and_then(|lvl| chain.iter().position(|(l, ..)| *l == lvl))
6228            }
6229            _ => None,
6230        },
6231        _ => None,
6232    };
6233    let idx = scrutinee
6234        .filter(|&i| chain[i].1.is_some())
6235        .or_else(|| chain.iter().position(|(_, ind, _)| ind.is_some()))
6236        .ok_or_else(|| {
6237            ReCheckError::ill(
6238                "fixpoint has no inductive parameter for structural recursion".to_string(),
6239            )
6240        })?;
6241    Ok((
6242        chain[idx].0,
6243        chain[idx].1.clone().unwrap(),
6244        chain[idx].2,
6245        idx,
6246    ))
6247}
6248
6249/// Verify the fixpoint `body` (with `rec` bound at level `fix_level`) terminates: locate
6250/// the structural parameter and check that every recursive call decreases it. A single
6251/// fixpoint is the one-entry case of the block guard.
6252fn check_terminates(genv: &Context, body: &Db, fix_level: usize) -> RResult<()> {
6253    let (struct_level, ind, guard_body, struct_pos) = locate_struct(genv, body, fix_level + 1)?;
6254    let mut fix_positions = HashMap::new();
6255    fix_positions.insert(fix_level, struct_pos);
6256    guard(
6257        genv,
6258        guard_body,
6259        &fix_positions,
6260        struct_level,
6261        &ind,
6262        &HashMap::new(),
6263        struct_level + 1,
6264    )
6265}
6266
6267/// Verify a MUTUAL block of `n` fixpoint bodies terminates. The `n` names occupy levels
6268/// `base .. base+n-1`, so each body lives beneath all of them. Every member's structural
6269/// position is found first (assembling `level → position`); then each body is guarded so
6270/// that a call to ANY member decreases the CURRENT body's structural parameter — the
6271/// mutual Giménez guard, independently re-derived alongside the main kernel's.
6272fn check_terminates_mutual(genv: &Context, defs: &[Db], base: usize) -> RResult<()> {
6273    let n = defs.len();
6274    let base_depth = base + n;
6275    let mut fix_positions = HashMap::new();
6276    let mut located: Vec<(usize, String, &Db)> = Vec::with_capacity(n);
6277    for (j, body) in defs.iter().enumerate() {
6278        let (struct_level, ind, guard_body, struct_pos) = locate_struct(genv, body, base_depth)?;
6279        fix_positions.insert(base + j, struct_pos);
6280        located.push((struct_level, ind, guard_body));
6281    }
6282    for (struct_level, ind, guard_body) in &located {
6283        guard(
6284            genv,
6285            guard_body,
6286            &fix_positions,
6287            *struct_level,
6288            ind,
6289            &HashMap::new(),
6290            struct_level + 1,
6291        )?;
6292    }
6293    Ok(())
6294}
6295
6296/// Walk `term` (at `depth`) checking every recursive call — to ANY block member whose
6297/// level → structural-position mapping is in `fix_positions` — applies a structurally-
6298/// smaller argument (a variable whose level is in `smaller`, which maps each constructor-bound
6299/// variable's level to the inductive its own type heads — matching on the structural parameter
6300/// `struct_level` of `struct_type` seeds it, and matching on an ENTRY of it extends it, because
6301/// the structural-subterm relation is transitive).
6302fn guard(
6303    genv: &Context,
6304    term: &Db,
6305    fix_positions: &HashMap<usize, usize>,
6306    struct_level: usize,
6307    struct_type: &str,
6308    smaller: &HashMap<usize, String>,
6309    depth: usize,
6310) -> RResult<()> {
6311    match term {
6312        Db::App(..) => {
6313            let (head, args) = spine(term);
6314            if let Db::Var(k) = &head {
6315                if let Some(&pos) = level_of(depth, *k).and_then(|lvl| fix_positions.get(&lvl)) {
6316                    // A recursive call to some member: the argument at THAT member's
6317                    // structural position must be structurally smaller — a constructor-
6318                    // bound variable, or an APPLICATION `h a…` whose head `h` is one (the
6319                    // applied-smaller / Giménez rule, sound by strict positivity — see the
6320                    // main kernel's `verify_structural_arg_smaller`).
6321                    match args.get(pos) {
6322                        Some(arg) => {
6323                            let mut h: &Db = arg;
6324                            while let Db::App(f, _) = h {
6325                                h = f;
6326                            }
6327                            match h {
6328                                Db::Var(j)
6329                                    if level_of(depth, *j)
6330                                        .is_some_and(|l| smaller.contains_key(&l)) => {}
6331                                Db::Var(_) => {
6332                                    return Err(ReCheckError::ill(
6333                                        "recursive call on an argument not headed by a \
6334                                         structurally-smaller variable"
6335                                            .to_string(),
6336                                    ))
6337                                }
6338                                _ => {
6339                                    return Err(ReCheckError::ill(
6340                                        "recursive call whose structural argument is not a \
6341                                         variable or an application of one — cannot certify it \
6342                                         decreases"
6343                                            .to_string(),
6344                                    ))
6345                                }
6346                            }
6347                        }
6348                        None => {
6349                            return Err(ReCheckError::ill(
6350                                "recursive call is missing its structural argument".to_string(),
6351                            ))
6352                        }
6353                    }
6354                    for a in &args {
6355                        guard(
6356                            genv,
6357                            a,
6358                            fix_positions,
6359                            struct_level,
6360                            struct_type,
6361                            smaller,
6362                            depth,
6363                        )?;
6364                    }
6365                    return Ok(());
6366                }
6367            }
6368            guard(
6369                genv,
6370                &head,
6371                fix_positions,
6372                struct_level,
6373                struct_type,
6374                smaller,
6375                depth,
6376            )?;
6377            for a in &args {
6378                guard(
6379                    genv,
6380                    a,
6381                    fix_positions,
6382                    struct_level,
6383                    struct_type,
6384                    smaller,
6385                    depth,
6386                )?;
6387            }
6388            Ok(())
6389        }
6390        Db::Match {
6391            disc,
6392            motive,
6393            cases,
6394        } => {
6395            // The return motive is an ordinary subterm and MUST be guarded too (a recursive
6396            // occurrence in the return predicate would otherwise evade the check).
6397            guard(
6398                genv,
6399                motive,
6400                fix_positions,
6401                struct_level,
6402                struct_type,
6403                smaller,
6404                depth,
6405            )?;
6406            // A match on the (un-shadowed) structural parameter guards the recursive
6407            // calls in its cases: each constructor argument is a structural subterm.
6408            // A match guards when its scrutinee's fields are structural subterms of the
6409            // structural parameter: the parameter ITSELF, or a variable already known smaller,
6410            // since the subterm relation is transitive. The second case is what admits
6411            // `match n with Succ m => match m with Succ k => ... f k` - every `| n+2 => ...`
6412            // definition there is.
6413            if let Db::Var(k) = &**disc {
6414                if level_of(depth, *k) == Some(struct_level) {
6415                    return guard_match_cases(
6416                        genv,
6417                        cases,
6418                        struct_type,
6419                        fix_positions,
6420                        struct_level,
6421                        smaller,
6422                        depth,
6423                    );
6424                }
6425                if let Some(ind) = level_of(depth, *k)
6426                    .and_then(|lvl| smaller.get(&lvl))
6427                    .filter(|i| !i.is_empty())
6428                {
6429                    let ind = ind.clone();
6430                    return guard_match_cases(
6431                        genv,
6432                        cases,
6433                        &ind,
6434                        fix_positions,
6435                        struct_level,
6436                        smaller,
6437                        depth,
6438                    );
6439                }
6440            }
6441            guard(
6442                genv,
6443                disc,
6444                fix_positions,
6445                struct_level,
6446                struct_type,
6447                smaller,
6448                depth,
6449            )?;
6450            for c in cases {
6451                guard(
6452                    genv,
6453                    c,
6454                    fix_positions,
6455                    struct_level,
6456                    struct_type,
6457                    smaller,
6458                    depth,
6459                )?;
6460            }
6461            Ok(())
6462        }
6463        // Guard a binder's DOMAIN annotation (current depth) as well as its body (one
6464        // deeper). `Fix` has no domain.
6465        Db::Lam(dom, inner) | Db::Pi(dom, inner) => {
6466            guard(
6467                genv,
6468                dom,
6469                fix_positions,
6470                struct_level,
6471                struct_type,
6472                smaller,
6473                depth,
6474            )?;
6475            guard(
6476                genv,
6477                inner,
6478                fix_positions,
6479                struct_level,
6480                struct_type,
6481                smaller,
6482                depth + 1,
6483            )
6484        }
6485        Db::Fix(inner) => guard(
6486            genv,
6487            inner,
6488            fix_positions,
6489            struct_level,
6490            struct_type,
6491            smaller,
6492            depth + 1,
6493        ),
6494        // A nested mutual block introduces `n` fresh levels; its own termination is checked
6495        // when it is type-checked. Descend into each body, past those `n` binders — an
6496        // outer recursive call from within it must still decrease.
6497        Db::MutualFix { defs, .. } => {
6498            for b in defs {
6499                guard(
6500                    genv,
6501                    b,
6502                    fix_positions,
6503                    struct_level,
6504                    struct_type,
6505                    smaller,
6506                    depth + defs.len(),
6507                )?;
6508            }
6509            Ok(())
6510        }
6511        Db::Let(ty, value, body) => {
6512            // `ty`/`value` at the current depth; `body` one binder deeper.
6513            //
6514            // A let whose VALUE is an already-smaller variable binds the SAME VALUE, so its own
6515            // level inherits that smallness - zeta makes `let x := v in b` and `b[x := v]` the
6516            // same term, and a guard that disagrees rejects a definition for how it was spelled.
6517            guard(
6518                genv,
6519                ty,
6520                fix_positions,
6521                struct_level,
6522                struct_type,
6523                smaller,
6524                depth,
6525            )?;
6526            guard(
6527                genv,
6528                value,
6529                fix_positions,
6530                struct_level,
6531                struct_type,
6532                smaller,
6533                depth,
6534            )?;
6535            let mut inner = smaller.clone();
6536            if let Db::Var(k) = &**value {
6537                if let Some(ind) = level_of(depth, *k).and_then(|lvl| smaller.get(&lvl)) {
6538                    inner.insert(depth, ind.clone());
6539                }
6540            }
6541            guard(
6542                genv,
6543                body,
6544                fix_positions,
6545                struct_level,
6546                struct_type,
6547                &inner,
6548                depth + 1,
6549            )
6550        }
6551        Db::Var(k) => {
6552            // A bare member name (not the head of a guarded call) is the higher-order
6553            // escape — a recursive name used as a first-class value. Reject it.
6554            if level_of(depth, *k).is_some_and(|lvl| fix_positions.contains_key(&lvl)) {
6555                Err(ReCheckError::ill(
6556                    "recursive name occurs as a first-class value, not applied to a \
6557                     structurally-smaller argument"
6558                        .to_string(),
6559                ))
6560            } else {
6561                Ok(())
6562            }
6563        }
6564        Db::Sort(_) | Db::Global(_) | Db::Const { .. } | Db::Lit(_) => Ok(()),
6565    }
6566}
6567
6568/// Guard each case of a match on the structural parameter: mark every constructor
6569/// argument it binds as structurally smaller, then check the case body.
6570fn guard_match_cases(
6571    genv: &Context,
6572    cases: &[Db],
6573    struct_type: &str,
6574    fix_positions: &HashMap<usize, usize>,
6575    struct_level: usize,
6576    smaller: &HashMap<usize, String>,
6577    depth: usize,
6578) -> RResult<()> {
6579    // Only the constructor's VALUE FIELDS are bound by a case — its Π-telescope past the
6580    // inductive's parameters, which the discriminant fixes. Counting the whole telescope
6581    // over-peels on any parameterised inductive, and when the motive is a function type the
6582    // case's extra λ (an ordinary function parameter, a subterm of nothing) was marked
6583    // structurally smaller. `termination.rs` miscounted identically, so BOTH kernels admitted a
6584    // non-terminating fixpoint and `False` became inhabited by a closed term built from nothing
6585    // but the standard library. The two-kernel guarantee is worth nothing against a shared blind
6586    // spot, which is why this arithmetic is spelled out in both places.
6587    let num_type_params = genv.inductive_num_params(struct_type);
6588    let fields: Vec<Vec<String>> = genv
6589        .get_constructors(struct_type)
6590        .iter()
6591        .map(|(_, t)| named_field_heads(genv, t, num_type_params))
6592        .collect();
6593    for (i, case) in cases.iter().enumerate() {
6594        let heads: &[String] = fields.get(i).map(|v| v.as_slice()).unwrap_or(&[]);
6595        let mut smaller2 = smaller.clone();
6596        let mut cur = case;
6597        let mut d = depth;
6598        // Peel one λ per VALUE FIELD (a parametric inductive's case binds fewer than its
6599        // constructor's total parameter count — type parameters are fixed), recording each
6600        // bound variable's level as structurally smaller together with the inductive its own
6601        // type heads, so a nested match on it knows which constructors to expect.
6602        for head in heads {
6603            if let Db::Lam(_, inner) = cur {
6604                smaller2.insert(d, head.clone());
6605                cur = inner;
6606                d += 1;
6607            } else {
6608                break;
6609            }
6610        }
6611        guard(
6612            genv,
6613            cur,
6614            fix_positions,
6615            struct_level,
6616            struct_type,
6617            &smaller2,
6618            d,
6619        )?;
6620    }
6621    Ok(())
6622}
6623
6624/// Independently validate an indexed motive's complete generic telescope.
6625/// The de Bruijn representation enters each binder directly; only the retained
6626/// family application is shifted as its scope grows. No named-kernel typing or
6627/// telescope validation is reused.
6628fn check_indexed_motive(
6629    genv: &Context,
6630    lctx: &dyn LocalTypes,
6631    motive: &Db,
6632    disc_ty: &Db,
6633    parameters: usize,
6634    arguments: &[Db],
6635) -> RResult<()> {
6636    let (mut family, _) = spine(disc_ty);
6637    let mut arity = infer(genv, lctx, &family)?;
6638    for parameter in &arguments[..parameters] {
6639        let Db::Pi(_, body) = whnf_in_owned(genv, lctx, arity) else {
6640            return Err(ReCheckError::ill(
6641                "inductive parameter telescope is too short",
6642            ));
6643        };
6644        arity = beta_open_owned(body.into_db(), parameter);
6645        family = Db::App(DbBox::new(family), DbBox::new(parameter.clone()));
6646    }
6647    let mut motive_type = infer(genv, lctx, motive)?;
6648    let mut inner = extend_local(lctx);
6649    for _ in parameters..arguments.len() {
6650        let Db::Pi(domain, body) = whnf_in_owned(genv, &inner, arity) else {
6651            return Err(ReCheckError::ill("inductive index telescope is too short"));
6652        };
6653        let Db::Pi(actual_domain, actual_body) = whnf_in_owned(genv, &inner, motive_type) else {
6654            return Err(ReCheckError::ill("indexed motive lacks an index binder"));
6655        };
6656        if !def_eq(genv, &inner, &actual_domain, &domain) {
6657            return Err(ReCheckError::ill("indexed motive index domain mismatch"));
6658        }
6659        inner.push(domain.into_db());
6660        family = Db::App(DbBox::new(shift(&family, 1, 0)), DbBox::new(Db::Var(0)));
6661        arity = body.into_db();
6662        motive_type = actual_body.into_db();
6663    }
6664    if !matches!(whnf_in_owned(genv, &inner, arity), Db::Sort(_)) {
6665        return Err(ReCheckError::ill(
6666            "discriminant leaves unapplied inductive indices",
6667        ));
6668    }
6669    let Db::Pi(domain, codomain) = whnf_in_owned(genv, &inner, motive_type) else {
6670        return Err(ReCheckError::ill(
6671            "indexed motive lacks a major-premise binder",
6672        ));
6673    };
6674    if !def_eq(genv, &inner, &domain, &family) {
6675        return Err(ReCheckError::ill("indexed motive major domain mismatch"));
6676    }
6677    inner.push(domain.into_db());
6678    if !matches!(whnf_in_owned(genv, &inner, codomain.into_db()), Db::Sort(_)) {
6679        return Err(ReCheckError::ill("indexed motive codomain is not a sort"));
6680    }
6681    Ok(())
6682}
6683
6684/// Type a `match`: discriminant must be inductive; the motive (function `λx:I.T` or a
6685/// raw type) gives the return type; case count must equal constructor count; each case
6686/// is checked against the type derived from its constructor's signature; and a `Prop`
6687/// discriminant may only large-eliminate into `Type` if it is a subsingleton.
6688fn infer_match(
6689    genv: &Context,
6690    lctx: &dyn LocalTypes,
6691    disc: &Db,
6692    motive: &Db,
6693    cases: &[Db],
6694) -> RResult<Db> {
6695    // 1. Discriminant's inductive type and its type arguments.
6696    let disc_ty = whnf_in_owned(genv, lctx, infer(genv, lctx, disc)?);
6697    let (ind_name, type_args) = extract_inductive(genv, &disc_ty).ok_or_else(|| {
6698        ReCheckError::unsupported(format!(
6699            "match discriminant of unrecognized type {}",
6700            from_db(&disc_ty, lctx.len())
6701        ))
6702    })?;
6703
6704    // An empty `match` is `ex falso`, which requires an UNINHABITED discriminant type. A
6705    // zero-constructor inductive this kernel can produce a literal of is not one.
6706    if inhabited_without_a_constructor(genv, &ind_name) {
6707        return Err(ReCheckError::ill(format!(
6708            "'{ind_name}' has no constructors but is inhabited by a literal, so a match on it \
6709             is not ex falso"
6710        )));
6711    }
6712
6713    // 2. Parameter/index split: the first `p` type arguments are uniform parameters; any
6714    // remaining ones are INDICES the motive abstracts over (an indexed family like `Eq`).
6715    // `indexed == false` is the ordinary eliminator, handled exactly as before.
6716    let p = genv.inductive_num_params(&ind_name).min(type_args.len());
6717    let indexed = type_args.len() > p;
6718    let eff_motive = if indexed {
6719        check_indexed_motive(genv, lctx, motive, &disc_ty, p, &type_args)?;
6720        None
6721    } else {
6722        Some(effective_motive(genv, lctx, motive, &disc_ty)?)
6723    };
6724
6725    // 3. Coverage. For a NON-indexed inductive this is one case per constructor. For an INDEXED
6726    // one it is one case per constructor the discriminant's indices still ALLOW (SPEC F): a
6727    // constructor whose declared result index provably clashes with the scrutinee's could not
6728    // have produced it, so it owes no branch. Supplying all of them stays legal.
6729    let all_names: Vec<String> = genv
6730        .get_constructors(&ind_name)
6731        .iter()
6732        .map(|(n, _)| n.to_string())
6733        .collect();
6734    let ctor_names: Vec<String> = if !indexed || cases.len() == all_names.len() {
6735        all_names.clone()
6736    } else {
6737        let allowed = db_constructors_the_indices_allow(genv, lctx, &ind_name, p, &type_args);
6738        allowed.iter().map(|&i| all_names[i].clone()).collect()
6739    };
6740    if cases.len() != ctor_names.len() {
6741        return Err(ReCheckError::ill(format!(
6742            "match on {} has {} cases but {} constructors the indices allow",
6743            ind_name,
6744            cases.len(),
6745            ctor_names.len()
6746        )));
6747    }
6748
6749    // 4. Each case against its constructor-derived type.
6750    for (case, cname) in cases.iter().zip(ctor_names.iter()) {
6751        let case_ty = match &eff_motive {
6752            Some(eff) => case_type(genv, eff, cname, &type_args, &disc_ty)?,
6753            None => case_type_indexed(genv, motive, cname, &type_args[..p], &disc_ty)?,
6754        };
6755        check_case(genv, lctx, case, &case_ty)?;
6756    }
6757
6758    // 5. Reuse the non-indexed motive already checked above in this exact
6759    // immutable environment and local scope. Standalone fixpoint return-type
6760    // discovery still validates its own motive through match_return_type.
6761    let ret = match eff_motive {
6762        Some(eff) => whnf_in_owned(
6763            genv,
6764            lctx,
6765            Db::App(DbBox::new(eff), DbBox::new(disc.clone())),
6766        ),
6767        None => match_return_type(genv, lctx, motive, disc, &disc_ty)?,
6768    };
6769
6770    // 6. The elimination restrictions. SProp eliminates only into SProp: definitional irrelevance
6771    // equates every inhabitant, so a match out of one into a relevant sort equates its branches.
6772    // A family that is a proposition at some instance of its universe levels eliminates into a
6773    // larger sort only if it is a subsingleton (empty, or one constructor with purely propositional
6774    // arguments); for a family in `Sort u`, which is `Prop` at `u := 0`, a result whose level is not
6775    // at most the family's is such an elimination at that instance. The main kernel states the full
6776    // argument; both kernels must agree here or a `0 = 1` survives in one of them.
6777    let disc_sort = match whnf_in_owned(genv, lctx, infer(genv, lctx, &disc_ty)?) {
6778        Db::Sort(u) => u,
6779        other => {
6780            return Err(ReCheckError::ill(format!(
6781                "the scrutinee's type lives in {other:?}, not a sort"
6782            )))
6783        }
6784    };
6785    if disc_sort.is_never_prop() {
6786        return Ok(ret);
6787    }
6788    let ret_sort = match whnf_in_owned(genv, lctx, infer(genv, lctx, &ret)?) {
6789        Db::Sort(u) => u,
6790        other => {
6791            return Err(ReCheckError::ill(format!(
6792                "the match's result lives in {other:?}, not a sort"
6793            )))
6794        }
6795    };
6796    if matches!(disc_sort, Universe::SProp) && !matches!(ret_sort, Universe::SProp) {
6797        return Err(ReCheckError::ill(format!(
6798            "elimination of the definitionally-irrelevant proposition '{ind_name}' into a relevant sort"
6799        )));
6800    }
6801    let large = if disc_sort.equiv(&Universe::Prop) {
6802        !ret_sort.equiv(&Universe::Prop)
6803    } else {
6804        !ret_sort.is_subtype_of(&disc_sort)
6805    };
6806    if large && !is_subsingleton(genv, &ind_name)? {
6807        return Err(ReCheckError::ill(format!(
6808            "large elimination of non-subsingleton proposition '{}' into a larger sort",
6809            ind_name
6810        )));
6811    }
6812
6813    Ok(ret)
6814}
6815
6816/// Extract the inductive name and its type arguments from a (head-normal) type: peel the
6817/// application spine; the head must be a `Global` registered as an inductive.
6818fn extract_inductive(genv: &Context, ty: &Db) -> Option<(String, Vec<Db>)> {
6819    let (head, args) = spine(ty);
6820    match head {
6821        Db::Global(name) | Db::Const { name, .. } if genv.is_inductive(&name) => Some((name, args)),
6822        _ => None,
6823    }
6824}
6825
6826/// Resolve the constructor at the same universe arguments as its discriminant.
6827/// Type inference remains this checker's own de Bruijn implementation.
6828fn constructor_at_levels(genv: &Context, name: &str, disc_ty: &Db) -> RResult<(Db, Db)> {
6829    let (head, _) = spine(disc_ty);
6830    let constructor = match head {
6831        Db::Const { levels, .. } if genv.poly_declaration(name).is_some() => Db::Const {
6832            name: name.to_string(),
6833            levels,
6834        },
6835        _ => Db::Global(name.to_string()),
6836    };
6837    let ty = infer(genv, &[], &constructor)?;
6838    Ok((constructor, ty))
6839}
6840
6841/// The expected type of the case for `ctor_name`, given the `motive` and the
6842/// discriminant's `type_args`. The constructor's type `Π(p₀:U₀)…Π(pₘ₋₁:Uₘ₋₁). Ind …`
6843/// has its leading `|type_args|` parameters instantiated by the type arguments
6844/// (β-style), and its final codomain replaced by `motive (Ctor type_args value_args)`,
6845/// leaving `Π(value params). motive (Ctor …)`. Pure de Bruijn — no names to capture.
6846fn case_type(
6847    genv: &Context,
6848    motive: &Db,
6849    ctor_name: &str,
6850    type_args: &[Db],
6851    disc_ty: &Db,
6852) -> RResult<Db> {
6853    let (ctor_head, ctor_db) = constructor_at_levels(genv, ctor_name, disc_ty)?;
6854
6855    // Instantiate the type parameters (each `type_args[i]` is closed over the telescope).
6856    let mut body = ctor_db;
6857    for ta in type_args {
6858        match body {
6859            Db::Pi(_dom, rest) => body = beta_open_owned(rest.into_db(), ta),
6860            _ => {
6861                return Err(ReCheckError::ill(format!(
6862                    "constructor '{}' has fewer parameters than the discriminant's type arguments",
6863                    ctor_name
6864                )))
6865            }
6866        }
6867    }
6868
6869    // Peel the remaining value-parameter telescope.
6870    let mut value_doms = Vec::new();
6871    let mut cur = body;
6872    while let Db::Pi(dom, rest) = cur {
6873        value_doms.push(dom.into_db());
6874        cur = rest.into_db();
6875    }
6876    let num_val = value_doms.len();
6877    let lift = num_val as isize;
6878
6879    // Build `Ctor type_args value_vars` at the bottom of the value telescope.
6880    let mut applied = ctor_head;
6881    for ta in type_args {
6882        applied = Db::App(DbBox::new(applied), DbBox::new(shift(ta, lift, 0)));
6883    }
6884    for p in 0..num_val {
6885        applied = Db::App(DbBox::new(applied), DbBox::new(Db::Var(num_val - 1 - p)));
6886    }
6887
6888    let motive_bot = shift(motive, lift, 0);
6889    let cod = whnf_in_owned(
6890        genv,
6891        &[],
6892        Db::App(DbBox::new(motive_bot), DbBox::new(applied)),
6893    );
6894
6895    // Re-wrap the value parameters.
6896    let mut case_ty = cod;
6897    for dom in value_doms.into_iter().rev() {
6898        case_ty = Db::Pi(DbBox::new(dom), DbBox::new(case_ty));
6899    }
6900    Ok(case_ty)
6901}
6902
6903/// A match's return type, indexed-aware. For an ordinary (non-indexed) inductive it is the
6904/// motive applied to the discriminant. For an INDEXED family the motive abstracts over the
6905/// indices too, so it is applied to the discriminant's own index arguments and THEN the
6906/// discriminant — `Eq.rec`'s motive `P` yields `P y h` for a scrutinee `h : Eq A x y`.
6907fn match_return_type(
6908    genv: &Context,
6909    lctx: &dyn LocalTypes,
6910    motive: &Db,
6911    disc: &Db,
6912    disc_ty: &Db,
6913) -> RResult<Db> {
6914    let (ind_name, type_args) = extract_inductive(genv, disc_ty).ok_or_else(|| {
6915        ReCheckError::unsupported(format!(
6916            "match discriminant of unrecognized type {}",
6917            from_db(disc_ty, lctx.len())
6918        ))
6919    })?;
6920    let p = genv.inductive_num_params(&ind_name).min(type_args.len());
6921    if type_args.len() > p {
6922        let mut ret = motive.clone();
6923        for idx in &type_args[p..] {
6924            ret = Db::App(DbBox::new(ret), DbBox::new(idx.clone()));
6925        }
6926        ret = Db::App(DbBox::new(ret), DbBox::new(disc.clone()));
6927        Ok(whnf_in_owned(genv, lctx, ret))
6928    } else {
6929        let eff = effective_motive(genv, lctx, motive, disc_ty)?;
6930        Ok(whnf_in_owned(
6931            genv,
6932            lctx,
6933            Db::App(DbBox::new(eff), DbBox::new(disc.clone())),
6934        ))
6935    }
6936}
6937
6938/// The expected case type for `ctor_name` in an INDEXED match. Only the inductive's
6939/// `params` are instantiated (not the trailing indices); the constructor's remaining value
6940/// arguments become the case's `Π` binders; and the codomain is the `motive` applied to
6941/// the constructor's RESULT indices (its declared return-type arguments past the
6942/// parameters) and then the constructor value. Pure de Bruijn — mirrors [`case_type`].
6943fn case_type_indexed(
6944    genv: &Context,
6945    motive: &Db,
6946    ctor_name: &str,
6947    params: &[Db],
6948    disc_ty: &Db,
6949) -> RResult<Db> {
6950    let (ctor_head, ctor_db) = constructor_at_levels(genv, ctor_name, disc_ty)?;
6951
6952    // Instantiate the inductive's PARAMETERS only (the leading `params.len()` binders).
6953    let mut body = ctor_db;
6954    for pa in params {
6955        match body {
6956            Db::Pi(_dom, rest) => body = beta_open_owned(rest.into_db(), pa),
6957            _ => {
6958                return Err(ReCheckError::ill(format!(
6959                    "constructor '{}' has fewer parameters than the inductive",
6960                    ctor_name
6961                )))
6962            }
6963        }
6964    }
6965
6966    // Peel the value-parameter telescope; the residual is the constructor's result type.
6967    let mut value_doms = Vec::new();
6968    let mut cur = body;
6969    while let Db::Pi(dom, rest) = cur {
6970        value_doms.push(dom.into_db());
6971        cur = rest.into_db();
6972    }
6973    let num_val = value_doms.len();
6974    let lift = num_val as isize;
6975
6976    // The constructor's RESULT indices: its result-type spine arguments past the params
6977    // (already expressed under the value binders, so no shift).
6978    let (_head, res_args) = spine(&cur);
6979    let result_indices: Vec<Db> = res_args.into_iter().skip(params.len()).collect();
6980
6981    // Build `Ctor params value_vars` at the bottom of the value telescope.
6982    let mut applied = ctor_head;
6983    for pa in params {
6984        applied = Db::App(DbBox::new(applied), DbBox::new(shift(pa, lift, 0)));
6985    }
6986    for i in 0..num_val {
6987        applied = Db::App(DbBox::new(applied), DbBox::new(Db::Var(num_val - 1 - i)));
6988    }
6989
6990    // `motive result_indices… applied`, all under the value binders.
6991    let mut cod = shift(motive, lift, 0);
6992    for ri in &result_indices {
6993        cod = Db::App(DbBox::new(cod), DbBox::new(ri.clone()));
6994    }
6995    cod = Db::App(DbBox::new(cod), DbBox::new(applied));
6996    let cod = whnf_in_owned(genv, &[], cod);
6997
6998    // Re-wrap the value parameters.
6999    let mut case_ty = cod;
7000    for dom in value_doms.into_iter().rev() {
7001        case_ty = Db::Pi(DbBox::new(dom), DbBox::new(case_ty));
7002    }
7003    Ok(case_ty)
7004}
7005
7006/// Whether the re-checker can produce a value of `ind` without any constructor — i.e. whether
7007/// `ind` is one of the carriers its own `Db::Lit` typing rule inhabits.
7008///
7009/// An empty `match` passes coverage for any inductive with zero constructors, and that is only
7010/// `ex falso` if nothing inhabits the type. These carriers have no constructors and are inhabited
7011/// anyway, so an empty match on one proves its motive from a value that exists. The main kernel
7012/// states the same rule on `empty_match_would_be_a_lie`; both kernels need it, because counting
7013/// constructors is exactly the step they would otherwise get identically wrong.
7014fn inhabited_without_a_constructor(genv: &Context, ind: &str) -> bool {
7015    genv.get_constructors(ind).is_empty()
7016        && matches!(
7017            ind,
7018            "Int" | "Nat" | "Float" | "Text" | "Duration" | "Date" | "Moment"
7019        )
7020}
7021
7022/// Decompose a `Db` into a CONSTRUCTOR head and its arguments, bridging a `Nat` literal to its
7023/// Peano spelling so `Vect A 0` and `Vect A Zero` are the same index to the unifier below.
7024fn db_constructor_head(genv: &Context, t: &Db) -> Option<(String, Vec<Db>)> {
7025    let bridged = if let Db::Lit(Literal::Nat(n)) = t {
7026        if !crate::int_inductive::reads_nat_literal(genv, n) {
7027            return None;
7028        }
7029        db_nat_peano_step(t)
7030    } else {
7031        db_int_constructor(genv, t).unwrap_or_else(|| t.clone())
7032    };
7033    let (head, args) = spine(&bridged);
7034    match head {
7035        Db::Global(name) | Db::Const { name, .. } if genv.is_constructor(&name) => {
7036            Some((name, args))
7037        }
7038        _ => None,
7039    }
7040}
7041
7042/// Demand a scrutinee index head in its actual local context. Declared
7043/// constructor indices have a different de Bruijn scope and remain syntactic.
7044fn db_demanded_index_constructor_head(
7045    genv: &Context,
7046    lctx: &dyn LocalTypes,
7047    t: &Db,
7048) -> Option<(String, Vec<Db>)> {
7049    if WHNF_EXHAUSTED.with(|flag| flag.get()) {
7050        return None;
7051    }
7052    if let Some(head) = db_constructor_head(genv, t) {
7053        return Some(head);
7054    }
7055    let exposed = whnf_in(genv, lctx, t);
7056    // Keep the surrounding exhaustion flag set and refuse to infer a clash
7057    // from a reduction that did not finish.
7058    if WHNF_EXHAUSTED.with(|flag| flag.get()) {
7059        return None;
7060    }
7061    db_constructor_head(genv, &exposed)
7062}
7063
7064/// Whether constructor disjointness may be used for `ctor`'s inductive.
7065///
7066/// Only at `Type` level. `Prop` is proof-irrelevant: two distinct constructors of a
7067/// propositional inductive ARE definitionally equal, so their difference proves nothing and a
7068/// clash there would discharge a branch that is in fact reachable. A family in `Sort u` is a
7069/// proposition at `u := 0`, so the arity must end in a sort no instance of its levels makes
7070/// `Prop`; an arity ending in anything but a written sort grants nothing.
7071fn db_disjointness_available(genv: &Context, ctor: &str) -> bool {
7072    let Some(ind) = genv.constructor_inductive(ctor) else {
7073        return false;
7074    };
7075    let Some(ind_ty) = genv.get_global(ind) else {
7076        return false;
7077    };
7078    let Ok(mut cur) = to_db(ind_ty, &mut Vec::new()) else {
7079        return false;
7080    };
7081    while let Db::Pi(_, rest) = cur {
7082        cur = rest.into_db();
7083    }
7084    matches!(cur, Db::Sort(level) if level.is_never_prop())
7085}
7086
7087/// Whether two index terms PROVABLY cannot be made equal. `flexible` holds the de Bruijn
7088/// indices — as seen from the constructor's RESULT — of the binders still free to be anything.
7089///
7090/// The only ground ever given is constructor disjointness. The two sides live in different
7091/// scopes, which is harmless precisely because nothing is ever concluded from a VARIABLE: a
7092/// variable on either side means "could be anything", and that is the safe answer.
7093fn db_indices_clash(
7094    genv: &Context,
7095    lctx: &dyn LocalTypes,
7096    scrutinee: &Db,
7097    declared: &Db,
7098    flexible: &[usize],
7099) -> bool {
7100    if let Db::Var(k) = declared {
7101        if flexible.contains(k) {
7102            return false;
7103        }
7104    }
7105    // The declared side stays in its own scope. If it has no constructor head,
7106    // there is no disjointness question to demand from the scrutinee.
7107    let Some((cd, args_d)) = db_constructor_head(genv, declared) else {
7108        return false;
7109    };
7110    let Some((cs, args_s)) = db_demanded_index_constructor_head(genv, lctx, scrutinee) else {
7111        return false;
7112    };
7113    if !db_disjointness_available(genv, &cs) || !db_disjointness_available(genv, &cd) {
7114        return false;
7115    }
7116    if cs != cd {
7117        return genv.constructor_inductive(&cs) == genv.constructor_inductive(&cd);
7118    }
7119    args_s
7120        .iter()
7121        .zip(args_d.iter())
7122        .any(|(a, b)| db_indices_clash(genv, lctx, a, b, flexible))
7123}
7124
7125/// **SPEC F** for the re-checker — which of `ind`'s constructors the discriminant's INDICES
7126/// still allow, as positions in registration order. The re-checker's own reading of the rule
7127/// the main kernel states on `constructors_the_indices_allow`: a `Match` on an indexed family
7128/// owes a branch only for the constructors that could have produced the scrutinee.
7129///
7130/// De Bruijn makes "still free to be anything" a set of INDICES rather than a set of names, so
7131/// this side cannot be fooled by a shadowed binder — a different arithmetic for the same rule,
7132/// which is the point of having two kernels.
7133fn db_constructors_the_indices_allow(
7134    genv: &Context,
7135    lctx: &dyn LocalTypes,
7136    ind: &str,
7137    num_params: usize,
7138    disc_args: &[Db],
7139) -> Vec<usize> {
7140    let (params, disc_indices) = disc_args.split_at(num_params.min(disc_args.len()));
7141    let ctors: Vec<(String, Term)> = genv
7142        .get_constructors(ind)
7143        .iter()
7144        .map(|(n, t)| (n.to_string(), (*t).clone()))
7145        .collect();
7146    (0..ctors.len())
7147        .filter(|&i| {
7148            let Ok(mut cur) = to_db(&ctors[i].1, &mut Vec::new()) else {
7149                return true;
7150            };
7151            // The constructor's parameters are the scrutinee's own.
7152            for value in params {
7153                match cur {
7154                    Db::Pi(_, rest) => cur = beta_open(&rest.into_db(), value),
7155                    _ => return true,
7156                }
7157            }
7158            // What is left binds the fields, each free to be anything: from the result, the
7159            // variables below the field count.
7160            let mut fields = 0usize;
7161            while let Db::Pi(_, rest) = cur {
7162                cur = rest.into_db();
7163                fields += 1;
7164            }
7165            let flexible: Vec<usize> = (0..fields).collect();
7166            let (_head, result_args) = spine(&cur);
7167            let declared: &[Db] = if result_args.len() > num_params {
7168                &result_args[num_params..]
7169            } else {
7170                &[]
7171            };
7172            !disc_indices
7173                .iter()
7174                .zip(declared.iter())
7175                .any(|(s, d)| db_indices_clash(genv, lctx, s, d, &flexible))
7176        })
7177        .collect()
7178}
7179
7180/// Whether an inductive is a subsingleton `Prop` — the re-checker's independent reading of the
7181/// same CIC criterion the main kernel states on [`crate::type_checker::is_subsingleton_prop`]:
7182/// zero constructors, or exactly one whose every binder past the inductive's **parameters** is
7183/// propositional **or occurs among the indices of the constructor's result**. Only these may be
7184/// large-eliminated into `Type`.
7185///
7186/// De Bruijn makes the index clause exact where names cannot: a field bound at telescope
7187/// position `p` is, from under all `depth` binders of the result, the variable `depth-1-p`.
7188/// There is no shadowing to reason about — two distinct binders are two distinct indices — so
7189/// this side needs no conservative repeat-name refusal, and the two kernels reaching the same
7190/// verdict by different arithmetic is the point of having two.
7191fn is_subsingleton(genv: &Context, ind: &str) -> RResult<bool> {
7192    let ctors: Vec<(String, Term)> = genv
7193        .get_constructors(ind)
7194        .iter()
7195        .map(|(n, t)| (n.to_string(), (*t).clone()))
7196        .collect();
7197    match ctors.len() {
7198        0 => Ok(true),
7199        1 => {
7200            let num_params = genv.inductive_num_params(ind);
7201            let ctor_db = to_db(&ctors[0].1, &mut Vec::new())?;
7202            let mut lctx: Vec<Db> = Vec::new();
7203            let mut cur = ctor_db;
7204            let mut depth = 0usize;
7205            // Telescope positions of the fields that are not propositional.
7206            let mut owed: Vec<usize> = Vec::new();
7207            while let Db::Pi(dom, rest) = cur {
7208                if depth >= num_params && !infer_sort(genv, &lctx, &dom)?.equiv(&Universe::Prop) {
7209                    owed.push(depth);
7210                }
7211                lctx.push(dom.into_db());
7212                cur = rest.into_db();
7213                depth += 1;
7214            }
7215            if owed.is_empty() {
7216                return Ok(true);
7217            }
7218            let (_head, args) = spine(&cur);
7219            let indices: &[Db] = if args.len() > num_params {
7220                &args[num_params..]
7221            } else {
7222                &[]
7223            };
7224            Ok(owed.iter().all(|&position| {
7225                let as_seen_from_the_result = depth - 1 - position;
7226                indices
7227                    .iter()
7228                    .any(|a| matches!(a, Db::Var(k) if *k == as_seen_from_the_result))
7229            }))
7230        }
7231        _ => Ok(false),
7232    }
7233}
7234
7235/// Infer `t`'s type and require it to be a sort; return that universe.
7236fn infer_sort(genv: &Context, lctx: &dyn LocalTypes, t: &Db) -> RResult<Universe> {
7237    let ty = whnf_in_owned(genv, lctx, infer(genv, lctx, t)?);
7238    match ty {
7239        Db::Sort(u) => Ok(u),
7240        other => Err(ReCheckError::ill(format!(
7241            "expected a type, got something of type {}",
7242            from_db(&other, lctx.len())
7243        ))),
7244    }
7245}
7246
7247/// Check a match branch against its constructor-derived telescope. Each explicit
7248/// binder annotation must be a type and definitionally equal to the corresponding
7249/// field domain before the branch body is checked in that extended context.
7250fn check_case(genv: &Context, lctx: &dyn LocalTypes, case: &Db, case_ty: &Db) -> RResult<()> {
7251    match (case, case_ty) {
7252        (Db::Lam(annotation, body), Db::Pi(dom, cod)) => {
7253            if !matches!(
7254                whnf_in_owned(genv, lctx, infer(genv, lctx, annotation)?),
7255                Db::Sort(_)
7256            ) || !def_eq(genv, lctx, annotation, dom)
7257            {
7258                return Err(ReCheckError::ill(
7259                    "match branch binder annotation differs from its constructor field type"
7260                        .to_string(),
7261                ));
7262            }
7263            let mut ext = extend_local(lctx);
7264            ext.push((**dom).clone());
7265            check_case(genv, &ext, body, cod)
7266        }
7267        _ => check(genv, lctx, case, case_ty),
7268    }
7269}
7270
7271fn check(genv: &Context, lctx: &dyn LocalTypes, t: &Db, expected: &Db) -> RResult<()> {
7272    // A fixpoint checked against a type: bound at that type, a terminating fixpoint's body must
7273    // have it, as the main kernel's `check_type` asks. A fixpoint this does not type falls to
7274    // inference, which reads the type off the body.
7275    if let Db::Fix(body) = t {
7276        if check_terminates(genv, body, lctx.len()).is_ok() {
7277            let mut ext = extend_local(lctx);
7278            ext.push(expected.clone());
7279            if let Ok(got) = infer(genv, &ext, body) {
7280                if is_sub(genv, &ext, &got, &shift(expected, 1, 0)) {
7281                    return Ok(());
7282                }
7283            }
7284        }
7285    }
7286    let inferred = infer(genv, lctx, t)?;
7287    if is_sub(genv, lctx, &inferred, expected) {
7288        Ok(())
7289    } else {
7290        Err(ReCheckError::ill(format!(
7291            "type mismatch: have {}, expected {}",
7292            from_db(&whnf_in(genv, lctx, &inferred), lctx.len()),
7293            from_db(&whnf_in(genv, lctx, expected), lctx.len())
7294        )))
7295    }
7296}
7297
7298fn lit_type_name(l: &Literal) -> &'static str {
7299    match l {
7300        Literal::Int(_) | Literal::BigInt(_) => "Int",
7301        Literal::Nat(_) => "Nat",
7302        Literal::Float(_) => "Float",
7303        Literal::Text(_) => "Text",
7304        Literal::Duration(_) => "Duration",
7305        Literal::Date(_) => "Date",
7306        Literal::Moment(_) => "Moment",
7307    }
7308}
7309
7310// An active Context is a name map, not a historical telescope. Recover only the
7311// demanded dependency closure, then independently check its predecessor-scoped types.
7312struct LocalPlan<'a> {
7313    bindings: Vec<(&'a str, &'a Term)>,
7314    issue: Option<ReCheckError>,
7315    max_depth: usize,
7316}
7317
7318struct LocalAdmission {
7319    remaining: usize,
7320    max_depth: usize,
7321    #[cfg(test)]
7322    high_water: usize,
7323}
7324
7325enum LocalAdmissionFrame<'a> {
7326    Node(&'a Term, usize),
7327    Db(&'a Db, usize),
7328    Dbs(&'a [Db], usize),
7329    Level(&'a Universe, usize),
7330    Levels(&'a [Universe], usize),
7331    Bind(&'a str, &'a Term, usize),
7332    Restore(usize),
7333    Cases(&'a [Term], usize),
7334    Bodies(&'a [(String, Term)], usize),
7335}
7336
7337impl LocalAdmission {
7338    fn new(limit: usize) -> Self {
7339        Self {
7340            remaining: limit,
7341            max_depth: 0,
7342            #[cfg(test)]
7343            high_water: 0,
7344        }
7345    }
7346
7347    // Slice continuations keep scratch bounded by depth, not the arity of a
7348    // malicious Match. Binder names are borrowed; no annotation trees are cloned.
7349    fn free_names<'a>(&mut self, term: &'a Term) -> RResult<Vec<&'a str>> {
7350        self.scan(LocalAdmissionFrame::Node(term, 0))
7351    }
7352
7353    fn admit_db(&mut self, term: &Db) -> RResult<()> {
7354        self.scan(LocalAdmissionFrame::Db(term, 0)).map(|_| ())
7355    }
7356
7357    fn scan<'a>(&mut self, root: LocalAdmissionFrame<'a>) -> RResult<Vec<&'a str>> {
7358        use LocalAdmissionFrame as Frame;
7359        let mut frames = vec![root];
7360        let mut bound: Vec<&str> = Vec::new();
7361        let mut free = std::collections::BTreeSet::new();
7362        while let Some(frame) = frames.pop() {
7363            #[cfg(test)]
7364            {
7365                self.high_water = self.high_water.max(frames.len() + 1);
7366            }
7367            match frame {
7368                Frame::Restore(len) => bound.truncate(len),
7369                Frame::Bind(name, body, depth) => {
7370                    frames.push(Frame::Restore(bound.len()));
7371                    bound.push(name);
7372                    frames.push(Frame::Node(body, depth));
7373                }
7374                Frame::Cases(cases, depth) => {
7375                    if let Some((first, rest)) = cases.split_first() {
7376                        frames.push(Frame::Cases(rest, depth));
7377                        frames.push(Frame::Node(first, depth));
7378                    }
7379                }
7380                Frame::Bodies(defs, depth) => {
7381                    if let Some(((_, first), rest)) = defs.split_first() {
7382                        frames.push(Frame::Bodies(rest, depth));
7383                        frames.push(Frame::Node(first, depth));
7384                    }
7385                }
7386                Frame::Levels(levels, depth) => {
7387                    if let Some((first, rest)) = levels.split_first() {
7388                        frames.push(Frame::Levels(rest, depth));
7389                        frames.push(Frame::Level(first, depth));
7390                    }
7391                }
7392                Frame::Level(level, depth) => {
7393                    if self.remaining == 0 || depth > crate::type_checker::MAX_TERM_DEPTH {
7394                        return Err(ReCheckError::resource_limit(
7395                            "active local universe exceeds the independent input admission limit",
7396                        ));
7397                    }
7398                    self.remaining -= 1;
7399                    self.max_depth = self.max_depth.max(depth);
7400                    match level {
7401                        Universe::Succ(a) => frames.push(Frame::Level(a, depth + 1)),
7402                        Universe::Max(a, b) | Universe::IMax(a, b) => {
7403                            frames.push(Frame::Level(b, depth + 1));
7404                            frames.push(Frame::Level(a, depth + 1));
7405                        }
7406                        Universe::SProp | Universe::Prop | Universe::Type(_) | Universe::Var(_) => {
7407                        }
7408                    }
7409                }
7410                Frame::Dbs(terms, depth) => {
7411                    if let Some((first, rest)) = terms.split_first() {
7412                        frames.push(Frame::Dbs(rest, depth));
7413                        frames.push(Frame::Db(first, depth));
7414                    }
7415                }
7416                Frame::Db(t, depth) => {
7417                    if self.remaining == 0 || depth > crate::type_checker::MAX_TERM_DEPTH {
7418                        return Err(ReCheckError::resource_limit(
7419                            "inferred local type exceeds input admission limit",
7420                        ));
7421                    }
7422                    self.remaining -= 1;
7423                    self.max_depth = self.max_depth.max(depth);
7424                    match t {
7425                        Db::Sort(level) => frames.push(Frame::Level(level, depth)),
7426                        Db::Const { levels, .. } => frames.push(Frame::Levels(levels, depth)),
7427                        Db::Pi(a, b) | Db::Lam(a, b) | Db::App(a, b) => {
7428                            frames.push(Frame::Db(b, depth + 1));
7429                            frames.push(Frame::Db(a, depth + 1));
7430                        }
7431                        Db::Fix(body) => frames.push(Frame::Db(body, depth + 1)),
7432                        Db::Let(a, b, c) => {
7433                            frames.push(Frame::Db(c, depth + 1));
7434                            frames.push(Frame::Db(b, depth + 1));
7435                            frames.push(Frame::Db(a, depth + 1));
7436                        }
7437                        Db::MutualFix { defs, .. } => frames.push(Frame::Dbs(defs, depth + 1)),
7438                        Db::Match {
7439                            disc,
7440                            motive,
7441                            cases,
7442                        } => {
7443                            frames.push(Frame::Dbs(cases, depth + 1));
7444                            frames.push(Frame::Db(motive, depth + 1));
7445                            frames.push(Frame::Db(disc, depth + 1));
7446                        }
7447                        Db::Var(_) | Db::Global(_) | Db::Lit(_) => {}
7448                    }
7449                }
7450                Frame::Node(t, depth) => {
7451                    if self.remaining == 0 || depth > crate::type_checker::MAX_TERM_DEPTH {
7452                        return Err(ReCheckError::resource_limit(
7453                            "active local telescope exceeds the independent input admission limit",
7454                        ));
7455                    }
7456                    self.remaining -= 1;
7457                    self.max_depth = self.max_depth.max(depth);
7458                    match t {
7459                        Term::Var(name) => {
7460                            if !bound.iter().rev().any(|b| *b == name) {
7461                                free.insert(name.as_str());
7462                            }
7463                        }
7464                        Term::Pi {
7465                            param,
7466                            param_type,
7467                            body_type,
7468                        } => {
7469                            frames.push(Frame::Bind(param, body_type, depth + 1));
7470                            frames.push(Frame::Node(param_type, depth + 1));
7471                        }
7472                        Term::Lambda {
7473                            param,
7474                            param_type,
7475                            body,
7476                        } => {
7477                            frames.push(Frame::Bind(param, body, depth + 1));
7478                            frames.push(Frame::Node(param_type, depth + 1));
7479                        }
7480                        Term::App(f, a) => {
7481                            frames.push(Frame::Node(a, depth + 1));
7482                            frames.push(Frame::Node(f, depth + 1));
7483                        }
7484                        Term::Let {
7485                            name,
7486                            ty,
7487                            value,
7488                            body,
7489                        } => {
7490                            frames.push(Frame::Bind(name, body, depth + 1));
7491                            frames.push(Frame::Node(value, depth + 1));
7492                            frames.push(Frame::Node(ty, depth + 1));
7493                        }
7494                        Term::Fix { name, body } => frames.push(Frame::Bind(name, body, depth + 1)),
7495                        Term::MutualFix { defs, .. } => {
7496                            // Each body requires at least one admitted node. Check before
7497                            // retaining the names, not after allocating for arbitrary arity.
7498                            if bound.len().saturating_add(defs.len()) > self.remaining {
7499                                return Err(ReCheckError::resource_limit(
7500                                    "active local mutual block exceeds input admission limit",
7501                                ));
7502                            }
7503                            frames.push(Frame::Restore(bound.len()));
7504                            bound.extend(defs.iter().map(|(name, _)| name.as_str()));
7505                            frames.push(Frame::Bodies(defs, depth + 1));
7506                        }
7507                        Term::Match {
7508                            discriminant,
7509                            motive,
7510                            cases,
7511                        } => {
7512                            frames.push(Frame::Cases(cases, depth + 1));
7513                            frames.push(Frame::Node(motive, depth + 1));
7514                            frames.push(Frame::Node(discriminant, depth + 1));
7515                        }
7516                        // Universe leaves occupy their Term's existing depth; only
7517                        // nested level edges add depth. This preserves the ordinary
7518                        // zero-based Term depth boundary while sizing recursive level clones.
7519                        Term::Sort(level) => frames.push(Frame::Level(level, depth)),
7520                        Term::Const { levels, .. } => frames.push(Frame::Levels(levels, depth)),
7521                        Term::Global(_) | Term::Lit(_) | Term::Hole => {}
7522                        Term::Annotated { term, .. } => frames.push(Frame::Node(term, depth + 1)),
7523                    }
7524                }
7525            }
7526        }
7527        Ok(free.into_iter().collect())
7528    }
7529}
7530
7531impl<'a> LocalPlan<'a> {
7532    fn prepare(ctx: &'a Context, term: &'a Term, limit: usize) -> RResult<Self> {
7533        struct Pending<'a> {
7534            binding: Option<(&'a str, &'a Term)>,
7535            dependencies: std::vec::IntoIter<&'a str>,
7536        }
7537        let mut admission = LocalAdmission::new(limit);
7538        let roots = admission.free_names(term)?;
7539        let mut pending = vec![Pending {
7540            binding: None,
7541            dependencies: roots.into_iter(),
7542        }];
7543        let mut state = HashMap::<&str, bool>::new(); // false = gray, true = complete
7544        let mut bindings = Vec::new();
7545        let mut issue = None;
7546        while let Some(frame) = pending.last_mut() {
7547            if let Some(name) = frame.dependencies.next() {
7548                match state.get(name) {
7549                    Some(true) => continue,
7550                    Some(false) => {
7551                        issue.get_or_insert_with(|| {
7552                            ReCheckError::ill(format!(
7553                                "cyclic active local type dependency at '{name}'"
7554                            ))
7555                        });
7556                        continue;
7557                    }
7558                    None => {}
7559                }
7560                let Some(ty) = ctx.get(name) else {
7561                    issue.get_or_insert_with(|| {
7562                        ReCheckError::ill(
7563                            crate::type_checker::unbound_diagnosis(name)
7564                                .unwrap_or_else(|| format!("unbound local variable '{name}'")),
7565                        )
7566                    });
7567                    state.insert(name, true);
7568                    continue;
7569                };
7570                let dependencies = admission.free_names(ty)?;
7571                state.insert(name, false);
7572                pending.push(Pending {
7573                    binding: Some((name, ty)),
7574                    dependencies: dependencies.into_iter(),
7575                });
7576            } else {
7577                let finished = pending.pop().expect("pending frame");
7578                if let Some((name, ty)) = finished.binding {
7579                    state.insert(name, true);
7580                    bindings.push((name, ty));
7581                }
7582            }
7583        }
7584        // Finish admission even after a missing/cyclic dependency: double_check
7585        // may need the main verdict, whose clones must also fit the admitted stack.
7586        Ok(Self {
7587            bindings,
7588            issue,
7589            max_depth: admission.max_depth,
7590        })
7591    }
7592
7593    fn check(&self, ctx: &Context) -> RResult<(Vec<String>, Vec<Db>)> {
7594        if let Some(issue) = &self.issue {
7595            return Err(issue.clone());
7596        }
7597        let mut names = Vec::with_capacity(self.bindings.len());
7598        let mut lctx = Vec::with_capacity(self.bindings.len());
7599        for (name, ty) in &self.bindings {
7600            let lowered = to_db(ty, &mut names)?;
7601            infer_sort(ctx, &lctx, &lowered)?;
7602            // Stored in precisely the predecessor scope expected by var_type.
7603            lctx.push(lowered);
7604            names.push((*name).to_string());
7605        }
7606        Ok((names, lctx))
7607    }
7608}
7609
7610thread_local! {
7611    static LOCAL_CONTEXT_BUDGET_DEPTH: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
7612}
7613
7614// A read-only ownership predicate also usable by optional metadata admission:
7615// logical depth zero does not mean the scoped telescope allowance is inactive.
7616fn recheck_budget_active() -> bool {
7617    WHNF_DEPTH.with(|d| d.get() != 0) || LOCAL_CONTEXT_BUDGET_DEPTH.with(|d| d.get() != 0)
7618}
7619
7620#[cfg(test)]
7621thread_local! {
7622    static LOCAL_BUDGET_ENTRIES: std::cell::Cell<Option<usize>> = const { std::cell::Cell::new(None) };
7623}
7624
7625struct LocalContextBudget;
7626impl LocalContextBudget {
7627    fn enter() -> Self {
7628        #[cfg(test)]
7629        LOCAL_BUDGET_ENTRIES.with(|count| {
7630            if let Some(n) = count.get() {
7631                count.set(Some(n + 1));
7632            }
7633        });
7634        if !recheck_budget_active() {
7635            WHNF_FUEL.with(|f| f.set(MAX_RECHECK_STEPS));
7636            begin_check();
7637        }
7638        LOCAL_CONTEXT_BUDGET_DEPTH.with(|d| d.set(d.get() + 1));
7639        Self
7640    }
7641}
7642impl Drop for LocalContextBudget {
7643    fn drop(&mut self) {
7644        LOCAL_CONTEXT_BUDGET_DEPTH.with(|d| d.set(d.get() - 1));
7645    }
7646}
7647
7648fn local_outcome<T>(outcome: RResult<T>) -> RResult<T> {
7649    match outcome {
7650        Ok(value) => Ok(value),
7651        Err(e) if WHNF_EXHAUSTED.with(|e| e.get()) => Err(cut_short(&e, "active-local reduction")),
7652        Err(e) => Err(e),
7653    }
7654}
7655
7656// Read the existing entitlement; never migrate an owned TLS budget to a new
7657// thread, increase a ceiling, or recursively clone an output to size its stack.
7658fn local_stack_admitted(depth: usize) -> RResult<()> {
7659    if depth <= crate::type_checker::MAX_TERM_DEPTH
7660        && (depth <= crate::term_store::INLINE_DEPTH
7661            || crate::term_store::stack_bytes_for_depth(depth)
7662                <= crate::term_store::kernel_stack_bytes())
7663    {
7664        Ok(())
7665    } else {
7666        Err(ReCheckError::resource_limit(
7667            "open inferred type exceeds the current kernel stack entitlement",
7668        ))
7669    }
7670}
7671
7672fn recheck_open(ctx: &Context, term: &Term, plan: &LocalPlan<'_>) -> RResult<Term> {
7673    if !crate::type_checker::inside_kernel() {
7674        if let Some(r) = crate::term_store::deepen_stack_with_depth(term, plan.max_depth, || {
7675            recheck_open(ctx, term, plan)
7676        }) {
7677            return r;
7678        }
7679    }
7680    local_stack_admitted(plan.max_depth)?;
7681    let _prefix_scope = PrefixScope::enter(ctx);
7682    let _budget = LocalContextBudget::enter();
7683    fix_factory_begin();
7684    local_outcome((|| {
7685        let (mut names, lctx) = plan.check(ctx)?;
7686        let db = to_db(term, &mut names)?;
7687        let ty = infer(ctx, &lctx, &db)?;
7688        let mut output = LocalAdmission::new(MAX_RECHECK_TERM_NODES);
7689        output.admit_db(&ty)?;
7690        local_stack_admitted(output.max_depth)?;
7691        Ok(from_db_with_external(&ty, names.len(), &names))
7692    })())
7693}
7694
7695fn double_check_open(ctx: &Context, term: &Term, plan: &LocalPlan<'_>) -> DoubleCheck {
7696    if !crate::type_checker::inside_kernel() {
7697        if let Some(r) = crate::term_store::deepen_stack_with_depth(term, plan.max_depth, || {
7698            double_check_open(ctx, term, plan)
7699        }) {
7700            return r;
7701        }
7702    }
7703    if let Err(ReCheckError::Unsupported(why)) = local_stack_admitted(plan.max_depth) {
7704        return DoubleCheck::MainOnlyReCheckerIncomplete(why);
7705    }
7706    let _prefix_scope = PrefixScope::enter(ctx);
7707    let _budget = LocalContextBudget::enter();
7708    fix_factory_begin();
7709    let independent = local_outcome((|| {
7710        let (mut names, lctx) = plan.check(ctx)?;
7711        let db = to_db(term, &mut names)?;
7712        let ty = infer(ctx, &lctx, &db)?;
7713        let mut output = LocalAdmission::new(MAX_RECHECK_TERM_NODES);
7714        output.admit_db(&ty)?;
7715        local_stack_admitted(output.max_depth)?;
7716        Ok((names, lctx, ty))
7717    })());
7718    // Unsupported is no verdict whatever main would decide. Avoid asking main
7719    // to clone an unsupported deep/ill-formed assumption merely for diagnostics.
7720    if let Err(ReCheckError::Unsupported(why)) = &independent {
7721        return DoubleCheck::MainOnlyReCheckerIncomplete(why.clone());
7722    }
7723    let main = crate::infer_type(ctx, term);
7724    match (main, independent) {
7725        (Ok(main_ty), Ok((mut names, lctx, re_ty))) => {
7726            // Main output is not an assumption. Admit it before lowering, and
7727            // reject additional unaccounted names rather than enlarging lctx.
7728            let mut admission = LocalAdmission::new(MAX_RECHECK_TERM_NODES);
7729            if let Err(e) = admission.free_names(&main_ty) {
7730                let why = match e.incomplete() {
7731                    Some(incomplete) => incomplete.prefixed("main inferred type cannot be lowered"),
7732                    None => Incomplete::unsupported(format!(
7733                        "main inferred type cannot be lowered: {e:?}"
7734                    )),
7735                };
7736                return DoubleCheck::MainOnlyReCheckerIncomplete(why);
7737            }
7738            if let Err(ReCheckError::Unsupported(why)) = local_stack_admitted(admission.max_depth) {
7739                return DoubleCheck::MainOnlyReCheckerIncomplete(why);
7740            }
7741            match to_db(&main_ty, &mut names) {
7742                Ok(m) if def_eq(ctx, &lctx, &m, &re_ty) => DoubleCheck::Agreed,
7743                Ok(_) if WHNF_EXHAUSTED.with(|e| e.get()) => {
7744                    DoubleCheck::MainOnlyReCheckerIncomplete(stopped(
7745                        "comparing inferred open types was cut short",
7746                    ))
7747                }
7748                Ok(_) => DoubleCheck::Disagree(format!(
7749                    "kernels inferred different types: main={}, recheck={}",
7750                    main_ty,
7751                    from_db_with_external(&re_ty, names.len(), &names)
7752                )),
7753                Err(_) => DoubleCheck::MainOnlyReCheckerIncomplete(Incomplete::unsupported(
7754                    "inferred type outside the checked active local telescope",
7755                )),
7756            }
7757        }
7758        (Ok(_), Err(ReCheckError::Ill(why))) => DoubleCheck::Disagree(format!(
7759            "main kernel accepted but re-checker rejected: {why}"
7760        )),
7761        (Err(e), Ok(_)) => DoubleCheck::Disagree(format!(
7762            "re-checker accepted but main kernel rejected: {e:?}"
7763        )),
7764        (Err(_), Err(ReCheckError::Ill(_))) => DoubleCheck::Agreed,
7765        (_, Err(ReCheckError::Unsupported(why))) => DoubleCheck::MainOnlyReCheckerIncomplete(why),
7766    }
7767}
7768
7769// ---------------------------------------------------------------------------
7770// Public API
7771// ---------------------------------------------------------------------------
7772
7773/// Independently re-check `term` in `ctx`, returning its inferred type on success.
7774///
7775/// A SEPARATE implementation from [`infer_type`](crate::infer_type): a de Bruijn core
7776/// (now including the `Match` eliminator) with its own reduction and cumulative
7777/// conversion, so a bug in one checker is unlikely to be shared by the other. Returns
7778/// [`ReCheckError::Unsupported`] for the fragment it does not yet cover (`Hole`,
7779/// or an unrecognized inductive), or when resource admission refuses a demand.
7780/// Active local assumptions are dependency-ordered and independently sort-checked;
7781/// unsupported demands never become a false pass.
7782pub fn recheck(ctx: &Context, term: &Term) -> RResult<Term> {
7783    if let Some(r) = crate::annotation::erased(term, |term| recheck(ctx, term)) {
7784        return r;
7785    }
7786    if !ctx.has_local_bindings() {
7787        return recheck_closed(ctx, term);
7788    }
7789    let plan = LocalPlan::prepare(ctx, term, MAX_RECHECK_TERM_NODES)?;
7790    if plan.bindings.is_empty() && plan.issue.is_none() {
7791        return recheck_closed(ctx, term);
7792    }
7793    recheck_open(ctx, term, &plan)
7794}
7795
7796fn recheck_closed(ctx: &Context, term: &Term) -> RResult<Term> {
7797    // ONE STACK DISCIPLINE, NOT TWO. The main kernel sizes its stack from the term's own depth
7798    // at its outermost entry; this one used to meter against an absolute byte budget unrelated
7799    // to the stack it actually had. Two kernels that run out of room in different places do not
7800    // corroborate each other across the gap — `double_check` reports `MainOnlyReCheckerIncomplete`
7801    // on an ordinary telescope. Sizing here, through the same door, is what makes the band one
7802    // band. `deepen_stack` returns `None` on the re-entrant call inside the closure, which falls
7803    // through to the body below, so the measurement is paid exactly once.
7804    if !crate::type_checker::inside_kernel() {
7805        if let Some(r) = crate::term_store::deepen_stack(term, || recheck_closed(ctx, term)) {
7806            return r;
7807        }
7808    }
7809    // The re-checker descends untrusted input exactly as the main kernel does, so it refuses
7810    // at the same door — the two kernels run out of room on the same terms rather than one
7811    // reporting while the other aborts the process.
7812    if crate::type_checker::depth_exceeds(term, crate::type_checker::MAX_TERM_DEPTH) {
7813        return Err(ReCheckError::resource_limit(format!(
7814            "term nests deeper than the kernel's limit of {}",
7815            crate::type_checker::MAX_TERM_DEPTH
7816        )));
7817    }
7818    let _prefix_scope = PrefixScope::enter(ctx);
7819    fix_factory_begin(); // sole factory creation for this public check
7820    begin_check();
7821    let outcome = to_db(term, &mut Vec::new())
7822        .and_then(|db| infer(ctx, &[], &db))
7823        .map(|ty| from_db(&ty, 0));
7824    match outcome {
7825        // An ACCEPTANCE stands, even if a reduction along the way was cut short. Cutting a
7826        // reduction short can only LOSE an equality, never invent one: if `a ⟶* a'` and
7827        // `b ⟶* b'` and the two partial reducts match, `a` and `b` have a common reduct, which
7828        // IS definitional equality. A conversion that succeeded, succeeded.
7829        Ok(ty) => Ok(ty),
7830        // A REJECTION after an abandoned reduction is evidence of nothing: the two sides may
7831        // differ only in how far they got. Reported as an incompleteness, which makes the term
7832        // honestly single-checked instead of manufacturing a soundness alarm.
7833        Err(e) if take_budget_exhausted() => Err(cut_short(&e, "reduction")),
7834        Err(e) => Err(e),
7835    }
7836}
7837
7838/// The verdict of cross-checking a term with BOTH kernels.
7839#[derive(Debug, Clone, PartialEq)]
7840pub enum DoubleCheck {
7841    /// Both kernels accepted with definitionally-equal types, or both rejected as ill-typed.
7842    /// Check the inference result as well when agreement must establish acceptance.
7843    Agreed,
7844    /// The independent checker reached no verdict, for example because a construct
7845    /// or resource requirement is unsupported. This does not establish acceptance
7846    /// or rejection by the main kernel. Open-input admission can stop before main
7847    /// inference runs; callers needing a main verdict must check it separately.
7848    /// An incomplete independent check never establishes two-kernel agreement.
7849    MainOnlyReCheckerIncomplete(Incomplete),
7850    /// The two kernels DISAGREE: one accepted and the other rejected, or they inferred
7851    /// non-equal types. A soundness alarm that must never fire on a valid proof.
7852    Disagree(String),
7853}
7854
7855/// Cross-check `term` against both [`infer_type`](crate::infer_type) and `recheck`.
7856///
7857/// The de Bruijn criterion in action: a proof term is most trustworthy when two
7858/// independently-written kernels, on different representations, agree on its type.
7859/// Disagreement is surfaced loudly; an incomplete re-check (for example an unresolved `Hole`) is
7860/// surfaced honestly rather than dressed up as agreement.
7861pub fn double_check(ctx: &Context, term: &Term) -> DoubleCheck {
7862    if let Some(r) = crate::annotation::erased(term, |term| double_check(ctx, term)) {
7863        return r;
7864    }
7865    if !ctx.has_local_bindings() {
7866        return double_check_closed(ctx, term);
7867    }
7868    let plan = match LocalPlan::prepare(ctx, term, MAX_RECHECK_TERM_NODES) {
7869        Ok(plan) => plan,
7870        Err(ReCheckError::Unsupported(why)) => {
7871            return DoubleCheck::MainOnlyReCheckerIncomplete(why)
7872        }
7873        Err(ReCheckError::Ill(why)) => {
7874            return DoubleCheck::MainOnlyReCheckerIncomplete(Incomplete::unsupported(format!(
7875                "active local admission did not produce a checked telescope: {why}"
7876            )))
7877        }
7878    };
7879    if plan.bindings.is_empty() && plan.issue.is_none() {
7880        return double_check_closed(ctx, term);
7881    }
7882    double_check_open(ctx, term, &plan)
7883}
7884
7885fn double_check_closed(ctx: &Context, term: &Term) -> DoubleCheck {
7886    // Sized ONCE here, so both kernels run on the same stack rather than each arranging its own
7887    // and the comparison of their two answers running on whatever is left of the caller's.
7888    if !crate::type_checker::inside_kernel() {
7889        if let Some(r) = crate::term_store::deepen_stack(term, || double_check_closed(ctx, term)) {
7890            return r;
7891        }
7892    }
7893    let main = crate::infer_type(ctx, term);
7894    let recheck_result = recheck_closed(ctx, term);
7895    match (main, recheck_result) {
7896        (Ok(main_ty), Ok(re_ty)) => {
7897            take_budget_exhausted();
7898            match (to_db(&main_ty, &mut Vec::new()), to_db(&re_ty, &mut Vec::new())) {
7899                (Ok(m), Ok(r)) if def_eq(ctx, &[], &m, &r) => DoubleCheck::Agreed,
7900                // A comparison whose reduction was CUT SHORT decided nothing, so the two types
7901                // being "different" is not evidence the kernels disagree.
7902                (Ok(_), Ok(_)) if take_budget_exhausted() => {
7903                    DoubleCheck::MainOnlyReCheckerIncomplete(stopped(format!(
7904                        "comparing the two inferred types was cut short (main={main_ty}, recheck={re_ty})",
7905                    )))
7906                }
7907                (Ok(_), Ok(_)) => DoubleCheck::Disagree(format!(
7908                    "kernels inferred different types: main={}, recheck={}",
7909                    main_ty, re_ty
7910                )),
7911                _ => DoubleCheck::MainOnlyReCheckerIncomplete(Incomplete::unsupported(
7912                    "inferred type outside re-checker fragment",
7913                )),
7914            }
7915        }
7916        (Ok(_), Err(ReCheckError::Unsupported(why))) => {
7917            DoubleCheck::MainOnlyReCheckerIncomplete(why)
7918        }
7919        (Ok(_), Err(ReCheckError::Ill(why))) => DoubleCheck::Disagree(format!(
7920            "main kernel accepted but re-checker rejected: {}",
7921            why
7922        )),
7923        (Err(e), Ok(_)) => DoubleCheck::Disagree(format!(
7924            "re-checker accepted but main kernel rejected: {:?}",
7925            e
7926        )),
7927        // Both kernels examined the term and both rejected it: that IS agreement, and the
7928        // strongest rejection the API can report.
7929        (Err(_), Err(ReCheckError::Ill(_))) => DoubleCheck::Agreed,
7930        // The main kernel rejected and the re-checker DECLINED TO LOOK. A checker that never
7931        // examined the term has not concurred with anything, so this is single-checked and
7932        // flagged — not agreement. Collapsing it into `Agreed` is how a `Hole`, which the
7933        // re-checker refuses to parse at all, could be reported as corroborated by both.
7934        (Err(_), Err(ReCheckError::Unsupported(why))) => {
7935            DoubleCheck::MainOnlyReCheckerIncomplete(why)
7936        }
7937    }
7938}
7939
7940// Independent Int representation bridge. Consult shared declaration metadata, but
7941// check its types and construct/read de Bruijn values here, without the main reducer.
7942fn db_canonical_int_environment(genv: &Context) -> bool {
7943    let global = |name: &str| Db::Global(name.to_string());
7944    for family in ["Nat", "Int"] {
7945        if !genv.is_inductive(family)
7946            || genv.inductive_num_params(family) != 0
7947            || genv.poly_declaration(family).is_some()
7948            || genv.get_definition_body(family).is_some()
7949        {
7950            return false;
7951        }
7952        let Some(ty) = genv.get_global(family) else {
7953            return false;
7954        };
7955        if to_db(ty, &mut Vec::new()).ok() != Some(Db::Sort(Universe::Type(0))) {
7956            return false;
7957        }
7958    }
7959    for (family, names) in [
7960        ("Nat", ["Zero", "Succ"]),
7961        ("Int", ["Int_ofNat", "Int_negSucc"]),
7962    ] {
7963        let constructors = genv.get_constructors(family);
7964        if constructors.len() != 2 {
7965            return false;
7966        }
7967        for ((name, ty), expected) in constructors.iter().zip(names) {
7968            if *name != expected
7969                || genv.constructor_inductive(expected) != Some(family)
7970                || genv.poly_declaration(expected).is_some()
7971                || genv.get_definition_body(expected).is_some()
7972            {
7973                return false;
7974            }
7975            let expected_type = if expected == "Zero" {
7976                global("Nat")
7977            } else {
7978                Db::Pi(DbBox::new(global("Nat")), DbBox::new(global(family)))
7979            };
7980            let Some(current) = genv.get_global(expected) else {
7981                return false;
7982            };
7983            if to_db(ty, &mut Vec::new()).ok() != Some(expected_type.clone())
7984                || to_db(current, &mut Vec::new()).ok() != Some(expected_type)
7985            {
7986                return false;
7987            }
7988        }
7989    }
7990    true
7991}
7992
7993fn db_int_constructor(genv: &Context, t: &Db) -> Option<Db> {
7994    let integer = match t {
7995        Db::Lit(Literal::Int(n)) => logicaffeine_base::BigInt::from_i64(*n),
7996        Db::Lit(Literal::BigInt(n)) => n.clone(),
7997        _ => return None,
7998    };
7999    if !db_canonical_int_environment(genv) {
8000        return None;
8001    }
8002    let (name, field) = if integer.is_negative() {
8003        (
8004            "Int_negSucc",
8005            integer.abs().sub(&logicaffeine_base::BigInt::from_i64(1)),
8006        )
8007    } else {
8008        ("Int_ofNat", integer)
8009    };
8010    Some(Db::App(
8011        DbBox::new(Db::Global(name.to_string())),
8012        DbBox::new(Db::Lit(Literal::Nat(field))),
8013    ))
8014}
8015
8016fn db_int_literal(genv: &Context, t: &Db) -> Option<Literal> {
8017    let Db::App(head, field) = t else { return None };
8018    let negative = match head.as_ref() {
8019        Db::Global(n) if n == "Int_ofNat" => false,
8020        Db::Global(n) if n == "Int_negSucc" => true,
8021        _ => return None,
8022    };
8023    if !db_canonical_int_environment(genv) {
8024        return None;
8025    }
8026    let one = logicaffeine_base::BigInt::from_i64(1);
8027    let mut count = logicaffeine_base::BigInt::from_i64(0);
8028    let mut field = whnf(genv, field);
8029    loop {
8030        match field {
8031            Db::Lit(Literal::Nat(n)) if !n.is_negative() => {
8032                count = count.add(&n);
8033                break;
8034            }
8035            Db::Global(n) if n == "Zero" => break,
8036            Db::App(f, a) if matches!(f.as_ref(), Db::Global(n) if n == "Succ") => {
8037                count = count.add(&one);
8038                field = whnf(genv, &a);
8039            }
8040            _ => return None,
8041        }
8042    }
8043    if negative {
8044        count = count.add(&one).negated();
8045    }
8046    Some(crate::term::int_lit(count))
8047}
8048
8049#[cfg(test)]
8050#[path = "../../logicaffeine_tests/unit/logicaffeine_kernel/recheck/recheck_differential_tests.rs"]
8051mod recheck_differential_tests;
8052
8053#[cfg(test)]
8054#[path = "../../logicaffeine_tests/unit/logicaffeine_kernel/recheck/beta_open_tests.rs"]
8055mod beta_open_tests;
8056
8057#[cfg(test)]
8058#[path = "../../logicaffeine_tests/unit/logicaffeine_kernel/recheck/reflexive_subtyping_tests.rs"]
8059mod reflexive_subtyping_tests;
8060
8061#[cfg(test)]
8062#[path = "../../logicaffeine_tests/unit/logicaffeine_kernel/recheck/fixed_point_structural_column_controls.rs"]
8063mod fixed_point_structural_column_controls;
8064
8065#[cfg(test)]
8066#[path = "../../logicaffeine_tests/unit/logicaffeine_kernel/recheck/borrowed_conversion_controls.rs"]
8067mod borrowed_conversion_controls;
8068
8069#[cfg(test)]
8070#[path = "../../logicaffeine_tests/unit/logicaffeine_kernel/recheck/bounded_borrowed_conversion_controls.rs"]
8071mod bounded_borrowed_conversion_controls;
8072
8073#[cfg(test)]
8074#[path = "../../logicaffeine_tests/unit/logicaffeine_kernel/recheck/checked_motive_reuse_controls.rs"]
8075mod checked_motive_reuse_controls;
8076
8077#[cfg(test)]
8078#[path = "../../logicaffeine_tests/unit/logicaffeine_kernel/recheck/owned_whnf_controls.rs"]
8079mod owned_whnf_controls;
8080
8081#[cfg(test)]
8082#[path = "../../logicaffeine_tests/unit/logicaffeine_kernel/recheck/k_probe_admission_controls.rs"]
8083mod k_probe_admission_controls;
8084
8085#[cfg(test)]
8086#[path = "../../logicaffeine_tests/unit/logicaffeine_kernel/recheck/whnf_scheduler_controls.rs"]
8087mod whnf_scheduler_controls;
8088
8089#[cfg(test)]
8090#[path = "../../logicaffeine_tests/unit/logicaffeine_kernel/recheck/nat_prefix_controls.rs"]
8091mod nat_prefix_controls;
8092
8093// Negative-only admission: never infer a type or accept a proof here.
8094fn definitely_fieldful_k_family(genv: &Context, lctx: &dyn LocalTypes, proof: &Db) -> bool {
8095    fn spend(left: &mut usize) -> Option<()> {
8096        if *left == 0 {
8097            return None;
8098        }
8099        *left -= 1;
8100        Some(())
8101    }
8102    fn rigid_motive_tail<'a>(mut tail: &'a Db, left: &mut usize) -> Option<(&'a Db, usize)> {
8103        let mut pending = 0usize;
8104        loop {
8105            spend(left)?;
8106            match tail {
8107                Db::App(f, _) => {
8108                    pending += 1;
8109                    tail = f;
8110                }
8111                Db::Lam(_, inner) => {
8112                    pending = pending.saturating_sub(1);
8113                    tail = inner;
8114                }
8115                Db::Global(_) | Db::Const { .. } => return Some((tail, pending)),
8116                _ => return None,
8117            }
8118        }
8119    }
8120    #[derive(Clone, Copy)]
8121    enum Header<'a> {
8122        Named(&'a Term),
8123        Indexed(&'a Db),
8124    }
8125    fn observe<'a>(
8126        genv: &'a Context,
8127        lctx: &'a dyn LocalTypes,
8128        proof: &Db,
8129        left: &mut usize,
8130    ) -> Option<()> {
8131        if !genv.simp_rules().is_empty() {
8132            return None;
8133        }
8134        let mut head = proof;
8135        let mut supplied = 0usize;
8136        loop {
8137            spend(left)?;
8138            match head {
8139                Db::App(f, _) => {
8140                    head = f;
8141                    supplied += 1;
8142                }
8143                _ => break,
8144            }
8145        }
8146        let mut family_arguments = 0usize;
8147        let mut header = match head {
8148            Db::Var(k) => {
8149                Header::Indexed(lctx.binding(lctx.len().checked_sub(k.checked_add(1)?)?)?)
8150            }
8151            Db::Global(name) => Header::Named(genv.get_global(name)?),
8152            Db::Const { name, levels } => {
8153                // Inferred legacy telescopes stay on the complete old path.
8154                let (params, ty) = genv.poly_declaration(name)?;
8155                if params.len() != levels.len() {
8156                    return None;
8157                }
8158                Header::Named(ty)
8159            }
8160            Db::Match { motive, .. } if supplied == 0 => {
8161                let (tail, arguments) = rigid_motive_tail(motive, left)?;
8162                family_arguments = arguments;
8163                Header::Indexed(tail)
8164            }
8165            Db::Fix(body) if supplied != 0 => {
8166                // This is only a necessary shape of a SUCCESSFUL inference.
8167                // It neither validates the motive nor bypasses fix termination.
8168                let mut tail = body.as_ref();
8169                for _ in 0..supplied {
8170                    spend(left)?;
8171                    let Db::Lam(_, inner) = tail else {
8172                        return None;
8173                    };
8174                    tail = inner;
8175                }
8176                spend(left)?;
8177                // Exact application only; another Lambda, computed body, or
8178                // mutual fix retains the full old K probe.
8179                let Db::Match { motive, .. } = tail else {
8180                    return None;
8181                };
8182                let (result, arguments) = rigid_motive_tail(motive, left)?;
8183                family_arguments = arguments;
8184                // match_return_type can fail, leave Lambda(s), or apply this
8185                // fixed result head. None can turn a fieldful family into a
8186                // fieldless K family. All ordinary validation stays in infer.
8187                supplied = 0;
8188                Header::Indexed(result)
8189            }
8190            _ => return None,
8191        };
8192        for _ in 0..supplied {
8193            spend(left)?;
8194            header = match header {
8195                Header::Named(Term::Pi { body_type, .. }) => Header::Named(body_type),
8196                Header::Indexed(Db::Pi(_, body)) => Header::Indexed(body),
8197                _ => return None,
8198            };
8199        }
8200        // Pi substitution/De Bruijn shifting cannot change a fixed Global/Const
8201        // result head. No residual variable, alias, Let or Match is guessed.
8202        loop {
8203            spend(left)?;
8204            header = match header {
8205                Header::Named(Term::App(f, _)) => {
8206                    family_arguments += 1;
8207                    Header::Named(f)
8208                }
8209                Header::Indexed(Db::App(f, _)) => {
8210                    family_arguments += 1;
8211                    Header::Indexed(f)
8212                }
8213                _ => break,
8214            };
8215        }
8216        let family = match header {
8217            Header::Named(Term::Global(name)) | Header::Indexed(Db::Global(name)) => name.as_str(),
8218            Header::Named(Term::Const { name, levels })
8219            | Header::Indexed(Db::Const { name, levels }) => {
8220                let (params, _) = genv.poly_declaration(name)?;
8221                if params.len() != levels.len() {
8222                    return None;
8223                }
8224                name.as_str()
8225            }
8226            _ => return None,
8227        };
8228        if !genv.is_inductive(family)
8229            || genv.get_definition_body(family).is_some()
8230            || genv.get_universe_poly(family).is_some()
8231            || genv
8232                .mutual_block_of(family)
8233                .is_some_and(|block| block.len() != 1)
8234        {
8235            return None;
8236        }
8237        // Explicit parameter metadata avoids the legacy inferred-split fallback.
8238        let parameters = genv.inductive_declared_params(family)?;
8239        let mut arity = genv.get_global(family)?;
8240        let mut arity_count = 0usize;
8241        loop {
8242            spend(left)?;
8243            match arity {
8244                Term::Pi { body_type, .. } => {
8245                    arity_count += 1;
8246                    arity = body_type;
8247                }
8248                _ => break,
8249            }
8250        }
8251        if !matches!(arity, Term::Sort(_))
8252            || family_arguments != arity_count
8253            || parameters > arity_count
8254        {
8255            return None;
8256        }
8257        let (name, mut constructor_type) = genv.unique_constructor_header(family)?;
8258        if genv.constructor_inductive(name) != Some(family) {
8259            return None;
8260        }
8261        // Observing parameters+1 syntactic Pis is enough to rule out a
8262        // fieldless constructor; do not walk an unnecessary residual body.
8263        for _ in 0..=parameters {
8264            spend(left)?;
8265            match constructor_type {
8266                Term::Pi { body_type, .. } => constructor_type = body_type,
8267                _ => return None,
8268            }
8269        }
8270        Some(())
8271    }
8272    observe(genv, lctx, proof, &mut 256).is_some()
8273}
8274
8275#[cfg(test)]
8276#[path = "../../logicaffeine_tests/unit/logicaffeine_kernel/recheck/k_fieldful_admission_controls.rs"]
8277mod k_fieldful_admission_controls;
8278
8279#[cfg(test)]
8280#[path = "../../logicaffeine_tests/unit/logicaffeine_kernel/recheck/k_fix_result_shape_controls.rs"]
8281mod k_fix_result_shape_controls;
8282
8283#[cfg(test)]
8284#[path = "../../logicaffeine_tests/unit/logicaffeine_kernel/recheck/k_direct_match_result_shape_controls.rs"]
8285mod k_direct_match_result_shape_controls;
8286
8287#[cfg(test)]
8288#[path = "../../logicaffeine_tests/unit/logicaffeine_kernel/recheck/k_motive_beta_head_controls.rs"]
8289mod k_motive_beta_head_controls;
8290// SOURCE DRAFT ONLY. Not installed or run. Review/freeze before runtime RED.
8291// Scaffold seam: try_nat_order_db_in(ctx, locals, term) forwards to the current
8292// literal-only try_nat_order_db(ctx,term), ignoring locals, until the candidate.
8293// NAT_ORDER_WORK is cfg(test) optional TLS, incremented at actual WHNF dispatch
8294// and cursor transition sites. It does not debit/refund fuel itself.
8295#[cfg(test)]
8296#[path = "../../logicaffeine_tests/unit/logicaffeine_kernel/recheck/independent_nat_order_prefix_controls.rs"]
8297mod independent_nat_order_prefix_controls;
8298// Additive source draft; no runtime assertions have executed.
8299#[cfg(test)]
8300#[path = "../../logicaffeine_tests/unit/logicaffeine_kernel/recheck/independent_observed_prefix_sharing_controls.rs"]
8301mod independent_observed_prefix_sharing_controls;
8302// Additive lease controls. Unrun; prior 125 assertions are retained separately.
8303#[cfg(test)]
8304#[path = "../../logicaffeine_tests/unit/logicaffeine_kernel/recheck/independent_prefix_lease_controls.rs"]
8305mod independent_prefix_lease_controls;
8306// Separate additive, never-run control. Frozen13 remain unchanged.
8307#[cfg(test)]
8308#[path = "../../logicaffeine_tests/unit/logicaffeine_kernel/recheck/prefix_lease_partial_exhaustion_control.rs"]
8309mod prefix_lease_partial_exhaustion_control;
8310
8311#[cfg(test)]
8312#[path = "../../logicaffeine_tests/unit/logicaffeine_kernel/recheck/open_context_controls.rs"]
8313mod open_context_controls;
8314
8315#[cfg(test)]
8316fn reference_resume_match(
8317    genv: &Context,
8318    lctx: &dyn LocalTypes,
8319    mut d: Db,
8320    motive: DbBox,
8321    cases: Vec<Db>,
8322) -> WhnfStep {
8323    // Peano bridge (K6): a `Nat(n)` literal is `Zero`/`Succ(Nat(n-1))` — expand
8324    // one step so the constructor-selection below fires (the recursor computes
8325    // on Nat literals, peeling one `Succ` per match), where the literal's reading holds
8326    // (`int_inductive::reads_nat_literal`).
8327    if matches!(&d, Db::Lit(Literal::Nat(n)) if crate::int_inductive::reads_nat_literal(genv, n)) {
8328        d = db_nat_peano_step(&d);
8329    }
8330    if let Some(constructor) = db_int_constructor(genv, &d) {
8331        d = constructor;
8332    }
8333    let (head, args) = spine(&d);
8334    if let Db::Global(cname) | Db::Const { name: cname, .. } = &head {
8335        if let Some(ind) = genv.constructor_inductive(cname) {
8336            let ctor_names: Vec<String> = genv
8337                .get_constructors(ind)
8338                .iter()
8339                .map(|(n, _)| n.to_string())
8340                .collect();
8341            if let Some(idx) = ctor_names.iter().position(|n| n == cname) {
8342                if idx < cases.len() {
8343                    // Indices are part of the result type, not constructor
8344                    // arguments. Drop only the uniform parameter prefix.
8345                    let parameters = genv.inductive_num_params(ind);
8346                    let Some(val_args) = args.get(parameters..) else {
8347                        return WhnfStep::Ready(Db::Match {
8348                            disc: DbBox::new(d),
8349                            motive,
8350                            cases,
8351                        });
8352                    };
8353                    let mut res = cases[idx].clone();
8354                    for a in val_args {
8355                        res = Db::App(DbBox::new(res), DbBox::new(a.clone()));
8356                    }
8357                    return WhnfStep::Reduce(res);
8358                }
8359            }
8360        }
8361    }
8362    // K can select a branch only for a fieldless singleton.
8363    // Its checked full or reachable pruned inventory has one case.
8364    // Avoid re-inferring a neutral discriminant when this necessary
8365    // condition already rules out singleton reduction.
8366    if cases.len() == 1 {
8367        if let Some(constructor) = k_constructor_db(genv, lctx, &d) {
8368            return WhnfStep::Reduce(Db::Match {
8369                disc: DbBox::new(constructor),
8370                motive,
8371                cases,
8372            });
8373        }
8374    }
8375    return WhnfStep::Ready(Db::Match {
8376        disc: DbBox::new(d),
8377        motive,
8378        cases,
8379    });
8380}
8381
8382#[cfg(test)]
8383#[path = "../../logicaffeine_tests/unit/logicaffeine_kernel/recheck/owned_db_match_controls.rs"]
8384mod owned_db_match_controls;
8385
8386/// Open an owned de Bruijn body with the same index rules as beta_open_at.
8387/// Existing body boxes/vectors survive; only substituted argument occurrences
8388/// need fresh shifted terms. Unused arguments are never traversed.
8389fn beta_open_owned(mut body: Db, arg: &Db) -> Db {
8390    fn child(body: &mut DbBox, arg: &Db, depth: usize) {
8391        if !body.facts().is_some_and(|f| f.required <= depth) {
8392            open(body, arg, depth);
8393        }
8394    }
8395    fn open(body: &mut Db, arg: &Db, depth: usize) {
8396        #[cfg(test)]
8397        beta_count_work(0);
8398        match body {
8399            Db::Var(k) if *k == depth => *body = shift(arg, depth as isize, 0),
8400            Db::Var(k) if *k > depth => *k -= 1,
8401            Db::Var(_) | Db::Sort(_) | Db::Global(_) | Db::Const { .. } | Db::Lit(_) => {}
8402            Db::Pi(a, b) | Db::Lam(a, b) => {
8403                child(a, arg, depth);
8404                child(b, arg, depth + 1);
8405            }
8406            Db::App(f, a) => {
8407                child(f, arg, depth);
8408                child(a, arg, depth);
8409            }
8410            Db::Match {
8411                disc,
8412                motive,
8413                cases,
8414            } => {
8415                child(disc, arg, depth);
8416                child(motive, arg, depth);
8417                for case in cases {
8418                    open(case, arg, depth);
8419                }
8420            }
8421            Db::Fix(body) => match body {
8422                FixBody::Owned(inner) => open(inner, arg, depth + 1),
8423                FixBody::Shared(_) => {
8424                    if !body.facts().is_some_and(|f| f.required <= depth + 1) {
8425                        *body = body.opened(arg, depth + 1);
8426                    }
8427                }
8428            },
8429            Db::MutualFix { defs, .. } => {
8430                let inner = depth + defs.len();
8431                for body in defs {
8432                    open(body, arg, inner);
8433                }
8434            }
8435            Db::Let(ty, value, body) => {
8436                child(ty, arg, depth);
8437                child(value, arg, depth);
8438                child(body, arg, depth + 1);
8439            }
8440        }
8441    }
8442    open(&mut body, arg, 0);
8443    body
8444}
8445
8446fn solve_domain_levels_owned(
8447    genv: &Context,
8448    lctx: &dyn LocalTypes,
8449    dom: Db,
8450    body: Db,
8451    arg: &Db,
8452) -> (Db, Db) {
8453    match db_domain_level_solution(genv, lctx, &dom, arg) {
8454        Some(subst) => (
8455            db_instantiate_universes(&dom, &subst),
8456            db_instantiate_universes(&body, &subst),
8457        ),
8458        None => (dom, body),
8459    }
8460}
8461
8462#[cfg(test)]
8463#[path = "../../logicaffeine_tests/unit/logicaffeine_kernel/recheck/owned_db_beta_controls.rs"]
8464mod owned_db_beta_controls;
8465
8466#[cfg(test)]
8467#[path = "../../logicaffeine_tests/unit/logicaffeine_kernel/recheck/immutable_fix_body_controls.rs"]
8468mod immutable_fix_body_controls;
8469
8470/// An immutable telescope view. Each stored type remains in its original binding
8471/// scope. Extensions own only new bindings and borrow the unchanged predecessor.
8472trait LocalTypes {
8473    fn len(&self) -> usize;
8474    fn parts(&self) -> (Option<&dyn LocalTypes>, &[Db]);
8475    /// Where this context remembers its number in the current conversion-evidence session.
8476    fn evidence(&self) -> Option<&std::cell::Cell<Option<(u64, u32)>>> {
8477        None
8478    }
8479    fn binding(&self, index: usize) -> Option<&Db> {
8480        let (mut parent, mut bindings) = self.parts();
8481        loop {
8482            let base = parent.map_or(0, LocalTypes::len);
8483            if index >= base {
8484                return bindings.get(index - base);
8485            }
8486            (parent, bindings) = parent?.parts();
8487        }
8488    }
8489}
8490impl LocalTypes for Vec<Db> {
8491    fn len(&self) -> usize {
8492        Vec::len(self)
8493    }
8494    fn parts(&self) -> (Option<&dyn LocalTypes>, &[Db]) {
8495        (None, self.as_slice())
8496    }
8497}
8498impl<const N: usize> LocalTypes for [Db; N] {
8499    fn len(&self) -> usize {
8500        N
8501    }
8502    fn parts(&self) -> (Option<&dyn LocalTypes>, &[Db]) {
8503        (None, self.as_slice())
8504    }
8505}
8506struct LocalExtension<'a> {
8507    parent: &'a dyn LocalTypes,
8508    base: usize,
8509    bindings: Vec<Db>,
8510    evidence: std::cell::Cell<Option<(u64, u32)>>,
8511}
8512impl LocalTypes for LocalExtension<'_> {
8513    fn len(&self) -> usize {
8514        self.base + self.bindings.len()
8515    }
8516    fn parts(&self) -> (Option<&dyn LocalTypes>, &[Db]) {
8517        (Some(self.parent), &self.bindings)
8518    }
8519    fn evidence(&self) -> Option<&std::cell::Cell<Option<(u64, u32)>>> {
8520        Some(&self.evidence)
8521    }
8522}
8523impl LocalExtension<'_> {
8524    fn push(&mut self, ty: Db) {
8525        self.bindings.push(ty);
8526        self.evidence.set(None);
8527    }
8528}
8529fn extend_local(lctx: &dyn LocalTypes) -> LocalExtension<'_> {
8530    LocalExtension {
8531        parent: lctx,
8532        base: lctx.len(),
8533        bindings: Vec::new(),
8534        evidence: std::cell::Cell::new(None),
8535    }
8536}
8537
8538#[cfg(test)]
8539#[path = "../../logicaffeine_tests/unit/logicaffeine_kernel/recheck/borrowed_local_context_controls.rs"]
8540mod borrowed_local_context_controls;
8541
8542// Limit speculative occurrence inspection independently of expression size. This
8543// does not admit a larger term or grant reduction fuel: failure uses the existing
8544// substitution path. Current immutable Fix facts may prove a subtree unaffected.
8545const OWNED_BETA_SCAN_NODES: usize = 256;
8546#[derive(Clone, Copy)]
8547struct BetaScan {
8548    occurrences: usize,
8549    needs_rebase: bool,
8550}
8551impl BetaScan {
8552    const UNAFFECTED: Self = Self {
8553        occurrences: 0,
8554        needs_rebase: false,
8555    };
8556    fn merge(self, other: Self) -> Self {
8557        Self {
8558            occurrences: self.occurrences + other.occurrences,
8559            needs_rebase: self.needs_rebase || other.needs_rebase,
8560        }
8561    }
8562}
8563// The same bounded occurrence walk also records outer indices affected by
8564// removing this binder. Count zero alone cannot justify identity: Var(1), for
8565// example, contains no Var(0) but still has to become Var(0).
8566fn beta_scan(body: &Db, depth: usize, left: &mut usize) -> Option<BetaScan> {
8567    fn child(body: &DbBox, depth: usize, left: &mut usize) -> Option<BetaScan> {
8568        if body.facts().is_some_and(|f| f.required <= depth) {
8569            *left = left.checked_sub(1)?;
8570            #[cfg(test)]
8571            beta_count_work(0);
8572            Some(BetaScan::UNAFFECTED)
8573        } else {
8574            beta_scan(body, depth, left)
8575        }
8576    }
8577    *left = left.checked_sub(1)?;
8578    #[cfg(test)]
8579    beta_count_work(0);
8580    match body {
8581        Db::Var(k) => Some(BetaScan {
8582            occurrences: usize::from(*k == depth),
8583            needs_rebase: *k > depth,
8584        }),
8585        Db::Sort(_) | Db::Global(_) | Db::Const { .. } | Db::Lit(_) => Some(BetaScan::UNAFFECTED),
8586        Db::Pi(a, b) | Db::Lam(a, b) => {
8587            Some(child(a, depth, left)?.merge(child(b, depth + 1, left)?))
8588        }
8589        Db::App(a, b) => Some(child(a, depth, left)?.merge(child(b, depth, left)?)),
8590        Db::Let(a, b, c) => Some(
8591            child(a, depth, left)?
8592                .merge(child(b, depth, left)?)
8593                .merge(child(c, depth + 1, left)?),
8594        ),
8595        Db::Match {
8596            disc,
8597            motive,
8598            cases,
8599        } => {
8600            let mut scan = child(disc, depth, left)?.merge(child(motive, depth, left)?);
8601            for case in cases {
8602                scan = scan.merge(beta_scan(case, depth, left)?);
8603            }
8604            Some(scan)
8605        }
8606        Db::MutualFix { defs, .. } => {
8607            let mut scan = BetaScan::UNAFFECTED;
8608            for body in defs {
8609                scan = scan.merge(beta_scan(body, depth + defs.len(), left)?);
8610            }
8611            Some(scan)
8612        }
8613        Db::Fix(body) => match body {
8614            FixBody::Owned(body) => beta_scan(body, depth + 1, left),
8615            FixBody::Shared(_) => body
8616                .facts()
8617                .filter(|f| f.required <= depth + 1)
8618                .map(|_| BetaScan::UNAFFECTED),
8619        },
8620    }
8621}
8622
8623// Preserve the existing occurrence-only test interface without an extra walk.
8624#[cfg(test)]
8625fn beta_occurrences(body: &Db, depth: usize, left: &mut usize) -> Option<usize> {
8626    beta_scan(body, depth, left).map(|scan| scan.occurrences)
8627}
8628
8629/// Shift exclusively owned syntax in place. Shared immutable Fix bodies retain
8630/// the existing copy/metadata rules; no shared syntax is mutated.
8631fn shift_owned(mut term: Db, delta: isize, cutoff: usize) -> Db {
8632    fn child(t: &mut DbBox, d: isize, c: usize) {
8633        if !t.facts().is_some_and(|f| f.required <= c) {
8634            walk(t, d, c);
8635        }
8636    }
8637    fn walk(t: &mut Db, d: isize, c: usize) {
8638        #[cfg(test)]
8639        beta_count_work(0);
8640        match t {
8641            Db::Var(k) => {
8642                if *k >= c {
8643                    *k = (*k as isize + d) as usize;
8644                }
8645            }
8646            Db::Pi(a, b) | Db::Lam(a, b) => {
8647                child(a, d, c);
8648                child(b, d, c + 1);
8649            }
8650            Db::App(a, b) => {
8651                child(a, d, c);
8652                child(b, d, c);
8653            }
8654            Db::Let(a, b, body) => {
8655                child(a, d, c);
8656                child(b, d, c);
8657                child(body, d, c + 1);
8658            }
8659            Db::Match {
8660                disc,
8661                motive,
8662                cases,
8663            } => {
8664                child(disc, d, c);
8665                child(motive, d, c);
8666                for case in cases {
8667                    walk(case, d, c);
8668                }
8669            }
8670            Db::MutualFix { defs, .. } => {
8671                let inner = c + defs.len();
8672                for body in defs {
8673                    walk(body, d, inner);
8674                }
8675            }
8676            Db::Fix(body) => match body {
8677                FixBody::Owned(body) => walk(body, d, c + 1),
8678                FixBody::Shared(_) => {
8679                    *body = body.shifted(d, c + 1);
8680                }
8681            },
8682            Db::Sort(_) | Db::Global(_) | Db::Const { .. } | Db::Lit(_) => {}
8683        }
8684    }
8685    if delta != 0 {
8686        walk(&mut term, delta, cutoff);
8687    }
8688    term
8689}
8690
8691/// Copy the argument only for uses before the final one, which takes ownership.
8692/// The count and rewrite follow exactly the same binder depths. Unknown shared
8693/// metadata and oversized bodies fall back to the borrowed-argument operation.
8694fn beta_open_consuming(mut body: Db, arg: Db) -> Db {
8695    let mut scan_left = OWNED_BETA_SCAN_NODES;
8696    let Some(scan) = beta_scan(&body, 0, &mut scan_left) else {
8697        return beta_open_deferred(body, arg);
8698    };
8699    // Only a complete scan can prove both substitution and rebasing absent.
8700    // Return the owned syntax intact; shared tickets and child storage survive.
8701    if scan.occurrences == 0 && !scan.needs_rebase {
8702        return body;
8703    }
8704    let mut remaining = scan.occurrences;
8705    fn child(body: &mut DbBox, arg: &mut Option<Db>, remaining: &mut usize, depth: usize) {
8706        if !body.facts().is_some_and(|f| f.required <= depth) {
8707            open(body, arg, remaining, depth);
8708        }
8709    }
8710    fn open(body: &mut Db, arg: &mut Option<Db>, remaining: &mut usize, depth: usize) {
8711        #[cfg(test)]
8712        beta_count_work(0);
8713        match body {
8714            Db::Var(k) if *k == depth => {
8715                *remaining -= 1;
8716                *body = if *remaining == 0 {
8717                    shift_owned(
8718                        arg.take().expect("last counted occurrence owns argument"),
8719                        depth as isize,
8720                        0,
8721                    )
8722                } else {
8723                    shift(
8724                        arg.as_ref().expect("earlier occurrence borrows argument"),
8725                        depth as isize,
8726                        0,
8727                    )
8728                };
8729            }
8730            Db::Var(k) if *k > depth => *k -= 1,
8731            Db::Var(_) | Db::Sort(_) | Db::Global(_) | Db::Const { .. } | Db::Lit(_) => {}
8732            Db::Pi(a, b) | Db::Lam(a, b) => {
8733                child(a, arg, remaining, depth);
8734                child(b, arg, remaining, depth + 1);
8735            }
8736            Db::App(a, b) => {
8737                child(a, arg, remaining, depth);
8738                child(b, arg, remaining, depth);
8739            }
8740            Db::Let(a, b, c) => {
8741                child(a, arg, remaining, depth);
8742                child(b, arg, remaining, depth);
8743                child(c, arg, remaining, depth + 1);
8744            }
8745            Db::Match {
8746                disc,
8747                motive,
8748                cases,
8749            } => {
8750                child(disc, arg, remaining, depth);
8751                child(motive, arg, remaining, depth);
8752                for case in cases {
8753                    open(case, arg, remaining, depth);
8754                }
8755            }
8756            Db::MutualFix { defs, .. } => {
8757                let inner = depth + defs.len();
8758                for body in defs {
8759                    open(body, arg, remaining, inner);
8760                }
8761            }
8762            Db::Fix(body) => match body {
8763                FixBody::Owned(body) => open(body, arg, remaining, depth + 1),
8764                FixBody::Shared(_) => {
8765                    debug_assert!(body.facts().is_some_and(|f| f.required <= depth + 1))
8766                }
8767            },
8768        }
8769    }
8770    open(&mut body, &mut Some(arg), &mut remaining, 0);
8771    debug_assert_eq!(remaining, 0);
8772    body
8773}
8774
8775#[cfg(test)]
8776#[path = "../../logicaffeine_tests/unit/logicaffeine_kernel/recheck/owned_beta_argument_controls.rs"]
8777mod owned_beta_argument_controls;
8778
8779/// A single traversal can retain the final substitution slot as an exclusive
8780/// borrow. Encountering another occurrence fills the previous slot by copying;
8781/// after the walk, the retained slot takes ownership of the original argument.
8782/// Only disjoint descendants are borrowed, so no pointer or unsafe mutation is
8783/// required and the enclosing syntax cannot move while a slot is retained.
8784fn beta_open_deferred(mut body: Db, arg: Db) -> Db {
8785    fn flush(last: &mut Option<(&mut Db, usize)>, arg: &Db) {
8786        if let Some((slot, depth)) = last.take() {
8787            *slot = shift(arg, depth as isize, 0);
8788        }
8789    }
8790    fn child<'a>(
8791        body: &'a mut DbBox,
8792        arg: &Db,
8793        last: &mut Option<(&'a mut Db, usize)>,
8794        depth: usize,
8795    ) {
8796        if !body.facts().is_some_and(|f| f.required <= depth) {
8797            open(body, arg, last, depth);
8798        }
8799    }
8800    fn open<'a>(body: &'a mut Db, arg: &Db, last: &mut Option<(&'a mut Db, usize)>, depth: usize) {
8801        #[cfg(test)]
8802        beta_count_work(0);
8803        match body {
8804            Db::Var(k) if *k == depth => {
8805                flush(last, arg);
8806                *last = Some((body, depth));
8807            }
8808            Db::Var(k) if *k > depth => *k -= 1,
8809            Db::Var(_) | Db::Sort(_) | Db::Global(_) | Db::Const { .. } | Db::Lit(_) => {}
8810            Db::Pi(a, b) | Db::Lam(a, b) => {
8811                child(a, arg, last, depth);
8812                child(b, arg, last, depth + 1);
8813            }
8814            Db::App(a, b) => {
8815                child(a, arg, last, depth);
8816                child(b, arg, last, depth);
8817            }
8818            Db::Let(a, b, c) => {
8819                child(a, arg, last, depth);
8820                child(b, arg, last, depth);
8821                child(c, arg, last, depth + 1);
8822            }
8823            Db::Match {
8824                disc,
8825                motive,
8826                cases,
8827            } => {
8828                child(disc, arg, last, depth);
8829                child(motive, arg, last, depth);
8830                for case in cases {
8831                    open(case, arg, last, depth);
8832                }
8833            }
8834            Db::MutualFix { defs, .. } => {
8835                let inner = depth + defs.len();
8836                for body in defs {
8837                    open(body, arg, last, inner);
8838                }
8839            }
8840            Db::Fix(body) => match body {
8841                FixBody::Owned(body) => open(body, arg, last, depth + 1),
8842                FixBody::Shared(_) => {
8843                    if !body.facts().is_some_and(|f| f.required <= depth + 1) {
8844                        // The old immutable-body operation owns its metadata
8845                        // policy. Finish any pending slot before delegating;
8846                        // a subsequent owned occurrence can again be deferred.
8847                        flush(last, arg);
8848                        *body = body.opened(arg, depth + 1);
8849                    }
8850                }
8851            },
8852        }
8853    }
8854    let mut last = None;
8855    open(&mut body, &arg, &mut last, 0);
8856    if let Some((slot, depth)) = last {
8857        *slot = shift_owned(arg, depth as isize, 0);
8858    }
8859    body
8860}
8861
8862#[cfg(test)]
8863#[path = "../../logicaffeine_tests/unit/logicaffeine_kernel/recheck/deferred_beta_argument_controls.rs"]
8864mod deferred_beta_argument_controls;
8865
8866#[cfg(test)]
8867#[path = "../../logicaffeine_tests/unit/logicaffeine_kernel/recheck/borrowed_inspection_controls.rs"]
8868mod borrowed_inspection_controls;
8869
8870#[cfg(test)]
8871#[path = "../../logicaffeine_tests/unit/logicaffeine_kernel/recheck/borrowed_structural_decision_controls.rs"]
8872mod borrowed_structural_decision_controls;
8873
8874#[cfg(test)]
8875#[path = "../../logicaffeine_tests/unit/logicaffeine_kernel/recheck/certified_order_recheck_controls.rs"]
8876mod certified_order_recheck_controls;
8877
8878#[cfg(test)]
8879#[path = "../../logicaffeine_tests/unit/logicaffeine_kernel/recheck/independent_power_controls.rs"]
8880mod independent_power_controls;
8881
8882#[cfg(test)]
8883#[path = "../../logicaffeine_tests/unit/logicaffeine_kernel/recheck/bounded_alias_conversion_controls.rs"]
8884mod bounded_alias_conversion_controls;
8885
8886#[cfg(test)]
8887#[path = "../../logicaffeine_tests/unit/logicaffeine_kernel/recheck/owned_match_conversion_controls.rs"]
8888mod owned_match_conversion_controls;
8889
8890#[cfg(test)]
8891#[path = "../../logicaffeine_tests/unit/logicaffeine_kernel/recheck/storage_controls.rs"]
8892mod storage_controls;
8893
8894#[cfg(test)]
8895#[path = "../../logicaffeine_tests/unit/logicaffeine_kernel/recheck/storage_accounting_controls.rs"]
8896mod storage_accounting_controls;
8897
8898#[cfg(test)]
8899#[path = "../../logicaffeine_tests/unit/logicaffeine_kernel/recheck/storage_differential_controls.rs"]
8900mod storage_differential_controls;
8901
8902#[cfg(test)]
8903#[path = "../../logicaffeine_tests/unit/logicaffeine_kernel/recheck/definition_cache_controls.rs"]
8904mod definition_cache_controls;
8905
8906#[cfg(test)]
8907#[path = "../../logicaffeine_tests/unit/logicaffeine_kernel/recheck/zero_shift_controls.rs"]
8908mod zero_shift_controls;
8909
8910#[cfg(test)]
8911#[path = "../../logicaffeine_tests/unit/logicaffeine_kernel/recheck/dead_binder_controls.rs"]
8912mod dead_binder_controls;
8913
8914#[cfg(test)]
8915#[path = "../../logicaffeine_tests/unit/logicaffeine_kernel/recheck/argument_edge_controls.rs"]
8916mod argument_edge_controls;
8917
8918#[cfg(test)]
8919#[path = "../../logicaffeine_tests/unit/logicaffeine_kernel/recheck/head_closure_controls.rs"]
8920mod head_closure_controls;
8921
8922#[cfg(test)]
8923#[path = "../../logicaffeine_tests/unit/logicaffeine_kernel/recheck/head_closure_adversarial_controls.rs"]
8924mod head_closure_adversarial_controls;
8925
8926#[cfg(test)]
8927#[path = "../../logicaffeine_tests/unit/logicaffeine_kernel/recheck/head_closure_level_copy_controls.rs"]
8928mod head_closure_level_copy_controls;
8929
8930#[cfg(test)]
8931#[path = "../../logicaffeine_tests/unit/logicaffeine_kernel/recheck/head_closure_binder_gate_controls.rs"]
8932mod head_closure_binder_gate_controls;
8933
8934#[cfg(test)]
8935#[path = "../../logicaffeine_tests/unit/logicaffeine_kernel/recheck/fix_argument_edge_controls.rs"]
8936mod fix_argument_edge_controls;
8937
8938#[cfg(test)]
8939#[path = "../../logicaffeine_tests/unit/logicaffeine_kernel/recheck/open_mutual_controls.rs"]
8940mod open_mutual_controls;