Skip to content

fix(python): let enclosing-function variables shadow callback names (#5658) - #5798

Open
ishyverma wants to merge 2 commits into
Graphify-Labs:v8from
ishyverma:fix/python-closure-var-not-callback-5658
Open

ishyverma wants to merge 2 commits into
Graphify-Labs:v8from
ishyverma:fix/python-closure-var-not-callback-5658

Conversation

@ishyverma

Copy link
Copy Markdown

What does this PR do?

Fixes #5658.

The Python indirect-call guard only knew the caller's own parameters and locals. A nested function that passes on a variable captured from its enclosing function had that name treated as a free reference, and the cross-file resolver bound it to any same-named function in the corpus. The issue's reproduction, on current v8:

# pkg/walker.py
def extract_file(path):
    source = path.read_bytes()
    def walk(node):
        return read_text(node, source)   # source: bytes captured from extract_file
    return walk
# pkg/cli.py
def placeholder(graph):
    def source(record): ...

gives indirect_call walk -> pkg_cli_placeholder_source (INFERRED 0.85). On graphify's own graphify/ package that nested source() collects 126 such edges and tops the god-node list.

How:

  • extractors/engine.py: before the body walk, each Python body gets the parameters and locals of its enclosing functions (via scope_parents) folded into extra_locals, the same channel JS: a variable captured from an enclosing function is not shadowed, so passing it as an argument fabricates an indirect_call to any same-named function in the corpus #5217 uses for JS closures. That set already feeds the indirect-reference shadow check and the bare-call local-data check.
    • Class scopes are skipped, as Python skips them.
    • Walking outward, a name a nearer scope imports (_python_local_import_names) or defines with def hides the same name further out, so def outer(h): def inner(): from lib import h still resolves to lib.h.
    • Nested defs are not variable bindings here (_python_local_bound_names stops at them), so a def from an enclosing function still resolves through the lexical scope map.
  • ARCHITECTURE.md: a short paragraph next to the lambda-parameter shadowing rule.

This is the first of the two checks the issue suggests (enclosing-scope bindings). The second (a nested def is never reachable by bare name from another module) is not needed for these cases and is left out to keep the change narrow. #3607 (open) covers a different case, a nested def in an enclosing scope; this PR is about enclosing variables.

Type of change

  • Bug fix
  • New feature
  • Documentation
  • Tests or CI
  • Refactor
  • Security fix

Verification & Invariants

Invariant: a name bound as a variable in any enclosing function scope is a value for a nested function, never a reference to a same-named function elsewhere, unless a nearer scope rebinds it with an import or a def.

Bug cases (fail before, pass after):

  • the issue's reproduction (captured source passed as an argument);
  • an enclosing local passed as an argument and an enclosing parameter listed in a collection, each with a same-named function in another module.

Guards (pass before and after):

  • a free name in a nested function (an imported callback) still resolves;
  • a sibling nested def passed by name still resolves;
  • a class attribute does not shadow the module function in a method;
  • a nested function's own import wins over an enclosing parameter;
  • a nearer def wins over a farther variable.

The existing test_local_import_over_parameter_keeps_its_edge (direct calls) also covers the import precedence and passes.

Limitations:

  • global/nonlocal declarations are not modelled: a name an enclosing function declares global is still treated as its local, so a callback through it gets no edge (fails closed).
  • Only scopes linked through scope_parents are walked. A method of a class defined inside a function is already extracted as that function's nested function, so it does see the function's locals (checked: def outer(handler): class K: def m(self): run(handler) no longer binds to another module's handler).

Cache: the Python extractor output changes (fewer indirect_call edges), so it needs an AST cache schema bump. I've left that to the maintainers' release step, as with other extractor changes.

  • Read the CONTRIBUTING.md guide.
  • Reproduced the issue and identified the invariant.
  • Made the smallest fix necessary.
  • Added a regression test (if bug fix) or isolated boundary test.
  • Kept the PR description synchronized with the final implementation.
  • Documented any limitations / unsupported cases explicitly.

How was this tested?

uv run pytest tests/test_python_enclosing_scope_shadow.py   # 7 passed
# without the source change: 2 failed (bug cases), 5 passed (guards)
uv run pytest tests -n auto                                  # 13029 passed, 166 skipped, 5 xfailed
uv run pytest tests/test_architecture_doc.py                 # 38 passed
uv run ruff check .                                          # All checks passed!
uv run pyright                                               # 784 errors, same as v8; engine.py 20 before and after
graphify extract <graphify/ package> --code-only             # 130 indirect_call edges removed, nothing added:
                                                             # 126 into cli's nested source(), 4 others, all captured variables
                                                             # (line in bash.py, call_parts in paths.py, _default_graph_path in serve.py)

Graphify-specific checklist

  • I updated generated skill artifacts (uv run python -m tools.skillgen --bless) when changing their source fragments. (n/a)
  • I confirmed that AST/structural extraction remains deterministic (no ambient state dependencies like ENV variables).
  • I reviewed changes for security implications (no unsafe interpolation into shell/Python).
  • I confirmed no API keys or local-only graph data are included.
  • (If applicable) I disclosed AI authorship in my commit messages.

…raphify-Labs#5658)

The indirect-call guard only knew the caller's own parameters and
locals. A nested function that passed on a variable captured from its
enclosing function (`source` bound in `extract_file`, read in `walk`)
had that name treated as a free reference, and the cross-file resolver
bound it to any same-named function in the corpus. On graphify's own
package this gave a nested `source()` in cli.py 126 fabricated
`indirect_call` edges.

For Python, each nested body now walks with the parameters and locals
of its enclosing functions folded into `extra_locals` (the same channel
Graphify-Labs#5217 uses for JS closures). Class scopes are skipped as in Python. A
name that a nearer scope imports or defines with `def` hides the same
name further out, so a local import and a nested def still resolve.

Tests: tests/test_python_enclosing_scope_shadow.py; the two bug cases
fail without this change, the five guards pass both ways.

Co-Authored-By: Claude Opus 5.5
@ishyverma
ishyverma requested a review from safishamsi as a code owner December 5, 2026 10:16

@graphify-labs graphify-labs Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Graphify review View in Graphify

Review before merging · Merge confidence 4/5

1 bug · High impact

The extractor now adds enclosing Python function bindings to the names that block indirect-call matching.

P2  A middle function’s global declaration changes nested name resolution · engine.py:14934

What this review covered
  • We didn't review 1 file that isn't source code, such as docs, config, images, or generated or third-party code.
  • One review pass used all of its turns for reading code, so it reported from what it had already read.
  • 2 of 2 changed files inspected. This is scope, not a correctness guarantee.
Code graph · 5061 functions depend on this change
  • 1 function became more coupled. _extract_generic() (23 callers).
  • 693 of 693 test files are affected by this change.
  • Gate, test list and every flagged function: in the Graphify check.

Reviewed e6e9fad · 2 earlier findings not re-checked

Comment thread graphify/extractors/engine.py Outdated
Comment on lines +14875 to +14878
scope = scope_parents.get(caller_nid)
while scope and scope not in seen_scopes:
seen_scopes.add(scope)
scope_locals = local_bound_names.get(scope, frozenset())

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2  A global callback can be hidden by an enclosing local

A nested function that declares a name global can lose its indirect-call edge when an enclosing function has a local with the same name.

Exclude names declared global in the nested function from python_enclosing_locals.

Evidence · checked against the code

Expected: The callback name resolves to the module-level binding, and the extractor retains the indirect-call edge to that callable.
Actually: The enclosing local is included in the nested caller’s shadow set, so the indirect-reference guard can suppress the edge.

  • Independent source review: Checked the existing global test and the indirect-argument handler. The test exercises handler() as a direct call and does not pass handler as a callback, so it does not counter this claim.
  • The added tests do not cover global declarations.
  • The omitted edge occurs when the nested function's global name is also locally bound in an enclosing function.
Prompt to fix with AI
In graphify/extractors/engine.py, python_enclosing_locals (lines 14875-14878):
Problem: A `global` callback can be hidden by an enclosing local
Expected: The callback name resolves to the module-level binding, and the extractor retains the indirect-call edge to that callable.
Actually: The enclosing local is included in the nested caller’s shadow set, so the indirect-reference guard can suppress the edge.
Fix it at the cause, and add a test that fails without the fix.

Graphify · Checked against the code · View in Graphify

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in e6e9fad. A name declared global in the nested function (or in a function between it and the outer local) now resolves to the module binding, so the callback edge stays. Covered by test_global_declaration_in_the_nested_function_reaches_the_module_5658 and test_global_declaration_in_a_middle_function_hides_an_outer_local_5658, which both fail without the change.

Comment thread graphify/extractors/engine.py Outdated
Comment on lines +14875 to +14878
scope = scope_parents.get(caller_nid)
while scope and scope not in seen_scopes:
seen_scopes.add(scope)
scope_locals = local_bound_names.get(scope, frozenset())

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2  Comprehension targets hide names in nested functions

A comprehension target in an enclosing function can make the extractor drop a real indirect-call edge from a nested function.

Do not propagate comprehension targets as enclosing function locals in python_enclosing_locals.

Evidence · checked against the code

Expected: The nested function’s reference can resolve to the module-level callable because the comprehension target does not bind in the enclosing function.
Actually: The extractor propagates the target name to the nested function and suppresses the inferred indirect-call edge.

  • Independent source review: The new scope logic accounts for nearer lexical definitions and imports, but the inspected path does not treat comprehension targets as a separate scope or otherwise exclude them. The existing nested-closure test covers JavaScript, not this Python case, so it does not mitigate the reported path.
Prompt to fix with AI
In graphify/extractors/engine.py, python_enclosing_locals (lines 14875-14878):
Problem: Comprehension targets hide names in nested functions
Expected: The nested function’s reference can resolve to the module-level callable because the comprehension target does not bind in the enclosing function.
Actually: The extractor propagates the target name to the nested function and suppresses the inferred indirect-call edge.
Fix it at the cause, and add a test that fails without the fix.

Graphify · Checked against the code · View in Graphify

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in e6e9fad. Comprehension targets of an enclosing function are no longer passed down to nested functions, since they are bound in the comprehension. Covered by test_comprehension_target_does_not_shadow_in_a_nested_function_5658, which fails without the change.

…ows (Graphify-Labs#5658)

The enclosing-locals set added for Graphify-Labs#5658 took each outer function's full
local set, so two cases dropped a real indirect-call edge:

- `global handler` in the nested function (or in a function between it
  and the outer local) names the module binding, but the outer local
  still hid it.
- A comprehension target (`[h for h in xs]`) is bound in the
  comprehension's own scope, yet it was propagated to nested functions.

Enclosing scopes now contribute their locals without comprehension
targets and without names they declare `global`; a `global` name also
hides the same name further out, as in CPython's symtable. Three
regression tests fail without this change.

Co-Authored-By: Claude Opus 5.5
Comment on lines +14931 to +14934
scope_locals = _python_visible_locals(scope)
bound |= scope_locals - claimed
claimed |= scope_locals | _python_scope_claims(scope)
scope = scope_parents.get(scope)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2  A middle function’s global declaration changes nested name resolution

A nested function can be linked to a module callback even when it captures a same-named local from a farther enclosing function.

Keep middle’s global handler scoped to middle in _python_scope_claims.

Evidence · checked against the code

Expected: The nested function captures the farther function’s local binding; the extractor should suppress an indirect edge to a same-named module callback.
Actually: The extractor treats the intervening global declaration as hiding the farther local, allowing a false indirect-call edge to the module callback.

  • Independent source review: Inspected the indirect-reference caller and its shadowing guard: it skips names present in enclosing_locals, and the nested call passes python_enclosing_locals into that guard. In this case the middle function’s global claim wrongly keeps the outer binding out of that set, so the guard does not stop the false edge.
  • Some lookups asked for files or lines that do not exist; the review was told and carried on.
Prompt to fix with AI
In graphify/extractors/engine.py, _python_scope_claims (lines 14931-14934):
Problem: A middle function’s `global` declaration changes nested name resolution
Expected: The nested function captures the farther function’s local binding; the extractor should suppress an indirect edge to a same-named module callback.
Actually: The extractor treats the intervening global declaration as hiding the farther local, allowing a false indirect-call edge to the module callback.
Fix it at the cause, and add a test that fails without the fix.

Graphify · Checked against the code · View in Graphify

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Python: a closure variable passed as an argument fabricates indirect_call to a same-named nested function in another module

1 participant