Skip to content

feat(plugins): add built-in SQL Language plugin, Dialects, Hazards Metric, and calibrated Reference ranges - #434

Merged
avidianity merged 17 commits into
mainfrom
feat/224-sql-and-hazards
Nov 24, 2026
Merged

avidianity merged 17 commits into
mainfrom
feat/224-sql-and-hazards

Conversation

@avidianity

@avidianity avidianity commented Nov 24, 2026 •

Copy link
Copy Markdown
Owner

Summary

Adds the built-in SQL Language plugin (codeint-lang-sql, plugins/languages/sql/, plugin name sql, powered by sqlparser = "=0.64.0" in two layers per ADR 0018), four configured Dialects (postgresql, mysql covering MariaDB, sqlite, duckdb, plus generic SQL default), the language-neutral Hazards Metric (hazards, per ADR 0016) with 32 SQL Hazard line rules (27 statement rules and 5 schema-backed rules built from repository SQL files per Workspace package and Dialect), calibrated SQL Reference ranges across 20 pre-2023 public SQL repositories (proposed ADR 0022), and complete CLI, MCP, SARIF, Markdown, JSON report schema, and user documentation support.
Leaves all reports for repositories without SQL or Hazard-capable languages unchanged.

Closes #224
Closes #297
Closes #298
Closes #299
Closes #300
Closes #301
Closes #302
Closes #303
Closes #304
Closes #305
Closes #306
Closes #307
Closes #308
Closes #309
Closes #310
Closes #311
Closes #312
Closes #313
Closes #314
Closes #315
Closes #316
Closes #317
Closes #318
Closes #319
Closes #320
Closes #321
Closes #322
Closes #323
Closes #324
Closes #325
Closes #326
Closes #327
Closes #328
Closes #329
Closes #330
Closes #331
Closes #332
Closes #333
Closes #334
Closes #335
Closes #336
Closes #337
Closes #338
Closes #339
Closes #340
Closes #341
Closes #342
Closes #343
Closes #344
Closes #345
Closes #346
Closes #347
Closes #348
Closes #349
Closes #350
Closes #351
Closes #352
Closes #353
Closes #354
Closes #355
Closes #356
Closes #357
Closes #358
Closes #359
Closes #360
Closes #361
Closes #362
Closes #363
Closes #364
Closes #365
Closes #366
Closes #367
Closes #368
Closes #369
Closes #370
Closes #371
Closes #372
Closes #373
Closes #374
Closes #375
Closes #376
Closes #377
Closes #378
Closes #379
Closes #380
Closes #381
Closes #382
Closes #383
Closes #384
Closes #386
Closes #388
Closes #389
Closes #390
Closes #391
Closes #392
Closes #393

Tier

Tier 3 from the tier check (cargo run --locked -p xtask -- risk-tier --base origin/main): touches .rules (tier map rule ".rules"), crates/plugin-host/ (tier map rule "crates/plugin-host/**", reserving "hazards" as a built-in Metric key and registering SQL Seam 2 conformance), and updates expected built-in language list and report schema assertions in crates/cli/tests/check.rs and crates/report/tests/report_schema.rs. Adds docs/adr/0022-sql-reference-ranges.md (status: proposed, awaiting Owner acceptance).

Task

Spec #224 (Spec: SQL Language plugin and the Hazards Metric) and all 95 sub-issues (#297 through #393):

  • Part 1 (SQL Language plugin shell with the tokenizer layer #297-SQL guide page #314): sql built-in Language plugin with sqlparser = "=0.64.0" tokenizer and per-statement parser layers, statements as functions with object names, decision points and Cognitive complexity, Duplication tokens, 2 Flagged line rules (or-chain-collapses-to-in, having-without-aggregate), absent import Metrics (has_imports: false), Source set rules (database dumps, Drizzle/Atlas migration markers, prisma/migrations/ and drizzle/ folders, hand-written migrations as Production, test/tests/fixtures/testdata/*.test.sql/test_*.sql), templated SQL skipping (templated SQL), rejected statements listed in TOON/JSON/Markdown and report schema, Workspace package sections and languages filter, Seam 2 conformance, and docs/guide/sql.md.
  • Part 2 (sql.dialects configuration key #315-Guide: Dialects, with a monorepo example #329): sql.dialects configuration key (postgresql, mysql, sqlite, duckdb) with exit-2 unknown-dialect and overlapping-dialect validation, multi-dialect monorepo routing without changing the 0.3.0 Plugin interface, stored routines as single functions (PostgreSQL dollar-quoted bodies, MySQL DELIMITER and routines, SQLite triggers, DuckDB macros), DuckDB dot-commands and PostgreSQL backslash commands, Dialect shown in rejected_statements, codeint init suggesting sql.dialects only when SQL files exist without guessing a Dialect, and Dialects guide.
  • Part 3 (Hazards Metric #330-Hazards guide page #371): language-neutral hazards Metric (crates/metrics/src/hazards.rs), reserved "hazards" key, absent form for languages without rules, multi-language denominator isolation, hazards.disabled_rules with exit-2 unknown-rule validation, budgets.{source_set}.hazards (passes when absent), codeint diff + regression_limits.hazards / regression_limits.{source_set}.hazards + diff SARIF new findings only, codeint trend, ResultCache invalidation (cache_version = 7), all 27 statement-level SQL Hazard line rules on parsed ASTs, strict secret non-leakage across all formats/stderr/MCP, Generated vs hand-written migration Hazards, codeint schema, MCP tools, external WASM language plugin Hazards test, and docs/guide/hazards.md.
  • Part 4 (SQL schema from table statements, with the table count in the report #372-Guide: the SQL schema and its rules #382): pure SqlSchema::build across Production/Test/Generated SQL (never Vendored, skipping down.sql rollbacks and CREATE TEMP TABLE) in path order, scoped per (Workspace package, Dialect) and root per Dialect, sql_schemas table counts in reports, all 5 schema-backed Hazard line rules (unknown-column, text-compared-to-number, filter-on-unindexed-column, order-by-unindexed-column, join-on-unindexed-column) silent on unknown tables and ambiguous columns, and schema guide.
  • Part 5 (SQL proof on 5 public PostgreSQL repositories #383-The sql Language plugin publishes its Reference range #393): Dialect Proof across 21 public repositories (5 PostgreSQL, 5 MySQL/MariaDB, 5 SQLite, 5 DuckDB, and 1 multi-dialect repository authelia/authelia) with hand-checked rule matches and defect fixes with fresh regression tests; 20-repository pre-2023 SQL Reference range calibration panel (docs/adr/0022-sql-reference-ranges.md, status: proposed) and published SQL Reference ranges for Erosion, Duplication, and Verbosity (Import cycles absent).

Fail-first test

  • Test: plugins/languages/sql/tests/{conformance,hazards,schema_rules}.rs (47 integration tests) + plugins/languages/sql/src/schema/tests.rs (6 pure unit tests), crates/config/tests/sql_hazards.rs (8 tests), crates/metrics/src/hazards/tests.rs (7 tests), crates/report/src/hazards_tests.rs (6 tests) + crates/report/tests/report_schema.rs, crates/plugin-host/tests/conformance.rs (built_in_sql_plugin_passes_seam_2_conformance), crates/plugin-host/src/wasm_metric/tests.rs (hazards reserved key), crates/cli/tests/integration/{sql,hazards}.rs (11 process-boundary tests including secret non-leakage across TOON/JSON/Markdown/SARIF/MCP), crates/cli/tests/plugins.rs (external_wasm_language_plugin_with_hazard_rules_populates_hazards_metric), and crates/cli/tests/check.rs (sql_check_displays_calibrated_reference_ranges_next_to_sql_values).
  • Before the change: failed before implementation, on Part 5 proof defect checks (bare-CR line-bound overflow on OHDSI/Vocabulary-v5.0, SQLite/DuckDB/PG/MySQL false positives), and on Round 1 and Round 2 Prove reproducers (parse_dollar_tag EOF/EOL slice panic, recursive Spanned::span() / Expr / SetExpr / Box<Expr> drop stack overflows on 2 MiB rayon worker threads, CREATE VIEW routine-splitting trap, HAVING aggregate alias, PG dollar-quoted body alignment, PG E'...' backslash escape, PL/pgSQL CURSOR FOR SELECT depth leak, duplicate HAVING aggregate list, and CREATE TABLE IF NOT EXISTS overwrite).
  • After the change: passed.

Checks

Check Result
cargo fmt --all --check passed
cargo clippy --workspace --all-targets --locked -- -D warnings passed
cargo test --locked -p codeint-lang-sql passed (53 tests: 6 unit, 18 conformance, 10 hazards, 19 schema_rules)
cargo test --locked -p codeint-config -p codeint-metrics -p codeint-report -p codeint-plugin-host passed (246 tests)
cargo test --locked -p codeint-cli --test check --test plugins --test reference passed (203 tests)
cargo test --locked -p codeint-cli --test integration -- diff:: sql:: hazards:: passed (64 tests)
cargo run --locked -p codeint-cli -- diff origin/main --format toon passed (0 regressions)
cargo run --locked -p xtask -- no-comments --base origin/main passed
cargo run --locked -p xtask -- merged-result passed

Safety proof

  • Safety fact: (1) Adding the built-in SQL Language plugin and Hazards Metric leaves all 6 existing built-in Language plugins, the 0.3.0 WIT Plugin interface, external WASM plugins, and reports for non-SQL repositories unchanged, and (2) untrusted/adversarial SQL inputs never panic, never overflow the stack on 2 MiB rayon worker threads, perform zero host I/O, validate all configuration errors with exit code 2, and never leak matched secret text in any output format, stderr, or MCP response.
  • Proof:
    • Blast Radius Verifier proved Safety Fact 1 (wit/ unchanged, existing 6 language plugins unchanged, 449 tests across plugin-host, config, metrics, report, and cli pass; non-SQL Python repository with budgets.production.hazards: 0.0 passes with hazards, rejected_statements, and sql_schemas absent across check/diff/trend/MCP in all formats).
    • Round 1 Blast Radius + Round 2 and Round 3 Clean-Rerun Verifiers proved Safety Fact 2 on commit d22e824: #![forbid(unsafe_code)], zero host I/O in plugins/languages/sql/src/, zero .span() recursive calls, iterative Expr and SetExpr walkers, MAX_PARSED_STATEMENT_TOKENS = 12_000 single-statement parser cap, verified across multi-file 2 MiB rayon worker stress runs (13,000 UNION ALL, 22,000 invalid +, 100,000 valid +, boundary 5,990 + and 2,990 UNION ALL, $ident at EOF/EOL, bare CR, unclosed quotes, and secret non-leakage across all formats/stderr/MCP).
  • interrogate:
    • Round 1 (commit fb47cc7): Blast Radius found 2 crashes (parse_dollar_tag eager .then_some EOF/EOL panic; stack overflow in Spanned::span() / recursive Expr walks on 2,000-term chains); Independent Verifier found 7 SQL edge cases (CREATE VIEW with begin/trigger, HAVING aggregate alias, PG dollar-quoted body expansion alignment, PG E'...' backslash escape, PL/pgSQL CURSOR FOR SELECT depth leak, duplicate HAVING_AGGREGATES subset, CREATE TABLE IF NOT EXISTS overwrite); CI found stale cache_version == 6 test assertion. All 10 fixed in 7a9ed6d with fresh regression tests.
    • Round 2 (commit 7a9ed6d): Verified all 9 Round 1 SQL fixes PASS and found 2 remaining stack overflows on 2 MiB rayon worker threads (recursive visit_set_expr on 13,000 UNION ALL and sqlparser::ast::Expr recursive Drop on 22,000+ operator chains). Fixed in d22e824 by converting all 4 SetExpr walkers to iterative stacks and adding MAX_PARSED_STATEMENT_TOKENS = 12_000 with 2 MiB-stack regression tests.
    • Round 3 Clean Rerun (commit d22e824): Safety Fact 1 PROVEN, Safety Fact 2 PROVEN, Verdict: PASS (0 open verified findings) across all multi-file rayon 2 MiB crash reproducers, boundary cases, and targeted test suites.

Runtime evidence

  • Build revision: d22e824 (calibration measured on release 07ffb95; subsequent commits 7a9ed6d and d22e824 fix edge-case bugs and stack safety with zero metric regressions).
  • Verdict: PASS
  • Feature map: generic SQL and 4 configured Dialects (postgresql, mysql, sqlite, duckdb), hazards Metric with 32 rules (27 statement + 5 schema), hazards.disabled_rules, Budgets and Regression limits, diff/trend/SARIF/Markdown/MCP/schema/init/cache support, rejected_statements, sql_schemas table counts, and calibrated SQL Reference ranges.
  • Part 5 Dialect Proof (21 public repositories, 0 crashes):
    • 5 PostgreSQL (LemmyNet/lemmy, pgMemento/pgMemento, NikolayS/postgres_dba, coder/coder, concourse/concourse): 2,436 Production SQL files, 84,153 lines; rejected share 0.99%-21.74%.
    • 5 MySQL/MariaDB (mysql/mysql-sys, shlomi-noach/common_schema, apache/cloudstack, Dolibarr/dolibarr, osTicket/osTicket): 1,724 Production SQL files, 114,673 lines; rejected share 2.53%-45.38% (upstream sqlparser lacks MySQL CREATE DEFINER=... FUNCTION and SET @var :=).
    • 5 SQLite (stashapp/stash, ankitects/anki, mozilla/application-services, moneymanagerex/general-reports, clementine-player/Clementine): 315 Production SQL files, 8,985 lines; rejected share 0.0%-19.8%.
    • 5 DuckDB (CtrlSpice/otel-desktop-viewer, davidgasquez/filecoin-data-portal, DBatUTuebingen/DiDi, DBatUTuebingen/TaDa, teaguesterling/sitting_duck): 270 Production SQL files, 17,484 lines; 192 dot-command lines handled with 0 rejections; 16 templated files skipped cleanly; rejected share 3.0%-16.2%.
    • Multi-dialect (authelia/authelia, 204 files, 6,039 lines across postgres/mysql/sqlite): without sql.dialects gives 1 merged generic schema (30 tables), 46 rejected (2.82%: postgres 2/389, mysql 26/398, sqlite 18/825); with sql.dialects gives 3 isolated schemas (30/30/30 tables), 42 rejected (2.58%: postgres 0/389, mysql 24/398, sqlite 18/825).
    • Hand-checked fired rules across all 21 repos; fixed every surfaced Source set, statement-hazard, and schema-hazard false positive in 065414a and bare-CR line-bound bug on OHDSI/Vocabulary-v5.0 in 07ffb95 with fresh regression tests.
  • Part 5 SQL Reference Range Panel (docs/adr/0022-sql-reference-ranges.md, 20 pre-2023 public SQL repositories):
    • Walked ranks 1-92 (1,978 Production SQL files, 427,252 Production SQL lines, 3.25s total wall time).
    • Largest by Production SQL lines: OHDSI/Vocabulary-v5.0 (480 files, 127,897 lines) in 0.31s / 575.9 MiB max RSS; highest peak RSS: pgpartman/pg_partman (123 files, 126,807 lines) in 0.91s / 762.5 MiB max RSS.
    • Published 10th-90th percentile Reference ranges: Erosion 0.094..0.976, Duplication 0.042..0.921, Verbosity 0.042..0.921, Import cycles absent; source "codeint panel of 20 SQL repositories, ADR 0022, codeint 0.6.0".

Gaps

  • Deferred coverage: none.
  • Pre-existing failures: none.
  • Environmental failures: none.

Add sql.dialects and hazards.disabled_rules configuration with JSON Schema validation, Hazards Budgets and Regression limits across all Source sets, optional sql.dialects starter hint, language-agnostic Hazards Metric with per-package breakdowns and stable FindingIds, and reserve the hazards key for external Metric plugins.
…hema

Add user guides for the built-in SQL Language plugin and the Hazards Metric, document all SQL and Hazards configuration keys, report fields, and all 32 Hazard line rules in docs/reference.md, and update README, llms.txt, GLOSSARY.md, .rules, and guide pages.

Closes #314
Closes #329
Closes #371
Closes #382
Fix SQL source-set classification, statement-level hazard false positives, and SQL schema/rule defects identified across the 21-repository dialect proof:

- Classify -- Code generated + DO NOT EDIT headers in the first 20 lines as Generated, and testdata folders, *.test.sql, and test_*.sql files as Test.
- Exclude LEFT [OUTER] JOIN ... ON TRUE and INSERT ... SELECT ... WHERE TRUE ON CONFLICT from always-true-condition.
- Exclude LATERAL joins from tables-without-join-condition and resolve join/comma-join line numbers backward from the current clause relation rather than scanning inside earlier subqueries.
- Exclude MySQL multi-table DELETE/UPDATE statements filtered by an INNER JOIN ... ON or USING condition from delete-without-filter and update-without-filter.
- Exclude empty string literals from plain-text-secret, CREATE VIEW queries from count-without-filter, and DISTINCT ON from distinct-over-join.
- Skip down.sql / *.down.sql rollback migrations and CREATE TEMP / TEMPORARY TABLE definitions when building cross-file SQL schemas.
- Handle PostgreSQL @PARAM unary PGAbs expressions, DuckDB/PostgreSQL row variables, CompoundFieldAccess subscripts, and SQLite empty/URL double-quoted literals in unknown-column.
- Respect composite PK/index prefixes and same-table leading-index AND chains across filter-on-unindexed-column, join-on-unindexed-column, and order-by-unindexed-column, and exclude aggregates and grouped CASE expressions in ORDER BY.
@github-actions github-actions Bot added the tier-3 Tier 3 from the tier check label Nov 24, 2026
…he test

- Fix parse_dollar_tag slice bounds panic on $<ident> at EOF/EOL using lazy Option::then.
- Eliminate recursive .span() calls and recursive Expr walks via iterative ast_loc helpers and explicit worklist stacks so 2500-term expressions never overflow the stack.
- Restrict starts_routine_header to the object kind immediately following CREATE modifiers so non-routine DDL does not swallow subsequent statements.
- Treat aggregate SELECT aliases referenced in HAVING as aggregated in having-without-aggregate.
- Pair expanded PostgreSQL dollar-quoted routine bodies with their outer token start Location so preceding dollar-quoted literals do not misalign source_lines.
- Track PostgreSQL E'...' backslash escapes in the CLI command line scanner.
- Exclude CURSOR FOR and FOR SELECT/EXECUTE/VALUES/WITH from PL/pgSQL routine FOR loop depth tracking.
- Reuse flagged::is_aggregate_call in function-on-filter-column instead of a smaller duplicate list.
- Preserve existing table columns and indexes when CREATE TABLE IF NOT EXISTS matches an existing table.
- Update diff integration cache_version assertion from 6 to 7.
@avidianity
avidianity marked this pull request as ready for review November 24, 2026 15:31
@avidianity
avidianity merged commit b28dc83 into main Nov 24, 2026
13 of 14 checks passed
@avidianity
avidianity deleted the feat/224-sql-and-hazards branch November 24, 2026 17:06
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment