From c7caf56f836e24735302345ce4baadedbb6f7c14 Mon Sep 17 00:00:00 2001 From: alberto Date: Sun, 29 Nov 2026 06:06:50 -0600 Subject: [PATCH] Cancel waits up to 30 s for a run that is still starting (Dagster cannot terminate it then); still starting is a 409 with Retry-After --- tests/test_runs.py | 23 +++++++++++++++++++++++ webapi/runs.py | 9 +++++++++ 2 files changed, 32 insertions(+) diff --git a/tests/test_runs.py b/tests/test_runs.py index 72b6983..6f8fc9d 100644 --- a/tests/test_runs.py +++ b/tests/test_runs.py @@ -255,3 +255,26 @@ def test_a_locked_run_storage_is_read_again(monkeypatch): with pytest.raises(HTTPException) as raised: runs.graphql("q", {}) assert raised.value.status_code == 503 + + +def test_cancel_waits_for_a_starting_run(monkeypatch): + """Dagster refuses to terminate a run that is still STARTING: cancel waits for it to start.""" + from webapi import runs + + statuses = iter(["STARTING", "STARTING", "STARTED", "CANCELING"]) + terminated = [] + + class Client: + def get_run_status(self, run_id): + class S: + value = next(statuses) + + return S() + + def terminate_run(self, run_id): + terminated.append(run_id) + + monkeypatch.setattr(runs.time, "sleep", lambda s: None) + answer = runs.cancel_run("r1", client=Client()) + assert terminated == ["r1"] + assert answer.status == "CANCELING" diff --git a/webapi/runs.py b/webapi/runs.py index a5e96b6..e4cea98 100644 --- a/webapi/runs.py +++ b/webapi/runs.py @@ -108,6 +108,7 @@ def dagster() -> DagsterGraphQLClient: LOCKED = "database is locked" # Dagster's SQLite run storage, busy while a run writes its events LOCK_RETRIES = 5 +STARTING_WAIT_S = 30 def _locked(payload: dict) -> bool: @@ -243,8 +244,16 @@ def _status(client: DagsterGraphQLClient, run_id: str) -> str: @router.post("/{run_id}/cancel") def cancel_run(run_id: str, client: DagsterGraphQLClient = Depends(dagster)) -> Cancel: status = _status(client, run_id) + deadline = time.monotonic() + STARTING_WAIT_S # Dagster cannot terminate a run still starting + while status == "STARTING" and time.monotonic() < deadline: + time.sleep(0.5) + status = _status(client, run_id) if status in ("SUCCESS", "FAILURE", "CANCELED"): raise HTTPException(409, detail=f"the run already ended: {STATE[status]}") + if status == "STARTING": + raise HTTPException( + 409, detail="the run is still starting; try again", headers={"Retry-After": "5"} + ) try: client.terminate_run(run_id) except DagsterGraphQLClientError as e: