Skip to content

Score bills through the Public API App v3 uses (p451 groundwork) - #246

Draft
DTrim99 wants to merge 8 commits into
mainfrom
score-via-public-api
Draft

DTrim99 wants to merge 8 commits into
mainfrom
score-via-public-api

Conversation

@DTrim99

@DTrim99 DTrim99 commented Dec 3, 2026 •

Copy link
Copy Markdown
Collaborator

From the 2027 sessions, /encode-bill scores bills through the Public API App v3 uses (Teamverse p451), so the tracker's numbers are App v3's numbers: same dataset, model version and cache. Each bill also gets a saved App v3 report its review PR links. This PR is inert until the Public API credential exists: without PUBLIC_API_CLIENT_ID and PUBLIC_API_CLIENT_SECRET, the scripts say so and /encode-bill keeps using compute_impacts.py. It stacks on #242, whose readiness lookup it uses.

What it adds

  • scripts/public_api.py, the calls App v3 makes, with every call carrying an Auth0 client-credentials token:
    • Token: POST https://policyengine-api.uk.auth0.com/oauth/token with grant_type, client_id, client_secret and audience: https://api.policyengine.org/. It's cached until 60 seconds before expires_in.
    • Policy: POST /us/policy with {label, data}, returning result.policy_id.
    • Economy run: GET /us/economy/{policy}/over/{baseline}?region=state/xx&time_period=YYYY.
      • It polls while computing.
      • A 502 whose retry_after_seconds is 180 or less is waited out, up to twice. A longer or missing wait raises.
    • Report record: POST /us/simulation twice (current law is the stored policy 2), then POST /us/report, then PATCH /us/report with status: complete and the output as a JSON string, the way App v3 completes a report.
    • Saved report: POST /v2/user-reports?country_id=us with legacy_report_id and a PolicyEngine-Unauthenticated-User UUID that is stable per bill. It returns the saved report's UUID, which opens at policyengine.org/us/report/{uuid}.
    • Bill values never reach a URL path: the country is checked, IDs must be integers, and the region must match a known pattern.
  • scripts/score_via_api.py scores a reform for one year, or a range with --multi-year --through.
    • Input: --reform-id reads reform_impacts; --reform-json takes publish-reform's config.
    • Output: the result is mapped onto the shapes compute_impacts.py writes, and --output writes them to a file. --write upserts reform_impacts and sets research.app_report_id/app_report_url; before migration 010 it falls back to model_notes.
    • Refused: reforms that name a built-in reform (_use_reform), since the API can't take them.
  • scripts/compare_estimates.py builds the comparison rows and calibration check.
    • Rows: validation_metadata.comparisons in the contract's format (Define the fields App v3 reads for a 2027 bill report #241 section 3: source, tier, kind, estimate, unit, window, pe_estimate, ratio, band, url, note).
    • Sources: the stored fiscal note, the fiscal-finder's key_findings lines, external_analyses, and the scorecard's nearest bills, which are labeled as not this bill.
    • Amount parsing: a number counts as money only with a $ or a scale word, so "FY2028" is never read as an amount. When the text gives no sign, it borrows PolicyEngine's and says so in the row's note.
    • Calibration check: calibration_check is the readiness lookup for the bill's reform and state. There's also a markdown table for the PR, and --write with the migration-010 fallback.
  • /encode-bill gets one new section, "Scoring through the Public API (p451)", before Phase 5b. It says when to use these scripts, to copy the intake fields onto research, and to put the comparison table and the App v3 report link in the PR.

Household examples (added 4 December)

Each bill report in App v3 will show three example households (David, 4 December). This PR adds the tracker side, since it uses the same client and credential:

  • The calls: POST /us/household, then GET /us/household/{id}/policy/{policy_id} under current law and under the bill: the calls App v3's household builder makes (app-v2 app/src/api/household.ts, householdCalculation.ts; API household_routes.py), so the stored numbers match what the builder recomputes. Labels and model_version come from GET /us/metadata.
    • The API reads the household's year from the age of you; with another name for the head it silently uses the current year. The situation therefore uses the builder's names (you, your partner, your first dependent, your tax unit, your household), which also lets the builder open it as is.
  • scripts/household_examples.py: builds each household from a compact spec (--spec, 1–3 households with an id, label and reason), computes it, maps it to the contract's shape, checks it (problems()), prints a table for the review PR, and with --write stores reform_impacts.household_examples.
    • It checks the column and the bill's row before any API call: a missing column exits 3, a missing row 1 (so it never creates a stub row), and a missing credential 2. There's no local fallback, so the numbers can't drift from App v3's model.
    • It refuses households App v3's builder can't make (two unmarried adults, married filing separately). Adults can carry other inputs (for example pension income), so a retirement-exclusion bill can have a target household.
  • Migration 013_add_household_examples.sql adds the JSONB column. Not applied. The number may change at merge, since Add row level security to processed_bills #229 also wants 013.
  • /encode-bill gets a "Household examples" phase: choose three households for the bill (the household its main provision targets, a typical household for the state, and a contrast where a phase-out or cap bites or nothing changes), run the script, put the table in the PR, and write it with the bill. Phase 5b's chart stays.
  • Contract: section 5 of docs/APP_V3_BILL_CONTRACT.md gives the shape and rules. Two details: federal_income_tax is the model's income_tax, and changes leaves out the headline amounts, sums of other variables and totals that restate them, so it lists the lines that actually moved (a credit, a deduction).

Differences from compute_impacts.py output

The API result has no district household counts and no district poverty, so those fields are null instead of guessed:

  • Left null: householdsAffected, totalBenefit, povertyPctChange and childPovertyPctChange.
  • Added: each district's population (people) and relativeChange.

The model version and dataset come from the result's policyengine_bundle (after #1173, a state run names the ACS local-area release, its revision and sha256), not from installed packages.

What the credential needs (for Anthony)

Secret, in state-legislative-tracker Value
PUBLIC_API_CLIENT_ID An Auth0 machine-to-machine client in the policyengine-api tenant (production), authorized for the API https://api.policyengine.org/, with its client ID added to PUBLIC_API_SERVER_CLIENT_IDS
PUBLIC_API_CLIENT_SECRET That client's secret

The defaults are production. For staging, set the variables PUBLIC_API_URL=https://staging-api.policyengine.org, PUBLIC_API_AUTH0_DOMAIN=policyengine-api-staging.uk.auth0.com and PUBLIC_API_AUDIENCE=https://staging-api.policyengine.org/.

Checks

  • uv run --with pytest --with requests --with pyyaml --with numpy --with pandas --with python-dotenv pytest scripts/test_score_via_api.py scripts/test_readiness_lookup.py scripts/test_compute_impacts_datasets.py scripts/test_publish_analysis.py: 94 passed, 43 of them new. All mocked; no network. After merging main on 4 December and adding the household examples: 492 passed (pytest scripts/ without test_compute_impacts_datasets.py), 69 of them new for the examples.
    • The client: token request and renewal, a refused token (the error names Auth0's reason, never the secret), polling through computing to ok, a 502 waited out, a 502 with no or a long wait, the timeout, path safety, and the report and saved-report calls with their headers.
    • The mapping: the result → field mapping, checked against a Georgia result built from the API repo's own US fixture (tests/fixtures/economy_results.py) plus a policyengine_bundle. Also the at-large district rule, multi-year notes, an enacted bill over its baseline policy, and the fallbacks before 010.
    • The comparisons: amount parsing, tiers, bands and rows from every source; the calibration check offline on Add a readiness lookup: calibration and scorecard evidence for a reform in a state #242's fixtures.
  • ruff check and ruff format on the new files: clean.
  • There have been no live calls. They would get 403 until the client exists.

Questions for Anthony

  1. One client per consuming repository, or a shared PolicyEngine-servers client?
  2. Is a v1 report output plus a legacy_report_id saved report the right way to give each bill an App v3 link, or should this wait for POST /v2/reports (app-v2 #1627)?
  3. Does App v3 need anything stored on the v1 report beyond what App v3's own markReportCompleted sends (status: complete plus the output string)?

🤖 Generated with Claude Code

- scripts/public_api.py: the Auth0 client-credentials token (cached until
  shortly before it expires) and the calls App v3 makes: create a policy,
  poll the state economy run (computing until ok; a 502 with a short
  retry_after is waited out, a long or missing one raises), create the v1
  simulations and report, store the result on it, and save a v2 user
  report anyone can open at /us/report/{uuid}. Shapes and the production
  tenant and audience are from policyengine-api master.
- scripts/score_via_api.py: scores a reform (from reform_impacts or a
  publish-reform config) for one year or a range, maps the result onto the
  shapes compute_impacts.py writes, takes the dataset and model version
  from policyengine_bundle, and writes reform_impacts plus research's
  App v3 report link (falling back to model_notes before migration 010).
  Built-in reforms (_use_reform) are refused.
- scripts/compare_estimates.py: validation_metadata.comparisons rows in
  the contract's format (tier, kind, ratio, band) from the stored fiscal
  note, the fiscal-finder's key findings and external analyses, and the
  scorecard's nearest bills; calibration_check from the readiness lookup;
  a markdown table for the PR.
- /encode-bill: a section saying to use these when the credential is set.

Inert until PUBLIC_API_CLIENT_ID and PUBLIC_API_CLIENT_SECRET exist.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
DTrim99 added a commit that referenced this pull request Dec 3, 2026
Anthony added PUBLIC_API_CLIENT_ID and PUBLIC_API_CLIENT_SECRET as repo
secrets on 3 December. #246 scores through the Public API when they are
set; without this the auto-encode job never sees them and keeps scoring
with compute_impacts.py.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
DTrim99 and others added 2 commits December 3, 2026 14:42
After #242's review, the readiness lookup marks a reform whose paths the
dependency trace never recorded as "not resolved" (or "partly traced").
The comparison step's markdown for the review PR now says so, so an empty
check doesn't read as no gaps.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@DTrim99
DTrim99 changed the base branch from readiness-lookup to main December 3, 2026 21:12
… band

Pavel's review of #241: abs(0.9 - 1) is 0.09999999999999998 in floating
point, so a ratio of exactly 0.9 fell in under_10 while 1.1 went to
10_to_25. The gap is now rounded to four places, matching the stored ratio
and the contract's rule.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
readiness_lookup reports an empty reform dict as "not resolved" with no
path (Pavel's review of #242, suggestion B). calibration_check strips the
_ keys, so a reform with only those reached lookup() empty. It now returns
None before any download, as with --no-calibration, and says why on stderr.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
DTrim99 and others added 3 commits December 4, 2026 11:29
…via the Public API

scripts/household_examples.py computes a bill's example households the way
App v3's household builder does: POST /us/household with the situation, then
GET /us/household/{id}/policy/{policy_id} under the stored current-law policy
(or an enacted bill's baseline policy) and under the bill's policy. Labels,
units and the model version come from GET /us/metadata. The result follows
the household examples contract: rounded whole dollars, net income change
from the rounded amounts, and up to five changed lines of $1 or more,
largest first, leaving out headline amounts, sums and restated totals.

- public_api.py: create_household, household_under_policy and metadata,
  with the same path checks as the other calls and a 300 s timeout for a
  cold worker.
- Spec: 1-3 compact households (adults with ages and earnings, children's
  ages, married), built with App v3's entity names.
- validate()/problems() check a finished object; the CLI refuses to write
  one that fails.
- --write upserts reform_impacts.household_examples. Before migration 013
  it stops before computing anything (exit 3). Without the credential it
  stops (exit 2); there is no local fallback.
- --markdown writes the review PR table.
- scripts/sql/013_add_household_examples.sql adds the column (number may
  change at merge: #229 also wants 013). Not applied.
- 69 mocked tests: spec -> situation, result -> example, the validator, the
  household calls' request shape and path safety, and the CLI messages.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
/encode-bill gets a "Household examples (Public API)" phase after Public API
scoring: how to choose the three households (target, typical for the state,
contrast), the spec, the command, checking the result, the PR table, and
--write when the bill is written. The PR template gets a Household examples
section. Phase 5b's chart stays.

The contract doc gets the household_examples field and section 5: its
shape, the rounding, changes and naming rules, and how the three households
are chosen. It is written once migration 013 is applied.

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.

1 participant