Skip to content

[soundness] Stmt::Defer and call-arg moves bypass A1b/A7 freeze and A2/A3 loan windows (data race at function exit) #98

Closed

Description

@sonson0910

The smallest .hy program that demonstrates it

// defer_repro.hy (main @ 8fb9238)
// Commands:
//   hyb check defer_repro.hy
//   hyb build defer_repro.hy -o defer_repro_bin
import "fmt"
import "time"

fn audit(m map[string]int) {
    for i in 0..5000 {
        m["defer"] = i
    }
}

fn worker(m map[string]int, done chan<- bool) {
    for i in 0..5000 {
        m["worker"] = i
    }
    done <- true
}

fn run() {
    m := map[string]int{"init": 0}
    done := make(chan bool, 1)

    // `defer` evaluates `m` (copying the map header) here, but executes
    // `audit(m)` at function exit — AFTER `task worker(move m, done)`
    // transfers ownership of `m` to the spawned task.
    defer audit(m)

    task worker(move m, done)
    time.sleep(1 * time.millisecond)
}

fn main() {
    run()
    time.sleep(50 * time.millisecond)
    fmt.println("done")
}

Additional affected forms in the same root cause:

  1. Alias use in defer before move (or defer before aliasing + move):
    m := map[string]int{"init": 0}
    m2 := m
    defer audit(m2)
    task worker(move m, done)
  2. Use in defer before a consuming API call (O13 / rule A7):
    import "rust/flate2"
    fn main() {
        w := flate2.new_writer(1, 6)
        defer w.write("late")
        w.finish()
    }
  3. move inside defer (defer cleanup(move m)) and inside call arguments (m2 := id(move m), eat(move m)):
    walk::own_uses marks Expr::Move operands as via_move: true (exempting them from check_uses), but Stmt::Defer and Stmt::Expr never invoked mark_move_in_value / check_non_owned_move, and collect_move_operands did not recurse into Expr::Call arguments. As a result, defer cleanup(move m); m["after"] = 1, fn run(p map[string]int) { defer cleanup(move p) }, and m2 := id(move m); task worker(move m2); m["main"] = 2 all passed with 0 diagnostics.
  4. Non-lexical loan window truncation on defer (O7 / rule A2 & O8 / rule A3):
    walk::flatten recorded last_use of bindings referenced inside Stmt::Defer at the lexical index of the defer statement rather than function exit (fn_end), and Stmt::Defer calls passed loop_end: None to process_call / lend_handle_args. Consequently, s := &m["a"]; defer bump(s); m["b"] = svc{count: 2} (map rehash while defer holds slot pointer s) and defer serde_json.to_string_pretty(doc); doc.set("k", 1) passed with 0 diagnostics.

What the checker should say

  • Reject (HYB-E3003, rule A1b): m (or its alias m2) is captured by defer audit(...), which executes at function exit after ownership of m leaves via task worker(move m, done).
  • Reject (HYB-E3003, rule A7): w is used by defer w.write(...) at function exit after w.finish() consumes ownership of w.
  • Reject (HYB-E3003 / HYB-E3004, rule A1b): move inside defer or call arguments must freeze the moved binding and reject non-owned bindings (parameters/receivers/captures/range vars).
  • Reject (HYB-E3102 rule A3 / HYB-E3101 rule A2): Map-slot loans (&m[k]) and boundary-handle borrow loans referenced or opened by defer remain live until function exit (fn_end).

What it actually said

$ hyb check defer_repro.hy
OK (0 diagnostics)

When lowered by hyb and executed under go run -race, the program immediately triggers a data race / concurrent map write between the spawned worker goroutine and the deferred audit(m) call at function exit:

==================
WARNING: DATA RACE
Write at 0x00c0000941b0 by goroutine 7:
  runtime.mapassign_faststr()
      /home/son/anaconda3/src/runtime/map_faststr.go:223 +0x0
  main.worker()
      defer_repro_bin.go:19 +0x58

Previous write at 0x00c0000941b0 by main goroutine:
  runtime.mapassign_faststr()
      /home/son/anaconda3/src/runtime/map_faststr.go:223 +0x0
  main.audit()
      defer_repro_bin.go:13 +0x4d
  main.run.deferwrap1()
      defer_repro_bin.go:28 +0x33
  main.run()
      defer_repro_bin.go:31 +0x125
==================
Found 1 data race(s)
exit status 66

Claimed severity

P0 — data race reachable in the checked subset

Anything else

  • Rules involved: SPEC-LANGUAGE §9 O5.1 / O5.2 / O5.4 (A1b, HYB-E3003 / HYB-E3004), O13 (A7, HYB-E3003), O7 (A2, HYB-E3101), and O8 (A3, HYB-E3102).
  • Root cause in hy-check:
    1. walk::flatten in compiler/crates/hy-check/src/walk.rs assigned last_use for bindings inside Stmt::Defer to the defer statement's lexical index instead of fn_end.
    2. check_fn in compiler/crates/hy-check/src/lib.rs (and closures.rs) only ran check_uses at the lexical position of Stmt::Defer (before subsequent move or consume statements) and had no Stmt::Defer / Stmt::Expr move handling.
    3. collect_move_operands in compiler/crates/hy-check/src/model.rs did not recurse into Expr::Call arguments.
    4. process_call / lend_handle_args in compiler/crates/hy-check/src/loans.rs created single-statement (last: idx) handle loans for Stmt::Defer calls instead of extending them to fn_end.

Payout / Wallet Addresses (Bounty Track #5)

  • USDT (TRC20): TCQwxbpYVdRWYNDs1JbnKyVHNRVaRJg1io
  • USDT / USDC (ERC20 / BEP20): 0x76d1c4283a2ff662ccf85c1f57655c29b4256756
  • Self-Custody EVM Wallet (ETH / USDC / USDT / any EVM chain or token): 0x6Cf7Fc00857f2bbd12fBF2E11BC5AacEF0e97985
  • USDC (Solana): 6dX8oqvvHj6Q936PVyTjVYKVk45soNpJ234aVqMm6ZJm

Activity

  1. added a commit that references this issue on Oct 15, 2026
  2. added 2 commits that reference this issue on Oct 17, 2026
    ebdde5c
    5f4f369
  3. limitlessprojects commented on Oct 18, 2026

    @limitlessprojects
    Owner

    Verified against main @ 0706813 — every scenario class in this report now rejects with the expected codes:

    Scenario Main behavior
    defer + spawn-move of shared map (the issue's defer_repro.hy) HYB-E3003 (corpus 56–58 pins)
    A7: consuming use after defer w.write; w.finish() HYB-E3003
    move-in-defer + later write (defer cleanup(move m); m["after"]=1) HYB-E3003
    move-in-call-arg (m2 := id(move m)) HYB-E3003
    A2/A3 defer loan window (s := &m["a"]; defer bump(s); m["api"]=…) HYB-E3102 (A3, loan live to fn exit) — value-precise, rebind-to-fresh control still ACCEPTS

    Landing evidence: pr-421 (2defedf, @exantiv, fixes #415/#438 — value-precise deferred-binding freeze), pr-395 (1ed45d5, @sonson0910 — mark moves in non-assignment statement expressions), pr-288 (5317e70 — defer-operand E2001), test pins spliced at 1980a40.

    Closing as fixed — thanks @sonson0910; the deferred-freeze precision landed essentially as this report asked.

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