Skip to content

fix(sql): keep writes from a structurally parsed T-SQL procedure (#5146) - #5211

Closed
houyunsun wants to merge 1 commit into
Graphify-Labs:v8from
houyunsun:sql-tsql-procedure-writes
Closed

houyunsun wants to merge 1 commit into
Graphify-Labs:v8from
houyunsun:sql-tsql-procedure-writes

Conversation

@houyunsun

Copy link
Copy Markdown
Contributor

What does this PR do?

Fixes #5146.

tree-sitter-sql 0.3.13 started parsing T-SQL CREATE PROCEDURE ... AS BEGIN ... END into a procedure_body instead of leaving it in an ERROR node. The read side picked that up fine (_walk_from_refs walks FROM/JOIN), but the write side did not: writes_to is only produced by _routine_body_refs, which runs over the masked text when the parse failed. So a procedure that the grammar now understands parses cleanly, gets its node and its reads, and quietly stops recording that it writes anything.

from pathlib import Path
from tempfile import TemporaryDirectory
from graphify.extractors import sql

with TemporaryDirectory() as tmp:
    path = Path(tmp) / "demo.sql"
    path.write_text("CREATE PROCEDURE dbo.D AS\nBEGIN\n DELETE FROM dbo.Payments WHERE Amount = 0\nEND\nGO\n")
    graph = sql.extract_sql(path)
    print([(e["relation"], n["label"]) for e in graph["edges"] for n in graph["nodes"] if n["id"] == e["target"]])

[] on v8, writes_to dbo.Payments on 0.3.11. Same for UPDATE dbo.Orders SET ..., INSERT INTO dbo.Log ..., SELECT ... INTO dbo.Archive and UPDATE o SET ... FROM dbo.Orders o. Four existing tests in tests/test_sql_tsql_procedures.py fail on v8 for exactly this reason.

Type of change

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

Verification & Invariants

  • Invariant: a statement the extractor can see in the tree writes to the same table as the equivalent statement in a file the grammar can't parse. Before this, the answer depended on which tree-sitter-sql version was installed, because the two code paths (masked text vs. tree) disagreed about which statements count.

  • What I did not touch: _walk_from_refs keeps its read logic as-is apart from skipping session temp objects; the write walk is a separate _walk_writes hung off create_procedure / create_function. Its CTE and derived-table rules exist for reasons documented in the file (#2577, #5147) and this change has no business rewriting them.

  • What could regress: a table could now get an extra writes_to next to its reads_from. That's the intended difference — a DELETE's target is not a read of itself, and the tests pin both directions.

  • Depends on the ERROR-node shape only where noted: the #/@ marker of a temp object is a separate ERROR node in 0.3.13, so both the write and the read walk look at the sibling marker rather than the name alone.

  • 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?

$ pytest tests/test_sql_tsql_procedures.py tests/test_sql_go_batches.py \
         tests/test_sql_cross_file_tables.py tests/test_sql_comma_joins_and_dblink.py \
         tests/test_sql_oracle_editionable.py -q
# before: 4 failed, 69 passed, 1 skipped
# after : 78 passed, 1 skipped

$ pytest tests/ -q            # full suite
# 2 failures, both pre-existing on v8 without this branch:
#   tests/test_multilang.py::test_sql_tsql_bracketed_procedure_is_recovered
#   tests/test_multilang.py::test_sql_escaped_double_quote_in_routine_name_is_consumed
#   (both come from `@BatchId INT` in the routine header, not the body)

$ ruff check graphify/extractors/sql.py tests/test_sql_tsql_procedures.py
All checks passed!

The five new tests in tests/test_sql_tsql_procedures.py cover the report's DELETE, the same statement without a trailing GO (so no ERROR node arms the masked scan at all), INSERT/UPDATE/SELECT ... INTO in one procedure, the alias target UPDATE o SET ... FROM x o, and temp tables staying out of the graph. All five fail on v8.

Graphify-specific checklist

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

Limitations

DELETE p FROM dbo.Payments p JOIN dbo.Orders o ON ... still lands its whole FROM in an ERROR node, with the table names swallowed inside it. 0.3.13 can't give the target back, so that shape produces no write edge — and, importantly, no bogus reads_from either. Recovering it would mean parsing the ERROR text, which is a different (and larger) change than this one; I left it alone and noted it here rather than guess.

tree-sitter-sql 0.3.13 parses `CREATE PROCEDURE ... AS BEGIN ... END` into a
`procedure_body` instead of leaving the statement in an ERROR node. That is
good news for reads, but it moved the body out of the masked-text scan that
produces `writes_to`, and `_walk_from_refs` only ever looked at FROM/JOIN —
so DELETE/UPDATE/INSERT and `SELECT ... INTO` in a T-SQL procedure silently
lost their edges. Nothing raises; the procedure still gets its node and its
reads, it just looks like it never writes anything.

`DELETE FROM dbo.Payments` is the report, but the same walk also drops
`UPDATE dbo.Orders SET ...`, `INSERT INTO dbo.Log ...`, `SELECT ... INTO
dbo.Archive` and `UPDATE o SET ... FROM dbo.Orders o`. Four tests in
tests/test_sql_tsql_procedures.py were failing on v8 for this reason.

`_walk_writes` reads the write targets off the tree, next to the existing
read walk rather than inside it — that one's CTE and derived-table handling
shouldn't be disturbed for this. It knows the three shapes the grammar uses
for a target (a `relation`, a naked object_reference after INSERT's
keyword_into, and the sibling FROM that DELETE keeps its table in) and folds
an alias-only target back onto the FROM relation that declares it.

Two related bits while in there: a `#temp` / `##temp` / `@tablevar` is not a
schema object, and 0.3.13 now splits the `#`/`@` marker off into an ERROR
node, so both the write target and the read walk were minting bare names
(`work`, `shared`) as tables.

Known gap, unrelated to this walk: `DELETE p FROM dbo.Payments p JOIN ...`
still puts the whole FROM into an ERROR node, so the target is unrecoverable
there — the statement produces no write edge and no bogus one either.
@github-actions

Copy link
Copy Markdown

Thanks for the pull request, @sunhouy. 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.10 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 Nov 14, 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 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.

Not checked: tests were not run; formal verification proved 0 of 1 changed function(s) (1 sampled, not proven).

Formal verification. PR-changed functions: 1/1 verified (0 proven, 1 may-equivalent, 0 distinguished) · 0 not verified.


Graphify review — findings

Adds writes_to edges for DELETE/UPDATE/INSERT/MERGE and SELECT ... INTO inside structurally parsed T-SQL procedures and functions, which lost them once tree-sitter-sql 0.3.13 stopped sending these bodies through the masked-text fallback (#5146). _write_table resolves the target, including aliased forms like UPDATE o SET ... FROM x o back to the FROM relation, and _table_of treats a lone single-part name as an alias, so a plain single-name UPDATE target can lose its write edge. Temp tables and table variables (#t, ##t, @t) are now skipped for both writes and FROM/JOIN reads instead of being minted as tables, and the new tests cover GO-separated procedures, CTEs, bracketed names and the DELETE FROM no-self-read case.

Worth a look

  • Plain single-name UPDATE target is misread as an alias, so the write edge is dropped — graphify/extractors/sql.py:857 · Escalate · high
    • NOT verified (no proof, no reproducing execution) — needs human review
Analysis details — impact, health, verification

Impact & health

Graphify review

Impact — 3208 functions depend on the 69 functions this change touches.

Health — this change adds coupling hotspots:

  • worse: extract_sql() — 55 callers, 13 callees
  • worse: walk() — 1 callers, 10 callees
  • new: _walk_writes() — 1 callers, 6 callees

Verification — 3208 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: 1631 function(s) in the blast radius were not formally verified this run

Test selection

Test selection

8 of 564 test file(s) selected (1%) via static blast radius.

  • tests/test_extract.py — impact
  • tests/test_multilang.py — impact
  • tests/test_pg_introspect.py — impact
  • tests/test_python_member_call_language_gate.py — impact
  • tests/test_sql_comma_joins_and_dblink.py — impact
  • tests/test_sql_go_batches.py — impact
  • tests/test_sql_oracle_editionable.py — impact
  • tests/test_sql_tsql_procedures.py — impact, changed-test

Selection is safe under the controlled-regression assumption; always-run tests + a periodic full run are the backstops. Advisory — it never changes the check verdict.

Formal verification

No difference found (not proven): No behavior difference found in extract\_sql (not a proof).

The verifier ran both versions of extract\_sql on many inputs and saw identical behavior every time. Strong evidence the change is safe, but evidence, not a proof.

Guarantee: Empirical: differential testing (both versions run on many generated inputs). A divergence on an untested input remains possible, so this is 'no counterexample found', not 'proven equivalent'.

Note: An input the sampler did not try could still differ.

· 1 grounded finding(s) anchored inline below; 2 more finding(s) on lines outside this diff (see the check run).

return r_tbl
return None

def _walk_writes(node, caller_nid: str) -> None:

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Health regression — _walk_writes()

fans out to 6 callees (efferent coupling).

Grounded coupling-delta finding (deterministic), not an LLM guess.

@safishamsi

Copy link
Copy Markdown
Member

Landed on v8 as e477379 via authorship-preserving cherry-pick, released in graphify 0.9.110. Thanks @sunhouy.

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.

SQL: tree-sitter-sql 0.3.13 drops writes from parsed T-SQL procedures

2 participants