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
14 changes: 14 additions & 0 deletions .github/test-suite-registry.json
Original file line number Diff line number Diff line change
Expand Up @@ -1204,6 +1204,20 @@
"related_issues": [7322],
"notes": "Basic-tier PR gate for the deploy registry checks (#7322); before this workflow the two checks ran only in the full flake check on main / the nix-ci schedule."
},
{
"id": "cargo-target-broker.python",
"paths": ["infra/cargo-target-broker/tests/test_cargo_target_broker.py"],
"invocation": "python3 -m unittest discover -s infra/cargo-target-broker/tests -v",
"venue": {
"workflow": ".github/workflows/cargo-target-broker-tests.yml",
"job_step": "python-tests / Run the cargo-target-broker suite",
"state": "active",
"dispatchable": true
},
"status": "mapped",
"related_issues": [11417],
"notes": "Eviction accounting for the cargo target broker: a failed LRU removal keeps its row and re-measured bytes (#11417). The broker had no tests before this suite."
},
{
"id": "yard-reaper.python",
"paths": ["infra/yard-reaper/tests/test_yard_reaper.py"],
Expand Down
43 changes: 43 additions & 0 deletions .github/workflows/cargo-target-broker-tests.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
name: cargo-target-broker-tests

# Test verification for infra/cargo-target-broker (#11417).
#
# The broker evicts whole cargo target dirs to hold the pool under its
# size cap. Its eviction accounting (a failed removal must keep the row
# and its bytes) is pinned by infra/cargo-target-broker/tests/. The
# suite is stdlib unittest against the real bin/cargo_target_broker.py:
# no network, no credentials, no external CLIs.

on:
schedule:
# Nightly instead of on every push to main (Drew, 2026-11-16; see
# .github/ci-policy.md "Nightly main CI").
- cron: "23 7 * * *"
workflow_dispatch:

permissions:
contents: read

concurrency:
group: ${{ github.workflow }}-${{ github.event_name == 'push' && github.run_id || github.ref }}
cancel-in-progress: true

jobs:
python-tests:
name: "python: cargo-target-broker suite"
runs-on: ubuntu-latest
timeout-minutes: 10
steps:
- name: Checkout
uses: actions/checkout@v7

- name: Set up Python
uses: actions/setup-python@v7
with:
python-version: "3.12"

- name: Assert the suite file exists
run: test -f infra/cargo-target-broker/tests/test_cargo_target_broker.py

- name: Run the cargo-target-broker suite
run: python3 -m unittest discover -s infra/cargo-target-broker/tests -v
32 changes: 30 additions & 2 deletions infra/cargo-target-broker/bin/cargo_target_broker.py
Original file line number Diff line number Diff line change
Expand Up @@ -262,19 +262,45 @@ def total_bytes(self) -> int:
def evict_until_under_cap(self, now: float) -> list[str]:
"""Evict LRU idle dirs while over cap. Never evicts a leased dir."""
evicted: list[str] = []
# Dirs whose removal failed this pass: their rows stay (so the
# bytes still count against the cap) and they are not retried
# in the same pass, so a stuck dir cannot spin this loop.
failed: set[int] = set()
while self.total_bytes() > self.cap_bytes:
leased = self.leased_dir_ids()
row = self.db.execute(
"SELECT * FROM dirs ORDER BY last_used_at ASC"
).fetchall()
victim = None
for r in row:
if r["id"] not in leased:
if r["id"] not in leased and r["id"] not in failed:
victim = self._row(r)
break
if victim is None:
break
shutil.rmtree(victim.path, ignore_errors=True)
error: OSError | None = None
try:
shutil.rmtree(victim.path)
except FileNotFoundError:
pass
except OSError as e:
error = e
if victim.path.exists():
# #11417: the dir (or part of it) is still on disk. Keep
# its row and re-measure what is left, so the cap keeps
# counting it and adopt_strays never re-registers it.
remaining = self.dir_size(victim.path)
self.db.execute(
"UPDATE dirs SET bytes_cached = ? WHERE id = ?",
(remaining, victim.id),
)
self.bump("eviction_failures")
failed.add(victim.id)
eprint(
f"target-broker: could not evict {victim.path}: "
f"{error or 'directory still present'}; kept {remaining} bytes on the books"
)
continue
self.db.execute("DELETE FROM dirs WHERE id = ?", (victim.id,))
self.bump("evictions")
evicted.append(str(victim.path))
Expand Down Expand Up @@ -427,6 +453,7 @@ def status(self) -> dict:
"dirs_created",
"dirs_adopted",
"evictions",
"eviction_failures",
"leases_expired",
)
},
Expand Down Expand Up @@ -527,6 +554,7 @@ def main(argv: list[str] | None = None) -> int:
print(
f"checkouts: {warm} warm / {cold} cold ({rate:.0f}% warm),"
f" evictions: {c['evictions']},"
f" failed evictions: {c['eviction_failures']},"
f" expired leases: {c['leases_expired']}"
)
return 0
Expand Down
115 changes: 115 additions & 0 deletions infra/cargo-target-broker/tests/test_cargo_target_broker.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,115 @@
"""Eviction accounting for the cargo target broker (#11417).

Oracle: the issue's acceptance shape. When removing an LRU victim fails,
its registry row and byte accounting must survive; when it succeeds, the
row goes and the eviction is counted.
"""

from __future__ import annotations

import importlib.util
import shutil
import sys
import tempfile
import unittest
from pathlib import Path
from unittest import mock

HERE = Path(__file__).resolve().parent
SPEC = importlib.util.spec_from_file_location(
"cargo_target_broker", HERE.parent / "bin" / "cargo_target_broker.py"
)
broker_mod = importlib.util.module_from_spec(SPEC)
sys.modules["cargo_target_broker"] = broker_mod
SPEC.loader.exec_module(broker_mod)


class EvictionTest(unittest.TestCase):
def setUp(self) -> None:
self.tmp = Path(tempfile.mkdtemp(prefix="ctb-test-"))
self.pool = self.tmp / "pool"
self.broker = broker_mod.Broker(
pool_root=self.pool,
state_dir=self.tmp / "state",
cap_bytes=100,
per_key=2,
ttl_secs=60,
)
self.broker.__enter__()

def tearDown(self) -> None:
self.broker.__exit__(None, None, None)
shutil.rmtree(self.tmp, ignore_errors=True)

def add_dir(self, name: str, size: int, last_used: float, key: str | None = None) -> Path:
path = self.pool / name
path.mkdir(parents=True)
(path / "blob").write_bytes(b"x" * size)
self.broker.db.execute(
"INSERT INTO dirs(key, path, created_at, last_used_at, bytes_cached)"
" VALUES(?, ?, ?, ?, ?)",
(key or name, str(path), last_used, last_used, size),
)
return path

def test_successful_eviction_drops_the_row(self) -> None:
old = self.add_dir("old", 80, 1.0)
self.add_dir("new", 80, 2.0)
evicted = self.broker.evict_until_under_cap(now=3.0)
self.assertEqual(evicted, [str(old)])
self.assertFalse(old.exists())
self.assertEqual(self.broker.total_bytes(), 80)
self.assertEqual(self.broker.counter("evictions"), 1)
self.assertEqual(self.broker.counter("eviction_failures"), 0)

def test_failed_removal_keeps_the_row_and_its_bytes(self) -> None:
old = self.add_dir("old", 80, 1.0)
new = self.add_dir("new", 80, 2.0)

def refuse(path, *args, **kwargs):
raise PermissionError(13, "Permission denied", str(path))

with mock.patch.object(broker_mod.shutil, "rmtree", side_effect=refuse):
evicted = self.broker.evict_until_under_cap(now=3.0)

# Nothing was evicted, both dirs are still on disk and on the books,
# and the loop terminated instead of retrying the stuck dir.
self.assertEqual(evicted, [])
self.assertTrue(old.exists() and new.exists())
paths = {str(r.path): r.bytes_cached for r in self.broker.all_rows()}
self.assertEqual(paths, {str(old): 80, str(new): 80})
self.assertEqual(self.broker.total_bytes(), 160)
self.assertEqual(self.broker.counter("evictions"), 0)
self.assertEqual(self.broker.counter("eviction_failures"), 2)

def test_partial_removal_rebooks_what_is_left(self) -> None:
old = self.add_dir("old", 80, 1.0)
(old / "small").write_bytes(b"y" * 5)
self.add_dir("new", 30, 2.0)

def partial(path, *args, **kwargs):
(Path(path) / "blob").unlink()
raise PermissionError(13, "Permission denied", str(Path(path) / "small"))

with mock.patch.object(broker_mod.shutil, "rmtree", side_effect=partial):
self.broker.evict_until_under_cap(now=3.0)

rows = {r.path.name: r.bytes_cached for r in self.broker.all_rows()}
self.assertEqual(rows, {"old": 5, "new": 30})
self.assertEqual(self.broker.counter("eviction_failures"), 1)

def test_a_failed_victim_is_not_readopted_as_a_stray(self) -> None:
old = self.add_dir("k", 80, 1.0, key="k")
self.add_dir("k.2", 80, 2.0, key="k")
with mock.patch.object(
broker_mod.shutil, "rmtree", side_effect=PermissionError("nope")
):
self.broker.evict_until_under_cap(now=3.0)
self.broker.adopt_strays("k", now=4.0)
self.assertEqual(self.broker.counter("dirs_adopted"), 0)
self.assertEqual(len(self.broker.all_rows()), 2)
self.assertTrue(old.exists())


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