Skip to content

C lane: a hot constructor built at a family stuck on an open index holds a field of a type the facts never saw, and its consumer takes the sealed node raw #853

Closed

Description

@nicolas-abril

The C lane prints 1 where the JS lane prints 5 for the program below (main at 15ae0c8, bend file.bend -o main.c, cc -std=c11 -O1 main.c -lpthread).

import Base
type P is Data:
  P{a: U32, b: U32}
def Q() -> Data:
  Sigma<&2,&2,U32,(x => U32)>
def Pw(xs: List<&2,Q()>) -> Data:
  match xs:
    case Nil{}: Unit
    case Con{h,t}: Sigma<&2,&2,P,(p => Unit)>
def build(xs: List<&2,Q()>) -> Pw(xs):
  match xs:
    case Nil{}: Unit{}
    case Con{Tuple{n,m},t}: Tuple{P{n,1},Unit{}}
def total(xs: List<&2,Q()>,ps: Pw(xs)) -> U32:
  match xs:
    case Nil{}: 0
    case Con{h,t}:
      match ps:
        case Tuple{P{a,b},u}: a
def main() -> IO(Unit):
  do IO<Unit>:
    +s : List<&2,Q()> <- IO.pure(List<&2,Q()>, [Tuple{5,3}])
    IO.print(U32.show(total(s,build(s))))

#|5
  • expected: 5
  • observed (C): 1

Cause

A constructor is hot by name (CID_HOT_T): a hot node seals its boxed fields at build (rfc_seal), and a hot node's consumer takes it through ctr_take, which reads the seal. A cold node's consumer takes it raw (term_loc and e.mem[sp + j]).

The facts that decide hotness are written where a type is bound: sharing the list of Sigma<U32, U32> heats Sigma, so every Tuple seals its fields. But Tuple is also built inside build at the type Pw(xs), a family stuck on an open index. The emitter never walks that instantiation, so P stays cold. The sealed P inside the hot Tuple reaches total, which takes it raw and reads the cell instead of the node: 1 is the cell's second word.

Each ingredient is needed: a shared list of pairs to heat Tuple; a family to hide P from the facts; a two-field record fed at runtime, since a constant folds to a static; the bind to keep the index open, since a once-called helper fuses and a constant argument reduces the family.

Possible solution: heat what a hot build holds

Hotness stays static and the runtime is untouched. Two facts are added:

  1. A hot constructor heats its field types where it is built, at that build's instantiation (emit_ctr). At the bound type this is what facts_hot already does; the build site catches the instantiations the facts never saw.
  2. A family stuck on an open index heats all of its arms' types, once per family (facts_fam). Without this the stuck application falls into the * fallback and heats everything, which on a real program (bendquest) heated 67 of 74 constructors.
diff --git a/bend2/comp.ts b/bend2/comp.ts
index 4bf46db5..703b491a 100644
--- a/bend2/comp.ts
+++ b/bend2/comp.ts
@@ -1652,12 +1652,43 @@ function node_fields(fl: File, t: string, node: Lay,
 // type (hot); a shared value of an erased parameter's type marks it
 // (poly). compile_book emits the book until a pass changes nothing.
 
+// A family stuck on an open index is one of its arms' types: its def
+// applied to the arguments up to the match that takes one, walked once.
+function facts_fam(fl: File, w: HTerm, local: boolean): boolean {
+  const m = term_spine(fl, w);
+  const fam = m.tld?.$ === "Def" && m.tld.v !== null && Bend.term_strip(
+    Bend.term_unapply(m.all.reduce((b, x) => Bend.term_apply(b, x),
+      m.tld.v))[0]);
+  if (!fam || fam.$ !== "Mat") {
+    return false;
+  }
+  const key = "m:" + (m.t as Of<"Ref">).k;
+  if (!fl.hot.has(key)) {
+    fl.hot.add(key);
+    const { arms, end } = mat_arms(fam);
+    [...arms.map(([, b]) => b), end].forEach((b) =>
+      facts_hot(fl, b, true, local));
+  }
+  return true;
+}
+
+// A hot constructor's fields are hot at this instantiation; its own erased
+// binder is not the def's parameter: a field typed by it is unknown, never
+// poly.
+function facts_ctr(fl: File, c: Bend.Ctr, xs: HTerm[]): void {
+  const own = ctr_tail(fl.book, c, xs).some((d) => !live_dom(d));
+  ctr_doms(fl.book, c, xs).forEach((A) => facts_hot(fl, A, true, own));
+}
+
 function facts_hot(fl: File, B: HTerm | null, force: boolean,
   local = false): void {
   const w = ty_wnf(fl.book, B);
   if (w?.$ === "Lam") {
     return facts_hot(fl, w.f(DUMMY), force, local);
   }
+  if (w?.$ === "App" && force && facts_fam(fl, w, local)) {
+    return;
+  }
   if (w?.$ !== "ADT") {
     const dom = w?.$ === "Var" && !local && tele_unbind(fl.book,
       (fl.book.tlds[fl.def] as Def).T).doms[w.i];
@@ -1679,10 +1710,7 @@ function facts_hot(fl: File, B: HTerm | null, force: boolean,
   if (tld?.$ === "ADT") {
     for (const c of tld.c) {
       fl.hot.add(c.k);
-      // A constructor's own erased binder is not the def's parameter: a
-      // field typed by it is unknown, never poly.
-      const own = ctr_tail(fl.book, c, w.x).some((d) => !live_dom(d));
-      ctr_doms(fl.book, c, w.x).forEach((A) => facts_hot(fl, A, true, own));
+      facts_ctr(fl, c, w.x);
     }
   }
 }
@@ -2223,6 +2251,9 @@ function emit_ctr(fl: File, x: Of<"Ctr">, ty: HTerm | null,
       : `blk_node(e, ${val_own(fl, vs[0])[0]}, ${val_own(fl, vs[1])[0]})`],
     BOX);
   }
+  if (fl.hot.has(x.k)) {
+    facts_ctr(fl, fl.book.ctrs[x.k], adt.x);
+  }
   const pos = at ?? lay_of(fl.book, adt);
   const lay = lay_box(pos) ? lay_node(fl.book, x.k) : pos;
   const arm = lay_arm(lay, x.k);

Verified locally: the program prints 5 on both lanes; all sixteen benchmarks emit byte-identical C, so the runtime cost is zero; the local test gate passes but the two known local failures; 1500 fuzzer programs pass; bendquest's five spin scripts pass. comp.ts 61282 -> 61598 ttok.

The test above, as tests/run/family_field_hot.bend expecting 5, pins it.

Alternative considered: a seal test at every cold take

Instead of trusting the name fact, a cold take reads the seal bit of the node it has and takes a sealed one out of line (ctr_own = term_rfc(t) ? ctr_seal(e, t, n) : term_loc(t), with the cold path behind OUTLINE). This closes the hole regardless of what the facts see and is smaller (+191 ttok), but the bit test lands on every cold take in every hot loop: tree-bitonic +2.2%, tree-matmul +0.3%, the rest flat. Routing every owned take through ctr_take (-78 ttok) costs tree-bitonic +14%, and inlining the cold path +35%, from heap_alloc and span_fade inlined into the hot loops. The dispatch already ignores the seal bit and a two-arm if/else has no free slot for a third case, so there is no zero-cost dynamic placement.

Activity

  1. added
    bug
    compilation
    on Sep 19, 2026
  2. moorbrook commented on Sep 19, 2026

    @moorbrook
    Contributor

    A second trigger for this hole that needs no type family: a polymorphic Base def (Bool.pick) is enough to hide the concrete type from the facts.

    main at 15ae0c8, bend 2.0.16, Darwin arm64, Apple clang 21.0.0.

    bend seal.bend -o seal      # C
    bend seal.bend -o seal.js   # JS
    bend seal.bend              # checker
    import Base
    
    type RT is Data:
      RT{a: U32, b: U32, c: U32}
    
    # heats Some: a shared +Maybe binder over a boxed payload
    law twice:
      for +m: Maybe<&2, String>
      String
    
    def twice(m):
      String.append(Maybe.default(&2, String, m, ""),
        Maybe.default(&2, String, m, ""))
    
    # builds Some{RT} through a polymorphic Base def
    def mk(+x: U32) -> Maybe<&2, RT>:
      Bool.pick(Maybe<&2, RT>, U32.is_lt(x, 1000),
        Some{RT{x, (x + 1 : U32), (x + 7 : U32)}}, None{})
    
    def use(m: Maybe<&2, RT>) -> U32:
      match m:
        case None{}:
          0
        case Some{r}:
          match r:
            case RT{a, b, c}:
              (a + c : U32)
    
    law main:
      IO(Unit)
    
    def main():
      do IO<Unit>:
        p : Unit <- IO.print(twice(Some{"ab"}))
        q : U32 <- IO.try(U32, IO.random_u32())
        +r : U32 = q
        +i : U32 = (r % 97 : U32)
        IO.print(U32.show(i) ++ " -> " ++ U32.show(use(mk(i))))
    • expected (checker and JS): i -> 2 * i + 7
    • observed (C): one wrong value, the same for every i.
    C:  63 -> 51417606      JS: 11 -> 29
        86 -> 51417606          16 -> 39
        95 -> 51417606          23 -> 53
    

    The emitted C, build and take in the same spin:

    u64 nd_6 = heap_alloc(e, cls_fit(3));
    e.mem[nd_6 + 0] = x_8;
    e.mem[nd_6 + 1] = U32_BIN(x_8, +, 1ull);
    e.mem[nd_6 + 2] = U32_BIN(x_8, +, 7ull);
    u64 nd_7 = heap_alloc(e, cls_fit(1));
    e.mem[nd_7 + 0] = rfc_seal(e, term_ctr(CID_RT, nd_6));
    b_0 = term_ctr(CID_SOME, nd_7);
    ...
    u64 sp_4 = term_loc(f_4);
    u32 f_5 = e.mem[sp_4 + 0];
    u32 f_6 = e.mem[sp_4 + 1];
    u32 f_7 = e.mem[sp_4 + 2];
    heap_free(e, cls_fit(3), sp_4);

    The build seals RT because Some is hot by name; the take reads the one-word seal cell as the three-word node, and then frees a class-0 block at class 2, so the allocator is hit as well as the value.

    Two variants each restore the right answer, which isolates the ingredients:

    • drop twice and its Maybe<&2, String> binder: IO_HOTS is then 0 and nothing seals;
    • replace Bool.pick with a monomorphic def pick_rt(b: Bool, t: Maybe<&2, RT>, f: Maybe<&2, RT>) -> Maybe<&2, RT> that matches on b. This stays correct whether pick_rt is called once or from two sites, so it is not the once-called helper fusing: what matters is that the erased Kind argument of the polymorphic def keeps the instantiation out of the facts. Dumping fl.hot at the IO_HOTS site shows Some and t:Maybe in both programs and RT in neither, so the cold payload is necessary but not sufficient; the seal only happens on the Bool.pick path.

    x has to come in at runtime, as in the family repro, since a constant folds to a static.

    The Some{RT{..}} build here is a plain constructor at a closed instantiation, so the facts_ctr/emit_ctr half of the proposed fix looks like it would cover it, and the file is small enough to serve as a second regression test beside the family one.

  3. VictorTaelin commented on Sep 19, 2026

    @VictorTaelin
    Contributor

    Fixed in 2.0.17. A hot build now heats the field types of a constructor at its own instantiation, and a stuck family's arms are heated once per family, so the consumer never takes a sealed node raw. Pinned as tests/run/family_field_hot.bend.

    Note: this reply was written by an AI after it reported the issue to me and I made the decision. If anything here is wrong, reply and I will review it myself.

  4. jasisz commented on Sep 20, 2026

    @jasisz
    Contributor

    Moved this remaining case to #916 so it can be tracked separately: #916

    It is related to the facts_fam fix from #853 and independent of #901’s nested Mat hole.

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

    bugcompilation

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions