Skip to content
Open
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
4 changes: 3 additions & 1 deletion .flake8
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
# flake8 reads this file; it does not read pyproject.toml (#324). Editors and the pre-commit hook pick it up.
# scripts/lint.sh, which CI runs, passes the same options on its command line, and
# tests/unit/test_tool_config.py fails if the two disagree.
# E203 (whitespace before ":") is off because the formatter (ruff, #324) writes slices as `x[a + 1 :]`, as black does;
# flake8's documentation lists E203 as incompatible with that style.
[flake8]
max-line-length = 120
extend-ignore = E501,E221,E272
extend-ignore = E501,E221,E272,E203
7 changes: 7 additions & 0 deletions .git-blame-ignore-revs
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
# Commits that only reformat code, so `git blame` shows who last changed what a line does (#324).
# GitHub's blame view reads this file. For `git blame` locally, once per clone:
# git config blame.ignoreRevsFile .git-blame-ignore-revs
# Add a commit here only when it changes nothing but formatting.

# ruff format and import order over the tree, except csv_loader/
20cd32e8e8a203e9db27091cd74f861c5509e994
14 changes: 12 additions & 2 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -4,15 +4,25 @@
# pre-commit install (Windows PowerShell too: pre-commit runs these hooks itself)
# pre-commit run --all-files (optional: check the whole tree now)
#
# ruff import order (fixed in place) and formatting, as pyproject.toml [tool.ruff] configures them; a
# commit the hook changed stops, so you can look at the change and stage it
# flake8 the lint options in .flake8, which match scripts/lint.sh (the CI lint)
# bandit as scripts/lint.sh runs it: medium severity and up, not over test code (tests/, e2e/)
# gitleaks the secret scan, with the repository's .gitleaks.toml, over the staged changes (#326)
# mypy the type check configured in pyproject.toml (#323)
# gap-registers tests/unit/test_gap_registers_agree.py, when a gap register or the VCRM changes
#
# No formatter yet: adopting one means reformatting the codebase, which #324 wants as a separate one-off commit.
# Versions: flake8 and bandit are the minimums requirements-dev.txt asks for; gitleaks is the one security-scan.yml runs.
# Versions: ruff, flake8 and bandit are the minimums requirements-dev.txt asks for; gitleaks is the one
# security-scan.yml runs.
repos:
- repo: https://github.com/astral-sh/ruff-pre-commit
rev: v0.17.6
hooks:
- id: ruff-check
args: ["--fix"]
- id: ruff-format
types_or: [python] # not Markdown: see include in pyproject.toml [tool.ruff]

- repo: https://github.com/PyCQA/flake8
rev: 7.3.0
hooks:
Expand Down
7 changes: 6 additions & 1 deletion Makefile
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
.PHONY: test-free test-gate test-evals test-e2e test-all coverage \
test-unit test-system test-egress-blocked check-bundle security-evidence test-sit test-performance test-accessibility test-uat \
lint lint-diff typecheck health \
lint lint-diff format typecheck health \
eval-list eval-compare eval-summary select-tests \
csv-load csv-list csv-demo

Expand Down Expand Up @@ -114,6 +114,11 @@ lint:
lint-diff:
bash scripts/lint_diff.sh

# Format the code and order imports (#324), configured in pyproject.toml [tool.ruff]. `make lint` only checks.
format:
python3 -m ruff check --fix --quiet .
python3 -m ruff format --quiet .

# Static type check (#323): api/ and streamlit_app/, configured in pyproject.toml [tool.mypy]. The free-tier CI job
# runs it after the lint, and the pre-commit hook runs the same command.
typecheck:
Expand Down
18 changes: 16 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -304,7 +304,8 @@ python evals\runner.py --tiers p,i,s,e # 27 scenarios: Tier P 23, I 1, S 1, E
| `quality-gate.yml` — `integration-postgres` | ubuntu | the check named **integration (postgres service)**: passes only if the shards, the egress job and the coverage gate all passed (or were all skipped for a documentation-only change) |
| `python-validator-tests.yml` | windows | database-free markers |

The `free-tier` job also runs the lint (`make lint`) and the type check (`make typecheck`).
The `free-tier` job also runs the lint (`make lint`, which includes the format and import-order check) and the type
check (`make typecheck`).

### Local checks (pre-commit)

Expand All @@ -319,13 +320,26 @@ pre-commit run --all-files # optional: check the whole tree now

| Hook | Checks | Configured in |
|---|---|---|
| ruff-check | import order, fixed in place | `pyproject.toml` `[tool.ruff]` |
| ruff-format | formatting (black's style, 120 columns), fixed in place | `pyproject.toml` `[tool.ruff]` |
| flake8 | the CI lint options | `.flake8` (kept equal to `scripts/lint.sh` by a test) |
| bandit | security lint, medium severity and up, not over `tests/` or `e2e/` | `.pre-commit-config.yaml` |
| gitleaks | secrets in the staged changes | `.gitleaks.toml` |
| mypy | static types in `api/` and `streamlit_app/` (#323) | `pyproject.toml` `[tool.mypy]` |
| gap-registers | the gap registers in `docs/` agree with `docs/VCRM.md` | `tests/unit/test_gap_registers_agree.py` |

Run any of them alone with `make typecheck`, `make lint` or `pre-commit run <hook> --all-files`.
Run any of them alone with `make typecheck`, `make lint` or `pre-commit run <hook> --all-files`. `make format`
formats the whole tree and orders its imports. When a ruff hook changes a file the commit stops: look at the change,
`git add` it and commit again.

The tree was formatted in one commit, listed in `.git-blame-ignore-revs`. GitHub's blame view skips it already; for
`git blame` on your machine, run once per clone:

```bash
git config blame.ignoreRevsFile .git-blame-ignore-revs
```

`csv_loader/` is not formatted yet (`pyproject.toml` explains why); it is checked once it is.
`./preflight.sh` (or `preflight.ps1`) warns if the hooks are not installed.

---
Expand Down
3 changes: 2 additions & 1 deletion alembic/env.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,12 @@
import sys
from pathlib import Path

from alembic import context
from sqlalchemy import create_engine, text
from sqlalchemy.engine import URL
from sqlalchemy.pool import NullPool

from alembic import context

sys.path.insert(0, str(Path(__file__).resolve().parent.parent))

from api.config import settings # noqa: E402
Expand Down
1 change: 0 additions & 1 deletion alembic/versions/0001_baseline.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@
"""

from alembic import op

from api.config import settings

revision = "0001"
Expand Down
2 changes: 1 addition & 1 deletion alembic/versions/0002_registry_unique.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,9 @@
Create Date: 2026-10-26
"""

from alembic import op
from sqlalchemy import text

from alembic import op
from api.config import settings

revision = "0002"
Expand Down
1 change: 0 additions & 1 deletion alembic/versions/0003_import_counts.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@
"""

from alembic import op

from api.config import settings

revision = "0003"
Expand Down
1 change: 0 additions & 1 deletion alembic/versions/0004_control_schema.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@
"""

from alembic import context, op

from api.config import settings

revision = "0004"
Expand Down
1 change: 0 additions & 1 deletion alembic/versions/0005_login_lockout.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@
"""

from alembic import context, op

from api.config import settings

revision = "0005"
Expand Down
21 changes: 12 additions & 9 deletions alembic/versions/0006_append_only_audit.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,6 @@
"""

from alembic import op

from api.config import settings

revision = "0006"
Expand Down Expand Up @@ -68,7 +67,7 @@ def upgrade() -> None:
'before_value', r.before_value, 'after_value', r.after_value)::text, 'UTF8')), 'hex')
$$""")
# Chain the rows that already exist, oldest first.
op.execute(f"""DO $$
chain = f"""DO $$
DECLARE r RECORD; prev TEXT := NULL;
BEGIN
FOR r IN SELECT * FROM {t} ORDER BY id LOOP
Expand All @@ -77,7 +76,8 @@ def upgrade() -> None:
SELECT {s}.audit_row_hash(prev, a) INTO prev FROM {t} a WHERE a.id = r.id;
UPDATE {t} SET row_hash = prev WHERE id = r.id;
END LOOP;
END $$""".replace("TG_SCHEMA_PLACEHOLDER", _literal(settings.UPLOADS_SCHEMA))) # nosec B608 # {s}, {t} are quoted identifiers; the value is escaped by _literal
END $$""" # nosec B608 # {s}, {t} are quoted identifiers; the value is escaped by _literal
op.execute(chain.replace("TG_SCHEMA_PLACEHOLDER", _literal(settings.UPLOADS_SCHEMA)))
op.execute(f"""
CREATE FUNCTION {s}.audit_chain() RETURNS trigger LANGUAGE plpgsql AS $$
BEGIN
Expand All @@ -97,12 +97,15 @@ def upgrade() -> None:
END $$""")
# The trigger takes the id under its lock; the column default would take a second one.
op.execute(f"ALTER TABLE {t} ALTER COLUMN id DROP DEFAULT")
op.execute(f"CREATE TRIGGER audit_chain BEFORE INSERT ON {t} "
f"FOR EACH ROW EXECUTE FUNCTION {s}.audit_chain()")
op.execute(f"CREATE TRIGGER audit_no_change BEFORE UPDATE OR DELETE ON {t} "
f"FOR EACH ROW EXECUTE FUNCTION {s}.audit_reject_change()")
op.execute(f"CREATE TRIGGER audit_no_truncate BEFORE TRUNCATE ON {t} "
f"FOR EACH STATEMENT EXECUTE FUNCTION {s}.audit_reject_change()")
op.execute(f"CREATE TRIGGER audit_chain BEFORE INSERT ON {t} FOR EACH ROW EXECUTE FUNCTION {s}.audit_chain()")
op.execute(
f"CREATE TRIGGER audit_no_change BEFORE UPDATE OR DELETE ON {t} "
f"FOR EACH ROW EXECUTE FUNCTION {s}.audit_reject_change()"
)
op.execute(
f"CREATE TRIGGER audit_no_truncate BEFORE TRUNCATE ON {t} "
f"FOR EACH STATEMENT EXECUTE FUNCTION {s}.audit_reject_change()"
)


def downgrade() -> None:
Expand Down
13 changes: 8 additions & 5 deletions alembic/versions/0007_preserved_uploads.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,6 @@
"""

from alembic import op

from api.config import settings

revision = "0007"
Expand Down Expand Up @@ -69,10 +68,14 @@ def upgrade() -> None:
USING ERRCODE = 'insufficient_privilege';
END $$""")
for t in _TABLES:
op.execute(f"CREATE TRIGGER {t}_no_change BEFORE UPDATE OR DELETE ON {s}.{t} "
f"FOR EACH ROW EXECUTE FUNCTION {s}.audit_reject_change()")
op.execute(f"CREATE TRIGGER {t}_no_truncate BEFORE TRUNCATE ON {s}.{t} "
f"FOR EACH STATEMENT EXECUTE FUNCTION {s}.audit_reject_change()")
op.execute(
f"CREATE TRIGGER {t}_no_change BEFORE UPDATE OR DELETE ON {s}.{t} "
f"FOR EACH ROW EXECUTE FUNCTION {s}.audit_reject_change()"
)
op.execute(
f"CREATE TRIGGER {t}_no_truncate BEFORE TRUNCATE ON {s}.{t} "
f"FOR EACH STATEMENT EXECUTE FUNCTION {s}.audit_reject_change()"
)


def downgrade() -> None:
Expand Down
13 changes: 8 additions & 5 deletions alembic/versions/0008_review.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,6 @@
"""

from alembic import op

from api.config import settings

revision = "0008"
Expand Down Expand Up @@ -56,10 +55,14 @@ def upgrade() -> None:
edited_at TIMESTAMPTZ NOT NULL DEFAULT now())""")
for t in _TABLES:
op.execute(f"CREATE INDEX {t}_by_row ON {s}.{t} (upload_id, row_number, id)")
op.execute(f"CREATE TRIGGER {t}_no_change BEFORE UPDATE OR DELETE ON {s}.{t} "
f"FOR EACH ROW EXECUTE FUNCTION {s}.audit_reject_change()")
op.execute(f"CREATE TRIGGER {t}_no_truncate BEFORE TRUNCATE ON {s}.{t} "
f"FOR EACH STATEMENT EXECUTE FUNCTION {s}.audit_reject_change()")
op.execute(
f"CREATE TRIGGER {t}_no_change BEFORE UPDATE OR DELETE ON {s}.{t} "
f"FOR EACH ROW EXECUTE FUNCTION {s}.audit_reject_change()"
)
op.execute(
f"CREATE TRIGGER {t}_no_truncate BEFORE TRUNCATE ON {s}.{t} "
f"FOR EACH STATEMENT EXECUTE FUNCTION {s}.audit_reject_change()"
)


def downgrade() -> None:
Expand Down
13 changes: 8 additions & 5 deletions alembic/versions/0009_type_provenance.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@
"""

from alembic import op

from api.config import settings

revision = "0009"
Expand All @@ -30,11 +29,15 @@ def _schema() -> str:

def upgrade() -> None:
s = _schema()
op.execute(f"ALTER TABLE {s}.csv_files ADD COLUMN IF NOT EXISTS types_provenance TEXT "
"CHECK (types_provenance IN ('inferred_unconfirmed', 'user_confirmed'))")
op.execute(
f"ALTER TABLE {s}.csv_files ADD COLUMN IF NOT EXISTS types_provenance TEXT "
"CHECK (types_provenance IN ('inferred_unconfirmed', 'user_confirmed'))"
)
# s is the dialect-quoted schema identifier from settings, never request input.
op.execute(f"UPDATE {s}.csv_files SET types_provenance = 'inferred_unconfirmed' " # nosec B608
"WHERE mode = 'dynamic' AND types_provenance IS NULL")
op.execute(
f"UPDATE {s}.csv_files SET types_provenance = 'inferred_unconfirmed' " # nosec B608
"WHERE mode = 'dynamic' AND types_provenance IS NULL"
)


def downgrade() -> None:
Expand Down
40 changes: 27 additions & 13 deletions alembic/versions/0010_versioned_datasets.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,18 +25,20 @@
Create Date: 2026-11-09
"""

from alembic import op
from sqlalchemy import text

from alembic import op
from api.config import settings

revision = "0010"
down_revision = "0009"
branch_labels = None
depends_on = None

_SLUG = ("COALESCE(NULLIF(trim(both '_' from left(trim(both '_' from regexp_replace("
"lower(regexp_replace(file_name, '\\.csv$', '', 'i')), '[^a-z0-9]+', '_', 'g')), 40)), ''), 'dataset')")
_SLUG = (
"COALESCE(NULLIF(trim(both '_' from left(trim(both '_' from regexp_replace("
"lower(regexp_replace(file_name, '\\.csv$', '', 'i')), '[^a-z0-9]+', '_', 'g')), 40)), ''), 'dataset')"
)


def _schema() -> str:
Expand All @@ -54,8 +56,9 @@ def upgrade() -> None:
WHERE f.id = n.id""") # nosec B608
op.execute(f"ALTER TABLE {s}.csv_files ADD CONSTRAINT csv_files_dataset_version_key UNIQUE (dataset, version)")
op.execute(f"ALTER TABLE {s}.csv_files DROP CONSTRAINT csv_files_file_name_key")
op.execute(f"CREATE UNIQUE INDEX csv_files_non_dynamic_file_name ON {s}.csv_files (file_name) "
"WHERE mode <> 'dynamic'")
op.execute(
f"CREATE UNIQUE INDEX csv_files_non_dynamic_file_name ON {s}.csv_files (file_name) WHERE mode <> 'dynamic'"
)
op.execute(f"""CREATE TABLE {s}.row_flags (
upload_id BIGINT NOT NULL REFERENCES {s}.uploads (id),
row_number INTEGER NOT NULL CHECK (row_number > 0),
Expand All @@ -64,22 +67,33 @@ def upgrade() -> None:
matched_file_name TEXT NOT NULL,
matched_version INTEGER NOT NULL,
PRIMARY KEY (upload_id, row_number, kind))""")
op.execute(f"CREATE TRIGGER row_flags_no_change BEFORE UPDATE OR DELETE ON {s}.row_flags "
f"FOR EACH ROW EXECUTE FUNCTION {s}.audit_reject_change()")
op.execute(f"CREATE TRIGGER row_flags_no_truncate BEFORE TRUNCATE ON {s}.row_flags "
f"FOR EACH STATEMENT EXECUTE FUNCTION {s}.audit_reject_change()")
op.execute(
f"CREATE TRIGGER row_flags_no_change BEFORE UPDATE OR DELETE ON {s}.row_flags "
f"FOR EACH ROW EXECUTE FUNCTION {s}.audit_reject_change()"
)
op.execute(
f"CREATE TRIGGER row_flags_no_truncate BEFORE TRUNCATE ON {s}.row_flags "
f"FOR EACH STATEMENT EXECUTE FUNCTION {s}.audit_reject_change()"
)


def downgrade() -> None:
s = _schema()
dupes = op.get_bind().execute(text(
f"SELECT file_name, count(*) FROM {s}.csv_files GROUP BY file_name HAVING count(*) > 1" # nosec B608
)).fetchall()
dupes = (
op.get_bind()
.execute(
text(
f"SELECT file_name, count(*) FROM {s}.csv_files GROUP BY file_name HAVING count(*) > 1" # nosec B608
)
)
.fetchall()
)
if dupes:
listed = ", ".join(f"{name!r} x{count}" for name, count in dupes[:10])
raise RuntimeError(
f"Cannot restore UNIQUE (file_name) on {settings.UPLOADS_SCHEMA}.csv_files: versioned datasets "
f"share a file name ({listed}). Delete the older versions first, then downgrade.")
f"share a file name ({listed}). Delete the older versions first, then downgrade."
)
op.execute(f"DROP TABLE IF EXISTS {s}.row_flags")
op.execute(f"DROP INDEX IF EXISTS {s}.csv_files_non_dynamic_file_name")
op.execute(f"ALTER TABLE {s}.csv_files ADD CONSTRAINT csv_files_file_name_key UNIQUE (file_name)")
Expand Down
Loading
Loading