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
80 changes: 78 additions & 2 deletions infra/cargo-target-janitor/bin/cargo_target_janitor.py
Original file line number Diff line number Diff line change
Expand Up @@ -274,6 +274,33 @@ def load_queue_client(helper: Path):
STATES_CHUNK = 500


def _shape_int(reader: str, field: str, value) -> int:
# int() alone accepts bools and truncates floats, and raises raw
# TypeError/ValueError on the shapes a malformed row can carry --
# neither is acceptable in a reader (#6844): validate the shape
# and name the reader and the field in the SafetyError.
if isinstance(value, bool) or not isinstance(value, (int, str)):
raise SafetyError(
f"{reader}: invalid shape: {field} is "
f"{type(value).__name__}, expected an integer"
)
try:
return int(value)
except ValueError as exc:
raise SafetyError(
f"{reader}: invalid shape: {field}={value!r} is not an integer"
) from exc


def _shape_row(reader: str, row) -> dict:
if not isinstance(row, dict):
raise SafetyError(
f"{reader}: invalid shape: row is {type(row).__name__}, "
"expected an object"
)
return row


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

Expand Down Expand Up @@ -302,6 +329,20 @@ def queue_claims(client) -> set[int]:
f"&id=gt.{after}&order=id.asc&limit={CLAIMS_PAGE}"
)
page = module.http("GET", query, key) or []
if not isinstance(page, list):
raise SafetyError(
f"queue_claims: invalid shape: page is "
f"{type(page).__name__}, expected a list of rows"
)
for row in page:
_shape_row("queue_claims", row)
_shape_int("queue_claims", "id", row.get("id"))
payload = row.get("payload")
if payload is not None and not isinstance(payload, dict):
raise SafetyError(
f"queue_claims: invalid shape: payload is "
f"{type(payload).__name__}, expected an object"
)
rows.extend(page)
if len(page) < CLAIMS_PAGE:
break
Expand Down Expand Up @@ -345,6 +386,19 @@ def queue_task_states(client, task_ids: set[int]) -> dict[int, str]:
)
or []
)
if not isinstance(rows, list):
raise SafetyError(
f"queue_task_states: invalid shape: page is "
f"{type(rows).__name__}, expected a list of rows"
)
for row in rows:
_shape_row("queue_task_states", row)
_shape_int("queue_task_states", "id", row.get("id"))
if not isinstance(row.get("status"), str):
raise SafetyError(
f"queue_task_states: invalid shape: status is "
f"{type(row.get('status')).__name__}, expected a string"
)
states.update({int(row["id"]): str(row["status"]) for row in rows})
return states

Expand Down Expand Up @@ -389,11 +443,33 @@ def parse_fallback_scan(scan: dict) -> set[int]:
# under it. Stale/released/free do not protect here; the
# queue/claimed label union in FallbackClaimsSource covers the
# ambiguous broker-era residue separately.
if not isinstance(scan, dict):
raise SafetyError(
f"parse_fallback_scan: invalid shape: scan is "
f"{type(scan).__name__}, expected an object"
)
items = scan.get("items", [])
if not isinstance(items, list):
raise SafetyError(
f"parse_fallback_scan: invalid shape: items is "
f"{type(items).__name__}, expected a list"
)
issues = set()
for item in scan.get("items", []):
for item in items:
if not isinstance(item, dict):
raise SafetyError(
f"parse_fallback_scan: invalid shape: item is "
f"{type(item).__name__}, expected an object"
)
claim = item.get("claim") or {}
if not isinstance(claim, dict):
raise SafetyError(
f"parse_fallback_scan: invalid shape: claim is "
f"{type(claim).__name__}, expected an object"
)
number = _shape_int("parse_fallback_scan", "number", item.get("number"))
if claim.get("state") in {"live", "contested"}:
issues.add(int(item["number"]))
issues.add(number)
return issues


Expand Down
80 changes: 80 additions & 0 deletions infra/cargo-target-janitor/tests/test_cargo_target_janitor.py
Original file line number Diff line number Diff line change
Expand Up @@ -252,6 +252,17 @@ def http(self, method, query, key):
return self.rows[offset : offset + limit]


class RawQueueModule:
"""Queue-module stub returning one fixed page verbatim, so tests
can feed the readers shapes StubQueueModule cannot express."""

def __init__(self, page):
self.page = page

def http(self, method, query, key):
return self.page


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."""
Expand Down Expand Up @@ -294,6 +305,53 @@ def test_queue_claims_fails_closed_when_pages_never_end(self):
with self.assertRaises(janitor.SafetyError):
janitor.queue_claims((stub, "key"))

def test_queue_claims_malformed_shapes_raise_safety_error(self):
"""#6844: a malformed broker page/row must surface as a
SafetyError naming queue_claims, never a raw shape error --
a raw error kills the janitor with no refused run record."""
pages = [
{"error": "boom"}, # error-dict page
["not-a-row"], # string row
[{"queue": janitor.QUEUE, "status": "claimed",
"payload": {"repo": janitor.REPO}}], # missing row id
[{"id": "zz", "queue": janitor.QUEUE, "status": "claimed",
"payload": {"repo": janitor.REPO}}], # non-int id
[{"id": {"n": 1}, "queue": janitor.QUEUE, "status": "claimed",
"payload": {"repo": janitor.REPO}}], # dict id
[{"id": 1, "queue": janitor.QUEUE, "status": "claimed",
"payload": "not-an-object"}], # string payload
]
for page in pages:
with self.subTest(page=page):
with self.assertRaises(janitor.SafetyError) as caught:
janitor.queue_claims((RawQueueModule(page), "key"))
self.assertIn("queue_claims", str(caught.exception))

def test_queue_task_states_malformed_shapes_raise_safety_error(self):
"""#6844: same shape discipline for queue_task_states."""
pages = [
{"error": "boom"}, # error-dict page
["not-a-row"], # string row
[{"status": "claimed"}], # missing row id
[{"id": "zz", "status": "claimed"}], # non-int id
[{"id": 1}], # missing status
[{"id": 1, "status": {"s": "claimed"}}], # dict status
]
for page in pages:
with self.subTest(page=page):
with self.assertRaises(janitor.SafetyError) as caught:
janitor.queue_task_states((RawQueueModule(page), "key"), {1})
self.assertIn("queue_task_states", str(caught.exception))

def test_queue_readers_well_formed_controls_unchanged(self):
"""#6844 control: well-formed rows return exactly what the
unguarded readers returned."""
stub = StubQueueModule([claimed_row(i) for i in range(1, 6)])
self.assertEqual(janitor.queue_claims((stub, "key")), {1, 2, 3, 4, 5})
rows = [{"id": i, "status": "claimed"} for i in range(1, 4)]
got = janitor.queue_task_states((RawQueueModule(rows), "key"), {1, 2, 3})
self.assertEqual(got, {1: "claimed", 2: "claimed", 3: "claimed"})

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

Expand Down Expand Up @@ -394,6 +452,28 @@ def test_parse_fallback_scan_protects_live_and_contested_only(self):
}
self.assertEqual(janitor.parse_fallback_scan(scan), {1, 2})

def test_parse_fallback_scan_malformed_shapes_raise_safety_error(self):
"""#6844: a malformed scan document must surface as a
SafetyError naming parse_fallback_scan, never a raw shape
error -- a raw error kills the janitor with no refused
run record (the #6812 invisible-death mode)."""
scans = [
[], # list scan
{"items": {"number": 1}}, # dict items
{"items": ["not-an-item"]}, # string item
{"items": [{"number": 1, "claim": "live"}]}, # string claim
{"items": [{"claim": {"state": "live"}}]}, # missing number
{"items": [{"number": {"n": 1},
"claim": {"state": "live"}}]}, # dict number
{"items": [{"number": "zz",
"claim": {"state": "live"}}]}, # non-int number
]
for scan in scans:
with self.subTest(scan=scan):
with self.assertRaises(janitor.SafetyError) as caught:
janitor.parse_fallback_scan(scan)
self.assertIn("parse_fallback_scan", str(caught.exception))

def test_fallback_claimed_issue_protects_fb_worktree(self):
target = self.make_target("fb-6757/pkgs/id/target")
found = janitor.discover_targets(
Expand Down
Loading