Repository navigation
Description
Priority: P0, a known_edge is emitted for a function that provably cannot run, and the one that does run appears in no row. The single-write guard counts only the owning scope's bindings, so a cell rebound by nonlocal from a nested scope is treated as if it were assigned once.
What happens
def first() -> str:
return "first"
def second() -> str:
return "second"
def nonlocal_rebind() -> str:
fn = first # write 1
def swap() -> None:
nonlocal fn
fn = second # write 2 — from a NESTED scope
swap()
return fn() # runs `second`Engine output:
known_edge SIMPLE_CALL nonlocal_rebind -> first <- cannot run
known_edge SIMPLE_CALL nonlocal_rebind -> nonlocal_rebind.<locals>.swap
second is the target of no edge. The answer is not merely narrow, the single target it commits to is the value the cell holds before swap() runs, and swap() is called unconditionally on the line above the call. known_edge is the tier reserved for an answer the engine is certain of.
Expected behavior
fn is a closure cell with two writes, the second in a nested scope declared nonlocal. symtable reports the two scopes separately:
scope nonlocal_rebind : fn local=True free=False assigned=True
scope swap : fn local=False free=True assigned=True
The compiler writes the cell twice and reads it at the call (Python 3.10.18):
nonlocal_rebind:
line 10 LOAD_GLOBAL first ; STORE_DEREF fn <- write 1
line 16 LOAD_FAST swap ; CALL_FUNCTION 0 <- runs write 2
line 17 LOAD_DEREF fn ; CALL_FUNCTION 0 <- the call under test
swap:
line 14 LOAD_GLOBAL second ; STORE_DEREF fn <- write 2
And sys.setprofile over nonlocal_rebind() records {'nonlocal_rebind': 1, 'swap': 1, 'second': 1}, first never runs.
The correct answer is multi_inferred over {first, second} if the ordering is not modelled, or known_edge -> second if it is. Committing to first alone is the one answer that is wrong in both readings.
For contrast, the global sibling of this shape, global HANDLER; HANDLER = first in one function, HANDLER() in another, comes out ambiguous_unknown. That is a declared blind spot rather than a wrong answer, so the two halves of the rebinding channel currently fail differently.
The parser IR has what is needed
all-python-bindings.csv records both writes, and marks the second as a nonlocal assignment explicitly:
name bindingKind bindingOrigin isLocal isNonlocal isFree isAssigned bindingCount lines
fn CELL ASSIGNMENT true false false true 1 10-10
fn NONLOCAL MULTIPLE false true true true 2 13-14
The row for the nested scope carries bindingKind=NONLOCAL, isNonlocal=true and isAssigned=true. Nothing about this is missing or malformed, so the information the engine needs to know the cell is rebound is present on every run.
The pieces that exist
src/python/engine/resolution/value-flow.dl gates value flow on the binding being written once:
binding_value_method(p, b, r) :-
binding_rebinding(p, "1", _, _, b), <- bindingCount == 1
expr_binding(p, b, "STORE", tgt),
assign_pair(p, tgt, val),
expr_denotes_method(p, val, r).
binding_rebinding carries the count from the binding row, and the CELL row above has bindingCount = 1 because that is how many times its own scope assigns the name (line 10). The NONLOCAL row that assigns second is a separate binding with its own count, and nothing joins the two, so the guard concludes the name is single-write and the flow commits.
The NONLOCAL kind is already projected and already read, but only for name lookup, in src/python/engine/resolution/name-resolution.dl:
binding_is_free_kind(p, b) :- binding_decl(p, _, _, "NONLOCAL", _, b).
so the channel is visible to the resolver that finds which enclosing binding a free name refers to, and invisible to the one that decides what that binding holds.
Also unread: scope_declares_global and scope_declares_nonlocal in src/python/engine/projections/scopes.dl have no consumer anywhere outside projections/ (checked against every src/python/engine/*/*.dl that is not a projection). Those are the two relations that say a scope contains a rebinding channel at all.
Shape of the fix
The guard needs the number of writes to the binding, not to the binding row. A cell's writes are its own scope's assignments plus every NONLOCAL-kind assigned binding in a nested scope that resolves to it, the same resolution binding_is_free_kind already performs for lookup, reused to aggregate the count. Once the count is right the existing single-write guard does the correct thing on its own: the site falls out of binding_value_method and becomes a declared unknown rather than a wrong committed target, which is already a strict improvement. Unioning the two writes into multi_inferred is the fuller answer and is the same shape #222 took for module-level names.
The global half wants the mirror of this through isDeclaredGlobal / GLOBAL_EXPLICIT, but it is currently failing safe, so it is the lower priority of the two.
Why it is worth having
Rebinding a closure variable from an inner function is how Python writes a mutable captured slot without a class, memoisation flags, lazily-installed handlers, retry/backoff state, and "swap the implementation once at startup" wiring all take this form. Because the wrong answer arrives as known_edge, a consumer that trusts confidence tiers has no signal at all: the site looks fully resolved, and the function that actually runs is absent from the graph.
How it was measured
Parser revision: 79c8cd1, rebuilt with npm run build immediately before extraction. Engine: bf9e0cd. Python 3.10.18. IR, engine output and ground truth all regenerated from scratch for this run.
node <parser>/dist/index.js <src> proj false ir
bash src/pipeline/run-souffle.sh --language python \
--client-ir ir --library <empty-dir> --intermediate int --output outOracles: symtable for the binding kinds per scope, dis for the two STORE_DEREFs and the LOAD_DEREF at the call, and sys.setprofile for which function runs.
Related
- python: a callee name's multiple writes are never unioned, so the optional-dependency fallback is lost and the import is asserted as certain #222 (closed) is the same family, a callee name's multiple writes not unioned, but for writes in one scope (an import plus an assignment, or two assignments). Both writes are visible to the guard there because they share a binding row; here the second write lives in a different scope and a different row, so the count never reaches 2.
- python: a rebound attribute holding a library instance resolves to the first write #28 (closed) is the attribute-valued cousin: a rebound attribute resolving to the first write.
- python: a name with more than one write, or a value from a ternary, has no type at all #44 (closed) covers a name with more than one write having no type; this one does get a type, and it is the wrong one.
- python: a function declaring
selfand installed as a method at runtime has an untyped receiver #97 (open) also concerns free variables but is about an untypedselfreceiver on a runtime-installed method, not about a rebound cell's value.
Activity
Merge pull request #2023 from AxiomCodeAI/fix/python-nonlocal-rebind
github-actions commentedon Nov 19, 2026
Closed by #2023, which merged into
0.2.4and reacheddevin f5868f8.