Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
86 changes: 86 additions & 0 deletions .github/scripts/cases_fresh.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
"""Check that every syntax cases file a pull request touches is what SQLBabel's builder writes from its receipts.

usage: cases_fresh.py plan (in the evidence checkout; writes dialects= and builder= to GITHUB_OUTPUT)
cases_fresh.py check (in the SQLBabel checkout; reads DIALECTS and EVIDENCE)

plan lists the dialects whose syntax/<dialect>/ the pull request changes and resolves the SQLBabel
commit to build with: the full SHA of a `Builder: <sha>` line in the pull request body, or else the head
of SQLBabel's main. check requires a SQLBabel branch to contain that commit, then runs its builder for
each dialect with --check against the pull request's evidence. The dialects and the Snowflake families come from SQLBabel's Makefile.
"""

import os
import re
import subprocess
import sys
from pathlib import Path

SQLBABEL = "https://github.com/sqlstack-io/sqlbabel"
BUILDER_LINE = re.compile(r"^Builder:\s*(\S+)\s*$", re.MULTILINE)
FULL_SHA = re.compile(r"[0-9a-f]{40}")


def run(*command: str) -> str:
return subprocess.run(command, check=True, capture_output=True, text=True).stdout


def plan() -> None:
base = os.environ["BASE_SHA"]
changed = run("git", "diff", "--name-only", f"{base}...HEAD").splitlines()
dialects = sorted({path.split("/")[1] for path in changed if path.startswith("syntax/") and path.count("/") >= 2})
named = BUILDER_LINE.findall(os.environ.get("PR_BODY") or "")
if len(named) > 1:
sys.exit(f"cases-fresh: the body names {len(named)} Builder lines; name one")
if named and not FULL_SHA.fullmatch(named[0]):
sys.exit(f"cases-fresh: Builder must be a full 40-character SQLBabel commit SHA, not {named[0]!r}")
builder = named[0] if named else run("git", "ls-remote", SQLBABEL, "refs/heads/main").split()[0]
source = "the Builder line" if named else "SQLBabel main's head"
print(f"cases-fresh: dialects touched: {' '.join(dialects) or 'none'}", file=sys.stderr)
print(f"cases-fresh: builder {builder}, from {source}", file=sys.stderr)
with open(os.environ["GITHUB_OUTPUT"], "a", encoding="utf-8") as output:
output.write(f"dialects={' '.join(dialects)}\nbuilder={builder}\n")


def makefile_words(makefile: str, name: str) -> list[str]:
found = re.search(rf"^{name}\s*\??=\s*(.+)$", makefile, re.MULTILINE)
if found is None:
sys.exit(f"cases-fresh: SQLBabel's Makefile defines no {name}")
return found.group(1).split()


def on_branch(builder: str) -> None:
"""Exit unless a branch of SQLBabel contains `builder`: a SHA reachable only through a pull request ref is unreviewed."""
listed = subprocess.run(["git", "branch", "-r", "--contains", builder], capture_output=True, text=True)
branches = [line.strip() for line in listed.stdout.splitlines() if "->" not in line]
if listed.returncode != 0 or not branches:
sys.exit(f"cases-fresh: builder {builder} is on no SQLBabel branch; name a commit on main or on the paired pull request's branch")
shown = "origin/main" if "origin/main" in branches else branches[0]
print(f"cases-fresh: builder {builder} is on {shown} and {len(branches) - 1} other branches", flush=True)


def check() -> None:
on_branch(os.environ["BUILDER"])
evidence = Path(os.environ["EVIDENCE"]) / "syntax"
makefile = Path("Makefile").read_text(encoding="utf-8")
builders = makefile_words(makefile, "DIALECT_CASE_DIALECTS")
failed: list[str] = []
for dialect in os.environ["DIALECTS"].split():
tree = evidence / dialect
if dialect == "snowflake":
families = makefile_words(makefile, "SYNTAX_FAMILIES")
arguments = ["scripts.build_syntax_cases", "--check", "--evidence", str(tree),
"--receipts", str(tree / "receipts"), "--held", "coverage/syntax/held.jsonl", *families]
elif dialect in builders:
arguments = [f"scripts.build_syntax_obligations_{dialect}", "--check", "--evidence", str(tree)]
else:
sys.exit(f"cases-fresh: SQLBabel has no cases builder for syntax/{dialect}/; add one before recording it")
print(f"cases-fresh: {dialect}: python -m {' '.join(arguments)}", flush=True)
if subprocess.run(["uv", "run", "--no-project", "python", "-m", *arguments]).returncode != 0:
failed.append(dialect)
if failed:
sys.exit(f"cases-fresh: stale cases in {' '.join(failed)}: rebuild them with the receipts present and push")
print("cases-fresh: every touched cases file is what the builder writes")


if __name__ == "__main__":
{"plan": plan, "check": check}[sys.argv[1]]()
51 changes: 51 additions & 0 deletions .github/workflows/cases-fresh.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
name: Cases fresh

# Fails a pull request whose syntax cases file is not what SQLBabel's builder writes from the receipts
# beside it, such as a cases file built before its receipts were recorded. It runs on every pull request
# and passes at once when no syntax/<dialect>/ changes, so as a required check it never holds one up.
on:
pull_request:

permissions:
contents: read

jobs:
cases-fresh:
name: Cases match their receipts
runs-on: ubuntu-latest
timeout-minutes: 30
steps:
- uses: actions/checkout@v4
with:
path: evidence
fetch-depth: 0

- name: Find the touched dialects and the builder commit
id: plan
working-directory: evidence
env:
BASE_SHA: ${{ github.event.pull_request.base.sha }}
PR_BODY: ${{ github.event.pull_request.body }}
run: python3 .github/scripts/cases_fresh.py plan

- name: Check out SQLBabel at the builder commit
if: steps.plan.outputs.dialects != ''
uses: actions/checkout@v4
with:
repository: sqlstack-io/sqlbabel
ref: ${{ steps.plan.outputs.builder }}
path: sqlbabel
fetch-depth: 0

- name: Install uv
if: steps.plan.outputs.dialects != ''
uses: astral-sh/setup-uv@v6

- name: Rebuild each touched dialect's cases and compare
if: steps.plan.outputs.dialects != ''
working-directory: sqlbabel
env:
DIALECTS: ${{ steps.plan.outputs.dialects }}
BUILDER: ${{ steps.plan.outputs.builder }}
EVIDENCE: ${{ github.workspace }}/evidence
run: python3 ../evidence/.github/scripts/cases_fresh.py check
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -16,3 +16,4 @@ run-logs/
*run-log*.md
*hand-off*.md
*handoff*.md
__pycache__/
12 changes: 12 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,3 +7,15 @@ Recorded database answers that back SQLQuack's syntax and translation checks.
- `referee/<dialect>/` holds type and signature checks (`cases/`, `results/`, `functions/`).

Files are only ever added or appended to. SQLQuack pins one commit of this repository in its `evidence.toml`, with the SHA-256 of its files, and its make targets fetch and verify that commit. No credentials, account names or raw query logs are stored here.

## Cases must match their receipts

Every pull request runs the `Cases match their receipts` check. For each `syntax/<dialect>/` the pull request changes, it rebuilds the cases with SQLBabel's builder against the pull request's receipts and fails when a cases file differs, such as one built before its receipts were recorded. Rebuild the cases with the receipts present, then push.

The builder is SQLBabel main's head unless the pull request body names one SQLBabel commit by its full SHA on a line of its own:

```
Builder: 0123456789abcdef0123456789abcdef01234567
```

Name the head of the SQLBabel pull request that pins this evidence when its builder change has not reached main yet. The commit must be on a SQLBabel branch; one reachable only through a pull request ref fails. A pull request that changes no `syntax/` directory passes at once.
Loading