Skip to content

Store one cliff result per simulation run, and run every database statement through the ORM - #4327

Merged
anth-volk merged 22 commits into
masterfrom
v2plan/c1-37-cliff-results
Nov 24, 2026
Merged

anth-volk merged 22 commits into
masterfrom
v2plan/c1-37-cliff-results

Conversation

@anth-volk

@anth-volk anth-volk commented Nov 17, 2026 •

Copy link
Copy Markdown
Collaborator

Fixes #4326

Summary

This PR does two things:

  1. The cliff impacts table, below: revision bc334f9877b7, cliff_impacts and its grants.
  2. Every database statement through the ORM, in its own section: rule api.data.orm-only, and a rewrite of API v1's production code, scripts and tests to meet it.

The cliff impacts table

Adds revision bc334f9877b7 to the v2 chain (on 9d1d12a7ac58, autogenerated with --rev-id). It creates cliff_impacts: one row per cliff calculation of a simulation run, with the calculation's state and, once it succeeds, the run's cliff gap and cliff share. It also declares the table's grants.

Design decisions

The simulation API's change that writes the table and its change that starts calculations agreed this design before the revision was built:

  • One result per run, linked to the run, not a report. Every report naming the run shares the result. Cliffs need marginal tax rates, which recalculate each household with extra earnings, so a shared run never stores the cliff columns, and US national runs keep their region-group split. A request asking for cliffs starts a separate calculation of the run.
  • The row records the calculation's state: status (the v2_simulation_status type runs use), modal_call_id, error_message (code: message), started_at and completed_at. This lets a request tell "no result" from "being calculated" from "done".
  • At most one calculation per run that hasn't failed (uq_cliff_impacts_unfailed, partial unique on simulation_run_id where status <> 'failed', also declared for SQLite).
    • The simulation service inserts with ON CONFLICT (simulation_run_id) WHERE status <> 'failed' DO NOTHING, so two requests at once start one calculation.
    • A failed calculation never counts, as for runs: it stays as a record, and the next request inserts another.
    • Rejected: one row per run that a retry resets. That would need wider grants, and a stale call could write onto the reset row.
  • Checks: a succeeded or failed row has completed_at; a succeeded row has both numbers, and no other row has either. The numbers aren't range-checked: .py doesn't keep the share to at most 1, and a filtered simulation with no adults gives NaN.
  • CASCADE on the run, as poverty and inequality have. The result is part of its run, and nothing references it.
  • No version columns. A result inherits its run's catalog and package versions, so it is calculated only for a run on the versions the simulation API serves.
  • An index on (status, started_at), so the simulation API's stuck-run sweep can fail a calculation whose worker ended without an outcome.

Grants (policyengine_api/data/v2/privileges.py)

Role Privileges on cliff_impacts
policyengine_v2_simulation_service SELECT, INSERT, UPDATE (status, modal_call_id, error_message, completed_at, updated_at): insert a calculation, record its Modal call, or fail it when Modal refuses the call
policyengine_v2_modal_worker SELECT, UPDATE (status, modal_call_id, error_message, started_at, completed_at, updated_at, cliff_gap, cliff_share): claim, finish or fail; no INSERT
policyengine_v2_runtime SELECT
policyengine_v2_catalog_writer, policyengine_stage12_<environment> none

Neither simulation API role may change the run a row names or delete a row. The deploy's existing reconcile_v2_privileges.py apply and verify steps grant and check these after the schema upgrade; no role needs creating.

The revision

  • Post-generation correction: status reuses the baseline's v2_simulation_status type (postgresql.ENUM(..., create_type=False)), as 1356f658347d does for simulation_runs.status. The generated create_table would create the type again and fail. This is the only correction, and it is commented in the revision.
  • Downgrade: drops only the table, with its rows, and leaves the type to simulation_runs.
  • Compatibility: it writes no data and changes no other table. API v1's previous release doesn't map the table, so it keeps working at this revision.
  • Head: V2_ALEMBIC_HEAD_REVISION moves to bc334f9877b7.
  • Out of scope here:
    • report_runs' four cliff columns stay until a later revision drops them.
    • API v1 doesn't read the table yet.
    • Until the simulation API writes the table, no run has a cliff calculation.
  • Parent moved after Store dynamics like policies, create them through /v2/dynamics, and keep gov.simulation parameters out of policies #4325: the revision was generated on f519a77ba122. Store dynamics like policies, create them through /v2/dynamics, and keep gov.simulation parameters out of policies #4325's dynamics revision 9d1d12a7ac58, on the same parent, merged first, so this PR merges master and now revises 9d1d12a7ac58. Generating it again from there gives the same operations.

Docs

  • docs/engineering/skills/alembic-migrations.md: a section for this revision, plus the two simulation roles' rows in the role table.
  • The downgrade chains in that file, docs/migration/stage-9-v2-metadata.md and docs/migration/stage-12a-user-login.md.

CI for #4325's dynamics tests

#4325 added two PostgreSQL modules that no CI job ran. One of its tests broke when this revision moved onto the dynamics revision, and CI didn't catch it.

  • test_alembic_v2_dynamics.py::test_the_downgrade_fails_changing_nothing_while_a_dynamic_is_stored now downgrades to the dynamics revision instead of upgrading to it, because the head is now later than that revision. It also checks that the failed downgrade leaves legacy_policy_mappings.dynamic_id in place.
  • .github/scripts/test_alembic_v2_lifecycle.sh now runs test_alembic_v2_dynamics.py. These tests downgrade and upgrade the schema, so they run in the V2 Postgres migration lifecycle job, with its own database, like every other revision's migration tests.
  • v2-integration-check.yml's policy persistence step now also runs test_v2_dynamic_persistence.py, after the managed roles get their privileges, since it runs as API v1's runtime role.
  • The dynamics migration tests' engine fixture now checks that the target is the disposable database before upgrading it, as the cliff impacts fixture does.
  • tests/unit/test_alembic_workflows.py requires both modules where they now run, and that the migration tests stay out of the integration job.

Every database statement through the ORM

The rule

api.data.orm-only (rules/registry.toml) says that code reading or writing database rows:

  • declares tables only as SQLAlchemy ORM mapped classes, SQLModel classes included;
  • runs every statement through an ORM Session on those classes;
  • never uses Core Table objects, Connections or handwritten SQL, apart from the registry's named exceptions.

It's as strict as sim's sim.persistence.orm-only. It also covers tests, which sim's doesn't. It scans policyengine_api/, scripts/, tests/ and .github/. migrations/ is excluded, as for api.data.sqlalchemy-and-alembic-only.

How it's checked:

  • The checker, tests/unit/data/orm_access_support.py, is a port of sim's, with SQLModel treated as the ORM. It reports:
    • Core table declarations and reads;
    • engines and Connections outside the session-factory modules;
    • handwritten SQL: text, TextClause, literal_column, DDL, exec_driver_sql and driver cursors;
    • database drivers' connections opened outside the session-factory modules.
  • The tests: tests/unit/data/test_orm_only.py holds the rule tests, and the checker's unit tests are in test_orm_access_support.py and test_orm_only_exceptions.py.
  • Session-factory modules: only these may create an engine or open a Connection:
    • policyengine_api/data/orm.py and orm_pool_events.py;
    • policyengine_api/data/v1_sessions.py, which is new. Importing it loads no .env file, Cloud SQL connector or pool listeners;
    • policyengine_api/data/v2/database.py;
    • for the tests: tests/fixtures/database_sessions.py, the pool-events tests and their fake driver.
  • Exceptions: each no-orm-form exception names one statement SQLAlchemy can't express, in one module. Outside tests/, and wherever its match names no SQL text, it also names the function it is allowed in. The rule test fails on an unnamed finding, and on an exception that matches nothing. The exceptions:
    • in production code:
      • GRANT/REVOKE and CREATE ROLE in privilege reconciliation;
      • COPY, and the Connection the publishing Session holds, in catalog publication staging;
      • ANALYZE in publication statistics;
      • Alembic's need for a Connection, in the pending-revision check and the v1 schema migration script;
      • reading the dialect's name, in the user-types reads;
    • in tests: TRUNCATE, DROP TABLE, CREATE/DROP ROLE, GRANT, ALTER DEFAULT PRIVILEGES, CREATE VIEW, EXPLAIN, SQLite's BEGIN IMMEDIATE and its foreign-key PRAGMA.

The rules loader gains an optional function on exceptions, accepted only for this rule. The migrations skill (docs/engineering/skills/alembic-migrations.md, "Database statements through the ORM") says how to write each kind of statement.

Production changes

Callers see the same behaviour. The only API change is taking a Session or a Session factory where a function took a Connection or an Engine.

  • Privilege reconciliation reads pg_catalog through read-only mapped classes (postgres_system_catalog.py) and takes Sessions. run() takes session_factories=.
  • The migration target checks: qualify_v2_target(session, settings) and validate_v2_head_schema(session, table_names). migrations/v2/env.py wraps Alembic's Connection in a Session, which joins its transaction.
  • The migration qualification commands use Sessions whose transactions are READ ONLY (postgresql_readonly), with the shared pending_revisions.py.
  • Catalog publication:
    • The staging tables are SQLModel classes on their own registry (publication_staging_base.py). They stay TEMPORARY with ON COMMIT DROP, and Alembic never sees them.
    • With PostgreSQL's statement log on, one full publication sequence sends the same 691 statements as before, in the same order: the same COPY, INSERT ... SELECT, UPDATE and DELETE statements, and the same transactions.
  • Session-factory modules: the public engine functions became private (_v1_engine, _v2_engine, _build_v2_engine), and unpooled Session factories and schema inspectors were added.
  • The scripts v1_database_migration.py and process_v1_household_mirror_event.py take Sessions from v1_sessions.py.
  • The routes serialize through the mappers' columns. The response keys and their order are unchanged.

Behaviour that differs, all checked:

  • The qualification transactions send BEGIN READ ONLY instead of BEGIN then SET TRANSACTION READ ONLY.
  • Some catalog-read and lock statements take bound parameters where they had literals.
  • An ORM update always also sets updated_at on tables that update it automatically.

Environment variables

No deploy command, argument or environment variable changes.

  • Seed v2 database (Alembic through env.py, reconcile_v2_privileges.py, the qualification commands and catalog publication):
    • V2_MIGRATION_DATABASE_URL, V2_DATA_WRITE_DATABASE_URL and SIMULATION_ENTRYPOINT_URL are GitHub environment secrets, set in each step's env:.
    • V2_SUPABASE_PROJECT_REF and V2_SUPABASE_ENVIRONMENT are environment variables, and DEPLOYMENT_ENVIRONMENT is the workflow input, both in the job's env:.
  • Migrate v1 Cloud SQL (v1_database_migration.py through migrate_v1_cloud_sql.sh):
    • POLICYENGINE_DB_INSTANCE_CONNECTION_NAME and the POLICYENGINE_DB_*_PASSWORD_SECRET names are variables of the staging-database and production-database environments, which I confirmed with gh api.
    • The shell script reads the passwords from Google Secret Manager and exports them to the command.
    • Importing the script loads no .env file, as before this PR, so the URLs the shell script unsets stay unset. A unit test checks this.
  • Process one v1 household mirror event: unchanged.
  • CI (v2-integration-check.yml): the new test modules read V2_MIGRATION_DATABASE_URL, V2_ALEMBIC_DISPOSABLE_TEST, DEPLOYMENT_ENVIRONMENT and ALEMBIC_DATABASE_URL. All four are literal job-level values for the job's own PostgreSQL and MySQL services.
  • Unverified: whether the Secret Manager secrets those GitHub variables name exist and hold working passwords. Only GitHub's side was read.

Tests

  • Rewritten: every test that used handwritten SQL, Core tables, engines or Connections now uses ORM statements in Sessions, on mapped classes.
    • Older revisions' tables use small mapped classes on their own registries.
    • Schema reads use SQLAlchemy's Inspector.
  • Role privilege refusals send exactly the columns they test, through test-local mapped classes without onupdate or Python defaults. A temporary wrong column grant now fails the seven tests that the first rewrite had let pass.
  • ON CONFLICT on a partial index sends its condition as a literal. A bound value fails once psycopg prepares the statement.
  • New integration tests run qualify_v2_target's persistent path as non-owner roles. They also check privilege reconciliation's reads of default privileges, sequence, view and materialized-view grants, and CI runs them.
  • CI also runs Store dynamics like policies, create them through /v2/dynamics, and keep gov.simulation parameters out of policies #4325's two dynamics test modules, which no job ran before:
    • test_alembic_v2_dynamics.py, in the V2 Postgres migration lifecycle job;
    • test_v2_dynamic_persistence.py, in the cross-database integration job.

Review

Three review rounds ran. The first used four reviewers: production code, the rule and shared helpers, integration tests, and unit tests. Every bug found was fixed test-first; each round's failing tests have their own "(failing)" commit.

  • Round 1, eight bugs:
    • in the checker: exceptions broader than their reasons, DDL not reported, checks skipped in modules that import neither library, and query_plan;
    • stale rows from a metadata fixture;
    • the lost unit-level READ ONLY check;
    • refusals that updated_at weakened;
    • .env loading in the v1 migration script.
  • Round 2, three checker bugs: what counts as SQL text, module-level findings, and other ways of opening a driver connection.
  • Round 3, two checker bugs: punctuation or comments counted as SQL, and connection classes ending in Connection. No further round reviewed these last fixes.

Testing

Test-first: the first commit holds the failing tests, seen failing because there was no CliffImpact model, no cliff_impacts grants and no revision bc334f9877b7. The tests below were run by node ID against a disposable PostgreSQL 17 database.

  • Unit:
    • test_cliff_impact_models covers the columns, checks and indexes, and checks that SQLite keeps one unfailed calculation per run and refuses numbers on any row but a succeeded one.
    • The privilege manifest's tests for both simulation roles, the runtime role and the new table.
    • The revision chain, and this revision's operations and its one correction.
    • The v2 lifecycle script's test list.
    • test_simulation_run_models' per-simulation result tables.
  • Integration (test_alembic_v2_cliff_impacts, PostgreSQL):
    • the revision adds only its table and no enum type;
    • the downgrade leaves the type, and upgrading again works;
    • two inserts at once start one calculation, and a failed one is retried;
    • the checks, and the CASCADE.
  • Integration (test_v2_simulation_role_privileges, as the managed roles):
    • the simulation service inserts, joins, records a call and fails a calculation, and is refused claiming, writing numbers, changing the run or deleting;
    • the Modal worker claims and finishes, and is refused inserting, changing the run or deleting;
    • the runtime role reads a report run's results and is refused writing;
    • the catalog writer and the Stage 12 role can't read;
    • each simulation role can update exactly its declared columns.
  • Integration (test_alembic_v2_simulation_runs): the head foreign-key test now counts cliff_impacts among the simulation side's tables.
  • Checks:
    • alembic -c alembic-v2.ini check: no drift;
    • reconcile_v2_privileges.py apply --create-missing-roles and verify: pass;
    • also passing: lint-imports, python -m scripts.rules validate, python scripts/run_quality_guards.py, ruff, ruff format and mypy.
  • Explicit mypy on the changed policyengine_api/data/v2/models files reports the Field(sa_type=...) overload error on the new status, started_at and completed_at fields. That is the same error the existing SimulationRun fields have on master; the directory is outside make typecheck-v2.
  • Dynamics tests: the five tests of each module pass by node ID against PostgreSQL 17, and so do the three workflow tests, which failed first.
  • Environment variables: the CI changes add test files to .github/scripts/test_alembic_v2_lifecycle.sh and to one step of v2-integration-check.yml.
    • The lifecycle script's tests read V2_MIGRATION_DATABASE_URL and V2_ALEMBIC_DISPOSABLE_TEST. alembic-v2-check.yml sets both as literal job-level env: values, for the job's own PostgreSQL service.
    • test_v2_dynamic_persistence.py reads the same two, plus DEPLOYMENT_ENVIRONMENT for the managed roles' names, which defaults to test. v2-integration-check.yml sets all three as literal job-level env: values, for its own PostgreSQL service.
    • The deploy steps that apply the revision and grants are unchanged: seed-v2-database.yml, with V2_MIGRATION_DATABASE_URL from each GitHub environment's secrets.
  • No inline suppressions added.

🤖 Generated with Claude Code

anth-volk and others added 3 commits November 17, 2026 17:36
Each simulation run can have one cliff calculation that hasn't failed,
holding its state and, once it succeeds, the run's cliff gap and cliff
share. The tests cover the model, its checks and partial unique index,
the revision that adds the table, and the grants: the simulation service
starts calculations, the Modal workers finish them, the Public API reads
them, and the catalog writer and the Stage 12 role can do neither.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Add cliff_impacts (revision bc334f9877b7, autogenerated on f519a77ba122):
one row per cliff calculation of a simulation run, with its state and,
once it succeeds, the run's cliff gap and cliff share. A partial unique
index allows one calculation per run that hasn't failed, so identical
requests join it and a failed one never counts. The row is deleted with
its run, and inherits the run's versions. Its status reuses
v2_simulation_status, the revision's one post-generation correction.

The simulation service may insert calculations and record or fail their
Modal calls, the Modal workers may write their state and results, the
Public API may read them, and no other role may touch them.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The Stage 9 and Stage 12A runbooks' downgrade chains now start with
bc334f9877b7, and the head foreign-key test counts cliff_impacts among
the simulation side's tables. The changelog fragment and the skill
section say what each role may do, since the simulation API writes the
table only once its own change lands.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@codecov

codecov Bot commented Nov 17, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 95.67568% with 24 lines in your changes missing coverage. Please review.
✅ Project coverage is 93.76%. Comparing base (003ee49) to head (41d63f3).
⚠️ Report is 1 commits behind head on master.

Files with missing lines Patch % Lines
...yengine_api/data/v2/catalog/publication_staging.py 65.38% 4 Missing and 5 partials ⚠️
...licyengine_api/data/v2/privilege_reconciliation.py 91.93% 4 Missing and 1 partial ⚠️
policyengine_api/data/v2/catalog/initialization.py 75.00% 2 Missing ⚠️
policyengine_api/data/v2/catalog/publication.py 97.91% 0 Missing and 1 partial ⚠️
...yengine_api/data/v2/catalog/publication_pruning.py 95.45% 0 Missing and 1 partial ⚠️
..._api/data/v2/catalog/publication_reconciliation.py 96.29% 0 Missing and 1 partial ⚠️
...e_api/data/v2/household_migration_qualification.py 94.11% 1 Missing ⚠️
policyengine_api/data/v2/migration_target.py 92.85% 0 Missing and 1 partial ⚠️
policyengine_api/data/v2/pending_revisions.py 90.00% 0 Missing and 1 partial ⚠️
...gine_api/data/v2/policy_migration_qualification.py 94.73% 1 Missing ⚠️
... and 1 more
Additional details and impacted files
@@            Coverage Diff             @@
##           master    #4327      +/-   ##
==========================================
+ Coverage   93.63%   93.76%   +0.13%     
==========================================
  Files         408      412       +4     
  Lines       23282    23464     +182     
  Branches     3648     3653       +5     
==========================================
+ Hits        21799    22000     +201     
+ Misses        868      848      -20     
- Partials      615      616       +1     
Flag Coverage Δ
integration 58.66% <87.02%> (+0.86%) ⬆️
unit 90.92% <72.97%> (-0.04%) ⬇️

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

The v2 metadata now holds 51 tables.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The changelog fragment, the migrations skill, the revision's docstring and
two test docstrings now name the service API v1, and the test of its reads
is renamed to match. The revision's schema and grants are unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
anth-volk added a commit that referenced this pull request Nov 19, 2026
Brings in ddc422c, which changes #4327's wording from "the Public API"
to "API v1" and renames one privilege test. No file this branch changes
is touched, and revision bc334f9877b7 is unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The dynamics revision 9d1d12a7ac58 (#4325) reached master first on the same
parent, so the cliff impacts revision bc334f9877b7 now revises it, and stays
the v2 head. Generating it again from 9d1d12a7ac58 gives the same operations.
The revision tests list both in chain order, the cliff impacts integration
test downgrades to the dynamics revision, and the migrations skill and the
stage 9 and stage 12a downgrade notes name the dynamics revision's step.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
anth-volk and others added 2 commits November 20, 2026 01:13
The cliff impacts revision now follows the dynamics revision, so the test's
upgrade to the dynamics revision from the head did nothing, and its failing
downgrade then rolled back the cliff impacts step too, leaving the database at
bc334f9877b7. A downgrade to the dynamics revision restores what the test
checks: the dynamics downgrade fails and changes nothing while a dynamic is
stored.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The failed downgrade leaves legacy_policy_mappings.dynamic_id in place, which
the dynamics downgrade drops before the step that fails.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
anth-volk and others added 3 commits November 20, 2026 01:29
The V2 Postgres migration lifecycle job is to run test_alembic_v2_dynamics.py,
and the cross-database integration job test_v2_dynamic_persistence.py, after
the managed roles get their privileges, since it runs as the runtime role.
Both came with #4325, and no CI job runs either yet.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The V2 Postgres migration lifecycle script now runs test_alembic_v2_dynamics.py
after the cliff impacts module, against its own disposable database, and the
cross-database integration job runs test_v2_dynamic_persistence.py in its
policy persistence step, after the managed roles get their privileges. Both
read only V2_MIGRATION_DATABASE_URL, V2_ALEMBIC_DISPOSABLE_TEST and, for the
managed roles, DEPLOYMENT_ENVIRONMENT, which each job's env block already sets.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…gration job

The dynamics migration tests' engine fixture now checks that the target is the
disposable database before upgrading it, as the cliff impacts fixture does, so
without one the tests are skipped instead of migrating whatever is configured.
The integration workflow test now also requires that those migration tests
stay out of that job, and says why in its docstring.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
anth-volk added a commit that referenced this pull request Nov 24, 2026
Brings in 22616f1: #4327's CI now runs C1 · 36's dynamics migration
and persistence tests, and the dynamics downgrade test reaches its
revision by a downgrade. No file this branch changes is touched, and
no revision, model or grant changes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
anth-volk and others added 9 commits November 24, 2026 20:00
Adds rule api.data.orm-only: code that reads or writes database rows declares
tables only as SQLAlchemy ORM mapped classes, SQLModel classes included, and
runs every statement through an ORM Session against them, never through Core
Table objects, Connections or handwritten SQL, apart from the registry's named
exceptions. It scans production code, scripts and tests, as strictly as sim's
sim.persistence.orm-only, whose checker this ports with SQLModel treated as the
ORM. The rule test fails for now: it finds 1,692 places in 131 files, which the
following commits rewrite.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…o them

tests/fixtures/database_sessions.py is the tests' one session-factory module:
session factories for the disposable v2 PostgreSQL database as its owner or as a
managed role, for the disposable MySQL database and for in-memory SQLite copies;
act_as and act_as_owner through set_config; schema inspection; statement
recording; and the few statements with no ORM form (TRUNCATE, CREATE and DROP
ROLE, GRANT, SQLite's foreign-key PRAGMA), each a named exception. The shared
row helpers and fixtures now take sessions and add rows through mapped classes,
and the v1 and v2 session-factory modules gain unpooled session factories and
schema inspectors for the production modules that build their own engines.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Rewrites everything rule api.data.orm-only found (1,692 places in 131 files)
so code declares tables only as mapped classes and runs every statement
through an ORM Session; the rule test now passes.

- Production: privilege reconciliation reads Postgres's catalog through
  read-only mapped classes; the migration target checks, the three migration
  qualification commands (READ ONLY Sessions), the v1 schema migration and the
  household mirror script take Sessions from the session-factory modules,
  whose engine functions become private. Catalog publication's staging tables
  are SQLModel classes on their own registry, still TEMPORARY with ON COMMIT
  DROP, and a full publication sequence sends the same 691 statements as
  before. Commands, arguments and environment variables are unchanged.
- Tests: the Alembic lifecycle and revision tests, the report, run and role
  privilege tests, the persistence and v1 MySQL tests and the SQLite unit
  tests use the shared session factories, mapped classes (small ones for
  older revisions' tables) and SQLAlchemy's Inspector. ON CONFLICT on a
  partial index sends its condition as a literal, since a bound value fails
  once psycopg prepares the statement.
- The registry names each statement with no ORM form, in the module that
  runs it: GRANT and REVOKE, CREATE ROLE, COPY and the staging tables'
  Connection, ANALYZE, Alembic's need for a Connection, the dialect's name,
  and the tests' TRUNCATE, DROP TABLE, EXPLAIN, BEGIN IMMEDIATE and roles.
  The old Connection test helpers are gone, and the migrations skill
  describes every helper and exception.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- The checker reports a statement's constant arguments, so an exception for
  SQLite's foreign-key PRAGMA allows no other statement; findings name their
  enclosing function, and exceptions can be narrowed to one; DDL(...) is raw
  SQL; exec_driver_sql, get_bind, raw_connection, connection() and database
  drivers' connect calls are reported in modules that import neither
  SQLAlchemy nor SQLModel. The rules loader reads an exception's function.
- query_plan explains statements with an IN list, a literal parameter and a
  JSON parameter.
- The metadata catalog fixture reads a row changed after its commit.
- Importing the v1 schema migration script loads no .env file, the v2 schema
  inspector reads a plain SQLAlchemy Session, and read-only Sessions make
  every transaction READ ONLY.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- The checker reports a statement's constant arguments and each finding's
  enclosing function, and no-orm-form exceptions can name that function, so
  each exception allows only the statement its reason gives; production
  entries and entries that name only a variable must name their function.
  DDL(...) is raw SQL, and exec_driver_sql, get_bind, raw_connection,
  connection() and database drivers' connect calls are reported whatever a
  module imports. The rules loader and renderer read and show the function.
- query_plan compiles for the session's dialect, expands IN lists and literal
  parameters, and processes each bind, so it explains what the session runs.
- The metadata catalog fixtures expire rows on commit again, and
  serve_v1_sessions restores API v1's cached Session factory after the test.
- API v1's Session factories for one-off commands move to
  policyengine_api/data/v1_sessions.py, so importing the v1 schema migration
  script loads no .env file, Cloud SQL connector or observability runtime, as
  before the conversion. v2_schema_inspector reads any SQLAlchemy Session.
- Role privilege refusals send only the columns they test, through
  test-local mapped classes without onupdate or Python defaults, so a wrong
  column grant makes them fail again.
- New integration tests run qualify_v2_target's persistent path as non-owner
  roles and check privilege reconciliation's reads of default privileges,
  sequence, view and materialized-view grants; CI runs them.
- Duplicated test helpers are shared, two catalog fixtures expire on commit,
  test docstrings say API v1, and the docs describe the narrowed exceptions.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- An exception counts as naming SQL text only for a raw SQL construct or a
  statement method whose first argument holds literal SQL, so entries such as
  sqlite3.connect(':memory:') or text(f'{statement}') must name their function.
- An entry can name module level as its function (<module>), so a finding at
  module level outside tests can be declared.
- Opening a driver connection another way (psycopg.Connection.connect,
  pymysql.Connect, sqlite3.Connection(...) and the like) is reported outside
  session-factory modules.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- An exception counts as naming SQL text only for a raw SQL construct or a
  statement method whose first argument holds literal SQL; every other entry
  names its function. function = "<module>" declares a finding at module
  level. A call that opens a connection through psycopg, psycopg2, pymysql,
  sqlite3 or mysql.connector, by connect, Connect, Connection or
  AsyncConnection, is reported outside session-factory modules.
- The rules loader accepts an exception's function only on api.data.orm-only,
  and renders it only there; the v2 layer checks are tested to treat
  v1_sessions as database code.
- The migrations skill, the rules-registry skill, the v2 Alembic environment's
  docstring, the privilege test helpers' docs and the integration conftest
  describe what the code does.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- A test exception counts as naming one SQL statement only when its literal
  text holds a statement keyword outside SQL comments, so text(f'{statement};'),
  text(f'{statement} -- cleanup') or literal_column('count(*)') must name their
  function.
- Calling any driver class whose name ends with Connection, such as
  mysql.connector's MySQLConnection or psycopg2's RealDictConnection, is
  reported outside session-factory modules.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- A test exception names one SQL statement only when its literal text, with
  SQL comments removed, holds a statement keyword as a whole word; text built
  of punctuation, names or a comment around interpolated values names none.
- A call into a database driver package is reported outside session-factory
  modules when its last name is connect or Connect or ends with Connection,
  which covers MySQLConnection, CMySQLConnection and RealDictConnection.
- The v2 Alembic environment's comment says the head schema check runs only
  when a migration reaches the script heads.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
… the ORM

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@anth-volk anth-volk changed the title Store one cliff result per simulation run in the v2 database, with grants Store one cliff result per simulation run, and run every database statement through the ORM Nov 24, 2026
@anth-volk
anth-volk marked this pull request as ready for review November 24, 2026 19:56
@anth-volk
anth-volk requested a review from a team as a code owner November 24, 2026 19:56
@anth-volk
anth-volk merged commit d2b5dc3 into master Nov 24, 2026
24 checks passed
anth-volk added a commit to PolicyEngine/policyengine-sim-api that referenced this pull request Nov 24, 2026
public-api-commit moves from 63cce8273 to d2b5dc31, API v1's merge of
PolicyEngine/policyengine-api#4327, which adds the cliff_impacts table
(revision bc334f9877b7) and its grants in API v1's privilege manifest. The
`Public API schema` CI job now builds the table this change models, so its
comparison, privilege and write tests can pass.

That commit also contains #4325's revision 9d1d12a7ac58, which stores a
dynamic as it stores a policy: it drops dynamics.name and description and
requires country_id, tax_benefit_model_id, tax_benefit_model_version_id,
canonicalization_version and content_hash. insert_dynamic and insert_policy
now call one shared insert function, with a pair of statements for each
table, which writes those columns from the catalog version, with a
stand-in content hash of the new row's ID. Dynamic's docstring no longer
says a dynamic is named or belongs to no country, and the test rows'
docstrings name API v1.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
anth-volk added a commit that referenced this pull request Nov 24, 2026
C1 · 40's branch brings #4327's rule api.data.orm-only, which refuses
sa.Column(...) anywhere. As C1 · 40 does for the four cliff columns, the
five per-user columns (reports.label, description and user_id, and both
run tables' trigger) are SQLModel fields again, still left out of the
mappers by exclude_properties. Tests stop writing them through the
models, which can't set an excluded column; the privilege tests set
trigger through BudgetWindowRunColumns and ReportRunColumns, and the
column-mapping tests read the stored schema instead of Core tables.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
anth-volk added a commit to PolicyEngine/policyengine-sim-api that referenced this pull request Nov 24, 2026
#1096 moved public-api-commit to d2b5dc31, API v1's merge of
PolicyEngine/policyengine-api#4327, which contains 003ee4996, and rewrote
insert_dynamic to write the same columns. The conflicts keep main's pin and
helper, and this branch's Dynamic.country_id, with the model's docstring
saying that sim reads the country.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
anth-volk added a commit that referenced this pull request Nov 25, 2026
Revision d417fe8b1b17 now sits on 4e30076d4b9f, master's head, instead of
9d1d12a7ac58. Autogenerating it again from 4e30076d4b9f gives the same
operations, which its docstring and the migrations skill now say.

- The head constant, the revision chain test, this revision's own test, the
  lifecycle script and its workflow test, and the skill's downgrade-chain
  paragraph name the new order: d417fe8b1b17, 4e30076d4b9f, bc334f9877b7,
  9d1d12a7ac58.
- Master now runs every database statement through the ORM (rule
  api.data.orm-only). test_alembic_v2_user_dynamics.py and the saved-dynamic
  fixture in test_v2_user_identity_persistence.py move from Core connections
  and SQL text to the owner's Sessions, mapped classes and add_row; the rule's
  test listed their 20 findings before the change and none after.
- Both sides raised the import test's table count from 50 to 51; it is 52
  with cliff_impacts and user_dynamics.
- The report column drops test of the deploy's privilege steps upgraded only
  to 4e30076d4b9f, so apply refused while user_dynamics was declared but
  absent. It now upgrades to the head before applying, as the deploy does.

Each of those tests was seen failing by node ID before the change and passes
after it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

This branch was previously deployed

1 inactive deployment
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Store one cliff result per simulation run in the v2 database, with grants

1 participant