Repository navigation
fix(sql): strip T-SQL brackets and add reads_from/writes_to edges for procedures (#4635) - #4649
Deepjyoti-Sarmah wants to merge 2 commits into
Conversation
…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.
|
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. |
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 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— impacttests/test_cache_stale_import_target.py— impacttests/test_charmap_encoding.py— impacttests/test_chunking.py— impacttests/test_csharp_partial_classes.py— impacttests/test_definition_file_portability.py— impacttests/test_detect.py— impacttests/test_extract.py— impacttests/test_extract_cache_location.py— impacttests/test_extract_cli.py— impacttests/test_grammar_cache_key.py— impacttests/test_ignore_file_encoding.py— impacttests/test_incremental_mtime_collision.py— impacttests/test_java_member_calls.py— impacttests/test_js_member_collisions.py— impacttests/test_language_override_lifecycle.py— impacttests/test_language_overrides.py— impacttests/test_llm_backends.py— impacttests/test_manifest_ingest.py— impacttests/test_multilang.py— impact, changed-testtests/test_objc_field_table_remap.py— impacttests/test_out_dir_evidence.py— impacttests/test_partial_cache.py— impacttests/test_pg_introspect.py— impacttests/test_pipeline.py— impacttests/test_python_inherited_method_calls.py— impacttests/test_python_property_reads.py— impacttests/test_python_pytest_fixture_receivers.py— impacttests/test_rust_self_member_calls.py— impacttests/test_rust_use_trees.py— impacttests/test_semantic_cache_basename_recovery.py— impacttests/test_semantic_cache_out_root.py— impacttests/test_skill_persisted_scan_options.py— impacttests/test_skill_semantic_all_cached.py— impacttests/test_skillgen.py— impacttests/test_sql_tsql_procedures.py— impact, changed-testtests/test_stale_prune.py— impacttests/test_stat_index_husk.py— impacttests/test_stat_index_multi_root.py— impacttests/test_stat_index_portability.py— impacttests/test_watch_manifest_location.py— impacttests/test_word_count_cache.py— impacttests/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)
graphify/extractors/MIGRATION.md§ Helper classification (lines 53-66): references changed symbols_name
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).
|
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/ |
What does this PR do?
Fixes #4635. On a T-SQL project the SQL graph was close to empty:
[dbo].[Country]got the labeldbo].[Country, and it never matcheddbo.Country.reads_fromedges, in any dialect.INSERT/UPDATE/DELETE/MERGEmade 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 isdbo].[Country. It also has nocreate_procedurenode at all, so thecreate_procedurebranch insql.pynever runs. EvenCREATE 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 noinsertorupdatenode to read.So this PR reads procedure bodies as text, not from the tree:
Ids don't change:
_make_idalready 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 .):After:
Type of change
writes_tois a new relation. Nothing outsidesql.pylists relation names, so it needs no registration.Verification & Invariants
A procedure has a
reads_fromedge to each table it reads and awrites_toedge 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.Merge Danger
Door: two-way. Ids are unchanged.
_AST_CACHE_SCHEMAgoes 20 -> 21 so cached.sqlextractions 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-sampleswide-world-importers/wwi-ssdt(336.sqlfiles):containsedgesreads_fromand 129writes_to. All 319 were checked against the source: 314 have the keyword right before the table name, and 5 areUPDATE sih ... FROM Warehouse.StockItemHoldings AS sihalias updates.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.sqlbuild procedures inside multi-lineN'...'strings).test_multilang.pychange their expected routine label to the bracket-free form ([dbo].[usp_Real]()->dbo.usp_Real()).test_sql_tsql_bracketed_procedure_is_recoverednow filters to routine nodes, since the procedure's tables now appear as stubs.Limitations
dbo.Ordersnodes. v8 does the same. Answering "what writes todbo.Orders" across a project needs that fixed. Filed as #.GOwithout;still swallows the next statement in the tree, so a secondCREATE TABLEafterGOis lost. Filed as #.graph.jsonkeeps one edge per pair, so onlywrites_toshows.extract()returns both.MERGE ... USING srcrecords no read.TRUNCATEandEXECaren't modelled.BULK INSERT dbo.Tcounts as a write.CREATE/ALTERat the start of a line inside a body (CREATE INDEX ... ON #t) ends the body early.CREATE TABLE #tandCREATE TABLE @tdon't.create_procedureandfb_proc_or_triggerbranches are dead on this grammar. They're left as they are.How was this tested?
New tests in
tests/test_sql_tsql_procedures.pyrunextract()orextract_sql()on small files, including the issue's four, and assert(source, relation, target)triples. None calls a private helper.[dbo].[Orders]anddbo.Ordersin one file are one tabledbo.Orders,dbo.AddPayment();[a]]b]->a]b;"dbo"."V"keptCREATE PROCEDURE p AS SELECT ..., with(x INT), with@x INT ... BEGIN ENDINSERT,UPDATE,DELETE,MERGE,SELECT ... INTOgivewrites_to;DELETE FROMisn't a readUPDATE o ... FROM dbo.Orders owritesdbo.Orders#work,##shared,@idsare skippedGO-separated procedures keep their own tables; comments and strings are ignoredOn v8 the guards pass because v8 makes no procedure edges. They catch a fix that attaches too much.
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
uv run python -m tools.skillgen --bless) when changing their source fragments. (N/A: no skill fragments touched.)