Skip to content

fix(sql): a CTE name is no longer emitted as a reads_from table (#2577) - #2579

Closed
wilyan09007 wants to merge 2 commits into
Graphify-Labs:v8from
wilyan09007:fix/issue-2577
Closed

wilyan09007 wants to merge 2 commits into
Graphify-Labs:v8from
wilyan09007:fix/issue-2577

Conversation

@wilyan09007

Copy link
Copy Markdown

Addresses the first of the three defects in #2577: a CTE name emitted as a reads_from table target.

The defect

A name bound by WITH <name> AS (...) is scoped to the statement that declares it, so it is not a table. _walk_from_refs has no CTE awareness and emits a reads_from edge for every FROM/JOIN reference it finds, so a reference to the CTE mints a bare _ref_stub.

That is what makes it a cross-language problem rather than a cosmetic one. _ref_stub is deliberately sourceless so a table defined in another file can still resolve at corpus level (#2324, #1402), which means the CTE name enters the graph carrying no schema, file, or language namespace and can collide with a same-named node from any other language.

The fix collects the CTE names declared inside a statement and skips them when walking FROM/JOIN references. Stub IDs themselves are untouched, so cross-file table resolution keeps working.

Reproduction

Worth flagging for anyone verifying this: Reproducer A in the issue does not reach the code being blamed. Its PL/pgSQL CREATE FUNCTION body makes tree-sitter-sql emit a root ERROR node, so extraction takes the recovery path at t == "ERROR", which deliberately does not scan the body for FROM/JOIN ("PL/pgSQL loop variables and locals would produce junk reads_from targets"). On v8 with tree-sitter-sql 0.3.11 that snippet produces no reads_from edges at all.

The same defect does reproduce through a statement the grammar parses, since _walk_from_refs only runs for create_view / create_function / create_procedure nodes that parse cleanly:

CREATE TABLE users (id SERIAL PRIMARY KEY, role TEXT NOT NULL);

CREATE VIEW v_roles AS
  WITH levels AS (SELECT 'admin' AS role)
  SELECT * FROM users JOIN levels ON levels.role = users.role;

Before:

nodes: ['cte2.sql', 'users', 'v_roles', 'levels']
 EDGE reads_from -> 'levels' EXTRACTED

Note levels next to the real nodes: the table and view get fully-qualified ids, the CTE gets the bare name. After the change the levels node and its edge are gone, and the users reference still emits its reads_from edge.

Test

tests/fixtures/sample_cte.sql plus test_sql_cte_is_not_read_as_a_table in tests/test_multilang.py. It asserts the CTE never becomes a node or a reads_from target, and that the real table in the same JOIN still does, so it cannot pass by simply dropping the edges. The test fails on v8 without the change and passes with it.

Scope

This covers only the CTE defect. I could not reproduce the other two on v8 with tree-sitter-sql 0.3.11, and I think they may not be reachable in 0.9.37 at all.

reads_from has exactly three emission sites: two inside the fb_proc_or_trigger branch, which is Firebird syntax and never appears for these files, and _walk_from_refs, which matches from and join nodes only. None of them can turn a column list into a table target, so I do not see how defect 2 (an INSERT column list emitting one edge per column) can occur on this code. Running the reporter's fn_seed_stages() shape produces both function nodes and zero edges. Defect 3 depends on those edges existing, so it goes the same way.

The likely explanation is version skew. The ERROR recovery path stopped scanning bodies for FROM/JOIN in #1910 (2026-07-15), with the comment that loop variables and locals produced junk reads_from targets, which is exactly the shape defect 2 describes. A build predating that would show all three symptoms together.

So defects 2 and 3 may already be fixed rather than outstanding. Confirming that needs the graphify and tree-sitter-sql versions from the environment that produced the report. If they can still be reproduced on 0.9.37 I am happy to take another pass.

Testing notes

python -m pytest tests/test_multilang.py -k sql passes (14 tests). For the wider run I captured a baseline first: on v8 on Windows with only the sql extra installed, tests/test_multilang.py + tests/test_extract.py are already 131 failed / 89 passed before any edit, several of them because tree-sitter-sql is installed at all (test_extract_warns_when_sql_extra_missing asserts the opposite). With this change the failure list is byte-identical and the pass count goes from 89 to 90, the new test.

…hify-Labs#2577)

A name bound by `WITH <name> AS (...)` is scoped to the statement that declares
it, so it is not a table. `_walk_from_refs` had no CTE awareness and emitted a
`reads_from` edge for any FROM/JOIN reference, which for a CTE minted a bare
`_ref_stub`.

Those stubs are deliberately sourceless so a table defined in another file can
still resolve at corpus level, which means the CTE name entered the graph with
no schema, file, or language namespace and collided with any same-named node
from another language.

Collect the CTE names declared inside a statement and skip them when walking
FROM/JOIN references. Real table references in the same clause are unaffected.

@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 reviewed this change.

Worth a look — the grounded gate found no coupling regressions or blocking issues, but 1 advisory finding(s) below merit a look before merge.


Graphify review — findings

This PR modifies the SQL extractor to distinguish common table expressions (CTEs) from actual table references. It adds a _cte_names helper that collects names bound by WITH ... AS (...), and updates _walk_from_refs to skip those names when emitting reads_from edges. A new fixture (sample_cte.sql), a new test, and a changelog entry (#2577) are included to cover the behavior.

Worth a look

  • CTE names computed at wrong scope leak across statements — graphify/extractors/sql.py:335 · Escalate · medium
    • agreed by 2 of 2 members but NOT verified (no proof, no reproducing execution) — consensus is not a verdict; needs human review
Analysis details — impact, health, verification

Impact & health

Graphify review

Impact — 432 functions depend on the 279 functions this change touches.

Health — grade A; 4 existing hotspot(s) in the area this change touches (pre-existing, not introduced here):

  • dispatch_command() — 2 callers, 117 callees (high)
  • extract_sql() — 4 callers, 8 callees (medium)
  • walk() — 1 callers, 8 callees (medium)
  • test_poisoned_manifest_is_healed() — 0 callers, 6 callees (medium)

Verification — 432 functions in the blast radius were not formally verified this run (proofs are advisory here).

Gate & verification

graphify gate

PASS — objectively clean (no health regressions, tests not run — proofs not run this pass (advisory)). Grounded, not self-assessed.

Advisory (not blocking):

  • verification_scope: 289 function(s) in the blast radius were not formally verified this run

· 1 grounded finding(s) anchored inline below.

Comment thread graphify/extractors/sql.py Outdated
Comment on lines 329 to 331
if cte_names is None:
cte_names = _cte_names(node)
if node.type in ("from", "join"):

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

CTE names computed at wrong scope leak across statements — agreed by 2 of 2 members but NOT verified (no proof, no reproducing execution) — consensus is not a verdict; needs human review

Graphify suggests a fix:

Suggested change
if cte_names is None:
cte_names = _cte_names(node)
if node.type in ("from", "join"):
# Recompute per statement: CTE scope ends at the statement that declares it,
# so names must not leak into sibling statements of the same subtree.
if cte_names is None or node.type == "statement":
cte_names = _cte_names(node)
if node.type in ("from", "join"):

The names were collected once for the whole node handed to `_walk_from_refs`.
A SQL-standard routine body (Postgres 14+ `BEGIN ATOMIC`) holds sibling
statements under that node, so a CTE declared in one hid a real table of the
same name from the rest of the body: a later `FROM orders` matched the earlier
CTE and its `reads_from` edge was dropped.

Gather the names per scope on the way down instead, and carry inherited names
inward so a CTE body can still reference a sibling or recursive CTE. A subquery
is scoped the same way, since it brings its own WITH clause.

@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 reviewed this change.

Looks safe to merge — no coupling regressions and no blocking issues, checked against the code graph (not a self-assessment).


Graphify review — findings

This PR adds SQL Common Table Expression (CTE) awareness to the SQL extractor (graphify/extractors/sql.py). It introduces logic to collect names bound by WITH ... AS (...) clauses on a per-scope basis and skips emitting reads_from edges to those names when they appear in FROM/JOIN clauses, with scoping intended to distinguish CTE names from real tables across sibling statements and nested scopes. The change also adds two SQL test fixtures (sample_cte.sql, sample_cte_scope.sql) and two new tests in tests/test_multilang.py covering the CTE-as-table case and the statement-level scoping case, plus a CHANGELOG entry. The surface area is confined to the SQL extractor and its tests.

No blocking issues surfaced. 3 lower-confidence candidates did not survive cross-model review.

Analysis details — impact, health, verification

Impact & health

Graphify review

Impact — 434 functions depend on the 281 functions this change touches.

Health — grade A; 4 existing hotspot(s) in the area this change touches (pre-existing, not introduced here):

  • dispatch_command() — 2 callers, 117 callees (high)
  • extract_sql() — 4 callers, 8 callees (medium)
  • walk() — 1 callers, 8 callees (medium)
  • test_poisoned_manifest_is_healed() — 0 callers, 6 callees (medium)

Verification — 434 functions in the blast radius were not formally verified this run (proofs are advisory here).

Gate & verification

graphify gate

PASS — objectively clean (no health regressions, tests not run — proofs not run this pass (advisory)). Grounded, not self-assessed.

Advisory (not blocking):

  • verification_scope: 291 function(s) in the blast radius were not formally verified this run

safishamsi added a commit that referenced this pull request Aug 9, 2026
…2568, #2565, #2561, #2577, #2575)

These changes are interleaved across engine.py/extract.py by function, so
they land as one batch.

#2568 (thanks @imagineers-tyler): the 0.9.37 #2552 callback-body fix
unioned sibling closures' local names under the shared declaration, so a
local in one callback suppressed a real indirect_call in a sibling. Locals
are now scoped per body (keyed by body id, via walk_calls' extra_locals).
Restore-only, never fabricates; #2552 capture preserved.

#2565 (thanks @kskchaitanya1993): Kotlin property initializers — class,
top-level, companion, and `by lazy {}` — now seed call extraction, so
`val repo = createRepo()` produces a calls edge; literal initializers
produce none; FQ calls compose with the #2550 resolver.

#2561 (thanks @fakewaffle): Swift receiver typing now handles
`@Environment(Store.self)` (whitelisted; @Query/keypath/dotted skipped to
avoid a wrong edge) and in-corpus factory bindings via a marked concrete
return type; opaque/array/out-of-corpus returns stay unresolved.

#2577 (thanks @wilyan09007, PR #2579): the SQL extractor no longer emits a
reads_from edge to a CTE name. WITH names are scoped per query (a subquery
CTE no longer suppresses an outer real table of the same name), so a CTE
no longer mints a bare stub that binds to an unrelated same-named symbol.

#2575 (thanks @phudayyy, PR #2574): a dynamic `import('…')` inside a nested
function or at module scope now produces an edge, dynamic_import is
included in affected, and calls inside nested named functions are
collected; a dynamic import already captured as a deferred imports_from is
not double-counted.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@safishamsi

Copy link
Copy Markdown
Member

Shipped in v0.9.38 (graphifyy==0.9.38). Your CTE-exclusion fix is what landed for #2577, refined so CTE names are scoped per query (a subquery CTE no longer suppresses an outer real table of the same name). Credited in the release notes. Thanks @wilyan09007!

@safishamsi safishamsi closed this Aug 9, 2026
PerryLin-0420 pushed a commit to PerryLin-0420/graphify-decouple that referenced this pull request Aug 13, 2026
…raphify-Labs#2568, Graphify-Labs#2565, Graphify-Labs#2561, Graphify-Labs#2577, Graphify-Labs#2575)

These changes are interleaved across engine.py/extract.py by function, so
they land as one batch.

Graphify-Labs#2568 (thanks @imagineers-tyler): the 0.9.37 Graphify-Labs#2552 callback-body fix
unioned sibling closures' local names under the shared declaration, so a
local in one callback suppressed a real indirect_call in a sibling. Locals
are now scoped per body (keyed by body id, via walk_calls' extra_locals).
Restore-only, never fabricates; Graphify-Labs#2552 capture preserved.

Graphify-Labs#2565 (thanks @kskchaitanya1993): Kotlin property initializers — class,
top-level, companion, and `by lazy {}` — now seed call extraction, so
`val repo = createRepo()` produces a calls edge; literal initializers
produce none; FQ calls compose with the Graphify-Labs#2550 resolver.

Graphify-Labs#2561 (thanks @fakewaffle): Swift receiver typing now handles
`@Environment(Store.self)` (whitelisted; @Query/keypath/dotted skipped to
avoid a wrong edge) and in-corpus factory bindings via a marked concrete
return type; opaque/array/out-of-corpus returns stay unresolved.

Graphify-Labs#2577 (thanks @wilyan09007, PR Graphify-Labs#2579): the SQL extractor no longer emits a
reads_from edge to a CTE name. WITH names are scoped per query (a subquery
CTE no longer suppresses an outer real table of the same name), so a CTE
no longer mints a bare stub that binds to an unrelated same-named symbol.

Graphify-Labs#2575 (thanks @phudayyy, PR Graphify-Labs#2574): a dynamic `import('…')` inside a nested
function or at module scope now produces an edge, dynamic_import is
included in affected, and calls inside nested named functions are
collected; a dynamic import already captured as a deferred imports_from is
not double-counted.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
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.

2 participants