Repository navigation
fix(sql): a CTE name is no longer emitted as a reads_from table (#2577) - #2579
wilyan09007 wants to merge 2 commits into
Conversation
…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.
There was a problem hiding this comment.
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.
| if cte_names is None: | ||
| cte_names = _cte_names(node) | ||
| if node.type in ("from", "join"): |
There was a problem hiding this comment.
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:
| 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.
There was a problem hiding this comment.
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
…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]>
|
Shipped in v0.9.38 ( |
…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]>
Addresses the first of the three defects in #2577: a CTE name emitted as a
reads_fromtable 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_refshas no CTE awareness and emits areads_fromedge for everyFROM/JOINreference 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_stubis 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/JOINreferences. 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 FUNCTIONbody makes tree-sitter-sql emit a rootERRORnode, so extraction takes the recovery path att == "ERROR", which deliberately does not scan the body forFROM/JOIN("PL/pgSQL loop variables and locals would produce junk reads_from targets"). Onv8with tree-sitter-sql 0.3.11 that snippet produces noreads_fromedges at all.The same defect does reproduce through a statement the grammar parses, since
_walk_from_refsonly runs forcreate_view/create_function/create_procedurenodes that parse cleanly:Before:
Note
levelsnext to the real nodes: the table and view get fully-qualified ids, the CTE gets the bare name. After the change thelevelsnode and its edge are gone, and theusersreference still emits itsreads_fromedge.Test
tests/fixtures/sample_cte.sqlplustest_sql_cte_is_not_read_as_a_tableintests/test_multilang.py. It asserts the CTE never becomes a node or areads_fromtarget, and that the real table in the sameJOINstill does, so it cannot pass by simply dropping the edges. The test fails onv8without the change and passes with it.Scope
This covers only the CTE defect. I could not reproduce the other two on
v8with tree-sitter-sql 0.3.11, and I think they may not be reachable in 0.9.37 at all.reads_fromhas exactly three emission sites: two inside thefb_proc_or_triggerbranch, which is Firebird syntax and never appears for these files, and_walk_from_refs, which matchesfromandjoinnodes 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'sfn_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
ERRORrecovery path stopped scanning bodies forFROM/JOINin #1910 (2026-07-15), with the comment that loop variables and locals produced junkreads_fromtargets, 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
graphifyandtree-sitter-sqlversions 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 sqlpasses (14 tests). For the wider run I captured a baseline first: onv8on Windows with only thesqlextra installed,tests/test_multilang.py+tests/test_extract.pyare 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_missingasserts the opposite). With this change the failure list is byte-identical and the pass count goes from 89 to 90, the new test.