Repository navigation
Conversation
anth-volk
added this pull request to stack #3917
October 14, 2026 18:47
anth-volk
force-pushed
the
ruff-complexity-application
branch
2 times, most recently
from
October 14, 2026 20:04
984feb4 to
e599f21
Compare
anth-volk
force-pushed
the
ruff-complexity-application
branch
5 times, most recently
from
October 14, 2026 22:56
a838da6 to
44ad18f
Compare
Add characterization tests for the application functions that exceed ruff's complexity and argument limits, covering the branches the existing suite did not reach: the ASGI request telemetry order, migration request records and route groups, the v1 household, saved-policy and simulation route error paths, mirror metric log records, saved-policy event decoding, comparison report state rules, household document and v1 translation failures, catalog extraction failures and staging rows, report-run creation, and the statements that map legacy households and saved policies. A small recording session double records each statement (compiled for PostgreSQL) and ORM write in order, so the mapping tests pin the exact queries and writes. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Replace the literal limits and HTTP statuses that ruff's PLR2004 flags with named constants (or HTTPStatus members) in the runtime cache version, the ordinal suffix and place-code checks, the catalog version, identifier and metadata page limits, the legacy date-range split and the gateway and simulation-entrypoint status checks. Error messages keep their wording. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…e value infer_route_group now reads exact paths from a table and searches a path's leading segments up to a named depth, instead of eight separate returns. get_migration_context and get_migration_log_context take the explicit database sources a v2 request names as one ExplicitDatabaseSources value, replacing the use_configured_db_sources flag and its two source arguments; None keeps the configured sources. Migration logging and the tests are updated to match. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…cord register_migration_request_logging now registers thin hooks over three module helpers: record the request's start and identifiers, apply them to the response, and record its migration context. log_migration_request takes one ServedRequest value instead of seven keyword arguments, and the three v2 resource checks share one path parser with a named segment count. The ASGI shell and the tests build ServedRequest values. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…esponse steps create_asgi_app now assembles the app from module helpers: a shutdown lifespan, module-level exception handlers, a request-context middleware and the native routers. The middleware's per-request work moves to _serve_with_request_context, which sets the request's context variables through _RequestContextTokens, records native routes through _NativeRouteTelemetry (begin, annotate the response, log, finish) and applies the response identifiers in _finish_response. The runtime and logger calls happen in the same order, and each still swallows its own errors. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…ne value _record_calculation_failure takes the cell (entity plural, entity id, variable and period) as a _HouseholdCell and the axis population, which is None when the household has no axes, instead of nine separate arguments. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
get_household_under_policy and _calculate now hand a failure to a helper that maps it to its error response in the same precedence as the old except clauses, and _calculate parses the prepared household in its own step. The unrecognized-inputs response is built in one place, and the status comparisons use HTTPStatus members. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
set_user_policy and update_user_policy now read their write configuration, mirror committed events to v2 and validate update fields through shared helpers, and update_user_policy answers the committed update in its own step. The failure record takes one _UserPolicyWriteAttempt instead of five keyword arguments; the legacy ID bound and the 503 comparison are named. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
create_simulation moves its five BadRequest checks into _require_simulation_identity, which raises them in the same order. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
run_v2_operation runs a route's service call and answers a failure with the first V2ErrorMapping it matches (the error's own message or a fixed one), or a 500 with the route's fallback message. The household and policy routes declare their mappings in the order of their old except clauses, so each failure gets the same status and message. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The user-household and user-policy create routes now call a module helper that checks the body and query countries agree and runs the creation, so the router builders stay within the complexity limit. Route registration, order and signatures are unchanged. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The parameter-value listing route reads its query into a frozen ParameterValueListingQuery dependency, whose fields keep the route's OpenAPI parameters byte-identical. The reader protocol and V2MetadataService take a ParameterValueFilter (parameter, current, now) instead of three keyword arguments, the service resolves it with parameter_value_selection, and read_parameter_values takes the resolved ParameterValueSelection. read_parameter_children reads the dialect from the session it is given, so MetadataDatabaseSession no longer exposes dialect_name. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…ison checks ComparisonReportRecord.validate_state keeps its signature and delegates to module helpers: the report lifecycle check (with the successful-report rules in their own step) and the comparison check, which dispatches on comparison_status to the incomplete, completed or failed rules. The rules run in the same order and raise the same messages. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…mbership steps normalize_household_document now checks the supported collections, the saved SPM selection, each collection's records (identity, then contents) and the people's memberships in separate helpers, in the same order and with the same messages and key order. The two require_json_value validators check a container's members in their own helper. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
… people steps translate_legacy_household now checks the source collections, translates each collection's groups (their values and member memberships) and the people in separate helpers that share a _LegacyTranslation holding the person ids, memberships and values read so far. Groups and people are read in the same order and raise the same errors. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
create_legacy_household_mapping takes the LegacyHouseholdSnapshot, which supplies the v1 country, household id and API version, instead of those three values as separate arguments. The insert statement is unchanged. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
read_user_household_page and read_user_household_rows take a UserHouseholdListing (country, user, optional household, offset and limit) instead of five keyword arguments; V2UserHouseholdService.list_user_households keeps its signature and builds the listing. The query is unchanged. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…ne value each LegacyUserPolicyRevision carries a v1 revision's country, saved-policy id, reform label, fingerprint, source revision and changed fields through persist_legacy_user_policy_mapping, apply_existing_legacy_user_policy_mapping, validate_existing_legacy_user_policy_mapping and the mapping insert and update connectors, which also take the projected association instead of its user and policy ids. UserPolicyListing describes a requested page of associations for read_user_policy_page and read_user_policy_rows; list_user_policies keeps its signature. The statements, writes and their order are unchanged. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
create_report_run takes a ReportRunPackageVersions (country package and PolicyEngine.py versions) instead of two separate arguments; it validates them in the same order and stores the same run. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…on steps normalize_json_value now dispatches through an ordered table of type normalizers (float, enum, date, mapping, sequence) and unwraps scalars in its own helper. _normalize_country checks the model identity, release manifest, default dataset and region registry, normalizes parameter nodes, selects each region's dataset and normalizes each region in separate helpers, called in the same order so the same error is raised first. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
_catalog_rows now maps each staging table to a module-level generator (model, variables, parameter nodes, parameters, parameter values, datasets and regions) instead of seven nested closures. Each generator stays lazy and yields the same rows. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…ne value _log_copy_operation and _log_mirror_event take the outcome, write sources, destination result and failure category as one frozen outcome value instead of five or six keyword arguments. The logged records are unchanged. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
mirror_pending_user_policy_events_after_commit takes its event service, reform snapshot loader and mirror factory as one optional UserPolicyMirrorCollaborators value; any collaborator left None still takes its default. _log_mirror_operation takes the mirrored revision and the mirror outcome as two values instead of nine keyword arguments. The policy routes and the tests pass the new values; the logged records are unchanged. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
create_simulation_run and create_report_output_run take an optional NewSimulationRun or NewReportOutputRun holding the run's status, trigger, output, error, source run, spec snapshot, version manifest and fixed ID, with the same defaults, instead of up to ten keyword arguments. The report output service and the tests build the new values; the stored rows are unchanged. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
build_report_spec takes an optional EconomyReportSettings instead of three keyword arguments, with the same defaults; the spec check builds it from the stored economy spec. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The simulation lookup was only ever called with for_update=True, so it is renamed _lock_existing_simulation and always locks. PolicyService's _create_new_policy had no callers and is removed. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…own steps _decode_mirror_event now validates the changed fields and the event type against them in two module helpers, in the same order and with the same messages. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
GatewayAuthTokenProvider takes an optional GatewayAuthCredentials (issuer, audience, client ID, client secret and secret resource) instead of five positional arguments; any setting left None is still read from its environment variable. The tests build the credentials. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
find_unrecognized_household_inputs hands each known entity group to _find_unrecognized_entity_inputs, which reports each variable through _unrecognized_variable; findings keep their order. get_safe_json writes infinities through _safe_json_number. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Calling app.exception_handler(...) on the module-level handlers, as the nested decorators did, keeps their types acceptable to mypy; the handlers are registered the same way. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Cover the paths the refactor touched that no test reached: the 128 character catalog version limit, the one-date-range legacy period rule, the metadata page bounds, the five-digit place FIPS code, enum values that are also tuples or dates, and invalid migration flags in the log context. The new limit and enum tests pass on the pre-refactor code too. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
#3918 added _serialize_region_filter_value, which compares against the literal 255 (PLR2004). Name it MAX_REGION_FILTER_VALUE_LENGTH, the size of the catalog's filter_value column; the error message text is unchanged. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
anth-volk
force-pushed
the
ruff-complexity-application
branch
from
October 15, 2026 00:06
44ad18f to
30cb394
Compare
This branch was successfully deployed
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Fixes #3930
Summary
Phase 1 step 1.8, group 8b, part 2 of 3: the rest of
policyengine_api/, refactored within ruff's complexity limits. Stacked on #3932.tests/fixtures/recording_session.pyrecords every statement, compiled for PostgreSQL, and every ORM write, in order.asgi_factory, complexity 34 and 113 statements):exceptprecedence.run_v2_operation).ComparisonReportRecord.validate_statekeeps its Pydantic signature, with its checks split into helpers.ParameterValueListingQuerydependency; its OpenAPI is byte-identical.NewReportOutputRun,NewSimulationRunandReportRunPackageVersions.ServedRequestvalue.GatewayAuthTokenProvidertakesGatewayAuthCredentials.policy_service._create_new_policy, which had no callers, and an always-true lock flag.HTTPStatusmember, with messages unchanged._serialize_region_filter_value, so flat membership lists such as the England filter are stored as JSON arrays.255limit is nowMAX_REGION_FILTER_VALUE_LENGTH, with the message text unchanged.Testing
make testset at this branch's tip: 2,848 passed, which is the base plus part 1's 166 and this PR's 249.make typecheck-v2is clean. mypy on the 28 changed application files outside that gate gives identical output to the base.ruff check,ruff format --checkand the quality guards (migration-contracts,rules-registry,ci-scripts) pass./v2/openapi.jsonpreview, the legacy spec and every existing model and adapter schema are byte-identical, with and withoutOLD_SIMULATION_GATEWAY_URLset.tests/integration/test_v1_user_policy_dual_write.pyneeds MySQL and PostgreSQL; its 6 call sites were updated.CI completeruns until the PRs below merge.🤖 Generated with Claude Code