Skip to content

Read report cliffs from simulation runs' cliff results, and take include_cliffs on re-runs - #4329

Merged
anth-volk merged 29 commits into
masterfrom
v2plan/c1-40-report-cliffs
Nov 25, 2026
Merged

anth-volk merged 29 commits into
masterfrom
v2plan/c1-40-report-cliffs

Conversation

@anth-volk

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

Copy link
Copy Markdown
Collaborator

Fixes #4328

Builds on #4327 (revision bc334f9877b7, table cliff_impacts), which merged into master on 2026-11-24 as d2b5dc310; this PR now targets master.

Summary

  • Cliffs come from the simulation runs. An economy report run's result.cliff_impact is its two simulation runs' succeeded cliff_impacts rows, {baseline, reform}, once both have one, and null otherwise. Nothing in API v1 reads report_runs' four cliff columns any more, so a later revision can drop them. A report run that stored cliffs only in those columns now reads none.

  • Each economy report read gives cliffs: how far the two cliff calculations have got, for the run read in any status. It appears on the get, and on the create and re-run answers, but not on lists or searches, and is null for a report with no run.

    "cliffs": {
      "status": "running",
      "baseline": {"status": "succeeded", "error_message": null},
      "reform":   {"status": "running",   "error_message": null}
    }
    • A side's status: not_calculated, pending, running, succeeded, or failed. A side is failed when its newest calculation failed and none is under way; error_message then says why.
    • The overall status: succeeded once both sides are. Otherwise it is failed if either side is, else not_calculated if either side is, else running if either side is, else pending.
    • Which row a side reads: its simulation run's calculation that hasn't failed (at most one, by uq_cliff_impacts_unfailed), else its newest failed one. One query per distinct simulation run, so a report naming one run on both sides reads it once.
  • include_cliffs on re-runs. POST /v2/reports/{report_id}/runs takes include_cliffs (default false).

    • API v1 sends "include_cliffs": true to the simulation service only when asked, so a re-run that doesn't ask still works on a simulation service whose re-run body takes only force.
    • A household report or budget window asking for cliffs answers 422 before the simulation service is asked or anything is recorded; their creates already refuse the field.
    • The economy create already sends include_cliffs and is unchanged.
  • The four cliff columns leave ReportRun's mapper. They stay SQLModel fields, as Store one cliff result per simulation run, and run every database statement through the ORM #4327's rule api.data.orm-only requires of every column, and exclude_properties leaves them out of the mapper, so ReportRun's SQL never names them: no select, insert or update loads or writes them. The table, ck_report_runs_cliff_impact_complete and the grants are unchanged, so there is no revision. The simulation service can keep writing the columns until its own change deploys.

    • A value given to the constructor is never stored, and on a loaded run the attributes are the table's columns, not values; ReportRun's docstring says so.
    • Tests that set the columns, or read their types, go through tests.integration.privilege_statements.ReportRunColumns, which maps them on a registry of its own, and SQLite's copy of the schema (StoredTable.columns). The ORM guide's "Writing each kind of statement" describes this.
  • ORM only. Store one cliff result per simulation run, and run every database statement through the ORM #4327's rule api.data.orm-only runs every database statement through an ORM Session on mapped classes. This PR's own tests follow it: Session factories for the owner and the runtime role, recorded_statements for the statements the runtime role sends, and rows added through mapped classes.

  • File split. stored_reports.services reached its 800-line limit, so the code that reads reports as the requesting user sees them moves unchanged to stored_reports.requester_views.services. _requesters_view is renamed requesters_view there, because another module now imports it.

  • Changelog fragment: changelog.d/report-cliffs-from-simulation-runs.changed.md.

Merge and deploy order

  1. Store one cliff result per simulation run, and run every database statement through the ORM #4327's revision bc334f9877b7, applied with its grants in staging and production. This PR reads cliff_impacts as the runtime role.
  2. The simulation service's conversion of its database code to mapped classes and Sessions (C1 · 33a to C1 · 33e).
  3. The simulation service's C1 · 38, redone on that conversion, as the default worker's v2 app. It calculates and writes each run's cliff result, and stops writing the four columns. Calculate each simulation run's cliff gap and share as its own cliff result policyengine-sim-api#1096 won't merge as it stands.
  4. The simulation service's C1 · 39, redone on that conversion. It starts the cliff calculations on creates and re-runs with include_cliffs. Start each side's cliff calculation when a report asks for cliffs policyengine-sim-api#1099 won't merge as it stands.

This PR needs only step 1 to deploy safely, and doesn't depend on when steps 2 to 4 happen. Until step 4 deploys:

  • Asking for cliffs is refused. include_cliffs: true answers 422 and the whole request is refused: a create creates no report, and a re-run starts no run. On a create the simulation service answers cliffs_not_available; on a re-run, a validation error naming include_cliffs. API v1 passes either on as 422. The OpenAPI descriptions say so.
  • Reads show no cliffs. Nothing starts calculations, so every side reads not_calculated and result.cliff_impact is null.
  • Dropping the columns needs more than this PR. This release no longer depends on the four cliff columns, but it still maps reports.label, description and user_id and both trigger columns. A separate change (C1 · 40a) stops mapping those five, and must deploy before the later revision (C1 · 41) drops all nine.
  • Older stored cliffs aren't shown. A report run that stored cliffs in the four report_runs columns reads none, and they can't be calculated again until step 4. API v1's callers haven't been asking for cliffs, so few or none are expected, but production hasn't been counted.

Migration notes

  • Route group: v2 reports (/v2/reports: read, create, re-run). Nothing on the Flask path changes.
  • API contract changes, intended:
    • economy report items gain cliffs;
    • the re-run body gains include_cliffs;
    • result.cliff_impact now comes from the simulation runs' cliff results.
  • Generated documents: scripts/export_migration_contracts.py regenerates both migration contract documents unchanged; they don't record this route's answer shape.
  • Deployment: no deploy step, workflow, image, environment variable or secret changes.

Inline suppressions added

  • # noqa: PLR0913 on read_economy_result_rows, the database read of a report run's result rows. It now takes the cliff calculations the report service has already read, so a run's cliffs are read once whatever its status. Its other inputs (the session, the country, the run, its reform simulation run and the local-area flag) are each needed, and a parameter object used only by this one call would add a type without simplifying anything.
  • # noqa: PLR0913 on the integration test helper store_cliff_calculation, which takes the Session, the simulation run, the status and each column a test sets.

Testing

Each test was written first and seen failing for the expected reason, and committed with "(failing)" in the subject before the code that passes it. I ran only the tests this PR adds or changes, by node ID: 48 node IDs, 92 cases with their parameters, all passing. They include six of #4327's tests that read or set the four cliff columns, which this PR changes to read them from SQLite's copy of the schema or set them through ReportRunColumns. The PostgreSQL integration tests ran against a disposable PostgreSQL 17 database built from this branch, with reconcile_v2_privileges.py apply --create-missing-roles and verify, as the runtime role.

  • New:
    • tests/unit/v2/test_report_cliff_reads.py: each side's row; the side and overall statuses; cliff_impact; one run on both sides;
    • tests/integration/test_v2_report_cliff_reads.py: succeeded, still calculating and failed sides; the four columns not read; no run;
    • route, OpenAPI, client-body and re-run tests in test_report_read_routes.py, test_report_run_routes.py, test_simulation_report_reruns.py, test_v2_report_runs.py and test_v2_report_creation.py;
    • client tests pinning the simulation service's two current refusal bodies, in test_simulation_reports.py and test_simulation_report_reruns.py. These passed when written, because API v1 already answers both with 422.
  • Changed:
    • tests/fixtures/economy_results.py stores a result's cliffs as each simulation run's succeeded cliff_impacts row instead of the report run's columns;
    • the golden rebuild test expects no cliff impact from the report-run writer's rows;
    • the privilege manifest test, the report run model test, the migration test of report run types and three simulation role privilege tests read the cliff columns from the table, or set them through ReportRunColumns, instead of through ReportRun's mapper. The test of each role's declared update columns checks every column a model's mapper leaves out.

Also run: ruff, ruff format, make typecheck-v2 (mypy), lint-imports, python -m scripts.rules validate, python scripts/run_quality_guards.py and scripts/export_migration_contracts.py. Rule api.data.orm-only's findings, evaluated with its test's own functions, are empty. alembic -c alembic-v2.ini check finds no schema change, and reconcile_v2_privileges.py apply --create-missing-roles and verify pass; there is no revision or grant change. Explicit mypy on the changed policyengine_api/data/v2/models files reports only the Field(sa_type=...) overload errors those modules already have.

Reviewed in eight adversarial rounds:

  • Round 1 (the build): no bugs. Its code-quality findings are fixed: the economy read has its own method, descriptions are corrected, and a golden test that couldn't fail is replaced by one that fails if the report run's result columns hold a cliff column again.
  • Rounds 2 and 3 (wording for a later simulation service deploy): no behaviour bugs. They found test descriptions that misstated what the simulation service's report run writer stores, and imprecise OpenAPI text. All are fixed.
  • Rounds 4 to 6 (taking the cliff columns out of ReportRun): round 4 found a description implying this release survives the whole later column drop; round 5 found a category name that would have failed the v2 model-layer rule test. Both are fixed, along with their code-quality findings, and round 6 found no bugs.
  • Rounds 7 and 8 (merging Store one cliff result per simulation run, and run every database statement through the ORM #4327's ORM-only rule): round 7 found that six of Store one cliff result per simulation run, and run every database statement through the ORM #4327's tests, written while the cliff columns were still mapped, read or set them through ReportRun's mapper: five failed and one stopped checking them. All are fixed, and a test removed by mistake is back. Round 8 found no bugs, and its code-quality findings are fixed.

🤖 Generated with Claude Code

anth-volk and others added 7 commits November 17, 2026 19:22
…failing)

A report run's cliff impact comes from its two simulation runs' cliff_impacts
rows, not from report_runs' four cliff columns, and an economy report read
says how far each side's cliff calculation has got (cliffs). The fixtures
store a result's cliffs as each simulation run's succeeded calculation.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
An economy report run's cliff impact is its two simulation runs' succeeded
cliff_impacts rows, and no read uses report_runs' four cliff columns any
more, so C1 · 41 can drop them. Each side reads its run's calculation that
hasn't failed, else its newest failed one. Economy report reads (get, and
the create and re-run answers) gain cliffs: an overall status and each
side's status and error message, for a run in any status.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
POST /v2/reports/{id}/runs takes include_cliffs and passes it to the
simulation service, sending it only when asked; a household report's or
budget window's re-run asking for cliffs is refused with 422 before the
service is asked.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
POST /v2/reports/{id}/runs takes include_cliffs and sends it to the
simulation service only when true, so a re-run that doesn't ask still runs
on a simulation service that doesn't take the field yet. A household
report's or budget window's re-run asking for cliffs answers 422 before the
service is asked or anything recorded. The create body's include_cliffs now
says what it starts.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
stored_reports.services reached its 800-line limit. The code that reads
reports as the requesting user sees them (their saved report's label and
their newest requested run) moves unchanged to
stored_reports.requester_views.services; _requesters_view is renamed
requesters_view there, since the report service now imports it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Review round 1's quality findings: the economy read moves into
_economy_report, as household reports and budget windows have theirs; the
result's cliff_impact, the read and create routes, and a re-run of a run on
older versions now say how cliffs read and start, and that a simulation
service that doesn't calculate cliffs per simulation run yet refuses
include_cliffs with 422; get_report names the reform check for a run in any
status. The golden test that couldn't fail is replaced by one that fails if
the report run's result columns hold a cliff column again.

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 98.34711% with 2 lines in your changes missing coverage. Please review.
✅ Project coverage is 93.78%. Comparing base (41d63f3) to head (4766b12).
⚠️ Report is 33 commits behind head on master.

Files with missing lines Patch % Lines
...ices/v2/stored_reports/requester_views/services.py 94.28% 0 Missing and 2 partials ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##           master    #4329      +/-   ##
==========================================
+ Coverage   93.76%   93.78%   +0.01%     
==========================================
  Files         412      413       +1     
  Lines       23464    23537      +73     
  Branches     3653     3662       +9     
==========================================
+ Hits        22000    22073      +73     
  Misses        848      848              
  Partials      616      616              
Flag Coverage Δ
integration 58.77% <95.04%> (+0.11%) ⬆️
unit 90.91% <71.90%> (-0.02%) ⬇️

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.

anth-volk and others added 5 commits November 18, 2026 18:26
The simulation service keeps refusing include_cliffs until it calculates
cliffs per simulation run, so the OpenAPI document must say so wherever it
tells callers to ask for them. Two client tests pin that service's own 422
bodies, which the Public API already reads and answers as 422. Test wording
stops saying the report run writer has already stopped storing cliffs.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A simulation service that doesn't calculate cliffs per simulation run
refuses include_cliffs with 422 and creates or starts nothing, and that can
stay true for some time. The create and re-run routes, their 422 answers,
the re-run body, cliffs and the changelog fragment now say so, and that each
side stays not_calculated meanwhile.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The OpenAPI text must name include_cliffs: true, since false is accepted,
and say that a side with no calculation stays not_calculated, since a side
with a stored calculation keeps its status. Test support stops describing
sim's writers as if they had already changed: the fixture says it leaves out
the report run's cliff columns, which sim's writer can still fill.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The API text names include_cliffs: true, which is what such a service
refuses, and says only a side with no calculation stays not_calculated. A
re-run's request docstring no longer implies that every re-run without the
field runs: a stored report can still be refused for its own stored options.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The fixture and its callers say what they store rather than what sim's
writer stores, so the text holds before and after that writer changes, and
the create 422 keeps its sentence about the message beside the causes it
refers to. No behaviour changes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
anth-volk and others added 6 commits November 19, 2026 02:12
API v1 no longer uses report_runs' four cliff columns, but every whole-row
load of a report run still names them in its SQL. The release serving while
a later revision drops them would then fail each report read.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
ReportRun leaves baseline_cliff_gap, baseline_cliff_share, reform_cliff_gap
and reform_cliff_share out of its mapper, so API v1 neither selects nor
writes them. The table keeps the columns, their check constraint and their
grants, so there is no revision, and a release of this code keeps serving
report reads while a later revision drops them.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Unmapped columns declared as typed fields still look usable: a loaded report
run returns a Column object for them, and a value passed to the constructor
is dropped without an error. The table keeps them through a documented
direct SQLAlchemy category until a revision removes them.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The four columns move from typed SQLModel fields to __table_args__, so a
report run has no attribute or constructor field for them, and API v1's list
of direct SQLAlchemy uses names this one. The ReportRun description now says
this covers only these four: trigger is still mapped, so it needs an earlier
release of its own before a revision drops it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The earlier name contained the text the v2 model layer's rule forbids.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The category no longer contains text the v2 model layer's rule forbids, and
it says API v1 stopped using these columns rather than that nothing does:
the simulation service still writes them until its own change deploys.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
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>
Brings in e87b0ea, which merges master at 003ee49 (C1 · 36's
#4325: stored dynamics and revision 9d1d12a7ac58). Revision
bc334f9877b7 now revises 9d1d12a7ac58 and stays the only v2 head.
master's changes to files this branch also changes are route and
protocol wording and the dynamics protocols; none touches cliffs.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
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 7 commits November 24, 2026 23:16
Brings in 41d63f3, which adds rule api.data.orm-only and runs every
database statement in API v1 through an ORM Session on mapped classes.
Revision bc334f9877b7 and the cliff_impacts table are unchanged.

Resolved where the base's Sessions meet this branch's code:
- test_v2_report_runs.py's re-run stand-in (the one conflict) keeps
  this branch's cliff calculations, on the base's Session;
- store_cliff_calculation takes a Session and adds a CliffImpact row;
- the report creation and re-run tests with cliffs take the files' new
  owner_sessions fixture.

test_v2_report_cliff_reads.py's engines, listener and raw SQL, and
ReportRun's four Core cliff columns, still break the new rule; the
next commits convert them.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…the mapper (failing)

Rule api.data.orm-only, from the base branch, refuses Core Column
declarations, so the four cliff columns go back to SQLModel fields,
still left out of the mapper until C1 · 41's revision drops them (the
user's decision, 2026-11-24). The model test now requires them as
fields with no Core column in __table_args__, and a new test checks
that storing a report run, even one given a cliff value, writes none
of them.

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

Rule api.data.orm-only refuses Core Column declarations, engines,
Connections and handwritten SQL. This branch's own uses become ORM:

- ReportRun's four cliff columns are SQLModel fields again, still left
  out of the mapper by exclude_properties, so API v1 neither loads nor
  writes them, and alembic check finds no change (the user's decision,
  2026-11-24). DIRECT_SQLALCHEMY_EXCEPTIONS describes that form.
- test_v2_report_cliff_reads.py takes the owner's and the runtime
  role's Session factories, records the runtime role's statements with
  recorded_statements, and stores rows through Sessions.
- test_a_report_runs_own_cliff_columns_are_not_read goes: no ORM
  statement can set columns the mapper leaves out, and
  test_reading_a_report_and_its_runs_names_no_report_run_cliff_column
  already shows no read names them.
- RESULT_MODELS maps cliff_impacts, which economy_result_rows gives
  for each simulation run with a cliff impact.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The user's naming rule: "API v1", not "the Public API", in repository
text. Only the sentence this branch added; the test module text
changed with the ORM conversion.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
… the base's tests

Review round 7: the base's ORM rewrite reads the four cliff columns
through ReportRun's mapper and sets them with update(ReportRun), which
it could while they were mapped. With them left out of the mapper,
five of those tests failed at 7ac3104, and one stopped checking them:

- the privilege manifest test and the report run model test read the
  columns from SQLite's copy of the schema, whose StoredTable now has
  its columns;
- ReportRunColumns, on privilege_statements' registry of its own, maps
  the four columns, and the migration test and both privilege tests set
  them through it;
- test_each_simulation_role_updates_exactly_its_declared_columns checks
  the four through ReportRunColumns too. Seen failing for the Modal
  worker with the columns taken out of its declared UPDATE.

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

Review round 7's code-quality findings:
- 93e3be3 removed test_a_report_runs_own_cliff_columns_are_not_read
  saying no ORM statement can set the four columns; ReportRunColumns,
  on a registry of its own, can. The test is back, setting them through
  it, and is the one PostgreSQL check, as the runtime role, that a
  succeeded run with no cliff calculations reads not_calculated.
- DIRECT_SQLALCHEMY_EXCEPTIONS' "table_only_columns_awaiting_removal"
  becomes "columns_left_out_of_the_mapper": the columns are SQLModel
  fields again, so "table only" no longer fits.

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

Review round 8's code-quality findings (it found no bugs):
- test_each_simulation_role_updates_exactly_its_declared_columns takes
  the columns a model's mapper leaves out from its exclude_properties,
  sets them through the class UNMAPPED_COLUMN_CLASSES names, and fails
  for a model with such columns and no class, so the next column left
  out of a mapper can't drop out of the check. Its list is annotated
  and named for what it holds. Seen failing for the Modal worker with
  the cliff columns taken out of its declared UPDATE.
- The privilege_statements, privilege test and run model test module
  docstrings, and the ORM guide's "Writing each kind of statement", say
  how a test sets and reads a column a mapper leaves out.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@anth-volk
anth-volk changed the base branch from v2plan/c1-37-cliff-results to master November 24, 2026 22:30
@anth-volk
anth-volk marked this pull request as ready for review November 25, 2026 14:15
@anth-volk
anth-volk merged commit 16eb1ce into master Nov 25, 2026
26 checks passed
@anth-volk
anth-volk deleted the v2plan/c1-40-report-cliffs branch November 25, 2026 14:15
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.

Read report cliffs from simulation runs' cliff results, and take include_cliffs on re-runs

1 participant