def_inst reuses template specializations across unrelated functions due to un-scoped term_key collisions
Author: VacrinCreated Sep 29, 2026Updated Sep 30, 2026
Labelsbug
What you did
bend key_collision.bend --check-only
What happened
$ bend key_collision.bend --check-only
ALL PROOFS CHECKThe file
import Base
def app(~f: Unit -> Nat) -> Nat:
f(Unit{})
def g(x: Nat) -> Nat:
app(~{\{Unit: 0n; x} : Unit -> Nat})
def h(x: Bool) -> Nat:
app(~{\{Unit: 0n; x} : Unit -> Nat})
def main() -> Nat:
_ = g(42n)
h(True{})In bend2/bend.ts:3726-3736:
const key = xs.map((a) => term_key(term_lower(a))).join("\n");
...
const is = book.tmps[tm.k] ??= Object.create(null);
if (is[key] === undefined) {
const o = is[key] = tm.k + "~" + String(Object.keys(is).length);
...
}
return is[key];term_lower(a)strips context and typing information, lowering terms toLTermrelative to the local telescope depth.term_key(bend.ts:1192-1194) serializes the stripped AST:JSON.stringify(tm, (k, v) => k === "s" ? undefined : v).- In
g(x: Nat)andh(x: Bool), the variablexis lowered toVar("x", 0). Becauseterm_keycontains neither the variable's type, the enclosing definition name (lhs.def), nor lexical origin, both template arguments produce the identical JSON string. book.tmpsis a global table keyed only by template name (tm.k, e.g."app"). Becauseis[key]was already populated during the check ofg,hencounters a cache hit and reusesapp~0!
Distinction
This demonstrates that the template caching subsystem has an independent hygiene flaw: cache keys lack lexical qualification, causing cross-function specialization collisions whenever two callers construct structurally identical template arguments.
Suggested fix
Incorporate the caller's definition name or fully typed telescope context into the cache key in def_inst, or include variable types in term_key.
bend --version
bend 2.0.32
uname -sm
Linux x86_64
clang --version (the first line)
No response
Source: HigherOrderCO/Bend