Skip to content

fix(python): shadow enclosing-scope variables and skip unreachable nested defs in indirect_call - #5681

Open
m3lonxd wants to merge 2 commits into
Graphify-Labs:v8from
m3lonxd:fix/python-closure-indirect-call
Open

m3lonxd wants to merge 2 commits into
Graphify-Labs:v8from
m3lonxd:fix/python-closure-indirect-call

Conversation

@m3lonxd

@m3lonxd m3lonxd commented Dec 1, 2026

Copy link
Copy Markdown
Contributor

What does this PR do?

Fixes #5658 by closing both causes of fabricated indirect_call edges when nested Python functions pass closure-captured variables as call arguments or return/collection values:

  1. Python enclosing-scope variable shadowing (LEGB) in graphify/extractors/engine.py:
    • Unpacks as_pattern_target in _python_collect_assignment_targets and reads as_pattern aliases inside with_item and except_clause in _python_local_bound_names.
    • Walks scope_parents for nested Python functions when dispatching function_bodies into walk_calls, folding enclosing bound names into extra_locals.
    • Walks lexical_nids_by_scope first for Python in _emit_indirect_by_name, preventing another function's nested helper from matching via the file-wide label_to_nid fallback while leaving own-scope nested callbacks (def outer(): def cb(): ...; pool.submit(cb)) intact.
  2. Nested helper cross-file reachability guard in graphify/extract.py:
    • Builds function_nested_owner from contains edges (across both all_edges and resolution_context_edges for incremental runs) whose source is a non-class _callable.
    • Filters unreachable a.<locals>.b targets out of cross-file indirect_call candidate resolution before the single-candidate / tie-breaker step, so nested helpers neither create phantom cross-module edges nor interfere with real top-level targets.

Type of change

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

Verification & Invariants

Protects lexical shadowing (LEGB) and module/function boundary reachability:

  • Captured variables in enclosing Python scopes never fabricate indirect_call edges to unrelated same-named callables.

  • Functions nested inside another non-class callable (a.<locals>.b) cannot be referenced by bare name from another module or an unrelated function, on both cold and incremental rebuilds.

  • Measured on graphify/ (109 Python files): indirect_call edges targeting graphify_cli_placeholder_stale_sources_source (graphify/cli.py:L657) drop from 124 to 0.

  • 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 --frozen pytest tests/test_python_closure_indirect_call_5658.py tests/test_indirect*.py tests/test_issue_3405*.py tests/test_python_local_import_call_shadowing_5421.py tests/test_python_lambda_call_shadowing.py -q
-> 154 passed (new #5658 tests fail 4/6 on unmodified upstream/v8 and pass 6/6 with the fix)

uv run --frozen ruff check graphify/extractors/engine.py graphify/extract.py tests/test_python_closure_indirect_call_5658.py
-> All checks passed!

uv run --frozen pyright tests/test_python_closure_indirect_call_5658.py
-> 0 errors, 0 warnings, 0 informations

Dogfood extract on graphify/*.py (109 files):
-> node=graphify_cli_placeholder_stale_sources_source indirect_call=0 (down from 124)

Graphify-specific checklist

  • I updated generated skill artifacts (uv run python -m tools.skillgen --bless) when changing their source fragments. (Not applicable — no skill fragments changed.)
  • 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.

…sted defs in indirect_call

Closes Graphify-Labs#5658.

1. Unpack `as_pattern_target` in `_python_collect_assignment_targets` and
   `as_pattern` in `with_item` / `except_clause` inside
   `_python_local_bound_names`.
2. Walk enclosing `scope_parents` when entering Python `function_bodies` in
   `extractors/engine.py` so closure-captured variables shadow corpus-wide
   `indirect_call` targets per Python LEGB scoping.
3. Walk `lexical_nids_by_scope` for Python in `_emit_indirect_by_name` while
   excluding other functions' nested defs from file-wide `label_to_nid` fallback.
4. Build `function_nested_owner` from non-class callable `contains` edges in
   `extract.py` so `a.<locals>.b` helpers never resolve as cross-file
   `indirect_call` targets (on both full and incremental builds).

Co-Authored-By: Antigravity <[email protected]>
@m3lonxd
m3lonxd requested a review from safishamsi as a code owner December 1, 2026 07:15
@github-actions

github-actions Bot commented Dec 1, 2026

Copy link
Copy Markdown

Thanks for the pull request, @m3lonxd. A maintainer will review it soon.

Want to talk it through while it is in review? Come join us on our Discord server. For longer-form discussion there is also GitHub Discussions.

A couple of things that speed up review: make sure the test suite passes on Python 3.11 and 3.13, and that the change keeps extraction deterministic.

@github-actions github-actions Bot added the contributor Pull request from a returning community contributor label Dec 1, 2026

@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

P2  Global names in outer functions are mistaken for captured locals · engine.py:14632

What this review covered
  • Some lookups asked for files or lines that do not exist; the review was told and carried on.
  • 3 of 3 changed files inspected. This is scope, not a correctness guarantee.
Code graph · 6080 functions depend on this change
  • 2 functions became more coupled. extract() (1455 callers), _extract_generic() (23 callers).
  • 391 of 666 test files are affected by this change.
  • Gate, test list and every flagged function: in the Graphify check.

Reviewed f85bb1a · 1 earlier finding not re-checked

Comment on lines +14590 to +14593
anc = scope_parents.get(caller_nid)
while anc is not None and anc not in seen:
seen.add(anc)
bound |= local_bound_names.get(anc, set())

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  Global callbacks can disappear when an enclosing function binds the same name

A nested function that declares a name global can lose its indirect-call edge when an enclosing function binds that name.

Exclude global-declared names from _python_enclosing_bound_names.

Evidence · checked against the code

Expected: The reference resolves to the module-level callable and an indirect-call edge is emitted.
Actually: The ancestor walk adds the enclosing binding to extra_locals; the indirect-reference guard skips the name and omits the edge.

  • Independent source review: The existing global test uses a direct handler() call and asserts calls edges; it does not exercise passing handler as a callback, where the new ancestor-name set reaches the indirect-reference shadow guard.
  • The new tests exercise captured names but not a nested global declaration.
Prompt to fix with AI
In graphify/extractors/engine.py, _python_enclosing_bound_names (lines 14590-14593):
Problem: Global callbacks can disappear when an enclosing function binds the same name
Expected: The reference resolves to the module-level callable and an indirect-call edge is emitted.
Actually: The ancestor walk adds the enclosing binding to `extra_locals`; the indirect-reference guard skips the name and omits the edge.
Fix it at the cause, and add a test that fails without the fix.

Graphify · Checked against the code · View in Graphify

…ocal-import calls

Threads Python enclosing-function bound names via `py_indirect_locals` solely to
indirect-reference checks (`_emit_indirect_ref`) and subtracts the inner body's
own imports / `global` statements, keeping direct-call local-import resolution
(`test_local_import_over_parameter_keeps_its_edge`) intact.

Co-Authored-By: Antigravity <[email protected]>
Comment on lines +14629 to +14632
anc = scope_parents.get(caller_nid)
while anc is not None and anc not in seen:
seen.add(anc)
bound |= local_bound_names.get(anc, set())

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  Global names in outer functions are mistaken for captured locals

A nested function can lose its indirect_call edge to a module-level callable when an enclosing function assigns that name after declaring it global.

Exclude ancestor global declarations from _python_enclosing_bound_names.

Evidence · checked against the code

Expected: The nested function's reference resolves as a module-global name and is not shadowed as an enclosing local.
Actually: The ancestor assignment adds target to the nested function's indirect-local shadow set, so the extractor can omit the indirect_call edge to the module-level callable.

  • Independent source review: Checked the indirect-reference guard and the nested-function scope setup. The guard does skip a name found in enclosing_locals, but no inspected path removes an ancestor's global declaration from that set. The inspected nested-closure tests exercise JavaScript, not this Python case.
Prompt to fix with AI
In graphify/extractors/engine.py, _python_enclosing_bound_names (lines 14629-14632):
Problem: Global names in outer functions are mistaken for captured locals
Expected: The nested function's reference resolves as a module-global name and is not shadowed as an enclosing local.
Actually: The ancestor assignment adds `target` to the nested function's indirect-local shadow set, so the extractor can omit the `indirect_call` edge to the module-level callable.
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

contributor Pull request from a returning community contributor

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