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
4 changes: 4 additions & 0 deletions infra/cargo-target-janitor/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,10 @@ ad-hoc targets are considered.
- Queue data is read through `~/hatch/tools/repo-queue.py`'s transient
Bitwarden credential path; credentials are never printed or persisted.
Open PRs are read with `gh`. If either source is unavailable, cleanup stops.
Both liveness reads are paginated to completion (#6618) — claimed
tasks by offset, open PRs by page — and a read that cannot complete
within its page bound also stops cleanup: a truncated protection
set is treated as an unavailable source, never as ground truth.
- Default mode is **dry-run**. It prints each proposed path, size and reason,
plus every protected target. `--apply` is required to remove anything.
- Ad-hoc targets are exactly `target-<task-id>`; a registered worktree
Expand Down
131 changes: 94 additions & 37 deletions infra/cargo-target-janitor/bin/cargo_target_janitor.py
Original file line number Diff line number Diff line change
Expand Up @@ -183,14 +183,41 @@ def load_queue_client(helper: Path):
return module, key


CLAIMS_PAGE = 1000
# Fail-closed bound on pagination (#6618): a liveness read that cannot
# be completed inside the bound raises SafetyError and cleanup stops,
# rather than proceeding on a set that might be silently truncated.
MAX_CLAIM_PAGES = 100
STATES_CHUNK = 500


def queue_claims(client) -> set[int]:
"""Read only the pilot's claimed IDs through the existing helper."""
"""Read ALL the pilot's claimed IDs through the existing helper.

Paginated (#6618): a single page capped at 1000 rows silently
dropped every claimed task past row 1000 from the never-delete
set. Pages are followed with offset until a short page arrives;
needing more than MAX_CLAIM_PAGES pages fails closed.
"""
module, key = client
query = (
"tasks?select=id,queue,status,payload&"
f"queue=eq.{QUEUE}&status=eq.claimed&limit=1000"
)
rows = module.http("GET", query, key) or []
rows = []
offset = 0
for _ in range(MAX_CLAIM_PAGES):
query = (
"tasks?select=id,queue,status,payload&"
f"queue=eq.{QUEUE}&status=eq.claimed"
f"&limit={CLAIMS_PAGE}&offset={offset}"
)
page = module.http("GET", query, key) or []
rows.extend(page)
if len(page) < CLAIMS_PAGE:
break
offset += CLAIMS_PAGE
else:
raise SafetyError(
f"claimed-task read exceeded {MAX_CLAIM_PAGES} pages "
f"of {CLAIMS_PAGE}; refusing to trust a possibly-truncated set"
)
return {
int(row["id"])
for row in rows
Expand All @@ -201,45 +228,75 @@ def queue_claims(client) -> set[int]:


def queue_task_states(client, task_ids: set[int]) -> dict[int, str]:
"""States for a locally-built ID set, read in chunks (#6618).

Disposition of the old single `limit=1000` read: the ID set comes
from local fleet directories and can in principle exceed 1000, so
it is chunked — each query names at most STATES_CHUNK specific
IDs with limit=1000 > STATES_CHUNK, so no chunk's page can ever
truncate its answer.
"""
if not task_ids:
return {}
module, key = client
ids = ",".join(str(task_id) for task_id in sorted(task_ids))
rows = (
module.http(
"GET",
f"tasks?select=id,status&queue=eq.{QUEUE}&id=in.%28{ids}%29&limit=1000",
key,
states = {}
ordered = sorted(task_ids)
for start in range(0, len(ordered), STATES_CHUNK):
chunk = ordered[start : start + STATES_CHUNK]
ids = ",".join(str(task_id) for task_id in chunk)
rows = (
module.http(
"GET",
f"tasks?select=id,status&queue=eq.{QUEUE}&id=in.%28{ids}%29&limit=1000",
key,
)
or []
)
or []
)
return {int(row["id"]): str(row["status"]) for row in rows}
states.update({int(row["id"]): str(row["status"]) for row in rows})
return states


PR_PAGE = 100
MAX_PR_PAGES = 200


def open_pr_branches(repo: str = REPO) -> set[str]:
proc = subprocess.run(
[
"gh",
"pr",
"list",
"--repo",
repo,
"--state",
"open",
"--limit",
"500",
"--json",
"headRefName",
],
check=True,
capture_output=True,
text=True,
"""Read ALL open PR branch names, paginated (#6618).

The old single `gh pr list --limit 500` silently dropped every
open PR past the first 500 from the never-delete set. This pages
the REST pulls endpoint (per_page/page) until a short page; a
read that still has not terminated after MAX_PR_PAGES pages
fails closed instead of trusting a possibly-truncated set.
Both call sites (plan-time and the apply-loop re-check) use this
one function, so there is no second, weaker copy.
"""
branches = set()
for page_no in range(1, MAX_PR_PAGES + 1):
proc = subprocess.run(
[
"gh",
"api",
f"repos/{repo}/pulls?state=open&per_page={PR_PAGE}&page={page_no}",
],
check=True,
capture_output=True,
text=True,
)
try:
rows = json.loads(proc.stdout)
if not isinstance(rows, list):
raise TypeError("pulls response is not a list")
for row in rows:
branches.add(str(row["head"]["ref"]))
except (ValueError, KeyError, TypeError) as exc:
raise SafetyError(f"invalid gh PR response: {exc}") from exc
if len(rows) < PR_PAGE:
return branches
raise SafetyError(
f"open-PR read exceeded {MAX_PR_PAGES} pages of {PR_PAGE}; "
"refusing to trust a possibly-truncated set"
)
try:
rows = json.loads(proc.stdout)
return {str(row["headRefName"]) for row in rows}
except (ValueError, KeyError, TypeError) as exc:
raise SafetyError(f"invalid gh PR response: {exc}") from exc


def discover_targets(
Expand Down
106 changes: 106 additions & 0 deletions infra/cargo-target-janitor/tests/test_cargo_target_janitor.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,14 @@
#!/usr/bin/env python3
import importlib.util
import json
import re
import subprocess
import sys
import tempfile
import time
import unittest
from pathlib import Path
from unittest import mock

SCRIPT = Path(__file__).resolve().parents[1] / "bin/cargo_target_janitor.py"
spec = importlib.util.spec_from_file_location("janitor", SCRIPT)
Expand Down Expand Up @@ -208,5 +212,107 @@ def test_owner_changed_ignores_adhoc_targets(self):
self.assertFalse(janitor.owner_changed(recorded, {}))


def claimed_row(task_id):
return {
"id": task_id,
"queue": janitor.QUEUE,
"status": "claimed",
"payload": {"repo": janitor.REPO},
}


class StubQueueModule:
"""PostgREST stub honouring limit/offset and id=in.(...) semantics."""

def __init__(self, rows, always_full=False):
self.rows = rows
self.always_full = always_full
self.queries = []

def http(self, method, query, key):
self.queries.append(query)
limit = int(re.search(r"limit=(\d+)", query).group(1))
if "id=in." in query:
ids = {
int(x)
for x in re.search(r"id=in\.\%28([0-9,]+)\%29", query).group(1).split(",")
}
return [r for r in self.rows if r["id"] in ids][:limit]
offset = int(re.search(r"offset=(\d+)", query).group(1))
if self.always_full:
return self.rows[:limit]
return self.rows[offset : offset + limit]


class JanitorPaginationTests(unittest.TestCase):
"""#6618: the two deletion-safety liveness reads must be complete
or fail closed — a full page is never silently the whole set."""

def test_queue_claims_pages_past_1000(self):
stub = StubQueueModule([claimed_row(i) for i in range(1, 1006)])
got = janitor.queue_claims((stub, "key"))
self.assertEqual(got, set(range(1, 1006)))
self.assertGreaterEqual(len(stub.queries), 2)

def test_queue_claims_at_cap_boundary(self):
stub = StubQueueModule([claimed_row(i) for i in range(1, 1001)])
self.assertEqual(janitor.queue_claims((stub, "key")), set(range(1, 1001)))

def test_queue_claims_fails_closed_when_pages_never_end(self):
stub = StubQueueModule(
[claimed_row(i) for i in range(1, 1001)], always_full=True
)
with self.assertRaises(janitor.SafetyError):
janitor.queue_claims((stub, "key"))

def fake_gh(self, total, always_full=False):
calls = []

def fake_run(cmd, **kwargs):
calls.append(cmd)
page = int(re.search(r"[?&]page=(\d+)", cmd[-1]).group(1))
per_page = int(re.search(r"[?&]per_page=(\d+)", cmd[-1]).group(1))
if always_full:
rows = [{"head": {"ref": f"b{i}"}} for i in range(per_page)]
else:
start = (page - 1) * per_page
rows = [
{"head": {"ref": f"b{i}"}}
for i in range(start, min(start + per_page, total))
]
return subprocess.CompletedProcess(cmd, 0, stdout=json.dumps(rows))

return fake_run, calls

def test_open_pr_branches_pages_past_500(self):
fake_run, calls = self.fake_gh(600)
with mock.patch("subprocess.run", fake_run):
got = janitor.open_pr_branches()
self.assertEqual(got, {f"b{i}" for i in range(600)})
self.assertGreaterEqual(len(calls), 6)

def test_open_pr_branches_at_cap_boundary(self):
fake_run, _ = self.fake_gh(500)
with mock.patch("subprocess.run", fake_run):
self.assertEqual(janitor.open_pr_branches(), {f"b{i}" for i in range(500)})

def test_open_pr_branches_fails_closed_when_pages_never_end(self):
fake_run, _ = self.fake_gh(0, always_full=True)
with mock.patch("subprocess.run", fake_run):
with self.assertRaises(janitor.SafetyError):
janitor.open_pr_branches()

def test_queue_task_states_chunks_beyond_1000_ids(self):
rows = [
{"id": i, "status": "claimed" if i % 2 else "done"}
for i in range(1, 1201)
]
stub = StubQueueModule(rows)
got = janitor.queue_task_states((stub, "key"), set(range(1, 1201)))
self.assertEqual(len(got), 1200)
self.assertEqual(got[1200], "done")
self.assertEqual(len(stub.queries), 3)


if __name__ == "__main__":
unittest.main()
Loading