Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 4 additions & 3 deletions .github/scripts/run_live_staging_tests.sh
Original file line number Diff line number Diff line change
Expand Up @@ -29,9 +29,10 @@ uv run --frozen --extra dev python -m pytest \
# merges only after that deployment. Their requests are short (a
# submission, then a poll every few seconds) apart from the parity tests'
# /calculate and /calculate-full requests, which the tests wait for longer
# than the candidate's 300 s request timeout (V1_CALCULATION_TIMEOUT_SECONDS in
# tests/fixtures/integration/live_household_calculations.py): /calculate-full
# took 224 s on staging. The parallel check submits 6 calculations at once:
# than the candidate's 900 s request timeout (V1_CALCULATION_TIMEOUT_SECONDS in
# tests/fixtures/integration/live_household_calculations.py), so they get the
# candidate's own answer, a 504 included; /calculate-full took 224 s on
# staging. The parallel check submits 6 calculations at once:
# with the 3 other workers' requests, at most 3 wait for a free slot, as above.
uv run --frozen --extra dev python -m pytest \
-n 4 \
Expand Down
11 changes: 9 additions & 2 deletions .github/workflows/push.yml
Original file line number Diff line number Diff line change
Expand Up @@ -547,6 +547,10 @@ jobs:
CLOUD_RUN_MIN_INSTANCES: "0"
CLOUD_RUN_SERVICE_MIN_INSTANCES: "0"
CLOUD_RUN_MAX_INSTANCES: "1"
# Requests may run for 900 s here, so a slow household calculation
# answers instead of ending in a 504; production keeps cloud_run_env.sh's
# 300. Why: "Request timeout" in docs/migration/cloud-run-operations.md.
CLOUD_RUN_TIMEOUT: "900"
# uv installs uv.lock on the Cloud Run image's Python, not the 3.14
# that .python-version selects.
UV_PYTHON: "3.12"
Expand Down Expand Up @@ -656,8 +660,11 @@ jobs:
name: Run live simulations against the staging candidate
runs-on: ubuntu-latest
# The household calculation checks run after the other live tests and
# wait on Modal.
timeout-minutes: 30
# wait on Modal, and the parity check waits up to 920 s for each API v1
# answer. The two pytest runs together take about 20 minutes, so 45
# minutes leaves room for one answer that takes the full wait; two such
# answers in a row on one worker don't fit.
timeout-minutes: 45
needs: deploy-cloud-run-staging
if: |
!cancelled()
Expand Down
1 change: 1 addition & 0 deletions changelog.d/4372.changed.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
API v1's staging Cloud Run service lets a request run for up to 900 seconds instead of 300, so a slow household calculation on staging answers instead of ending in a 504 while it keeps running. Production keeps 300 seconds.
15 changes: 15 additions & 0 deletions docs/migration/cloud-run-operations.md
Original file line number Diff line number Diff line change
Expand Up @@ -146,6 +146,21 @@ Values measured and justified in
8 for the 100% Cloud Run cutover because at the 50/50 split the service already sat
pinned at the ceiling of 4 during the daytime peak (`instance_count` flatlined at
4.0), so carrying all traffic needs the extra headroom.
- **Request timeout: staging 900s, production 300s.** `cloud_run_env.sh` defaults
`CLOUD_RUN_TIMEOUT` to 300, the deploy script passes it to `gcloud run deploy` as
`--timeout`, and only `deploy-cloud-run-staging` pins it (`CLOUD_RUN_TIMEOUT: "900"`).
When a request passes the timeout, Cloud Run answers 504 but the calculation goes on:
Flask handles the request on a thread of the worker (a2wsgi's `WSGIMiddleware`), a
closed connection does not stop that thread, and a household calculation has no
deadline of its own, so it holds the worker's CPU and memory until it finishes. On
2026-11-30 staging's single instance, with its two workers, was calculating app v3
previews' households, and a reform calculation took about 600s. Every attempt answered
504 at 300s, and the retries added calculations until gunicorn reported a worker
killed by SIGKILL, most likely for running out of memory. 900s lets such a calculation
answer. It does not make one faster, and a caller with a shorter limit of its own,
such as app v3's 240s limit for a household calculation, still gives up first. Every
deploy sets the timeout on the new revision, so a change made by hand with `gcloud`
lasts only until the next release.
- **Warm capacity is applied by CI on every deploy as a service-level `--min`**, via
the `CLOUD_RUN_SERVICE_MIN_INSTANCES` env (production 2, staging 0). CI keeps the
revision-level `--min-instances 0`, because a revision-level minimum keeps a warm
Expand Down
9 changes: 5 additions & 4 deletions docs/migration/stage-11-v2-households.md
Original file line number Diff line number Diff line change
Expand Up @@ -421,10 +421,11 @@ cycle, six calculations submitted at once (each accepted within
`STAGING_HOUSEHOLD_SUBMIT_LIMIT_SECONDS`, 10 by default, and finished within
`STAGING_HOUSEHOLD_FINISH_LIMIT_SECONDS`, 300), a household across 401 axis
points, and a parity set of three US and three UK households compared value
by value with `/calculate` and `/calculate-full`. The parity set waits 320 s
for each `/calculate` or `/calculate-full` answer, longer than the candidate's
300 s Cloud Run request timeout: `/calculate-full` calculates every variable
the household leaves out, which took 224 s on staging. A unit test sends each
by value with `/calculate` and `/calculate-full`. The parity set waits 920 s
for each `/calculate` or `/calculate-full` answer, longer than the staging
candidate's 900 s Cloud Run request timeout, so it gets the candidate's own
answer, a 504 included. `/calculate-full` calculates every variable the
household leaves out, which took 224 s on staging. A unit test sends each
parity household through those routes with the installed country models and
replaces only the calculation, so a household the routes refuse before
calculating, in their input checks or situation parsing, fails before a
Expand Down
14 changes: 7 additions & 7 deletions tests/fixtures/integration/live_household_calculations.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,13 +50,13 @@
TRANSIENT_LIMIT_SECONDS = float(
os.environ.get("STAGING_HOUSEHOLD_TRANSIENT_LIMIT_SECONDS", "90")
)
# How long the check waits for the Public API's own /calculate or
# /calculate-full answer: longer than the candidate's Cloud Run request timeout
# (CLOUD_RUN_TIMEOUT in .github/scripts/cloud_run_env.sh, 300 s), so the check
# gets the candidate's own answer, a 504 included. /calculate-full calculates
# every variable the household leaves out and can take most of that: 224 s on
# staging, and up to 300 s in production.
V1_CALCULATION_TIMEOUT_SECONDS = 320.0
# How long the check waits for API v1's own /calculate or /calculate-full
# answer: longer than the staging candidate's Cloud Run request timeout
# (CLOUD_RUN_TIMEOUT, 900 s, set by push.yml's deploy-cloud-run-staging job),
# so the check gets the candidate's own answer, a 504 included.
# /calculate-full calculates every variable the household leaves out, which
# took 224 s on staging.
V1_CALCULATION_TIMEOUT_SECONDS = 920.0
FINISHED_STATUSES = {"succeeded", "failed"}
YEAR = "2026"
REFORM_START = f"{YEAR}-01-01"
Expand Down
51 changes: 51 additions & 0 deletions tests/unit/cloud_run_deploy_support.py
Original file line number Diff line number Diff line change
Expand Up @@ -330,6 +330,57 @@ def job_step(job: dict, step_name: str) -> dict:
return matching_steps[0]


STAGING_DEPLOY_JOB = "deploy-cloud-run-staging"


DEPLOY_CANDIDATE_COMMAND = "bash .github/scripts/deploy_cloud_run_candidate.sh"


# How long Cloud Run lets a request run before it answers 504. The deploy
# script passes it to gcloud as --timeout; cloud_run_env.sh defaults it to 300.
REQUEST_TIMEOUT_VARIABLE = "CLOUD_RUN_TIMEOUT"


def deploy_step_environment(job_name: str) -> dict[str, object]:
"""Return the env push.yml gives ``job_name``'s candidate deploy step.

As in GitHub Actions, the job's env is laid over the workflow's, and the
step's own env over both. Values are as YAML parses them, ``${{ }}``
expressions included.
"""
workflow = yaml.safe_load(push_workflow())
job = workflow["jobs"][job_name]
deploy_steps = [
step for step in job["steps"] if step.get("run") == DEPLOY_CANDIDATE_COMMAND
]
assert len(deploy_steps) == 1, (
f"expected one step of {job_name} to run {DEPLOY_CANDIDATE_COMMAND}"
)
return {
**(workflow.get("env") or {}),
**(job.get("env") or {}),
**(deploy_steps[0].get("env") or {}),
}


def deploy_step_request_timeout_setting(job_name: str) -> dict[str, str]:
"""Return the request timeout ``job_name``'s deploy step gets, as script env.

Empty when nothing sets it, so cloud_run_env.sh's default applies. GitHub
Actions passes a number as its text, and so does this.
"""
environment = deploy_step_environment(job_name)
if REQUEST_TIMEOUT_VARIABLE not in environment:
return {}
timeout_value = environment[REQUEST_TIMEOUT_VARIABLE]
unexpected_value_message = (
f"{job_name} sets {REQUEST_TIMEOUT_VARIABLE} to {timeout_value!r}"
)
assert isinstance(timeout_value, str | int), unexpected_value_message
assert not isinstance(timeout_value, bool), unexpected_value_message
return {REQUEST_TIMEOUT_VARIABLE: str(timeout_value)}


def workflow_job_block(workflow: str, job_name: str) -> str:
match = re.search(
rf"^ {re.escape(job_name)}:\n(?P<body>.*?)(?=^ [a-zA-Z0-9_-]+:|\Z)",
Expand Down
93 changes: 91 additions & 2 deletions tests/unit/test_cloud_run_push_workflow.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,25 @@

import re

import pytest
import yaml

from tests.fixtures.integration.live_household_calculations import (
V1_CALCULATION_TIMEOUT_SECONDS,
)
from tests.unit.cloud_run_deploy_support import (
PRODUCTION_CLOUD_RUN_SERVICE,
REPO,
REQUEST_TIMEOUT_VARIABLE,
STAGING_CLOUD_RUN_SERVICE,
STAGING_DEPLOY_JOB,
deploy_step_request_timeout_setting,
job_needs,
job_step,
push_workflow_jobs,
required_runtime_env,
run_script,
script_env,
)
from tests.unit.cloud_run_deploy_support import (
push_workflow as _push_workflow,
Expand All @@ -26,6 +38,11 @@
"scripts/set_cloud_run_revision.sh",
)
LIVE_TESTS_STEP = "Run live staging tests, one pytest worker per test"
LIVE_TESTS_JOB = "parallel-live-simulation-tests-staging-cloud-run"
LIVE_TESTS_JOB_LIMIT_MINUTES = 45
# The live job's two pytest runs together: 17 to 20 minutes in recent release
# runs.
LIVE_TEST_RUNS_SECONDS = 20 * 60
RELEASE_TESTS_JOB = "release-tests"
RELEASE_COMMIT_CONDITION = (
"(github.repository == 'PolicyEngine/policyengine-api')\n"
Expand Down Expand Up @@ -143,6 +160,70 @@ def test_push_workflow_pins_cloud_run_scaling_per_job():
assert "CLOUD_RUN_WEB_CONCURRENCY" not in workflow


PRODUCTION_DEPLOY_JOB = "deploy-cloud-run-candidate"
STAGING_REQUEST_TIMEOUT_SECONDS = "900"
DEFAULT_REQUEST_TIMEOUT_SECONDS = "300"


def _names_of_jobs_that_set(variable_name: str, jobs: dict[str, dict]) -> set[str]:
"""Return the jobs whose own env, or one of whose steps' env, sets it."""
job_names = set()
for job_name, job in jobs.items():
environment_blocks = [job.get("env") or {}]
environment_blocks.extend(
step.get("env") or {} for step in job.get("steps") or []
)
if any(variable_name in block for block in environment_blocks):
job_names.add(job_name)
return job_names


def test_only_the_staging_deploy_raises_the_cloud_run_request_timeout():
"""Staging's revisions let a request run for 900 s; production's keep 300 s.

No other job sets the timeout, so production keeps cloud_run_env.sh's
default. Why staging needs more: "Request timeout" in
docs/migration/cloud-run-operations.md.
"""
workflow = yaml.safe_load(_push_workflow())
jobs = workflow["jobs"]

assert REQUEST_TIMEOUT_VARIABLE not in (workflow.get("env") or {})
assert _names_of_jobs_that_set(REQUEST_TIMEOUT_VARIABLE, jobs) == {
STAGING_DEPLOY_JOB
}
assert deploy_step_request_timeout_setting(STAGING_DEPLOY_JOB) == {
REQUEST_TIMEOUT_VARIABLE: STAGING_REQUEST_TIMEOUT_SECONDS
}


@pytest.mark.parametrize(
("deploy_job", "expected_timeout_seconds"),
[
(STAGING_DEPLOY_JOB, STAGING_REQUEST_TIMEOUT_SECONDS),
(PRODUCTION_DEPLOY_JOB, DEFAULT_REQUEST_TIMEOUT_SECONDS),
],
)
def test_each_deploy_job_passes_its_request_timeout_to_gcloud(
deploy_job: str, expected_timeout_seconds: str
):
"""The deploy script, given the deploy step's timeout setting, deploys with it."""
timeout_setting = deploy_step_request_timeout_setting(deploy_job)

result = run_script(
".github/scripts/deploy_cloud_run_candidate.sh",
script_env(
**required_runtime_env(),
CLOUD_RUN_IMAGE_URI="us-central1-docker.pkg.dev/project/repo/api:sha",
CLOUD_RUN_TAG="stage3-test",
**timeout_setting,
),
)

assert result.returncode == 0, result.stderr
assert f"--timeout {expected_timeout_seconds} " in result.stdout


def _workflow_job_names(workflow: str) -> list[str]:
return re.findall(r"^ ([a-zA-Z0-9_-]+):$", workflow, flags=re.MULTILINE)

Expand Down Expand Up @@ -245,8 +326,16 @@ def _assert_live_tests_run_in_parallel_after_readiness(
in (live_test_script[household_checks:])
)
assert "-n 4" in live_test_script[household_checks - 200 : household_checks]
# They wait on Modal; 30 minutes leaves room for both runs.
assert "timeout-minutes: 30" in parallel_live_tests
# They wait on Modal, and the parity check waits up to
# V1_CALCULATION_TIMEOUT_SECONDS for each API v1 answer. The limit leaves
# room for the two pytest runs together and one answer that takes the
# full wait; two such answers in a row on one worker don't fit.
live_job_limit_minutes = push_workflow_jobs()[LIVE_TESTS_JOB]["timeout-minutes"]
assert live_job_limit_minutes == LIVE_TESTS_JOB_LIMIT_MINUTES
assert (
live_job_limit_minutes * 60
>= LIVE_TEST_RUNS_SECONDS + V1_CALCULATION_TIMEOUT_SECONDS
)
assert "tests/integration/test_live_v2_policies.py" not in parallel_live_tests
assert (
"API_BASE_URL: ${{ needs.deploy-cloud-run-staging.outputs.url }}"
Expand Down
23 changes: 16 additions & 7 deletions tests/unit/v2/test_live_household_parity_requests.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,9 @@
calculation itself is left out, so a household the routes refuse before
calculating fails here rather than in a release. A refusal during the
calculation, such as an SPM error, is not covered. The check waits longer than
the candidate's Cloud
Run request timeout (``CLOUD_RUN_TIMEOUT`` in
``.github/scripts/cloud_run_env.sh``) for the answer: ``/calculate-full`` can
take most of it, and the check should get the candidate's own answer.
the staging candidate's Cloud Run request timeout (``CLOUD_RUN_TIMEOUT``, which
push.yml's ``deploy-cloud-run-staging`` job sets) for the answer, so it gets
the candidate's own answer, a 504 included.
"""

from __future__ import annotations
Expand All @@ -33,7 +32,12 @@
calculate_with_v1,
)
from tests.integration.test_live_v2_household_parity import parity_households
from tests.unit.cloud_run_deploy_support import run_bash, script_env
from tests.unit.cloud_run_deploy_support import (
STAGING_DEPLOY_JOB,
deploy_step_request_timeout_setting,
run_bash,
script_env,
)

if TYPE_CHECKING:
from collections.abc import Iterator
Expand Down Expand Up @@ -77,12 +81,17 @@ def public_api(monkeypatch: pytest.MonkeyPatch) -> Iterator[httpx.Client]:


def candidate_request_timeout_seconds() -> float:
"""Return how long Cloud Run lets a request to the candidate run."""
"""Return how long Cloud Run lets a request to the staging candidate run.

The live checks run against the candidate ``deploy-cloud-run-staging``
deploys: cloud_run_env.sh's default, unless its deploy step's env sets
``CLOUD_RUN_TIMEOUT``.
"""
result = run_bash(
"-c",
"source .github/scripts/cloud_run_env.sh && cloud_run_set_defaults"
' && printf "%s" "$CLOUD_RUN_TIMEOUT"',
env=script_env(),
env=script_env(**deploy_step_request_timeout_setting(STAGING_DEPLOY_JOB)),
)
assert result.returncode == 0, result.stderr
return float(result.stdout)
Expand Down
Loading