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
65 changes: 54 additions & 11 deletions pkgs/cold-store-reaper/cold_store.py
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,17 @@
LIST_MAX_PAGES = 10_000
LIST_MAX_RESULTS = 1_000_000
D1_SYNC_PARAM_BUDGET = 90
# D1 answers a burst of REST queries with HTTP 429 ("Your account is
# generating too much load on D1 DBs") or 503 when it is shedding load.
# Nov 19: one 429 in the middle of a 47-statement sync failed the whole
# nightly sync-manifest step, though the account was far below its
# limits. Every sync statement is an idempotent upsert, so the same
# statement is simply sent again after a pause: Retry-After when D1
# gives one (capped), otherwise D1_SYNC_BACKOFF_SECONDS x attempt.
D1_SYNC_ATTEMPTS = 5
D1_SYNC_RETRY_STATUSES = (429, 503)
D1_SYNC_BACKOFF_SECONDS = 2.0
D1_SYNC_BACKOFF_CAP_SECONDS = 30.0


# R2 (DESIGN.md sections 4-5): the supabase-backups bucket is both a
Expand Down Expand Up @@ -483,6 +494,9 @@ def __init__(
# Injectable so tests can zero it: transport-retry backoff for
# the S3 layer (see _s3_request).
self.s3_backoff_seconds = S3_TRANSPORT_BACKOFF_SECONDS
# Injectable so tests can zero it: the pause between D1 sync
# retries after a 429/503 (see _d1_sync_post).
self.d1_backoff_seconds = D1_SYNC_BACKOFF_SECONDS

# ------------------------------------------------------------------ init
def init(self) -> dict:
Expand Down Expand Up @@ -1788,18 +1802,10 @@ def sync_manifest(self, dry_run: bool = False) -> dict:
if dry_run:
return total
token, url = self._d1_endpoint()
retries = 0
for stmt in statements:
status, _h, resp = http_request(
"POST",
url,
headers={
"Authorization": f"Bearer {token}",
"Content-Type": "application/json",
},
data=json.dumps(
{"sql": stmt["sql"], "params": stmt["params"]}
).encode(),
)
status, resp, used = self._d1_sync_post(token, url, stmt)
retries += used
if status != 200:
raise ColdStoreError(
f"D1 sync failed (HTTP {status}) on table {stmt['table']}: "
Expand All @@ -1814,8 +1820,45 @@ def sync_manifest(self, dry_run: bool = False) -> dict:
f"D1 sync rejected a {stmt['table']} statement: "
f"{_d1_first_error_message(payload) or 'unknown error'}"
)
total["retries"] = retries
return total

def _d1_retry_delay(self, headers: dict, attempt: int) -> float:
"""Seconds to wait before retry number `attempt` (1-based)."""
retry_after = None
for key, value in (headers or {}).items():
if key.lower() == "retry-after":
try:
retry_after = float(value)
except (TypeError, ValueError):
retry_after = None
break
if retry_after is not None and retry_after >= 0:
return min(retry_after, D1_SYNC_BACKOFF_CAP_SECONDS)
return min(self.d1_backoff_seconds * attempt, D1_SYNC_BACKOFF_CAP_SECONDS)

def _d1_sync_post(self, token: str, url: str, stmt: dict):
"""POST one sync statement, retrying D1's load-shedding answers.

Returns (status, body, retries used). A 429 or 503 is retried up
to D1_SYNC_ATTEMPTS times in all; any other status, or the last
throttled answer, goes back to the caller unchanged.
"""
data = json.dumps({"sql": stmt["sql"], "params": stmt["params"]}).encode()
headers = {
"Authorization": f"Bearer {token}",
"Content-Type": "application/json",
}
attempt = 1
while True:
status, resp_headers, resp = http_request(
"POST", url, headers=headers, data=data
)
if status not in D1_SYNC_RETRY_STATUSES or attempt >= D1_SYNC_ATTEMPTS:
return status, resp, attempt - 1
time.sleep(self._d1_retry_delay(resp_headers, attempt))
attempt += 1

# ------------------------------------------------------------- backup-d1
@staticmethod
def _sql_literal(value) -> str:
Expand Down
91 changes: 91 additions & 0 deletions pkgs/cold-store-reaper/tests/test_cold_store.py
Original file line number Diff line number Diff line change
Expand Up @@ -936,6 +936,11 @@ def __init__(self):
self.fail = False
self.mode = None # "success_false" | "wrong_shape" definitive answers
self.db = None
# Answer the next `throttle` requests with throttle_status (D1's
# load shedding), with a Retry-After header when retry_after is set.
self.throttle = 0
self.throttle_status = 429
self.retry_after = None


def make_d1_handler(fake: FakeD1):
Expand Down Expand Up @@ -965,6 +970,27 @@ def do_POST(self):
"params": payload.get("params", []),
}
)
if fake.throttle > 0:
fake.throttle -= 1
body = json.dumps(
{
"success": False,
"errors": [
{
"message": "Your account is generating too much "
"load on D1 DBs. Please back off and try again later."
}
],
}
).encode()
self.send_response(fake.throttle_status)
self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", str(len(body)))
if fake.retry_after is not None:
self.send_header("Retry-After", str(fake.retry_after))
self.end_headers()
self.wfile.write(body)
return
if fake.mode == "success_false":
self._send(
200,
Expand Down Expand Up @@ -1707,6 +1733,71 @@ def test_sync_http_error_is_clear(self):
# The D1 API's own error text rides along, not just the status.
self.assertIn("fake failure", str(ctx.exception))

def test_sync_retries_a_throttled_statement_and_finishes(self):
# Nov 19: one HTTP 429 in the middle of the nightly sync failed
# the whole sync-manifest step. A throttled statement is sent
# again after a pause, and every row still arrives once.
self.store.d1_backoff_seconds = 0
with mock.patch.dict(os.environ, {"CLOUDFLARE_API_TOKEN": "fake-cf-token"}):
baseline = self.store.sync_manifest()
self.d1.requests.clear()
self.d1.throttle = 2
result = self.store.sync_manifest()
self.assertEqual(result["retries"], 2)
self.assertEqual(result["rows"], baseline["rows"])
self.assertEqual(len(self.d1.requests), result["statements"] + 2)
# The first statement was sent three times, unchanged.
first = self.d1.requests[0]
for req in self.d1.requests[1:3]:
self.assertEqual((req["sql"], req["params"]), (first["sql"], first["params"]))

def test_sync_retries_503_too(self):
self.store.d1_backoff_seconds = 0
self.d1.throttle = 1
self.d1.throttle_status = 503
with mock.patch.dict(os.environ, {"CLOUDFLARE_API_TOKEN": "fake-cf-token"}):
result = self.store.sync_manifest()
self.assertEqual(result["retries"], 1)

def test_sync_gives_up_after_the_last_attempt(self):
self.store.d1_backoff_seconds = 0
self.d1.throttle = cold_store.D1_SYNC_ATTEMPTS
with (
mock.patch.dict(os.environ, {"CLOUDFLARE_API_TOKEN": "fake-cf-token"}),
self.assertRaises(cold_store.ColdStoreError) as ctx,
):
self.store.sync_manifest()
self.assertIn("HTTP 429", str(ctx.exception))
self.assertIn("too much load", str(ctx.exception))
self.assertEqual(len(self.d1.requests), cold_store.D1_SYNC_ATTEMPTS)

def test_sync_honours_retry_after_capped(self):
self.d1.throttle = 1
self.d1.retry_after = 7
sleeps = []
with (
mock.patch.object(cold_store.time, "sleep", sleeps.append),
mock.patch.dict(os.environ, {"CLOUDFLARE_API_TOKEN": "fake-cf-token"}),
):
self.store.sync_manifest()
self.assertEqual(sleeps, [7.0])
self.assertEqual(
self.store._d1_retry_delay({"Retry-After": "3600"}, 1),
cold_store.D1_SYNC_BACKOFF_CAP_SECONDS,
)
self.store.d1_backoff_seconds = 2.0
self.assertEqual(self.store._d1_retry_delay({}, 3), 6.0)
self.assertEqual(self.store._d1_retry_delay({"Retry-After": "soon"}, 1), 2.0)

def test_sync_does_not_retry_other_errors(self):
self.d1.fail = True # HTTP 500 is not load shedding
with (
mock.patch.dict(os.environ, {"CLOUDFLARE_API_TOKEN": "fake-cf-token"}),
self.assertRaises(cold_store.ColdStoreError),
):
self.store.sync_manifest()
self.assertEqual(len(self.d1.requests), 1)

def test_sync_requires_token(self):
with mock.patch.dict(os.environ, self._env_without_token(), clear=True):
with self.assertRaises(cold_store.ColdStoreError):
Expand Down