Skip to content

fix(sql): one routine node for partially parsed T-SQL procedure headers (#5236) - #5324

Open
Deepjyoti-Sarmah wants to merge 5 commits into
Graphify-Labs:v8from
Deepjyoti-Sarmah:fix/5236-sql-partial-routine
Open

Deepjyoti-Sarmah wants to merge 5 commits into
Graphify-Labs:v8from
Deepjyoti-Sarmah:fix/5236-sql-partial-routine

Conversation

@Deepjyoti-Sarmah

Copy link
Copy Markdown
Contributor

What does this PR do?

Fixes #5236. On tree-sitter-sql 0.3.12 and later, one T-SQL CREATE PROCEDURE can produce two routine nodes. The second one has a broken name, and every read and write edge is attached to both.

The SQL extractor names a routine in two places:

extract_sql
  walk(tree)                      name = the grammar's object_reference text
  if root.has_error
    recovery scan (regex on text)  name = the regex capture
  _add_node merges the two by id

The merge only works if both places read the same name. Up to 0.3.11 the grammar had no parse for T-SQL's AS BEGIN ... END body, so the whole header was one ERROR node and only the recovery scan named the routine. From 0.3.12 the grammar parses the header as create_procedure, but it reads the name wrong:

header grammar's object_reference node minted by the walk
[dbo].[usp_Load] + @BatchId INT dbo].[usp_Load]\n @BatchId INT dbo.usp_Load@BatchId INT()
p @x INT INT INT()
"dbo"."a""b" "dbo"."a", then "b" as a separate ERROR node "dbo"."a"()
[a]]b] b b()

The recovery scan reads each of these correctly, so the file ends up with two ids for one declaration. A profiler trace (sys.setprofile on _add_node/_add_edge) on the issue's bracketed input shows the walk adding the bad node with reads_from and writes_to at sql.py:733, and recovery adding the good node with the same two edges at sql.py:1239.

The fix is in the recovery loop:

 for each CREATE FUNCTION/PROCEDURE match in the masked text
   fn_nid = id of the regex name
+  for each routine the walk added on this line under another id
+    remove it, its edges, and its routine_nids entries
   from_tree = fn_nid already exists
   add fn_nid
   if from_tree: skip the body scan
   scan the body for reads and writes

Because the walk's node is removed, recovery owns the routine and derives its edges from the body text, the same way it did on 0.3.11.

Why the walk's edges are dropped too

The walk's edges for a misread routine can't be trusted either. test_procedure_write_makes_a_non_read_edge[MERGE] passes on v8 only because of the duplicate. For CREATE PROCEDURE dbo.W @id INT AS BEGIN MERGE INTO dbo.Payments ..., the walk's node has no edges at all, and the writes_to dbo.Payments edge comes from the recovery node. A fix that only corrected the walk's name (so recovery saw the id as already found and skipped its body scan) broke that test. I tried it.

Three commits

304c8321  test(5236): pin one routine node for partially parsed SQL headers
0fb14ba7  fix(5236): drop the walk's misread routine when recovery names it
e2aa55f6  docs(5236): stop claiming AS BEGIN bodies never parse

The tests go in first and fail on their own. Reverting 0fb14ba7 removes the fix and leaves the tests, which then fail. The last commit only corrects a code comment and two test docstrings that said AS BEGIN never parses.

Type of change

  • Bug fix
  • New feature
  • Documentation (comment and docstrings only)
  • Tests or CI
  • Refactor
  • Security fix

Verification & Invariants

Invariant: one declaration gives one routine node, named the way the source text spells it, with each edge once.

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

Merge Danger

Door: two-way. No schema, id format or cache change. Reverting 0fb14ba7 restores v8 behaviour.

Blast Radius: small.

  • The new code only runs when the file has a parse error, and then only removes a walk routine that is on the same line as a recovered CREATE and has a different id.
  • On 0.3.11 the walk never mints a misread T-SQL routine, so nothing is removed.
  • Output for every .sql fixture under tests/ is identical to v8 on both 0.3.11 and 0.3.13. I compared every node and edge.
  • Ids of correctly named routines don't change. Graphs built on 0.3.12+ lose the bad duplicate node; that's the fix.

Limitations

  • The link between the two paths is the line number. It held for two procedures on one line, a comment inside the header, a multi-line header and CREATE OR ALTER. A routine whose CREATE keyword and grammar node start on different lines would not be matched. I haven't found such a shape.
  • Not fixed here: partially parsed PL/pgSQL functions miss body reads. For get_user in tests/fixtures/sample.sql, RETURN QUERY SELECT * FROM users gives no reads_from users edge on v8, on either grammar. Letting recovery also scan the bodies of error-bearing routines would add that edge, but it changes output outside this issue, so it belongs in its own issue.
  • Separate body-boundary bug. With two procedures on one line, the first one also picks up the second one's reads and writes. That happens on v8 with 0.3.11 too.

How was this tested?

Before and after, the issue's own script on tree-sitter-sql 0.3.13:

before  bracketed.sql ['dbo.usp_LoadDebtors()', 'dbo.usp_LoadDebtors@BatchId INT()']
        quoted.sql    ['"dbo"."a""b"()', '"dbo"."a"()']
after   bracketed.sql ['dbo.usp_LoadDebtors()']
        quoted.sql    ['"dbo"."a""b"()']

New tests in tests/test_multilang.py. Each asserts exactly one routine node with the full name, and that its reads_from/writes_to edges appear once:

test_sql_partially_parsed_routine_header_yields_one_node
  CREATE PROCEDURE p @x INT          -> p()
  CREATE PROCEDURE s.p @x INT        -> s.p()
  CREATE PROCEDURE [s].[p] @x INT    -> s.p()
  CREATE PROCEDURE "a""b"            -> "a""b"()
  CREATE PROCEDURE "s"."a""b"        -> "s"."a""b"()
  CREATE PROCEDURE [a]]b]            -> a]b()
test_sql_escaped_quote_function_name_yields_one_node
  CREATE FUNCTION "a""b"() ...       -> "a""b"()   (already broken on 0.3.11)

SQL tests (-k sql) at each commit, under both grammar versions:

commit tree-sitter-sql 0.3.11 tree-sitter-sql 0.3.13
v8 340268a7 (no new tests) 149 passed 145 passed, 2 failed (the two from the issue)
304c8321 tests 155 passed, 1 failed 145 passed, 9 failed
0fb14ba7 fix 156 passed 154 passed
e2aa55f6 docs 156 passed 154 passed

I measured three other fixes against the same tests before settling on this one:

candidate result
skip the walk's name when the tree shows an error near it fails p @x INT: the grammar reads INT with no error near the name
take the walk's name from the recovery regex breaks the MERGE write test (see above)
regex name, plus a body scan for error-bearing routines passes, but adds the get_user edge above, outside this issue

Full suite on 0.3.13: 11034 passed, 71 failed. All 71 also fail on v8 340268a7 in the same environment. They're Terraform, Pascal, C# and install tests, and this venv lacks the optional tree_sitter_hcl, tree_sitter_pascal and tree_sitter_language_pack grammars. No SQL test fails.

ruff check graphify/extractors/sql.py tests/test_multilang.py  -> All checks passed

Not tested: tree-sitter-sql releases before 0.3.11, and Windows. The change adds no path handling.

Graphify-specific checklist

  • I updated generated skill artifacts (uv run python -m tools.skillgen --bless) when changing their source fragments. (N/A: no skill fragments touched.)
  • I confirmed that AST/structural extraction remains deterministic (no ambient state dependencies like ENV variables). (The removal depends only on the parse tree and the source text.)
  • 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. (No trailer in the commit messages.)

From tree-sitter-sql 0.3.12 a T-SQL CREATE PROCEDURE header can partially
parse with a misread name: unparenthesised params absorbed or taken as the
name, a ""/]] escape truncating it. Each case must yield one routine node
with the full name and no doubled reads/writes. The CREATE FUNCTION "a""b"
case already fails on 0.3.11.
The tree walk and the whole-file recovery scan named one declaration twice
when the grammar misread a partially parsed routine header, leaving two
routine nodes and two copies of their edges. A walk routine on the same line
as a recovered CREATE under a different id is that misread: remove it, its
edges and its name lookups, and let recovery own the node and its refs.
The grammar partially parses T-SQL AS BEGIN...END procedures from
tree-sitter-sql 0.3.12, so update the recovery regex comment and the two
regression test docstrings that relied on the old behaviour.
@github-actions

Copy link
Copy Markdown

Thanks for the pull request, @Deepjyoti-Sarmah. 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 Nov 18, 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 code review View in Graphify

Review completed · 260a359527d9

Note

Merge confidence: 5/5 · Nothing blocking · 2 possible issues to check · 🟠 High impact
2 possible issues not confirmed

The SQL recovery scan now uses recovered names by line to distinguish parser-created routines with misread names.

Full summary

The SQL recovery scan now uses recovered names by line to distinguish parser-created routines with misread names. It removes unmatched parser nodes and edges, then adds the recovered routine and derives its table references.

No confirmed issues. We found 2 possible issues we couldn't confirm; see below.

Not confirmed (2 possible issues)

Leads worth a look; we didn't double-check these. They don't change the score.

Not confirmed · The trigger executes edge check is skipped on tree-sitter-sql 0.3.12 and later, so that edge is never verified there Inspect source

Detailed review · not confirmed

The test asserts the executes edge only when the installed grammar is older than 0.3.12. On newer grammars the check is skipped silently, so the test passes without checking the trigger edge.

The gate if not _ts_sql_at_least((0, 3, 12)) depends only on the grammar version. The comment says the trigger is only recovered on newer grammars and that recovery emits no executes edge there, but the test never asserts what the newer path does. The gate should key on whether the walk parses the trigger, or the test should assert the expected edge set for each grammar version.

  • Not checked: whether the installed grammar version actually parses the trigger on the walk path

  • Not checked: the expected edge set for grammars at 0.3.12 and later

  • Found by the per-file sweep; not double-checked.

Not confirmed · A genuine routine sharing a CREATE line with a misread one can be deleted when the recovery regex does not match it Inspect source

Detailed review · not confirmed

The cleanup loop drops any tree-built routine on a line whose id is not among the regex matches on that line, so a real second routine on the same line can be removed.

recovered_on_line is built only from routine_matches (lines 1237-1241), but the tree-built nodes come from the walk. The comment at lines 1234-1236 says the other routine on a shared line is real, yet the filter at lines 1253-1254 removes any walk node whose id is not in that regex set. If the tree parsed a routine the regex misses, nothing recreates it, and lines 1255-1260 delete its node, edges and routine_nids entry.

  • Did not verify whether tree-sitter-sql can produce a tree routine on the same line that the regex skips

  • Did not inspect the walk code that populates structured_routine_lines and routine_nids

  • Found by the per-file sweep; not double-checked.

Code graph and static checks · 3511 functions depend on this change

Impact & health

Impact — 3511 functions depend on the 217 functions this change touches.

Health — this change adds coupling hotspots:

  • worse: extract_sql() — 62 callers, 14 callees

Formal checks — 3511 functions this change can affect weren't formally checked in this review. Formal checks are informational only.

Gate & verification

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

Advisory (not blocking):

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

Test selection

10 of 593 test file(s) selected (2%) via static blast radius.

  • tests/test_extract.py — impact
  • tests/test_multilang.py — impact, changed-test
  • 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_non_ascii_table_names.py — impact
  • tests/test_sql_oracle_editionable.py — impact
  • tests/test_sql_oracle_packages.py — impact
  • tests/test_sql_tsql_procedures.py — impact

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.

Every flagged function

  • extract_sql() in graphify/extractors/sql.py:550 · 62 callers, 14 callees: fans out to 14 callees (efferent coupling); 62 callers depend on it (afferent coupling)

Recovery dropped every walk routine on a CREATE's line whose id differed
from the match, so a correctly parsed neighbour lost its node and the
trigger's executes edge. Drop only ids no recovery match on that line names.
@Deepjyoti-Sarmah

Copy link
Copy Markdown
Contributor Author

Confirmed the P2 and fixed in 1d1d142. It was a bit wider than reported: the same-line neighbour lost its node too, not only the trigger's executes edge (e.g. CREATE FUNCTION b() ... $$; CREATE PROCEDURE p @x INT AS SELECT 1; on one line dropped b).

Recovery now collects every id the scan finds on each line first, and drops a walk routine only when no match on its line names it. The misread header is still dropped; a real routine sharing the line is kept with its edges and routine_nids entry.

Added test_recovery_keeps_a_real_routine_sharing_the_misread_line: fails before, passes after. SQL/extract suites: 588 passed.

…gger

From tree-sitter-sql 0.3.12 the trigger in this test is only recovered,
and recovery emits no executes edge; v8 gives none there either. CI runs
0.3.11, so this passed there and failed locally on 0.3.12/0.3.13. The
label check, which catches the dropped neighbour routine, still runs on
every version.

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.

SQL: partially parsed procedure headers produce duplicate and malformed routine nodes with tree-sitter-sql 0.3.13

1 participant