Skip to content

Pin policyengine-core >=3.32.0 so concurrent requests stop failing - #41

Merged
MaxGhenis merged 4 commits into
mainfrom
fix/core-concurrency-guard
Oct 23, 2026
Merged

MaxGhenis merged 4 commits into
mainfrom
fix/core-concurrency-guard

Conversation

@MaxGhenis

@MaxGhenis MaxGhenis commented Oct 23, 2026 •

Copy link
Copy Markdown
Contributor

Fixes #38.

Summary

Calculations failed at random with "Calculation failed: The formula for '…' called numpy.random.seed(), but rules-engine formulas must be deterministic…". The cause is policyengine-core 3.28.0's runtime randomness guard running under concurrent requests. This PR moves the engine to policyengine-core 3.32.1, which has no runtime guard, and keeps policyengine-us at 1.755.5, the version production already runs. Displayed numbers do not change. The frontend now retries failed series requests and says so when it can't refine a cliff, instead of silently showing the coarse chart.

Root cause (verified)

  • Where /api/series runs. www.policyengine.org/us/cliffwatch/* is proxied to cliff-watch.vercel.app (policyengine-app-v2 website/src/data/appZoneRoutes.ts). NEXT_PUBLIC_CLIFF_WATCH_API_ORIGIN is unset (the live bundle falls back to the base path), so the browser calls the Vercel Python functions in api/. No cliff-watch Modal app is deployed in any environment.
  • Which engine. The production deployment (dpl_EKnkXrPr9eTPkxm49PkxhJXCxk9U, built from f908f97 on 2026-07-03) floated policyengine-us>=1.715.2. On that date it resolved policyengine-us 1.755.5 and policyengine-core 3.28.0, the newest core then (3.28.0 was released 2026-06-26 and 3.28.1 on 2026-07-06). A local replica of that environment matches live /api/series output exactly: 0 of 57,882 values differ across 7 households.
  • Concurrency. The Vercel project has fluid: true and elasticConcurrencyEnabled: true, so concurrent invocations share one Python process. The page itself sends parallel requests: refineCliffZones refines all cliff zones at once with Promise.all.
  • The race. core 3.28.0's forbid_randomness (simulations/randomness_guard.py) works like this:
    • While any formula runs, it replaces every public callable on numpy.random and stdlib random with a raiser.
    • It tracks this in module-global _depth and _variable_stack, with no lock.
    • Simulation.__init__ calls np.random.seed(0) and np.random.seed(hashed_input). When one request builds its Simulation while another thread is inside a formula, the seed call hits the raiser. The error names the other thread's innermost formula. That's how an Ohio request reported pa_tanf_earned_income_after_deductions_person.
  • The upstream fix. policyengine-core#519 (fixing #518) replaced the runtime guard with a static bytecode check that runs once, when each variable is built (variables/formula_randomness.py). It shipped in 3.30.0 on 2026-07-09, six days after production's build. The published wheels show the runtime guard in 3.27.0 through 3.29.2 and the static check from 3.30.0 on.

Reproduced locally. Production code on the replica environment (us 1.755.5, core 3.28.0), with 7 households × 3 rounds of parallel threads, gave 12 of 21 calculations failing with NonDeterministicFormulaError. The PA household failed naming loss_ald, as in the report.

Why policyengine-us is installed from a commit

PyPI no longer hosts policyengine-us 1.755.5; it keeps roughly one release a week. The nearest hosted releases change the numbers the app shows:

Candidate (all on core 3.32.1) vs live production, 7 households
1.755.5 built from release commit fc64cef 0 of 57,882 values differ
1.755.0 391 differ: the PA example loses Head Start ($17,337 → $0 at $0 earnings)
1.768.1 999 differ, across the AR, MD and NE examples
1.824.6 fails: ccdf_age_group no longer exists, and the calculator sets it

So pyproject.toml installs policyengine-us @ https://github.com/PolicyEngine/policyengine-us/archive/fc64cef….tar.gz. fc64cef is the commit that set the version to 1.755.5. The archive is 10.9 MB, and uv.lock records its sha256 (stable across downloads). The wheel built from it matches PyPI's 1.755.5 wheel exactly: 15,688 package files, every sha256 equal, same Requires-Dist.

policyengine-core is held at >=3.32.0,<3.32.2. 3.30.0 is the first release without the runtime guard; the floor is the 3.32 line this PR was verified on. 3.32.2 and later fail to load 1.755.5's parameter files, which the newer uprating-rounding validation rejects. uv.lock resolves 3.32.1.

Changes

  • pyproject.toml, requirements.txt, modal_app.py: the engine pins above, with the reasons in comments. Hatch is set to allow the direct reference.

  • uv.lock: committed. Vercel installs from it, and CI checks it with uv sync --locked.

  • /api/metadata now returns engine: {policyengine-us, policyengine-core, spm-calculator}, so a deployment can be checked from outside.

  • tests/test_engine_concurrency.py:

    • checks that core's runtime-guard module is absent;
    • runs 6 households in different states in parallel threads (3 rounds, synchronized by a barrier) and checks each result equals the serial result.

    Both tests fail on core 3.28.0, where the concurrency test reproduces the production error, and pass here.

  • .github/workflows/test.yml: runs the frontend tests (node --test) and the Python suite in the locked environment. Before this, CI only built the frontend.

  • Frontend:

    • calculateSeries retries twice on 500/502/503 or a dropped connection, including one that drops while the body is being read, but not on 504, where runSeries already falls back to a coarser step, and not on 4xx.
    • refineCliffZones reports failed zones.
    • The chart note now reads "Couldn't refine 1 of 2 cliff zones, so cliff edges there may be off by up to $2,500. Reload the page to try again." (Reload, not Find cliffs: see "Found along the way".)
    • After a coarse fallback, the note drops "refining around detected cliffs" once refinement finishes.
  • README: how the engine is pinned and checked.

Verified on the Vercel preview (cliff-watch-hckidu2v0, built from this branch)

  • /api/metadata → engine: {policyengine-us: 1.755.5, policyengine-core: 3.32.1, spm-calculator: 0.3.1}, so Vercel built the commit-URL pin from uv.lock.

  • /api/series for the 7 households is identical to live production: 0 of 57,882 values differ.

  • Concurrency (live_concurrency.py): rounds of 21 simultaneous requests, each round covering 7 states with a full-range series and two refinement-shaped requests per household.

    Target Requests Failed
    Current production 63 20, all "rules-engine formulas must be deterministic"
    Preview 63, then 168 0
  • Frontend, in a browser against a local dev stack on this branch, PA share link:

    • Clean run: 1 primary request plus 3 refinements, "refined to $100/year around 3 cliff zones", no notes.
    • Every refinement request forced to 500: 9 attempts (3 zones × 3), then the note "Couldn't refine 3 of 3 cliff zones, so cliff edges there may be off by up to $500. Reload the page to try again." The subtitle no longer claims refinement.
    • Only the first attempt of each refinement forced to 500: 6 attempts, all 3 zones refined, no note.

Invariants

  • Determinism across the engine change. /api/series output is identical to live production for every value, on the JEC example households (AR, MD, NE, PA, TX, WV) and an Ohio Social Security household. Checked with a differential test: live vs the locked environment, 0 of 57,882 values differ.
  • Concurrency. Parallel calculations in one process never raise, and each equals the same calculation run serially (test_concurrent_series_calculations_succeed_and_match_serial).
  • Retry bounds. A series request makes at most 3 attempts. It never retries a 4xx, a 504 or a malformed JSON body. A body that drops mid-read is retried. It surfaces the last error after its retries run out (unit tests in policyengineApi.test.js).
  • Refinement accounting. refinement_zone_count = refined + failed zones. A failed zone keeps its coarse points, and its gap stays one coarse step wide. A failure always produces a visible note (seriesRefine.test.js).

Test results

  • Python, locked env (py3.12): all passed, including the 2 new tests. On the 3.28.0 replica, both new tests fail.
  • Frontend: 69 passed (58 existing + 11 new). The dropped-body test fails on the previous retry loop.

Independent review

GPT-6.1 Sol via Subfleet, hard tier:

  • 1ead0bc: REQUEST_CHANGES.
    • A response body that dropped mid-read escaped the retry.
    • The note pointed at Find cliffs.
    • The core version history was wrong.
  • e2cc22b: APPROVE. All three are resolved, and the serial-vs-concurrent comparison was checked for nondeterministic fields. Its one remaining nit, wording in this description, is fixed.

Interaction with #40

#40 pins policyengine-us==1.755.5 and policyengine-core==3.28.0:

  • The core pin would reinstate this bug.
  • 1.755.5 can no longer be installed from PyPI, so its uv sync --locked and Vercel build will fail once re-run.

When #40 is rebased onto this, it should take this PR's pins and uv.lock (then re-lock). The new guard test fails on any core that still has the runtime guard.

Found along the way (not fixed here)

Every money field (CurrencyField) has step=500, so native form validation rejects ordinary amounts such as rent $10,800 or Social Security $15,600. Three of the six JEC example links (AR, NE, PA) carry such amounts. The rent field sits inside the collapsed "Advanced inputs" section, so the browser can't show its validation bubble ("An invalid form control … is not focusable"), and Find cliffs silently does nothing until the amount is changed to a multiple of $500. Share links still auto-calculate. This needs its own PR.

Not changed

The Modal fallback in modal_app.py gets the same pins but is not deployed: it is not in the production path and no cliff-watch Modal app exists.

axiom: n/a: dependency pins and frontend retry/notice for the cliff-watch app; no policy encoding change

🤖 Generated with Claude Code

MaxGhenis and others added 2 commits October 23, 2026 07:07
Production (Vercel, Fluid compute) runs several /api/series invocations in
one Python process. Its 2026-07-03 build resolved policyengine-core 3.28.0,
whose runtime randomness guard patched numpy.random process-wide while any
formula ran. A concurrent request's Simulation setup calls
np.random.seed(0), hit the patch, and failed with "rules-engine formulas
must be deterministic", naming the other request's formula. core 3.32.0
replaced the guard with a static check when variables are built.

The engine stays policyengine-us 1.755.5, which production has served
since July. PyPI no longer hosts it, so it is installed from its release
commit's archive; that wheel matches PyPI's 1.755.5 file for file, and
this locked environment reproduces live /api/series output exactly for the
six JEC example households and an Ohio household (0 of 57,882 values
differ). core 3.32.2+ reject 1.755.5's parameter files, so core is held
below 3.32.2.

- uv.lock pins the environment Vercel installs; requirements.txt and the
  Modal image use the same pins.
- /api/metadata reports engine versions so a deployment can be checked.
- tests/test_engine_concurrency.py runs series calculations in parallel
  threads. On core 3.28.0 it fails with the production error.
- CI runs the Python and frontend test suites.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A failed refinement request was only logged to the console, so the chart
silently kept the coarse step around that cliff and the "refining around
detected cliffs" note never cleared.

- Series requests retry twice on 500/502/503 or a dropped connection
  (not on 504, where runSeries already falls back to a coarser step).
- refineCliffZones reports how many zones failed; the chart note then
  says how many zones could not be refined and that cliff edges there may
  be off by up to one coarse step.
- After a coarse fallback, the note drops "refining around detected
  cliffs" once refinement finishes.

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

vercel Bot commented Oct 23, 2026 •

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated
cliff-watch Ready Ready Preview Oct 23, 2026 1:15pm UTC

Request Review

Find cliffs can be blocked by native form validation (money fields use
step=500, so share-link amounts like rent=10800 are invalid, and the
field sits in a collapsed section the browser cannot focus). Reloading
re-runs the calculation from the synced URL in every case.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Review follow-ups on #41:
- fetch resolves once headers arrive, so a connection that dropped while
  the body was read escaped the retry. Read the body inside the retry
  handling; malformed JSON is still not retried.
- The concurrency test now checks each concurrent result equals the same
  calculation run serially, and checks core's runtime-guard module is
  absent instead of a version number.
- Correct the version history: published core wheels 3.27.0 through
  3.29.2 carry the runtime guard; policyengine-core#519 replaced it in
  3.30.0 (2026-07-09).

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

This branch was successfully deployed

1 active deployment
Preview — e2cc22b4 Deployed Oct 23, 2026 by vercel[bot]
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.

Intermittent 'rules-engine formulas must be deterministic' errors from /api/series

1 participant