From e434e085fe794c77eaf3aa3799f0b92a915ccdc9 Mon Sep 17 00:00:00 2001 From: alberto Date: Sat, 28 Nov 2026 08:43:00 -0600 Subject: [PATCH] Runs API reads Dagster again when its SQLite run storage is locked; still locked is a 503 with Retry-After The Postgres TEA gate got a 502 polling an ingest: logsForRun failed with 'database is locked' while the run wrote its events. --- tests/test_runs.py | 35 +++++++++++++++++++++++++++++++++++ webapi/runs.py | 44 ++++++++++++++++++++++++++++++++++---------- 2 files changed, 69 insertions(+), 10 deletions(-) diff --git a/tests/test_runs.py b/tests/test_runs.py index 59c2f9c..adf6825 100644 --- a/tests/test_runs.py +++ b/tests/test_runs.py @@ -202,3 +202,38 @@ def test_execution_options_and_health(api): def test_tea_eegs_analyze_validates_scope(api): response = api.post("/tea/eegs/analyze", json={"scope": {"mode": "first_n"}}) assert response.status_code == 422 + + +def test_a_locked_run_storage_is_read_again(monkeypatch): + """Dagster's SQLite run storage is locked for a moment while a run writes: the read is retried, + and a storage that stays locked is a 503 the caller can retry, not a 502.""" + from fastapi import HTTPException + + from webapi import runs + + error = {"__typename": "PythonError", "message": "OperationalError: database is locked"} + locked = {"data": {"runOrError": {"__typename": "Run"}, "logsForRun": error}} + fine = { + "data": { + "runOrError": {"__typename": "Run"}, + "logsForRun": {"__typename": "EventConnection"}, + } + } + answers = [locked, locked, fine] + + class Answer: + status_code = 200 + + def __init__(self, payload): + self.payload = payload + + def json(self): + return self.payload + + monkeypatch.setattr(runs.time, "sleep", lambda s: None) + monkeypatch.setattr(runs.requests, "post", lambda *a, **k: Answer(answers.pop(0))) + assert runs.graphql("q", {}) == fine["data"] + monkeypatch.setattr(runs.requests, "post", lambda *a, **k: Answer(locked)) + with pytest.raises(HTTPException) as raised: + runs.graphql("q", {}) + assert raised.value.status_code == 503 diff --git a/webapi/runs.py b/webapi/runs.py index 5f6e397..323df31 100644 --- a/webapi/runs.py +++ b/webapi/runs.py @@ -1,6 +1,7 @@ """Runs live in Dagster: the API starts them and reads their state, never computes.""" import os +import time from typing import Literal import requests @@ -100,19 +101,42 @@ def dagster() -> DagsterGraphQLClient: return DagsterGraphQLClient(host, port_number=port) +LOCKED = "database is locked" # Dagster's SQLite run storage, busy while a run writes its events +LOCK_RETRIES = 5 + + +def _locked(payload: dict) -> bool: + results = (payload.get("data") or {}).values() + return LOCKED in str(payload.get("errors", "")) or any( + isinstance(r, dict) + and r.get("__typename") == "PythonError" + and LOCKED in r.get("message", "") + for r in results + ) + + def graphql(query: str, variables: dict) -> dict: + """Dagster's GraphQL answer; a read that found its run storage locked is tried again.""" host, port = _dagster_address() - try: - response = requests.post( - f"http://{host}:{port}/graphql", - json={"query": query, "variables": variables}, - timeout=15, + for attempt in range(LOCK_RETRIES + 1): + try: + response = requests.post( + f"http://{host}:{port}/graphql", + json={"query": query, "variables": variables}, + timeout=15, + ) + if response.status_code != 200: + raise HTTPException(502, detail=response.text) + payload = response.json() + except requests.RequestException as e: + raise HTTPException(502, detail=str(e)) from e + if not _locked(payload) or attempt == LOCK_RETRIES: + break + time.sleep(0.2 * 2**attempt) + if _locked(payload): + raise HTTPException( + 503, detail="Dagster's run storage is busy; try again", headers={"Retry-After": "5"} ) - if response.status_code != 200: - raise HTTPException(502, detail=response.text) - payload = response.json() - except requests.RequestException as e: - raise HTTPException(502, detail=str(e)) from e if "errors" in payload: raise HTTPException(502, detail=str(payload["errors"])) return payload["data"]