Skip to content

fix(sql): strip T-SQL brackets and add reads_from/writes_to edges for procedures (#4635) - #4649

Closed
Deepjyoti-Sarmah wants to merge 2 commits into
Graphify-Labs:v8from
Deepjyoti-Sarmah:fix/4635-tsql-procedures
Closed

Deepjyoti-Sarmah wants to merge 2 commits into
Graphify-Labs:v8from
Deepjyoti-Sarmah:fix/4635-tsql-procedures

Conversation

@Deepjyoti-Sarmah

Copy link
Copy Markdown
Contributor

What does this PR do?

Fixes #4635. On a T-SQL project the SQL graph was close to empty:

  1. Bracket names were mangled. [dbo].[Country] got the label dbo].[Country, and it never matched dbo.Country.
  2. Stored procedures had no reads_from edges, in any dialect.
  3. INSERT/UPDATE/DELETE/MERGE made no edge.

Both come from the grammar. tree-sitter-sql 0.3.11 has no T-SQL bracket identifiers: the outer [ and ] become ERROR tokens, and the name it keeps is dbo].[Country. It also has no create_procedure node at all, so the create_procedure branch in sql.py never runs. Even CREATE PROCEDURE p AS SELECT a FROM t1; lands in an ERROR node. The regex recovery then adds the procedure node, and nothing adds its edges. Without ; between statements, the grammar also merges the body, so the tree has no insert or update node to read.

So this PR reads procedure bodies as text, not from the tree:

 extract_sql
   labels and lookup keys
+    strip [ ] from each name part: [dbo].[Orders] -> dbo.Orders, [a]]b] -> a]b
   routine recovery (_ROUTINE_RECOVERY_RX, when the parse has errors)
     add routine node
+    body = after its name, up to the next CREATE/ALTER line, a GO line, or EOF
+    scan the body on the masked text (comments and strings blanked)
+      FROM / JOIN                                          -> reads_from
+      INSERT [INTO] / UPDATE / DELETE [FROM] / MERGE [INTO] / SELECT ... INTO -> writes_to
+      UPDATE o ... FROM dbo.Orders o                        -> alias resolves to dbo.Orders
+      skip CTE names, @variables, #temp/##temp, table-valued function calls
+    one edge per (routine, relation, table)

Ids don't change: _make_id already dropped the brackets, so only labels and in-file matching were wrong. Double-quoted names ("dbo"."V") keep their labels. Routines the tree parses cleanly (PostgreSQL $$ functions) keep their tree-based edges and aren't scanned a second time.

Before (the issue's repro, v8, graphify update .):

dbo].[Country reads_from dbo].[tbl_Country
(3 procedures: contains only)

After:

dbo.Country               reads_from  dbo.tbl_Country
dbo.GetOrderTotal()       reads_from  dbo.Orders
dbo.GetOrderTotal()       reads_from  dbo.Payments
dbo.GetOrderTotalPlain()  reads_from  dbo.Orders
dbo.GetOrderTotalPlain()  reads_from  dbo.Payments
dbo.AddPayment()          writes_to   dbo.Orders
dbo.AddPayment()          writes_to   dbo.Payments

Type of change

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

writes_to is a new relation. Nothing outside sql.py lists relation names, so it needs no registration.

Verification & Invariants

A procedure has a reads_from edge to each table it reads and a writes_to edge to each table it writes, and none to aliases, variables, temp tables, CTEs, or names in comments and strings. A name gets the same label and key with or without brackets.

  • 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. Ids are unchanged. _AST_CACHE_SCHEMA goes 20 -> 21 so cached .sql extractions re-run, and a revert re-runs them again. #4572 and #4573 also take 21, so whichever lands second needs 22.

Blast Radius: SQL only. On microsoft/sql-server-samples wide-world-importers/wwi-ssdt (336 .sql files):

v8 this PR
nodes 739 1011
non-contains edges 146 465
time (median of 3) 5.7 s 5.8 s
  • Removed: no v8 edge. The edges that show as removed in a text diff are the same edges with bracket-free labels.
  • Added: 190 reads_from and 129 writes_to. All 319 were checked against the source: 314 have the keyword right before the table name, and 5 are UPDATE sih ... FROM Warehouse.StockItemHoldings AS sih alias updates.
  • False positives: none among the 61 distinct targets. 13 are sys.* catalog views, which are real references. 36 edges sit on routines that only exist because of the mask's known multi-line-string hole (Configuration_*InMemory.sql build procedures inside multi-line N'...' strings).
  • Existing tests: 10 assertions in test_multilang.py change their expected routine label to the bracket-free form ([dbo].[usp_Real]() -> dbo.usp_Real()). test_sql_tsql_bracketed_procedure_is_recovered now filters to routine nodes, since the procedure's tables now appear as stubs.

Limitations

  • One node per file for undefined tables. A table no file defines, referenced from N files, becomes N stub nodes. In the repro that's three dbo.Orders nodes. v8 does the same. Answering "what writes to dbo.Orders" across a project needs that fixed. Filed as #.
  • GO without ; still swallows the next statement in the tree, so a second CREATE TABLE after GO is lost. Filed as #.
  • When a procedure both reads and writes a table, graph.json keeps one edge per pair, so only writes_to shows. extract() returns both.
  • MERGE ... USING src records no read. TRUNCATE and EXEC aren't modelled. BULK INSERT dbo.T counts as a write.
  • A CREATE/ALTER at the start of a line inside a body (CREATE INDEX ... ON #t) ends the body early. CREATE TABLE #t and CREATE TABLE @t don't.
  • Trigger and index labels keep their brackets.
  • The create_procedure and fb_proc_or_trigger branches are dead on this grammar. They're left as they are.

How was this tested?

New tests in tests/test_sql_tsql_procedures.py run extract() or extract_sql() on small files, including the issue's four, and assert (source, relation, target) triples. None calls a private helper.

Test v8 This PR
T1: [dbo].[Orders] and dbo.Orders in one file are one table fail pass
T2: no half-stripped labels; labels are dbo.Orders, dbo.AddPayment(); [a]]b] -> a]b; "dbo"."V" kept fail pass
T3: each repro procedure reads its tables fail pass
T4: plain CREATE PROCEDURE p AS SELECT ..., with (x INT), with @x INT ... BEGIN END fail pass
T5: INSERT, UPDATE, DELETE, MERGE, SELECT ... INTO give writes_to; DELETE FROM isn't a read fail pass
T9: UPDATE o ... FROM dbo.Orders o writes dbo.Orders fail pass
T10: #work, ##shared, @ids are skipped fail pass
T11: GO-separated procedures keep their own tables; comments and strings are ignored fail pass
guards: aliases, columns, variables, CTEs, two procedures in one file, top-level statements, function and view reads, one edge per triple pass pass

On v8 the guards pass because v8 makes no procedure edges. They catch a fix that attaches too much.

pytest tests/test_sql_tsql_procedures.py (tests on v8)    -> 25 failed, 8 passed
pytest tests/test_sql_tsql_procedures.py (this branch)    -> 33 passed
pytest test_multilang.py test_pg_introspect.py test_extract.py -> 448 passed
pytest -q -p no:randomly (full suite, --basetemp=/var/tmp) -> 8504 passed, 14 skipped
ruff check (changed files)                                 -> All checks passed

The cache bump was checked on the repro: a v8 run writes the cache, then this branch with the schema forced back to 20 serves the old labels and the single edge. At 21 it re-extracts and gives the 7 edges above.

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

…Labs#4635)

Bracket names like [dbo].[Orders] come out as the label `dbo].[Orders`,
stored procedures get no reads_from edges in any dialect, and
INSERT/UPDATE/DELETE/MERGE make no edge. Guards cover aliases, CTEs,
temp tables, variables, comments, strings and body boundaries.
…#4635)

tree-sitter-sql has no T-SQL bracket identifiers and no create_procedure
node, so bracket names were mangled and procedures only got a node from
the regex recovery, never an edge. Labels and lookup keys now drop the
brackets (ids are unchanged). Each recovered routine's body, up to the
next CREATE/ALTER, a GO line or EOF, is scanned on the masked text:
FROM/JOIN give reads_from, and INSERT/UPDATE/DELETE/MERGE/SELECT INTO
give writes_to. Alias updates resolve to their table; CTEs, variables
and temp tables are skipped.

AST cache schema 20 -> 21 so cached .sql extractions re-run.
@github-actions github-actions Bot added the contributor Pull request from a returning community contributor label Oct 21, 2026
@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.10 and 3.13, and that the change keeps extraction deterministic.

@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 2 advisory finding(s) below merit a look before merge.

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

Formal verification. 1 change(s) alter behavior, breaking input(s) attached. PR-changed functions: 2/2 verified (0 proven, 1 may-equivalent, 1 distinguished) · 0 not verified.

Behavior changes: \_norm\_ident changes behavior, here is the input that shows it.

The verifier found a concrete input on which \_norm\_ident behaves differently before and after the change. If that change is intended, ship it; if not, this is your bug.

Guarantee: This difference was REPRODUCED, the verifier actually ran both versions on that input and saw them disagree. It is real, not an artifact.

Evidence: On input \{"name":"'\['"\}, the old code produced '\[' but the new code produces '' (outputs first differ at character 1). Paste that input straight into a regression test.


Graphify review — findings

Adds reads_from/writes_to edges for T-SQL procedure bodies, which tree-sitter-sql can't parse, by scanning the comment-masked body text from the end of the routine name to the next CREATE/ALTER, a GO line, or EOF. The scan drops CTE names, temp tables, table-valued function calls and keyword-only matches like EXTRACT(... FROM ...), and resolves UPDATE alias ... FROM dbo.Orders alias back to the real table. Stubs created from this scan use the bracket-cleaned name for node ids, so they can diverge from stubs the tree path creates, and a valid CREATE TABLE inside a body ends the scan early. Strips T-SQL brackets from SQL display labels ([dbo].[Orders] becomes dbo.Orders) while node ids still come from the text as written, and _norm_ident now treats bracketed, half-bracketed and plain forms as the same name. Bumps _AST_CACHE_SCHEMA to 21 so cached .sql extractions re-run with the new labels and edges.

Worth a look

  • Body-scan ref stubs use the cleaned name for the node id, so they diverge from tree-created stubs — graphify/extractors/sql.py:885 · Escalate · medium
    • NOT verified (no proof, no reproducing execution) — needs human review
  • Recovered procedure bodies stop at valid in-body CREATE TABLE — graphify/extractors/sql.py:881 · Escalate · medium
    • NOT verified (no proof, no reproducing execution) — needs human review

Review partial — this diff was larger than one review pass covers, so later files were not reviewed; some findings may be missing.

Analysis details — impact, health, verification

Impact & health

Graphify review

Impact — 2824 functions depend on the 316 functions this change touches.

Health — this change adds coupling hotspots:

  • worse: extract() — 989 callers, 59 callees
  • worse: extract_sql() — 38 callers, 12 callees
  • worse: walk() — 1 callers, 9 callees

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

Test selection

Test selection

43 of 437 test file(s) selected (10%) via static blast radius.

  • tests/test_cache.py — impact
  • tests/test_cache_stale_import_target.py — impact
  • tests/test_charmap_encoding.py — impact
  • tests/test_chunking.py — impact
  • tests/test_csharp_partial_classes.py — impact
  • tests/test_definition_file_portability.py — impact
  • tests/test_detect.py — impact
  • tests/test_extract.py — impact
  • tests/test_extract_cache_location.py — impact
  • tests/test_extract_cli.py — impact
  • tests/test_grammar_cache_key.py — impact
  • tests/test_ignore_file_encoding.py — impact
  • tests/test_incremental_mtime_collision.py — impact
  • tests/test_java_member_calls.py — impact
  • tests/test_js_member_collisions.py — impact
  • tests/test_language_override_lifecycle.py — impact
  • tests/test_language_overrides.py — impact
  • tests/test_llm_backends.py — impact
  • tests/test_manifest_ingest.py — impact
  • tests/test_multilang.py — impact, changed-test
  • tests/test_objc_field_table_remap.py — impact
  • tests/test_out_dir_evidence.py — impact
  • tests/test_partial_cache.py — impact
  • tests/test_pg_introspect.py — impact
  • tests/test_pipeline.py — impact
  • tests/test_python_inherited_method_calls.py — impact
  • tests/test_python_property_reads.py — impact
  • tests/test_python_pytest_fixture_receivers.py — impact
  • tests/test_rust_self_member_calls.py — impact
  • tests/test_rust_use_trees.py — impact
  • tests/test_semantic_cache_basename_recovery.py — impact
  • tests/test_semantic_cache_out_root.py — impact
  • tests/test_skill_persisted_scan_options.py — impact
  • tests/test_skill_semantic_all_cached.py — impact
  • tests/test_skillgen.py — impact
  • tests/test_sql_tsql_procedures.py — impact, changed-test
  • tests/test_stale_prune.py — impact
  • tests/test_stat_index_husk.py — impact
  • tests/test_stat_index_multi_root.py — impact
  • tests/test_stat_index_portability.py — impact
  • tests/test_watch_manifest_location.py — impact
  • tests/test_word_count_cache.py — impact
  • tests/test_zero_node_no_cache.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.

Docs that may be stale (advisory)

Formal verification

Behavior changes: \_norm\_ident changes behavior, here is the input that shows it.

The verifier found a concrete input on which \_norm\_ident behaves differently before and after the change. If that change is intended, ship it; if not, this is your bug.

Guarantee: This difference was REPRODUCED, the verifier actually ran both versions on that input and saw them disagree. It is real, not an artifact.

Evidence: On input \{"name":"'\['"\}, the old code produced '\[' but the new code produces '' (outputs first differ at character 1). Paste that input straight into a regression test.

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.

· 3 more finding(s) on lines outside this diff (see the check run).

@safishamsi

Copy link
Copy Markdown
Member

Landed in 0.9.94, cherry-picked to preserve your authorship. T-sql bracketed identifiers are unbracketed and a procedure emits reads_from/writes_to edges. Thanks @Deepjyoti-Sarmah. Live on PyPI: https://pypi.org/project/graphifyy/0.9.94/

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.

T-SQL: bracket-quoted identifiers are mangled, stored procedures get no reads_from edges, writes are not modelled

2 participants