Skip to content

Soundness: nested-block closures miss subsequent moves of outer-block bindings in closure_scoped_envs (HYB-E3003) #3947

Open

Description

@CrowAleksito

Summary

When a closure literal (Expr::FnLit) is declared inside an inner block (if, for, match, select, or { ... }) and captures a may_share binding m declared in an enclosing intermediate block (i.e., m lives in st.scopes[d] rather than the function-root st.env), moving m in the enclosing block after the inner block has exited (task worker(move m, done)) fails to update the snapshot stored in st.closure_scoped_envs. Consequently, closures::check_closure_boundaries sees m.moved == None inside the closure's captured snapshot and accepts concurrent mutation (Verdict::Accept with 0 diagnostics instead of rejecting with HYB-E3003).

Root Cause (model.rs, freeze.rs, closures.rs)

  1. When the inner block exits, FnState::scope_pop() (compiler/crates/hy-check/src/model.rs:324-340) snapshots (snap_env, snap_aliases, snap_share) into self.closure_scoped_envs keyed by the FnLit's (line, col) position.
  2. When m (declared in an enclosing block st.scopes[d]) is subsequently moved via task worker(move m, done), Checker::mark_move (compiler/crates/hy-check/src/freeze.rs:329-365) updates b.moved = Some(MoveInfo { ... }) on st.scopes[d] via st.env_lookup_mut(m), but never updates already-captured snapshots in st.closure_scoped_envs.
  3. When the enclosing block exits (model.rs:443: self.scopes.pop()), the popped scope's .moved and .non_owned_origin states are discarded without being propagated to self.closure_scoped_envs.
  4. At function exit, closures::check_closure_boundaries (compiler/crates/hy-check/src/closures.rs:44-47) only syncs .moved from scoped_st.env.get(k) (the top-level function scope), which does not contain block-scoped bindings m.

Minimal Reproducer (repro_closure_scoped_move.hy)

fn worker(m map[string]int, done chan int) {
    m["worker"] = 1
    done <- 1
}

fn main() {
    done := make(chan int, 1)
    if true {
        m := map[string]int{"k": 1}
        if true {
            defer (fn() {
                m["k"] = 2
            })()
        }
        task worker(move m, done)
    }
    <-done
}
  • Expected: Verdict::Reject with HYB-E3003 (the deferred closure mutates m after m was moved to worker).
  • Actual: Verdict::Accept (0 diagnostics), causing a concurrent map write race at runtime.

Fix

  1. In Checker::mark_move (compiler/crates/hy-check/src/freeze.rs), propagate MoveInfo and non_owned_origin for all members into existing snapshots in st.closure_scoped_envs.
  2. In FnState::scope_pop (compiler/crates/hy-check/src/model.rs), propagate .moved and .non_owned_origin from popped_scope into self.closure_scoped_envs before dropping the scope.

Payout Wallet (Base USDC)

  • Base / EVM (USDC): 0x8132B258bC02F98EbcE321EFf18528938fB58940

Activity

  1. CrowAleksito commented on Nov 7, 2026

    @CrowAleksito
    Author

    Fix PR opened by original reporter (@CrowAleksito): #3949 — Official Base USDC wallet: 0x8132B258bC02F98EbcE321EFf18528938fB58940

  2. zongsm-cmyk commented on Nov 7, 2026

    @zongsm-cmyk
    Contributor

    Submitted clean fix with raw string test fixtures in PR #4056 (#4056).

    • Fixed st.closure_scoped_envs dual-write in freeze.rs and model.rs for block-scoped bindings.
    • Added recursive compound generic parameter unification in shape.rs.
    • Fixed test fixture syntax using r#"..."# so cargo test --workspace compiles cleanly without literal token collisions.

    Closes #3947
    Closes #3948

    /claim #3947
    Base (USDC) Payout Address: 0xC10373008eFb38192C87C375ac63aB12E27C684C

  3. CrowAleksito commented on Nov 7, 2026

    @CrowAleksito
    Author

    Updated original reporter PR #3949 (#3949) per @limitlessprojects review (using raw string literals r#...# in soundness_closure_scoped_moves_and_compound_generic.rs).

  4. added a commit that references this issue on Nov 9, 2026
    9703b90
  5. aaskfuqw commented on Nov 9, 2026

    @aaskfuqw

    Confirmation + two additions: (a) the channel-send / select-send sites, and (b) the filed repro as written cannot race — here is a variant that does

    I reproduced this root cause on main at 30206b5741eec013dfc270224eaae874dc232324. Two points worth adding to the report:

    (a) The same stale snapshot defeats the freeze at channel sends, not only at spawns

    ch <- move xs (statement send) and select { ch <- move xs: ... } (send arm) are also accepted with 0 diagnostics, and both emit Go that races. The mechanism is exactly the one described in the "Root Cause" section — the closure's captured view is snapshotted at the inner block's scope_pop, the later mark_move updates only the live scope, and check_closure_boundaries syncs .moved from the top-level env only — the check-site type does not matter.

    (b) The repro in the issue cannot race as written; this variant does

    The filed reproducer ends main with <-done before returning. The deferred write runs after that receive, i.e. after worker has already sent on done, so nothing overlaps. go build --race on it is silent (verified locally).

    Remove the wait and the race is real. This is the version I verified — hyb check → OK (0 diagnostics), exit 0; go build --race + run → WARNING: DATA RACE on the same word, main.sink vs the deferred closure:

    fn sink(ch <-chan []int, done chan<- bool) {
        xs := <-ch
        for i in 0..200000 {
            xs[0] = i
        }
        done <- true
    }
    
    fn main() {
        done := make(chan bool, 1)
        ch := make(chan []int, 1)
        task sink(ch, done)
    
        if true {
            xs := []int{0}
            if true {
                defer (fn() {
                    for i in 0..200000 {
                        xs[0] = i + 1
                    }
                })()
            }
            ch <- move xs
        }
    }

    Race-detector output (head):

    WARNING: DATA RACE
    Write at 0x00c00000c0c8 by goroutine 6:
      main.sink()
    Previous write at 0x00c00000c0c8 by main goroutine:
      main.main.func1()
      runtime.deferreturn()
    Goroutine 6 (running) created at:
      main.main()
    

    The map[string]int twin ends in fatal error: concurrent map writes in addition to the race report. A select { ch <- move m: } spelling also reproduces.

    Suggested regression fixtures

    1. slice + ch <- move xs after an inner-block defer closure, no <-done (above) → HYB-E3003.
    2. map twin → HYB-E3003.
    3. select { ch <- move xs: ... } spelling → HYB-E3003.
    4. Control: the issue's own task worker(move m, done) + <-done shape — currently accepted; keep it accepted or reject it consistently, but it must not be the only fixture, because it cannot demonstrate the race.

    Environment: release build of 30206b5 (HYB_PINNED_RUST=1.99.1), hyb build --race (Go 1.27.3 with the documented HYB_ALLOW_TOOLCHAIN_DRIFT=1, winlibs gcc 16.2.0 for cgo). No repository sources were modified for this run.

  6. aaskfuqw commented on Nov 9, 2026

    @aaskfuqw

    Second, distinct gap in the same snapshot machinery: an alias created after the capture keeps the moved value alive (the move is on the alias, not on the captured name)

    This is a different shape from the issue's reproducer, and I think it needs its own line in the fix — the snapshot is stale in two directions, not one.

    Minimal repro (alias_after_capture.hy)

    fn worker(m map[string]int, done chan<- bool) {
        for i in 0..2000000 {
            m["w"] = i
        }
        done <- true
    }
    
    fn main() {
        done := make(chan bool, 1)
        if true {                       // intermediate block: `shared` lives in st.scopes[d]
            shared := map[string]int{}
            if true {
                defer (fn() {           // capture snapshot taken here
                    for i in 0..2000000 {
                        shared["late"] = i
                    }
                })()
            }
            alias := shared             // NEW: alias created AFTER the snapshot
            task worker(move alias, done)
        }
    }

    hyb check → OK (0 diagnostics), exit 0.
    hyb build --race + run → WARNING: DATA RACE (write in main.main.func1 via runtime.deferreturn vs write in main.worker, mapassign_faststr, same address), 2/2 runs.

    Why this is a different failure from the issue's reproducer

    In the filed reproducer, the captured name itself is moved (task worker(move m, done)), and the snapshot's moved flag for m is stale. Here the captured name shared is never moved: the move is applied to alias, a binding created after the snapshot exists. The snapshot has no record of alias at all, and nothing propagates the new alias back into it — so the closure's view of shared never learns that anything derived from it was moved/frozen.

    Control that isolates the trigger

    Identical body without the intermediate block:

    fn main() {
        done := make(chan bool, 1)
        shared := map[string]int{}
        if true {
            defer (fn() {
                for i in 0..2000000 { shared["late"] = i }
            })()
        }
        alias := shared
        task worker(move alias, done)
    }

    → REJECT HYB-E3003 on this commit. So the hole is specifically the block-scoped capture snapshot, not the alias derivation itself.

    Channel-send spelling, same shape

    struct holder { m map[string]int }
    
    fn consumer(ch <-chan holder, done chan<- bool) {
        h := <-ch
        for i in 0..2000000 { h.m["w"] = i }
        done <- true
    }
    
    fn main() {
        done := make(chan bool, 1)
        ch := make(chan holder, 1)
        task consumer(ch, done)
        if true {
            shared := map[string]int{}
            if true {
                defer (fn() {
                    for i in 0..2000000 { shared["late"] = i }
                })()
            }
            var h holder
            h.m = shared
            ch <- move h
        }
    }

    hyb check → exit 0; hyb build --race → WARNING: DATA RACE. Note this one also needs the field-store alias (h.m = shared) to be recorded into the snapshot.

    Suggested fixtures

    1. alias_after_capture → HYB-E3003 (this comment's first program).
    2. the channel-send variant above → HYB-E3003.
    3. control: the flat (no intermediate block) twin must stay REJECTed, and a block-scoped program with no post-capture alias must stay accepted (the documented over-rejection guard).

    Fix shape

    The existing plan (propagate moved/non_owned_origin from popped scopes and re-sync snapshots at check_closure_boundaries) closes the filed reproducer, but not this one: here the snapshot is missing a derivation (alias := shared, h.m = shared) that happened after it was built. The snapshot needs the may_share/alias edges created after capture to be merged in as well — i.e. snapshot invalidation on any record_may_share/record_place_store_from_snapshot that touches a captured root, not only on mark_move.

    Environment: 30206b57, release build, hyb build --race with Go 1.27.3 (HYB_ALLOW_TOOLCHAIN_DRIFT=1) + winlibs gcc 16.2.0 for cgo. No repository sources modified.

  7. added 11 commits that reference this issue on Nov 9, 2026
    3da9078
    dfa5e32
    22b27c0
    b53cb57
    4ce0bdf
    db2850d
    d98c97d
    a3d2bda
    2b0bac6
    4d850a2
    70af916
  8. added 2 commits that reference this issue on Nov 19, 2026
    3124b63
    e46ec3b
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