Skip to content

A Kind-spliced lambda can make the all-green emitted book compute the unused column's value (kernel-certified 7n vs source 3n) #1178

Closed

Description

@yavuzerayut

What you did

BEND_NO_TELEMETRY=1 bend drift.bend --check-only, --verdict, and -o + kernel on the emitted book, with an oracle equality appended to the emitted book to certify what it actually computes.

(Corrected the file below to the exact reproducer; an earlier edit of this issue carried a hand-simplified variant that does not parse-check. This one is verified as-is.)

What happened

All three gates are green, but the emitted book computes a different value than the source: the source's use() evaluates to 3n, while the kernel-certified emitted book's use evaluates to 7n (an appended oracle def ora7 : {use == 7n : Nat} is ACCEPTED by the kernel on the emitted book, ora3 : {use == 3n : Nat} is rejected). The drift is deterministic and flips with the two columns' values (swapping 7n/3n flips the certified value), and propagates downstream (Nat.add(use(), 10n) certifies 17, not 13). Mechanism: the Kind-specialized parameter splices the inline identity lambda into the instance body; the splice is scope-moved onto the convoyed match parameters and routes to the UNUSED column's Mk{(z => 7n)} instead of the used Mk{(w => 3n). Ordinary's own reflexivity accepts {use() == 3n} at the source level — the two worlds disagree on the same definition's value (and if you assert it in the source, --verdict then fails, so the divergence is only visible through the emitted book).

The same shape at the type level (type-valued specialized lambda column convoyed through a match) is sharper: the kernel proves obs == MkT{Nat} while the source computes MkT{Bool}, again with all gates green — available on request.

This looks like the #1168 scope_move capture family reaching the value level while all gates stay green.

The file

import Base

type Box is Type:
  Mk{fn: Nat -> Nat}

def qof2(f: Box -> Box) -> Quant:
  &1

def Unit2(f: Box -> Box) -> Type:
  Unit

def get(b: Box) -> Nat:
  match b:
    case Mk{fn}: fn(0n)

def looseK(f: Box -> Box, g: Box, h: Box, -A: Kind(qof2(f)), -w: Unit2(f), b: Bool) -> Nat:
  match b:
    case True{}:  get(f(h))
    case False{}: get(f(h))

def use() -> Nat:
  looseK((y => y), Mk{(z => 7n)}, Mk{(w => 3n)}, Unit, Unit{}, True{})

bend --version

bend 2.0.32

uname -sm

Darwin arm64

clang --version (the first line)

Apple clang version 17.0.0 (clang-1700.0.13.5)

Activity

  1. yavuzerayut commented on Sep 29, 2026

    @yavuzerayut
    Author

    Severity escalation for this report (same mechanism, type level, verified the same way): with a type-valued specialized lambda column, the all-green emitted book proves the WRONG TYPE. Source computes MkT{f(t1)} = MkT{Bool}; appending oraNat : {obs == (.MkT, (Nat, ())) : BoxT} to the emitted book is ACCEPTED by the kernel (ALL PROOFS CHECK), while the true value oraBool : {obs == (.MkT, (Bool, ())) : BoxT} is rejected ("expected: obs, observed: (.MkT, (Bool, ()))").

    The cause is visible in the emission: the instance body splices the caller's identity lambda as (λx0 => x4 x5) — its own parameter x0 is ignored and the FIRST convoyed spine binder x4 (= Nat, the first type argument) is used instead, so the field value follows t0 rather than t1. The kernel's bidirectional App-on-Var rule checks the spliced lambda against a *1 motive, and the Typ Q2, Typ _ => true fit accepts any *2-typed type, so nothing catches the rebind. Swapping the caller's arguments flips the certified type deterministically (mirror variant), a constant lambda stays faithful, and a Nat-valued twin stays faithful — so the drift is specific to type-valued spliced columns convoyed through a match.

    The file (all gates green; oracle lives only in the emitted book):

    import Base
    
    type BoxT is Type:
      MkT{t: Type}
    
    def qof2(f: Type -> Type) -> Quant:
      &1
    
    def R(f: Type -> Type, b: Bool) -> Type:
      BoxT
    
    def k(f: Type -> Type, t0: Type, t1: Type, -A: Kind(qof2(f)), b: Bool) -> R(f, b):
      match b:
        case True{}:  MkT{f(t1)}
        case False{}: MkT{f(t1)}
    
    def obs() -> BoxT: k((T: Type) => T, Nat, Bool, Unit, True{})

    To certify: bend w8.bend -o w8.bendtt, append oraNat : {obs == (.MkT, (Nat, ())) : BoxT} = {==} to the book, run the kernel binary on it — ALL PROOFS CHECK; the Bool twin fails.

  2. yavuzerayut commented on Sep 29, 2026

    @yavuzerayut
    Author

    Reproduces on v2.0.33 (c05efd9): check-only and --verdict both green on the value-level file above (the translator is unchanged in 2.0.33, so expected — now demonstrated).

  3. jasisz commented on Sep 29, 2026

    @jasisz
    Contributor

    Here is a reduced type-level variant, reproduced on v2.0.34 (7d8a3eb).

    This is a composite escalation of this issue and #1131: the Kind-splice / convoy drift selects a different nominal type, while the non-injective BendTT constructor-label encoding lets the two distinct source constructors share the same kernel label. Together they produce an all-green drift from an imported type with a q0 field to a local type with a q1 field. No generated BendTT was edited.

    Reproducer

    File layout:

    template-carry.bend
    a-b/lib.bend
    

    a-b/lib.bend:

    type Dead is Data:
      K{-u: Unit}
    

    template-carry.bend:

    import Base
    import ./a-b/lib.bend as Far
    
    type a_2d_b_2f_lib.Live is Data:
      a_2d_b_2f_lib.K{u: Unit}
    
    type BoxT is Type:
      MkT{t: Type}
    
    def qof(f: Type -> Type) -> Quant:
      &1
    
    def R(f: Type -> Type, b: Bool) -> Type:
      BoxT
    
    def k(f: Type -> Type, emitted: Type, source: Type, -A: Kind(qof(f)), b: Bool) -> R(f, b):
      match b:
        case True{}: MkT{f(source)}
        case False{}: MkT{f(source)}
    
    def obs() -> BoxT:
      k((T: Type) => T, a_2d_b_2f_lib.Live -> Unit, Far.Dead -> Unit, Unit, True{})
    
    def Out(b: BoxT) -> Type:
      match b:
        case MkT{t}: t
    
    def carry(~v: Out(obs()), b: Bool) -> Out(obs()):
      match b:
        case True{}: v
        case False{}: v
    
    def matcher() -> Out(obs()):
      carry(~{\{Far.K: u => Unit{}} : Far.Dead -> Unit}, True{})
    

    On the clean tag checkout:

    bend --check-only template-carry.bend  -> ALL PROOFS CHECK
    bend --verdict template-carry.bend     -> ALL PROOFS CHECK
    bendtt template-carry.bendtt           -> ALL PROOFS CHECK
    

    The generated book contains the distinct q0 and q1 source datatypes:

    a_2d_b_2f_lib.Dead.arms ...
      .a_2d_b_2f_lib.K: Σ-x0 : Unit ...
    
    a_2d_b_2f_lib.Live.arms ...
      .a_2d_b_2f_lib.K: Σx0 : Unit ...
    

    but the specialized obs contains both columns and selects the local/live one in BendTT:

    (k.qv_ ∀x0 : a_2d_b_2f_lib.Live -> Unit
           ∀x0 : a_2d_b_2f_lib.Dead -> Unit
           -Unit (.True, ()))
    

    At the Bend level, the value passed to carry is explicitly checked as:

    Far.Dead -> Unit
    

    while the kernel certifies matcher : Out(obs), where the emitted obs selects:

    a_2d_b_2f_lib.Live -> Unit
    

    So the all-green certificate disagrees with the source on both nominal identity and constructor-field quantity (q0 -> q1). This is stronger as an impact demonstration than the numeric drift alone, but it is still the composition of the two already-reported translation bugs rather than a new independent root cause.

    Boundary: this does not yet construct a closed live Empty. Replacing the result field with Empty reaches Bend's specialization recheck, which rejects the instantiated body at carry~0 with expected: -e / observed: e.

  4. jasisz commented on Sep 29, 2026

    @jasisz
    Contributor

    Here is a smaller native observation of the same type-level drift on v2.0.34 (7d8a3eb). It makes the mismatched type a top-level Bend definition; the generated book itself is not edited.

    import Base
    
    type BoxT is Type:
      MkT{t: Type}
    
    def qof(f: Type -> Type) -> Quant:
      &1
    
    def R(f: Type -> Type, b: Bool) -> Type:
      BoxT
    
    def k(f: Type -> Type, emitted: Type, source: Type, -A: Kind(qof(f)), b: Bool) -> R(f, b):
      match b:
        case True{}: MkT{f(source)}
        case False{}: MkT{f(source)}
    
    def obs() -> BoxT:
      k((T: Type) => T, Unit, Empty, Unit, True{})
    
    def Out(b: BoxT) -> Type:
      match b:
        case MkT{t}: t
    
    def probe() -> Type:
      Out(obs())
    

    All three unmodified gates are green:

    bend --check-only probe.bend  -> ALL PROOFS CHECK
    bend --verdict probe.bend     -> ALL PROOFS CHECK
    bendtt probe.bendtt           -> ALL PROOFS CHECK
    

    The source checker establishes that probe() reduces to Empty:

    def source_probe_is_empty() -> {probe() == Empty : Type}:
      {==}
    

    --check-only accepts that control. Adding it makes --verdict fail, and the kernel reports:

    In source_probe_is_empty:
    expected: probe
    observed: Empty
    

    Conversely, appending only this diagnostic oracle to the emitted book is accepted by the kernel:

    probe_is_unit : {probe == Unit : *1} =
      {==}
    

    Thus the same generated top-level probe definition normalizes to Empty in Bend and to Unit in the certified BendTT book. This still does not construct a live inhabitant of Empty: attempting to consume the drift through an empty eliminator reaches the specialization/liveness checks (expected: -run / observed: run, or a live scrutinee).

  5. Vacrin commented on Sep 29, 2026

    @Vacrin

    Following up on @jasisz's observation of type-level drift: by controlling the parameter telescope passed to ap5, the convoy variable shadowing can be steered to produce pure, unboxed definitional type drift in both directions between bend.ts and bendtt.lean.

    More importantly, testing both directions reveals the exact dual boundary barrier in the Lean 4 kernel that prevents this compiler bug from forging an inconsistency or live inhabitant of Empty.


    1. Bidirectional Certified Type Drift

    The drift does not require a wrapper ADT (BoxT) or pattern-matching projections; the type definition itself normalizes directly to Unit in one checker and Empty in the other.

    Case A: Forward Drift (Unit in Bend $\to$ Empty in Lean)

    ap5(h) supplies h(Nat)(Unit)(Nat)(Nat)(Empty):

    import Base
    
    def ap5(h: Type -> Type -> Type -> Type -> Type -> Type) -> Type:
      h(Nat)(Unit)(Nat)(Nat)(Empty)
    
    def qof(f: Type -> Type -> Type -> Type -> Type -> Type) -> Quant:
      &1
    
    def U2(f: Type -> Type -> Type -> Type -> Type -> Type) -> Type:
      Unit
    
    def k(f: Type -> Type -> Type -> Type -> Type -> Type, -w: U2(f), g: Nat -> Nat, -A: Kind(qof(f)), b: Bool) -> Type:
      match b:
        case True{}:
          ap5(f)
        case False{}:
          _ = g(1n)
          Unit
    
    def main_type() -> Type:
      k((a => b => c => d => e => b), Unit{}, (x => 5n), Unit, True{})
    
    • Frontend: Evaluates parameter 2 (Unit). Ground equality {main_type == Unit : Type} = {==} passes bend --check-only (ALL PROOFS CHECK).
    • Kernel: Convoy elaboration shadows index 4, selecting parameter 5 (Empty). Appending ora_empty : {main_type == Empty : *1} = {==} to the emitted .bendtt passes the Lean 4 kernel with ALL PROOFS CHECK.
    • Polymorphic functions pass: Polymorphic identities (def id(x: main_type()) -> main_type(): x) and reflexivity lemmas (def rfl_on(x: main_type()) -> {x == x : main_type()}: {==}) pass bend --verdict cleanly (ALL PROOFS CHECK).

    Case B: Reverse Drift (Empty in Bend $\to$ Unit in Lean)

    Swapping arguments 2 and 5 in ap5 (h(Nat)(Empty)(Nat)(Nat)(Unit)):

    import Base
    
    def ap5(h: Type -> Type -> Type -> Type -> Type -> Type) -> Type:
      h(Nat)(Empty)(Nat)(Nat)(Unit)
    
    def qof(f: Type -> Type -> Type -> Type -> Type -> Type) -> Quant:
      &1
    
    def U2(f: Type -> Type -> Type -> Type -> Type -> Type) -> Type:
      Unit
    
    def k(f: Type -> Type -> Type -> Type -> Type -> Type, -w: U2(f), g: Nat -> Nat, -A: Kind(qof(f)), b: Bool) -> Type:
      match b:
        case True{}:
          ap5(f)
        case False{}:
          _ = g(1n)
          Unit
    
    def rev_type() -> Type:
      k((a => b => c => d => e => b), Unit{}, (x => 5n), Unit, True{})
    
    • Frontend: Evaluates parameter 2 (Empty). Ground equality {rev_type == Empty : Type} = {==} passes bend --check-only (ALL PROOFS CHECK).
    • Kernel: Shadowed index 4 selects parameter 5 (Unit). Appending ora_unit : {rev_type == Unit : *1} = {==} to the emitted .bendtt passes the Lean kernel with ALL PROOFS CHECK.

    2. The Dual Boundary Barrier Against Live Inhabitation

    With type drift established in both directions, we attempted to exploit it across the boundary via both Introduction (constructing an inhabitant) and Elimination (using ex-falso). Both attacks fail closed at the kernel:

    Attack Vector Probe Frontend (bend.ts) Kernel (bendtt.lean) Kernel Failure Mode
    Introduction win() -> main_type(): Unit{} Accepts (main_type ≡ Unit) Checks against Empty (<>) Fails closed: In win: a label of <>
    Elimination f(x: rev_type()) -> Nat: match x: Accepts (rev_type ≡ Empty, 0 arms) Checks Efq against Unit (<Unit>) Fails closed: In f: expected: an empty enum, observed: <Unit>

    Why It Fails Closed:

    1. The Constructor Barrier (Introduction): When bend.ts believes a type is Unit and permits returning Unit{}, the kernel checks constructor label .Unit against Empty (Enu []). In bendtt.lean:1040-1044 (Term.check), checking a label requires ks.contains k. Because <> has 0 labels, it is rejected with:
      SOME PROOFS FAIL
      In win:
      a label of <>
      
    2. The Eliminator Barrier (Elimination): When bend.ts believes a type is Empty and permits an empty match (match x:), safe.ts emits Efq (λ{}). The kernel checks Efq against the argument type, which in the kernel drifted to Unit (<Unit>). In bendtt.lean:1417, Efq is typed exclusively on Enu [], so the kernel rejects with:
      SOME PROOFS FAIL
      In f:
      expected: an empty enum
      observed: <Unit>
      

    3. Formal Invariance

    This confirms that convoy variable shadowing (#1178) is a fidelity defect (the emitted program computes a different type/value than the source) rather than a soundness breach in Lean BendTT:

    • In bendtt.lean:1529, 4235, Lean 4 machine-checks the theorem Claim.consistent:
      ∀ bk k d, Book.check bk = .ok () → Book.get bk k = some d → ¬ Conv bk d.T (Enu [])
    • In bendtt.lean:2733, Fire q x Efq = False, proving that ex-falso can never step on a closed term.

    The kernel's typing rules fail closed symmetrically against both false constructors and false eliminators.

  6. jasisz commented on Sep 29, 2026

    @jasisz
    Contributor

    @Vacrin nice write-up — the dual-barrier result matches what we see here. One gap in the pairing though, plus an update from the tip.

    The pairing. Both probes hit the barrier from the side where that gate is the one telling the truth:

    • Introduction used Case A (main_type: source sees Unit, kernel sees Empty) — the kernel rejects .Unit because its view is the true one there.
    • Elimination used Case B (rev_type: source sees Empty, kernel sees Unit) — same, mirrored.

    The combination that would actually matter is a def where both gates lie in the same direction: bend.ts wrongly reducing a computed type to something inhabited (so it accepts a real value at it), and the elaborator delivering that same inhabited type to the kernel. Before 0187512 the convoy drift supplied the second half for free — your Case B plus a hypothetical first half is exactly that composition. So "fails closed" is correct for elaborator-only bugs; the remaining path for the bounty is a bend.ts-side mis-reduction, with the drift as the (now historical) transport.

    Update: 0187512 closes the drift. Re-checked on the tip, with oracle defs appended to the emitted .bendtt of the minimal reproducer (the same k/qof/R/obs/Out scaffolding as your cases, with f = the one-argument identity and a single source argument — no imports, no wrapper ADT):

    • Appending probeUnit : (Out obs) = (.Unit, ()) now fails with a label of <> — the kernel computes Out obs ≡ Empty, agreeing with the source.
    • Your Case B oracle ora : {rev_type == Unit : *1} = {==} also fails on the tip.
    • The original reproducers of this issue (the Box/looseK shape, and the import-splice variant where a local type shares the imported file's constructor label) still pass --verdict, but only because the specialized argument now routes through the opaque model constant — the kernel-side type is stuck there (no inhabited drift, so no transport; a stuck type has no values).

    Where this leaves the hunt. Two observations from our side that your barriers are the boundary of:

    1. Every elaborator-only route to a live inhabitant of Empty is closed on the source side by four walls: the use tally (uses_close — an erased variable can never be a live application head), the def_inst instance recheck at the first live closed call (the real argument lands in head position), the ~-parameter model (no model whenever Empty appears in the parameter type's model path), and the live-scrutinee rule (bend.ts:3589, tests/check/erased_match_empty.bend). Together with your two kernel barriers this also pins the scrutinee of any match by its tree's constructor labels — only result types could ever drift, which is why the eliminator side never transports.
    2. The sharper target now: safe.ts makes its elaboration decisions through B.term_wnf / B.term_compare — the source's own evaluator. A mis-reduction of a computed type there (the share-cell machinery and its -2 marking, MAT arm walking, or the new Conversion checking normalizes before comparing, so identical large terms overflow the stack #1071 two-phase rigid pass with its in-place cell merging) would make bend.ts and the kernel agree on the same wrong type by construction — one bug, both gates green, no elaborator drift needed at all. That's where we're digging.
  7. Vacrin commented on Oct 4, 2026

    @Vacrin

    @jasisz Late follow-up since this closed: you're right about the pairing. Both of my probes hit the barrier from the side telling the truth. 0187512 didn't quite close it completely the let_term route still drifts on current main (565d7fd). It's a value-level drift with an all-green --verdict whose certified main differs from what bend2 runs, filed as #1326

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions