Skip to content

Release Stage 12 database sessions and keep original failures visible - #789

Merged
anth-volk merged 3 commits into
mainfrom
fix/stage12-db-session-release
Oct 14, 2026
Merged

anth-volk merged 3 commits into
mainfrom
fix/stage12-db-session-release

Conversation

@anth-volk

@anth-volk anth-volk commented Oct 13, 2026 •

Copy link
Copy Markdown
Contributor

Fixes #788

Same-Repository Draft PR Check

  • This PR is a draft.
  • This PR is from a branch in PolicyEngine/policyengine-sim-api, not a personal fork.

Summary

Stage 12 processes held pooled database sessions while they calculated or waited, so concurrent runs exhausted the session pooler's 15-client limit. From 6 to 13 October 2026, this caused 106 of the 153 production Stage 12 failures.

  • Release sessions after each operation: create_stage12_engine now uses NullPool, so each physical connection closes when its operation finishes, including after a rollback.
  • Retry only the step that opens a connection:
    • Each Stage12PersistenceStore operation now opens its connection in one place, through a ConnectionOpener (persistence library). The opener receives only the connect step. The operation's statements, and the COMMIT or ROLLBACK that ends it, run after the opener returns, so they are never retried.
    • The retry is decided by where the failure happened, not by the error. SQLAlchemy raises a failed COMMIT, ROLLBACK or BEGIN the same way as a refused connection: an OperationalError with no statement. A COMMIT can fail after the database has applied it. An earlier version of this PR retried on that error, so a coordinator whose claim committed but whose reply was lost would re-run its claim, find its own running row, and return a deduplicated success without dispatching any simulation.
    • The coordinator and worker build their store with open_connection_with_retry (stage12_runtime/database_retry.py). It backs off from 1 s, doubling up to 15 s with jitter, within a 60 s budget for each connection. Each retry is logged at WARNING with the store operation's name.
    • This covers every coordinator and worker store operation, not only the claims: child-state creation, the dispatch placeholder, attaching the Modal invocation, the result comparison and the failure records. With NullPool each of these opens its own pooler session, so each could otherwise fail a report on a single refused connection. On main they reused the coordinator's pooled connection.
    • Failed statements, failed commits and validation errors still fail immediately.
  • Keep the original failure visible in telemetry:
    • The coordinator and worker failure handlers now report the original error to telemetry first. They then attempt the failure-record write (stage12_runtime/failure_recording.py).
    • If that write fails, its error is logged and no longer replaces the error the handler raises.
    • The handlers still raise their stable RuntimeError with no cause (from None), as on main. The original error is therefore visible only in telemetry, not in the exception the Modal call returns.
    • A child failure is reported once.
  • No change to error_summary contents. Recording a redacted cause is a separate change.

Deployment

No environment variables, secrets or Modal function settings change. STAGE12_DATABASE_URL is read exactly as before. This PR doesn't change any workflow, Dockerfile or Modal configuration.

Two services use the changed persistence library. Both deploy through simulation-deploy.reusable.yml, which runs from simulation-deploy.yml on every push to main (staging, then production) and from the manual stage12-deploy.yml.

  • Stage 12 coordinator and workers (versioned v2 Modal app, deploy_stage12_v2 job): they get NullPool and the connection retry described above.
  • Cloud Run Simulation Entrypoint (deploy_entrypoint job):
    • stage12_backend builds one store at startup and reads it on each Stage 12 status request: get_report, then list_simulations.
    • On main, its pool kept up to 5 sessions open per instance between requests (up to 10 under load). Under NullPool, each status poll opens and closes 2 new pooler sessions, adding a connection handshake to each read, and the entrypoint holds no idle sessions between polls.
    • The entrypoint keeps the store's default opener, which does not retry. A refused connection fails that poll immediately, as on main, rather than holding the request for up to 60 s.
    • stage12_infrastructure (the configure_stage12_v2 job's validation) opens a single connection per run, so NullPool doesn't change it in practice.

Not included

  • Marking stale running rows as failed. This needs a scheduled function; see the follow-ups in the issue.
  • Switching to the transaction-mode pooler.

Merge notes

This PR edits the same failure handlers in coordination.py and simulation.py as #791 (record a redacted failure cause) and #793 (share the child wait deadline). The handlers here pass error_summary through a shared helper, so the redacted cause slots into that argument when rebasing. I suggest merging this PR first.

Testing

  • Persistence library (libs/policyengine-stage12-persistence/tests/test_store.py):
    • Regression test for the connection lifecycle: it runs the runtime engine configuration against a real SQLite driver, and checks that the physical connection closes after a successful and a failed transaction and that the next operation gets a new connection. Both cases fail with the previous QueuePool configuration.
    • Store operations open their connection through the opener, with their own operation name, before any statement. A refused connection reaches the opener, and the operation completes after the opener retries it.
    • A COMMIT failure produced by real SQLAlchemy (it has no statement) is raised after the opener returns and is not retried.
    • A store with the default opener, as the entrypoint uses, does not retry a refused connection.
  • tests/test_stage12_database_retry.py:
    • Delays grow and stay bounded, and jitter stays between half and all of the ceiling.
    • Retries stop when the budget is spent.
    • Errors other than a refused connection are not retried.
    • A telemetry failure doesn't stop a retry.
    • Without an observability runtime, each retry is logged at WARNING.
  • tests/test_stage12_runtime.py:
    • The runtime store retries a refused connection when creating child state, and logs the retry with that operation's name.
    • The runtime store does not retry a failed COMMIT.
    • The coordinator does not deduplicate against its own claim after a COMMIT reply is lost: it raises and dispatches nothing. This test fails on the previous version of this PR, which returned a deduplicated success.
    • The coordinator and the worker build their store with their own observability runtime.
    • Both report the original failure before a failure record they can't write.
    • A child failure is reported once, both when waiting for it fails and when dispatching it fails.
  • tests/test_stage12_failure_recording.py: without an observability runtime, the original failure and an unwritable failure record are each logged at ERROR.
  • Suites, on Python 3.13 with uv run --frozen:
    • libs/policyengine-stage12-persistence: 17 passed.
    • projects/policyengine-simulation-executor: 750 passed, 23 skipped.
    • projects/policyengine-simulation-entry: 158 passed.
    • libs/policyengine-simulation-contract was not run; it is unchanged.
  • Formatting, lint and types:
    • With the locked ruff (0.15.11), ruff format --check and ruff check pass on the changed files.
    • pyright reports no errors for stage12_runtime and the persistence library.
  • Not done: a production load test.

🤖 Generated with Claude Code

Stage 12 coordinators and workers held pooled database sessions open while
they calculated or waited, so concurrent runs exhausted the session
pooler's 15-client limit (EMAXCONNSESSION). The runtime engine now uses
NullPool, closing each physical connection when its operation finishes.

Coordinator and worker claims retry, with bounded jittered backoff (60 s
budget), only when a database connection could not be opened. No
statement reached the database in that case, so the retry cannot
duplicate a write. Failed statements and validation errors still fail
immediately.

Coordinator and worker failure handlers now report the original error to
telemetry before writing the failure record, and a failed write no longer
replaces the original error. A child failure is reported once.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
anth-volk and others added 2 commits October 14, 2026 18:42
The claim retry decided whether to retry from the error alone: an
OperationalError without a statement. SQLAlchemy raises a failed COMMIT,
ROLLBACK or BEGIN the same way, and a COMMIT can fail after the database
has applied it. Re-running the coordinator's claim then found its own
running row and returned a deduplicated success without dispatching the
simulations, leaving the report running.

Each persistence store operation now opens its connection through one
connection opener, which receives only the connect step. Statements,
COMMIT and ROLLBACK run after the opener returns, so no opener can retry
them. The coordinator and worker build their store with an opener that
retries a refused connection with the same bounded, jittered backoff
(1 s doubling to 15 s, 60 s budget) and WARNING telemetry naming the store
operation.

Every coordinator and worker store operation therefore retries a refused
connection, not only the claims. Under NullPool each operation opens its
own pooler session, so child-state creation, dispatch bookkeeping and the
later updates could each fail a report on one refusal. The Cloud Run
entrypoint keeps the default opener and does not retry, as before.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Cover the logger fallbacks used when no observability runtime is passed,
and check that a failed child dispatch is reported once. Correct the
failure-record docstring: the report and simulation handlers raise their
stable RuntimeError, so the original cause is visible only in telemetry.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@anth-volk
anth-volk marked this pull request as ready for review October 14, 2026 17:07
@anth-volk
anth-volk merged commit 5484278 into main Oct 14, 2026
11 checks passed
@anth-volk
anth-volk deleted the fix/stage12-db-session-release branch October 14, 2026 17:08
anth-volk added a commit that referenced this pull request Oct 14, 2026
#789 landed on main after this stack branched. Group 8a, which this PR
enables, flags its new code; each fix follows this PR's conventions:

- ARG001/ARG002: open_connection_once and the telemetry-recording test
  runtime keep keyword parameters their protocols pass, with reasons; the
  test's random.uniform stand-in prefixes its unused positional bound.
- PERF203: the connection retry loop catches each refused attempt by
  design, with a reason.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
anth-volk added a commit that referenced this pull request Oct 14, 2026
The rebase onto #789 reports a closed child-wait window to telemetry
before cancellation and report failure records are written, as every
other Stage 12 failure is. This test makes those writes fail and checks
that the timeout still reached telemetry first.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
anth-volk added a commit that referenced this pull request Oct 14, 2026
#789 landed on main after this stack branched. Group 8a, which this PR
enables, flags its new code; each fix follows this PR's conventions:

- ARG001/ARG002: open_connection_once and the telemetry-recording test
  runtime keep keyword parameters their protocols pass, with reasons; the
  test's random.uniform stand-in prefixes its unused positional bound.
- PERF203: the connection retry loop catches each refused attempt by
  design, with a reason.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
anth-volk added a commit that referenced this pull request Oct 14, 2026
The rebase onto #789 reports a closed child-wait window to telemetry
before cancellation and report failure records are written, as every
other Stage 12 failure is. This test makes those writes fail and checks
that the timeout still reached telemetry first.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
anth-volk added a commit that referenced this pull request Oct 14, 2026
The rebase onto #789 reports a closed child-wait window to telemetry
before cancellation and report failure records are written, as every
other Stage 12 failure is. This test makes those writes fail and checks
that the timeout still reached telemetry first.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
anth-volk added a commit that referenced this pull request Oct 14, 2026
The rebase onto #789 reports a closed child-wait window to telemetry
before cancellation and report failure records are written, as every
other Stage 12 failure is. This test makes those writes fail and checks
that the timeout still reached telemetry first.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
anth-volk added a commit that referenced this pull request Oct 14, 2026
The rebase onto #789 reports a closed child-wait window to telemetry
before cancellation and report failure records are written, as every
other Stage 12 failure is. This test makes those writes fail and checks
that the timeout still reached telemetry first.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
anth-volk added a commit that referenced this pull request Oct 16, 2026
* Enable ruff group 2 (typing-only imports) and fix everything it finds

Select TC and move imports used only in annotations under TYPE_CHECKING.
Pydantic evaluates model annotations and FastAPI evaluates endpoint
annotations at runtime, so ruff.toml lists the runtime-evaluated model base
classes (every project base, since ruff only checks direct bases) and the
FastAPI/APIRouter route decorators. scripts/rules matches policyengine-api.

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

* Register TC in the enforced ruff lint rule

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

* Move the typing-only imports #789 added under TYPE_CHECKING

#789 landed on main after this stack branched. TC, which this PR enables,
flags the annotation-only imports in its new database-retry and
failure-recording modules; they now load only under TYPE_CHECKING.

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

* Move the typing-only Callable import #795 added under TYPE_CHECKING

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

* Move the typing-only imports #791 added under TYPE_CHECKING

#791 landed on main after this stack branched. TC, which this PR enables,
flags the imports its new Stage 12 failure-cause module uses only in
annotations (Iterator, Mapping, ObservabilityRuntime, Stage and
StagePlan); they move under TYPE_CHECKING.

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

* List the Pydantic bases ruff reads through imports as runtime-evaluated

Ruff treats a class as runtime-evaluated when a base, read through the
import statements of the class's own module, is listed in
runtime-evaluated-base-classes, or is a class in that same module that is.
It never follows a re-export, and only follows inheritance within a
module. Four models had bases ruff reads at unlisted paths, so ruff would
have moved imports their annotations need under TYPE_CHECKING if they
gained any:

- ArtifactBaselineSimulation and PrecomputedSimulation subclass
  policyengine.py's policyengine.core.Simulation;
- AppSettings subclasses pydantic_settings.BaseSettings;
- EconomyComparison subclassed SingleYearMacroOutput through the
  executor's simulation_macro_output re-export.

The first two paths are listed as their subclasses import them. For
EconomyComparison, compat_models now imports SingleYearMacroOutput from
policyengine_simulation_contract.macro_output, the module that defines
it, and that path is listed: every project entry then names its defining
module, and the entry also covers subclasses elsewhere that import the
class from the contract. The ruff.toml comment now describes how ruff
resolves bases instead of "direct bases only".

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

* Check that ruff treats every Pydantic model as runtime-evaluated

The executor's test imports every module of the executor package and of
the project libraries installed with it; the entrypoint's imports every
module of its package. For every Pydantic model a module-level class
statement defines, they check that:

- ruff treats it as runtime-evaluated, resolving each base the way ruff
  does: through the model module's import statements as they stand at the
  class statement, reading Base[Item] as Base, following bases defined in
  the same module, and never following a re-export or an assignment. A
  failure names the model and the base path to list;
- its annotations resolve, with model_rebuild(raise_errors=True).

Unit tests pin the resolution: a listed base, a subscripted one, a
relative import, a same-module chain through Generic, an unlisted
re-export, an unlisted third-party base, an assigned alias, and a base
in a package's __init__.py, which ruff names with __init__ in its path.
The proof fixtures are compat_models.py before and after the previous
commit.

The executor's src/modal Modal entry files are not imported: they are
not part of the installed package, and importing them builds Modal
images and functions, which their tests do only with a fake Modal SDK
and a patched environment. A static test checks that every class there
derives only from builtins and the standard library, so none can be a
model. The gateway defines no Pydantic models. The entrypoint shares no
package with the executor that could hold test helpers, so it keeps a
copy of the resolution helpers.

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

* Register the runtime-evaluated model rule and document typing-only imports

sim.quality.runtime-evaluated-models-resolve is enforced by the two new
test files, which run in the executor and entrypoint jobs of the PR test
matrix. Its nodes span both projects, so they are listed from the
repository root without a project. The test files join the guard-test
discovery globs, so any test added to them must be registered.

docs/engineering/skills/typing-only-imports.md explains when ruff moves
an import, how it decides a model is runtime-evaluated, and how to list
model bases; AGENTS.md and the skills README point to it.

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

* Move the typing-only imports #781 added under TYPE_CHECKING

#781 landed on main after this stack branched. TC, which this PR enables,
flags the imports its contract job_progress module uses only in
annotations (Mapping and datetime), which move under TYPE_CHECKING, and
the cast in its new integration poll test, whose Client type is quoted.
The module's Pydantic models annotate their timestamps with AwareDatetime,
which stays a runtime import.

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

* List the StageReportingSimulation base #781 added as runtime-evaluated

#781 landed on main after this stack branched. It added
StageReportingSimulation, a policyengine.core.Simulation subclass, and
made ArtifactBaselineSimulation subclass it from another module. Ruff
reads that base through baseline_artifacts' import, which is not listed,
so it would no longer treat ArtifactBaselineSimulation as runtime-evaluated.
The sim.quality.runtime-evaluated-models-resolve guard names the path to
list; it is added beside the other project bases.

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

---------

Co-authored-by: Anthony Volk <14987227+anth-volk@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
anth-volk added a commit that referenced this pull request Oct 16, 2026
* Document the simulation contract library for ruff D

Validators, state helpers and URI functions get docstrings. Every Pydantic
model and enum whose class docstring would become a JSON-schema description
carries a D101 noqa instead, so the published contract schemas and the
OpenAPI documents built from them stay byte-identical.

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

* Document the FastAPI support library for ruff D

The ping and health models and the /ping/alive route are mounted in the
executor app, so they keep their existing (OpenAPI-visible) docstrings under
noqa. The no-op observability methods keep their explicit return None under
RET501 noqa, and two stray string statements in the GCP module become the
docstrings they were meant to be.

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

* Document the simulation observability library for ruff D

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

* Document the Stage 12 persistence library for ruff D

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

* Document the simulation entrypoint for ruff D

The entry routes are nested in create_app, so their docstrings (the OpenAPI
descriptions) are untouched and the generated spec is unchanged.

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

* Document the simulation gateway for ruff D

The /ping router endpoint keeps its OpenAPI description under a D205 noqa;
the golden OpenAPI test still passes. Two placeholder pass statements in the
test fixtures' mock exception classes go now that the classes have
docstrings (PIE790).

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

* Document the simulation executor for ruff D

Covers the executor package, the Modal apps, fixtures, scripts and test
docstrings. Docstrings are added to several Modal functions; images copy
src/modal into a layer, so this changes those layers like any source edit.
Protocol stubs keep their ... bodies.

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

* Document the integration tests, repo scripts and package markers for ruff D

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

* Document the Stage 12 schema-DDL proof fixtures for ruff D

The schema-authority proof reads the fixtures as text; the new docstrings
avoid DDL phrases, so the bad fixture is still rejected and the good one
accepted.

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

* Enable ruff group 4 (docstrings)

Select pydocstyle (D) and ignore D203 and D213, the incompatible halves of
the D203/D211 and D212/D213 pairs. Tests stay exempt from D1 only.

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

* Drop redundant return None from documented no-op methods

With a docstring as the body, the bare return None lines are redundant;
remove them instead of suppressing RET501.

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

* Document published contract models and routes

Replace the 61 D101 suppressions on contract, ping and health models with
class docstrings written for API consumers, and fix the /ping/alive and
gateway /ping route docstrings instead of suppressing D205. Pydantic and
FastAPI copy these into schema and operation descriptions, so the entry,
gateway and executor OpenAPI documents gain descriptions; paths, operations,
properties, types and required lists are unchanged. The gateway golden spec
is regenerated with generate_openapi.

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

* Use the Public API's docstrings in the shared rules tool

Both repos documented scripts/rules independently for ruff D, so the
copies drifted apart. Take the Public API's wording so the tool stays
byte-identical in both repos; only docstrings differ.

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

* Register D in the ruff-lint rule

sim.quality.ruff-lint now lists D, and the rendered rules page and
AGENTS.md Rules block are regenerated for the new tool hash.

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

* Put the docstrings #767 added in the imperative mood

#767 landed on main after this stack branched. D401, which this PR
enables, wants each docstring's summary line in the imperative mood.

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

* Put the docstrings #743 and #744 added in the D style

#743 and #744 landed on main after this stack branched. D, which this PR
enables, flags their new code: blank lines after docstrings (D202), a
two-line summary (D205, D209), summaries that are not in the imperative
mood (D401), an escaped backslash in the sentinel's module docstring
(D301), and three public functions without docstrings (D103).

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

* Put the docstrings #789 added in the D style

#789 landed on main after this stack branched. D, which this PR enables,
flags blank lines after its new docstrings (D202) and the undocumented
__call__ of its ConnectionOpener protocol (D102).

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

* Document the shared object store fake #787 added

#787 landed on main after this stack branched. D, which this PR enables,
flags the undocumented __init__ (D107), upload_bytes and read_bytes (D102)
of the in-memory object store it moved into the executor's fixtures.

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

* Put the docstrings #795 added in the D style

D, which this PR enables, flags the undocumented group_label property
(D102), the budget check's run-on summary (D205, D209) and two test
helpers' summaries that are not in the imperative mood (D401).

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

* Put the docstrings #791 added in the D style

#791 landed on main after this stack branched. D, which this PR enables,
flags blank lines after five of its new docstrings (D202) and the
undocumented __init__ (D107) and stage method (D102) of its StageProgress
tracker.

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

* Put the docstrings #758 added in the D style

#758 landed on main after this stack branched. D, which this PR enables,
flags its permission checks and deployed permission test:

- CallerAuthorizer's initializer and authorize now say what enforcement
  does with a caller that lacks a permission, and that the missing
  permission is always recorded;
- the permission_enforcement fixture says when it skips and when it
  raises, and the enforced-permission deployment test says what it
  checks;
- the blank lines after the docstrings of is_client_credentials,
  granted_permissions, the gty validator and the Cloud Run
  deployment-environment test helper go.

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

* Put the docstrings #781 added in the D style

#781 landed on main after this stack branched. D, which this PR enables,
flags its job progress code:

- the JobProgressReporter protocol and each of its methods say which
  stage boundary the runtime reports; the null reporter's methods say
  what they discard, with the docstring as the body;
- StoredJobProgressReporter's initializer, record, start, set_execution,
  enter, start_segments, segment_completed and attempts say how the
  record changes, including when a call changes nothing;
- the contract's job progress store functions say what they read and
  write, and StageReportingSimulation and its ensure say when the
  callback runs;
- the floor and maximum helpers, the Modal reporter factory, the
  published-record helper and the gateway's stage-field helper are in
  the imperative mood, and blank lines after docstrings go.

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

---------

Co-authored-by: Anthony Volk <14987227+anth-volk@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
anth-volk added a commit that referenced this pull request Oct 16, 2026
* Fix ruff TRY, EM and BLE findings in the FastAPI library

Exception messages move into a msg variable before the raise (EM), with
the text unchanged. The JWT decoder re-raises with a bare raise (TRY201).
Its two JWKS lookup error logs stay traceback-free under a TRY400 noqa,
because callers control the token and a traceback per bad token would let
them flood the logs. The token decode and the GCP project-id probe keep
except Exception under a BLE001 noqa: any decode failure must become a 403,
and any probe failure falls back to GOOGLE_CLOUD_PROJECT.

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

* Fix ruff TRY and EM findings in the simulation contract library

Exception messages move into a msg variable before the raise (EM), with
the text unchanged; Pydantic validators keep raising ValueError, so
callers still get the same ValidationError. resolve_spm_selection and
validate_spm_result move their try bodies into private helpers so no raise
sits inside the try (TRY301, TRY300); the same ValueErrors still become
the same SPMInputError, chained from the original.

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

* Fix ruff TRY, EM and BLE findings in the simulation observability library

Exception messages move into a msg variable before the raise (EM), with
the text unchanged. log_and_redact_exception's fallback log calls
logger.exception with the same explicit exc_info, so its output is
unchanged (TRY400). Its telemetry catch-all keeps except Exception under a
BLE001 noqa, because the helper must never raise.

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

* Fix ruff EM findings in the Stage 12 persistence library

Exception messages move into a msg variable before the raise, with the
text unchanged.

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

* Fix ruff TRY, EM and BLE findings in the simulation entrypoint

Exception messages move into a msg variable before the raise (EM), with
the text unchanged. forward() returns the proxied response from an else
block (TRY300). The four Stage 12 diagnostic error logs stay
traceback-free under a TRY400 noqa: three record only the error type, so a
traceback could carry request or calculation data, and the dispatch
timeout is fully described by its timeout. The Stage 12 context capture
keeps its telemetry catch-all under a BLE001 noqa.

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

* Fix ruff TRY, EM and BLE findings in the simulation gateway

Exception messages move into a msg variable before the raise (EM), with
the text unchanged. The auth misconfiguration log keeps its message and
gains a traceback through exc_info=True (TRY400). _runtime keeps
RuntimeError and _resolve_policyengine_route keeps ValueError under a
TRY004 noqa, because handlers and callers depend on those types. The
job-status and budget-window handlers keep their catch-alls under a
BLE001 noqa: call.get re-raises whatever the worker raised, and every
failure must become a failed-job response or fall back to the seed state.
The auth-bypass event keeps its catch-all too. The golden OpenAPI spec is
unchanged.

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

* Fix ruff TRY, EM and BLE findings in the simulation executor

Exception messages move into a msg variable before the raise (EM), with
the text unchanged. Raises inside try bodies move into private helpers
(_parse_policy_period_dates, _certified_us_spm_capability,
_require_artifact_digest, _require_local_authority_column), so the same
exceptions reach the same handlers (TRY301, TRY300); dump_package_version
narrows its try to the file read.

qualify_stage12_parity, a local operator CLI that nothing calls or
catches, now raises TypeError for a JSON value that is not an object. The
other TRY004 sites keep their types under a noqa: they cross a Modal
boundary, are documented or asserted by tests, or are recorded by type
name in telemetry and Stage 12 error summaries. The Stage 12 comparison
failure log stays traceback-free under a TRY400 noqa. Worker, cleanup and
telemetry catch-alls keep except Exception under a BLE001 noqa.

The Modal images copy src/modal and policyengine_simulation_executor, so
their layers change like any source edit; src/modal/app.py gains no
future import.

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

* Fix ruff EM findings in the integration tests and repo scripts

Exception messages move into a msg variable before the raise, with the
text unchanged.

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

* Enable ruff group 5 (exceptions and messages)

Select flake8-blind-except (BLE), flake8-errmsg (EM) and tryceratops
(TRY). The preceding commits fix every finding; deliberate catch-alls,
kept exception types and traceback-free error logs carry an inline noqa
with the reason. Tests get no exemption.

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

* Give every BLE001 suppression an inline reason

Enabling BLE activated suppressions that were written before the rule
was on. Seven had no reason, or kept it only in a comment above; they now
carry it inline, and the "- reason" ones use the "  # reason" form.

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

* Name hoisted SPM error codes error_code, not msg

The EM fix moves an exception's first literal argument into a variable
called msg. SPMInputError's first argument is an error code, followed by
the message, so those 20 variables are renamed error_code. The gateway
file also moves its BLE001 suppression reason to the "  # reason" form.

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

* Register TRY, EM and BLE in the ruff-lint rule

sim.quality.ruff-lint now lists the group 5 families, and the rendered
rules page and AGENTS.md Rules block are regenerated.

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

* Name hoisted parity mismatch codes error_code, not msg

ParityMismatch takes a code and a schema path, not a message, so the 26
variables the EM fix named msg are renamed error_code.

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

* Fix the group 5 changelog line's YAML and wording

The colon after "(TRY, EM, BLE)" made YAML read the item as a mapping
rather than a string. The line also said error types were unchanged,
but two type checks in qualify_stage12_parity.py now raise TypeError.

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

* Build the exception messages #743 and #744 added before raising

#743 and #744 landed on main after this stack branched. EM and TRY003,
which this PR enables, flag 34 raises in their sentinel, routing and
package-update code that pass a literal message. Each message now moves
into a msg variable before the raise, with the text unchanged.

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

* Build the exception messages #789's tests raise before raising

PR enables, flag five raises in its new Stage 12 tests that pass a literal
message; each message now moves into a msg variable first. TRY301 flags
the raise inside the pooling test's transaction, which moves into a small
helper so the same RuntimeError still ends that transaction.

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

* Build the exception messages #795 added before raising

#795 landed on main after this stack branched. EM and TRY003, which this
PR enables, flag its two new RuntimeError raises (a child that timed out
and a spent parent budget) and the cancel failure its test fake raises;
each message now moves into a msg variable first, with the text
unchanged. BLE001 flags _cancel_call, which now holds the best-effort
cancel loop this PR suppressed; it keeps that suppression with its
reason inline.

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

* Build the exception messages #791's tests raise before raising

#791 landed on main after this stack branched. EM and TRY003, which this
PR enables, flag ten raises in its new Stage 12 failure-cause and runtime
tests that pass a literal message; each message now moves into a msg
variable first, with the text unchanged. TRY301 flags the raise inside
the try of the _raised helper, which now captures the raised error, with
its traceback, through pytest.raises; that also drops the helper's blind
except and its BLE001 suppression.

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

* Write the BLE001 suppressions #791 added with an inline reason

#791 landed on main after this stack branched. Its two new blind-except
suppressions in the Stage 12 failure-cause module gave their reasons in
the "- reason" form; like every other BLE001 suppression in this PR,
they now use the "  # reason" form, with the reasons unchanged.

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

* Build the exception messages #758 added before raising

#758 landed on main after this stack branched. EM and TRY003, which this
PR enables, flag four raises with a literal message: the deployed
permission_enforcement fixture's RuntimeError and three stand-ins in its
permission tests. Each message now moves into a msg variable first, with
the text unchanged.

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

* Write the BLE001 suppression #758 added with an inline reason

#758 landed on main after this stack branched. The blind except around
its simulation_entry_permission_missing event gave its reason in the
"- reason" form; like every other BLE001 suppression in this PR, it now
uses the "  # reason" form, with the reason unchanged.

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

* Build the exception messages #781 added before raising

#781 landed on main after this stack branched. EM and TRY003, which this
PR enables, flag nine raises with a literal message: the contract's
segment-count validator and eight stand-ins in its executor and gateway
job progress tests. Each message now moves into a msg variable first,
with the text unchanged.

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

* Write the BLE001 suppressions #781 added with an inline reason

#781 landed on main after this stack branched. Its five new blind-except
suppressions, in the Modal app's reporter and stage-duration helpers, the
stored reporter's read and write, and the gateway's stage-field read,
gave their reasons in the "- reason" form; like every other BLE001
suppression in this PR, they now use the "  # reason" form, with the
reasons unchanged.

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

---------

Co-authored-by: Anthony Volk <14987227+anth-volk@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
anth-volk added a commit that referenced this pull request Oct 16, 2026
…#799)

* Exempt tests from SLF001, INP001 and PLC0415

Tests deliberately reach into private members, pytest test directories
aren't packages, and tests often import inside a test after patching the
environment. Application code still gets every rule.

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

* Drop response_model arguments that repeat the return type (ruff FAST001)

FastAPI takes the response model from the return annotation when
response_model is omitted, so the generated OpenAPI documents are unchanged.

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

* Fix ruff naming and builtin-shadowing findings (N, A, PLC0414, SLF001)

- Alias the shared exit registry as app_exit where it is imported, and keep
  the policyengine_fastapi.exit.exit name that projects import.
- Use snake_case for the OpenTelemetry provider and log-handler locals.
- Add the Error suffix to exceptions that never leave their project:
  BackendUnavailableError, BackendTimeoutError,
  TemporaryStage12UnsupportedRequestError and ParityMismatchError.
  TemporaryStage12DispatchFailed keeps its name, which the entry app logs
  as error_type.
- Keep the camelCase budget-window fields, which are published JSON, the
  explicit re-exports in stage12_execution, and the two deliberate private
  accesses, each with a reason.

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

* Resolve ruff INP001 per directory

Declare the script directories (.github/scripts, scripts and the executor's
scripts) and the rules proof fixtures as namespace packages in ruff.toml.
Ruff's full output, with every rule selected, is otherwise unchanged by the
setting.

The executor's src/modal/utils scripts keep an inline suppression instead:
declaring that directory, or adding an __init__.py, makes ruff treat it as
part of a first-party "modal" package and regroup its Modal SDK imports.
An __init__.py would also change the src.modal source baked into the Modal
images.

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

* Keep deliberate deferred imports in the shared library and CI script (ruff PLC0415)

Each deferred import keeps an inline reason: the GCP exporters, logging
instrumentation and metadata probe load only when used, and only the
bundle-versions command runs where policyengine is installed.

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

* Import the Stage 12 backend at the top of the entry app (ruff PLC0415)

app.py already imports stage12_backend at module level for its exception
types, so binding Stage12ComparisonBackend there too loads nothing new.

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

* Resolve ruff PLC0415 in the gateway

Bind SPMSelection in endpoints.py's existing policyengine_simulation_contract.spm
import. Keep the Modal function body's imports, which build the web app in
its container, and the smoke app's in-image imports, each with a reason.

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

* Resolve ruff PLC0415 in the executor

Move only imports that load nothing new and that no test patches:
pathlib and importlib, the policyengine_simulation_contract helpers, names
from a module the file already imports at the top, and RegionGroupStrategy,
which policyengine.core already loads.

Every other deferred import keeps an inline reason: Modal function bodies and
the image-build and smoke functions, lazily loaded policyengine models and
heavy libraries, call-time resolution that the tests' patch seams rely on,
and import cycles in the runtime.

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

* Wrap long lines in the shared libraries (ruff E501)

Split long messages and the GCP log format with implicit string
concatenation, so every string is unchanged, and rewrap two docstrings that
no published schema uses.

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

* Wrap long generated-client calls in the integration tests (ruff E501)

Bind the long generated endpoint functions to shorter local names before
calling them.

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

* Wrap long lines in the entry project (ruff E501)

Split long strings with implicit concatenation, so every value is unchanged.
The fake curl and gcloud scripts keep their single-line printf output with a
suppression on the string.

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

* Wrap long lines in the executor (ruff E501)

Split long messages and test strings with implicit concatenation, so every
value is unchanged, and shorten docstrings that no published schema uses.
The fake gh script keeps its single-line JSON output with a suppression on
the string.

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

* Wrap long lines in the gateway (ruff E501)

Split the Modal app's FastAPI description with implicit concatenation, so
the published text is unchanged, and shorten four test names.

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

* Wrap the Stage 12 DDL proof fixtures' docstrings (ruff E501)

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

* Enable ruff group 7 (structure and imports)

Select A, E, FAST, INP, N, PLC and SLF. Every finding outside the shared
scripts/rules tool is fixed or carries an inline reason; the rules tool's
findings are fixed upstream and synced separately.

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

* Register group 7 in the ruff-lint rule

sim.quality.ruff-lint now lists A, E, FAST, INP, N, PLC and SLF.

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

* Sync the rules tool from the Public API's group 7

The shared scripts/rules tool takes the Public API's group 7 fixes:
wrapped long lines, BaseUnavailableError, and assert_violation in its
tests. The rendered rules page picks up the tool's new hash.

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

* Fix the ruff group 7 findings in the code #743 and #744 added

#743 and #744 landed on main after this stack branched. Group 7, which
this PR enables, flags their new code; each fix follows this PR's
conventions:

- E501: wrap the long strings in their routing, sentinel, gateway and
  test code; every message and expected value reads the same.
- N818: RoutingConflict never leaves the executor, so it becomes
  RoutingConflictError, as this PR renames the other in-project errors.
- INP001: the sentinel script in src/modal/utils keeps the inline reason
  the other scripts there carry.
- PLC0415: the sentinel's deferred contract and runtime imports and the
  package updater's optional receipt import keep inline reasons.

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

* Keep the long Stage 12 test name #789 added under E501

#789 landed on main after this stack branched. E501, which this PR
enables, flags the signature line of its lost-commit coordinator test,
whose name cannot be wrapped; the line keeps a reasoned suppression
rather than a shorter, vaguer name.

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

* Fix the ruff group 7 findings in the code #791 added

#791 landed on main after this stack branched. E501, which this PR
enables, flags three long string literals in its Stage 12 failure-cause
tests; each is wrapped by implicit concatenation, with its value
unchanged. N818 flags Stage12FailureCause, whose name telemetry records
as the error type of every recorded cause, so it keeps its name under a
reasoned suppression, like TemporaryStage12DispatchFailed.

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

* Fix the ruff group 7 findings in the code #758 added

#758 landed on main after this stack branched. FAST002, which this PR
enables, flags the six entry routes that take the caller's identity as
a "caller: CallerIdentity | None = Depends(...)" parameter. FastAPI's
Annotated form can't be used: this module postpones annotations, and
FastAPI resolves them against the module's globals, where the per-app
permission dependency doesn't exist. No handler reads the parameter.

Each route now declares its permission dependency in the decorator's
dependencies, as the gateway's routes declare require_auth and as these
routes declared authentication before #758. FastAPI still runs the same
dependency before the body is read, so each route checks the same
permission, logs or rejects a missing one the same way, and the OpenAPI
document is unchanged. The CallerIdentity import is no longer used.

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

* Fix the ruff group 7 findings in the code #781 added

#781 landed on main after this stack branched. PLC0415, which this PR
enables, flags four of its deferred imports. As for the executor's other
deferred imports, only an import that loads nothing new and that no test
patches moves to the top:

- the Modal app's NULL_JOB_PROGRESS and StoredJobProgressReporter, whose
  module the app's top-level imports already load, move to the top;
- the job_progress_state store functions stay deferred, resolved per
  call so the tests can patch job_progress_state;
- StageReportingSimulation stays deferred in _build_simulation, resolved
  per call like its neighbours so the tests can patch it;
- the bundle-metadata builder's JOB_PROGRESS_CAPABILITY_VERSION stays
  deferred: the contract package, and pydantic with it, loads only when
  bundle metadata is built.

Each kept import carries its reason inline.

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

* List the lazily loaded packages for ruff instead of suppressing each import

Fourteen heavy or optional packages and modules are only ever imported
inside the function that needs them: the policyengine bundle, countries,
provenance and tax-benefit-model modules, policyengine_us, spm_calculator,
h5py, google.cloud, three OpenTelemetry exporters and instrumentations,
pythonjsonlogger, and the executor's spm and baseline_artifacts modules.
No application module imports any of them at module level.

ruff.toml now lists them in banned-module-level-imports and selects
TID253, so importing one at module level fails (TYPE_CHECKING imports are
still fine), and PLC0415 accepts their in-function imports without a
suppression. That removes 51 PLC0415 suppressions. Tests may still import
them at module level (TID253 joins the test exemptions).

Packages that some application module does import at module level
(pandas, microdf, huggingface_hub, policyengine.core and others) aren't
listed, so their deferred imports keep their reasons.

The nine Modal utility programs, run with python -m from a directory that
isn't a package, take INP001 in their existing file-level entry instead
of one suppression each.

Comments and configuration only: no code changes.

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

---------

Co-authored-by: Anthony Volk <14987227+anth-volk@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
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.

Stage 12 runs exhaust the database session pooler's 15-client limit

1 participant