메뉴
HN
Hacker News 17일 전

Sqlsure: AI 생성 SQL의 결정론적 의미론적 검사 도구

IMP
8/10
핵심 요약

AI가 작성한 SQL 쿼리의 논리적 오류(데이터 중복 집계, 민감 정보 노출 등)를 실행 전 0.1ms 만에 결정론적으로 검사해주는 도구입니다. dbt 테스트나 데이터베이스 메타데이터를 기반으로 작동하며, AI 에이전트가 스스로 오류를 수정할 수 있는 피드백을 제공하여 데이터 파이프라인의 신뢰성을 크게 높여줍니다.

번역된 본문

sqlsure: AI는 여러분의 SQL을 작성하고, sqlsure는 그것이 맞는지 확인합니다. 쿼리는 완벽하게 유효하고 오류 없이 실행되어 조용히 잘못된 숫자를 반환할 수 있습니다. 예를 들어 조인(join)으로 인해 수익이 이중으로 계산되거나, 평균이 단순 합산되거나, 환자 식별자가 노출될 수 있습니다. 데이터베이스는 이것을 잡지 못합니다. 린터(linter)도 잡지 못합니다. 자신의 SQL을 검토하는 LLM조차도 이것을 잡지 못합니다. sqlsure는 쿼리가 실행되기 전에 0.1ms 만에 결정론적으로 이를 잡아냅니다.

약속이 아닌 증명: 우리는 모든 텍스트-투-SQL(text-to-SQL) 모델이 평가받는 두 개의 벤치마크 골드 정답에 대해 sqlsure를 실행했습니다. 전문가가 작성한 2,568개의 쿼리, 45개의 플래그, 0개의 오탐지(False alarm)를 기록했습니다. 여기에는 sqlsure가 타겟팅하는 정확한 버그 클래스로 인해 8배나 잘못된 것이 증명된 BIRD 개발용 골드 정답과, 현재 상위 리포지토리에 제출된 스키마 결함이 포함되어 있습니다.

작동 방식: sqlsure는 팀이 이미 선언한 팩트(facts)를 기준으로 SQL을 판단합니다. dbt unique 테스트는 데이터의 세분성(grain)이 되고, relationships 테스트는 조인 카디널리티(join cardinality)가 되며, 한 줄의 메타 태그는 합산해도 안전한 것을 표시합니다. 배울 새로운 언어도, 수동으로 유지 관리할 모델도 없습니다. 규칙은 LLM 호출이 아닌 사전(dictionary) 조회입니다. 동일한 입력에 대해 매번 오프라인으로 동일한 판결을 내립니다. 모든 거부는 기계가 조치할 수 있는 수정안을 포함하므로 AI 에이전트가 스스로 복구합니다: 초안 작성 → 검사 → 수정 → 검사 → 실행. 우리의 벤치마크에서 수정안을 그대로 적용했을 때 10번 중 10번 모두 통과하는 쿼리가 생성되었습니다.

빠른 시작: pip install sqlsure

from sqlsure import SemanticModel, check
violations = check(sql, model) # []는 의미론적으로 안전하다는 뜻입니다

또는 복제하여 30초 데모를 실행하세요:

python check.py # 5개의 잘못된 쿼리가 거부되고, 1개가 수정안과 함께 승인됨
python -m sqlsure.scan path/to/dbt-repo --report report.md # 모든 dbt 리포지토리 감사

세 가지 문, 하나의 엔진:

  1. CI 게이트 — PR이 이중 집계할 때 머지(merge)를 차단합니다: python -m sqlsure.cli --model model.json query.sql # 위반 시 종료 코드 1
  2. MCP 서버 — AI 에이전트는 실행 전에 반드시 검사를 통과해야 합니다: claude mcp add sqlsure -- python -m sqlsure.mcp_server --model /abs/path/model.json 도구 참조 및 에이전트 루프 패턴은 docs/MCP.md를 참조하세요.
  3. 라이브러리 — 모든 텍스트-투-SQL 제품이나 에이전트 프레임워크 내부에 check()를 내장하세요. 드롭인(Drop-in) SemanticGate는 Vanna/WrenAI 스타일의 생성기를 감싸며, 의미론적 평가 지표는 실행 정확도가 무용지물일 때 NL2SQL 출력을 평가합니다.

규칙 (v0.1):

  • FANOUT error: 일대다 조인 후 가산적 측정항목(additive measure)의 SUM/COUNT
  • CHASM error: 두 개 이상의 팬아웃 조인이 서로 곱해지는 현상
  • ADDITIVITY error: 비가산적 측정항목(비율, 평균)의 SUM
  • SEMI_ADDITIVE error: 스냅샷 차원에 걸쳐 합산된 잔액/센서스
  • JOIN_KEY error: 선언된 관계와 일치하는 열이 없는 조인
  • CROSS_JOIN error: 조건자(predicate)가 없는 조인
  • WEIGHTED_AVG warning: 팬아웃에 의해 조용히 가중치가 재조정되는 AVG
  • UNDECLARED_JOIN warning: 선언된 관계가 없는 조인 (검증할 수 없음 ≠ 안전함)
  • SENSITIVE_COLUMN policy: 쿼리 출력에 노출된 PHI/PII 열

sqlsure가 무언가를 확인할 수 없을 때, "괜찮아 보임"이 아니라 "확인할 수 없음"이라고 말합니다. 정직한 불확실성은 하나의 기능입니다.

신뢰 속성:

  • 결정론적 — 동일한 SQL + 동일한 규칙집합 = 항상 동일한 판결; 규칙은 한 줄씩 감사할 수 있는 사전 조회입니다.
  • 오프라인 — 네트워크 호출 제로; 여러분의 SQL은 절대 머신을 떠나지 않습니다.
  • 데이터 접근 없음 — 쿼리 텍스트를 파싱할 뿐; 데이터베이스에 연결하지 않습니다.
  • 원격 측정(Telemetry) 없음 — 어떤 것도 수집하지 않습니다 (SECURITY.md).
  • 공급망(Supply chain) — 릴리스는 공개 CI 실행과 함께 태그된 커밋에서 PyPI 신뢰할 수 있는 퍼블리싱(Trusted Publishing, OIDC)을 통해서만 배포됩니다; 두 개의 런타임 종속성.

규칙집합의 출처:

  • dbt (현재 작동함): manifest.json 또는 schema.yml — 팀이 이미 작성한 테스트가 구성 없이도 강제 가능한 의미론이 됩니다.
  • 단순 PK/FK 선언 (현재 작동함 — 벤치마크 감사를 구동하는 데 사용됨)
  • 라이브 데이터베이스 자체 (현재 작동함): 의미론적 계층이 아예 없나요? sqlsure.introspect가 카탈로그에서 규칙집합을 구축합니다 — SQLite PRAGMA 또는 information_schema PK/FK (postgres/mysql). BIRD 자체 데이터베이스 파일을 인트로스펙트하여 벤치마크에 게시된 스키마에서 누락된 2개의 외래 키를 복구했습니다 (bird-bench/mini_dev#37).
from sqlsure.introspect import model_from_sqlite
model = model_from_sqlite("app.db") # PK -> grain
원문 보기
원문 보기 (영어)
sqlsure AI writes your SQL. sqlsure makes sure it's right. A query can be perfectly valid, run without error, and return a number that's silently wrong — revenue double-counted by a join, an average summed, a patient identifier exposed. Databases don't catch this. Linters don't catch this. LLMs reviewing their own SQL don't catch this. sqlsure does — deterministically, in 0.1 ms, before the query runs. Proof, not promises: we ran sqlsure over the gold answers of the two benchmarks every text-to-SQL model is graded on. 2,568 expert-written queries, 45 flags, zero false alarms — including a BIRD dev gold answer that is provably wrong by 8× from the exact bug class sqlsure targets, and a schema defect now filed upstream . How it works sqlsure judges SQL against facts your team already declared — dbt unique tests become grain, relationships tests become join cardinality, one-line meta tags mark what's safe to sum. No new language to learn, no model to maintain by hand. Rules are dictionary lookups, not LLM calls: same input, same verdict, every time, offline. Every rejection carries a machine-actionable fix , so AI agents self-repair: draft → check → fix → check → execute. In our benchmark, applying the fix verbatim produced a passing query 10/10 times. Quick start pip install sqlsure from sqlsure import SemanticModel , check violations = check ( sql , model ) # [] means semantically safe Or clone and run the 30-second demo: python check.py # 5 wrong queries rejected, 1 approved — with fixes python -m sqlsure.scan path/to/dbt-repo --report report.md # audit any dbt repo Three doors, one engine 1. CI gate — blocks the merge when a PR double-counts: python -m sqlsure.cli --model model.json query.sql # exit 1 on violations 2. MCP server — your AI agent must pass inspection before executing: claude mcp add sqlsure -- python -m sqlsure.mcp_server --model /abs/path/model.json See docs/MCP.md for tool reference and agent-loop patterns. 3. Library — embed check() inside any text-to-SQL product or agent framework. A drop-in SemanticGate wraps Vanna/WrenAI-style generators; a semantic eval metric scores NL2SQL output where execution-accuracy is blind. The rules (v0.1) Rule Severity Catches FANOUT error SUM/COUNT of additive measure after one-to-many join CHASM error two+ fan-out joins multiplying each other ADDITIVITY error SUM of a non-additive measure (rates, averages) SEMI_ADDITIVE error balances/censuses summed across their snapshot dimension JOIN_KEY error join on columns matching no declared relationship CROSS_JOIN error join with no predicate WEIGHTED_AVG warning AVG silently re-weighted by fan-out UNDECLARED_JOIN warning join with no declared relationship (unverifiable ≠ safe) SENSITIVE_COLUMN policy PHI/PII column exposed in query output When sqlsure can't verify something, it says "can't verify" — never "looks fine." Honest uncertainty is a feature. Trust properties Deterministic — same SQL + same rulebook = same verdict, always; rules are dictionary lookups, auditable line by line Offline — zero network calls; your SQL never leaves your machine No data access — parses query text ; never connects to a database No telemetry — nothing collected, ever ( SECURITY.md ) Supply chain — releases ship exclusively via PyPI Trusted Publishing (OIDC) from tagged commits with public CI runs; two runtime deps Where the rulebook comes from dbt (works today): manifest.json or schema.yml — the tests teams already wrote become enforceable semantics, zero config Plain PK/FK declarations (works today — powered the benchmark audits) The live database itself (works today): no semantic layer at all? sqlsure.introspect builds the rulebook from the catalog — SQLite PRAGMAs or information_schema PK/FK (postgres/mysql). Introspecting BIRD's own database files recovered 2 foreign keys missing from the benchmark's published schema ( bird-bench/mini_dev#37 ) from sqlsure . introspect import model_from_sqlite model = model_from_sqlite ( "app.db" ) # PK -> grain, FK -> join edges Hand-written JSON — model.example.json OSI and WrenAI MDL (working loaders in integrations/ ): OSI demonstrated on the spec's published examples; WrenAI MDL demonstrated on WrenAI's own shipped example manifest — primaryKey → grain, relationship joinType + condition → join edges, cube measures → additivity Cube, Snowflake Semantic Views — adapters on the roadmap; the engine only ever sees one SemanticModel Validated on 16/16 rule tests, 100% recall / 0% false positives on the paired benchmark ( docs/METRICS.md ) Real production repos (Mattermost's warehouse, Fivetran packages, dbt's jaffle shop) — docs/TEST-REPORTS.md Spider + BIRD gold queries — the zero-noise external audit above Learn more docs/EVIDENCE.md — what it does for you, every claim linked to a rerunnable measurement docs/ARCHITECTURE.md — how it physically works, ELI5 → god level, with real intermediate outputs docs/FOR-DUMMIES.md — every concept from zero docs/INTEGRATIONS.md — GitHub Action, pre-commit, MCP, Snowflake UDF / Cortex Agent tool, query-history audit docs/MCP.md — MCP server documentation CONTRIBUTING.md — adding rules and loaders Apache-2.0 · sqlsure.ai mcp-name: io.github.sqlsure/sqlsure