diff --git a/infra/cargo-target-janitor/README.md b/infra/cargo-target-janitor/README.md index 3bf3ad1bb..2d0d69690 100644 --- a/infra/cargo-target-janitor/README.md +++ b/infra/cargo-target-janitor/README.md @@ -1,9 +1,16 @@ # Cargo target janitor Keep fleet-worktree Cargo targets below the **150 GiB** cap. The primary -`~/git/code/pkgs/id/target` is out of scope. Only explicit directories under -`~/git/fleet/*/pkgs/id/target` and numeric `~/git/fleet/target-` -ad-hoc targets are considered. +`~/git/code/pkgs/id/target` is out of scope. Considered: directories under +`~/git/fleet/*/pkgs/id/target`, the `~/git/fleet/queue/*` sub-worktrees' +`pkgs/id/target` (one level deeper — ~82 GiB the top-level-only scan never +saw, #6812), repo-root cargo targets `~/git/fleet/*/target` and +`~/git/fleet/queue/*/target` when they hold build products (a `debug`, +`release`, or `.fingerprint` dir — ~114 GiB, #6812; a checkout's root +target belongs to the checkout, a non-checkout probe/scratch dir's root +target is treated like an ad-hoc target except that its owning dir +still exists, so it ages out instead of reading as worktree-gone), and +numeric `~/git/fleet/target-` ad-hoc targets. ## Safety policy @@ -16,9 +23,17 @@ ad-hoc targets are considered. task, a worktree whose branch has an open PR, an unmapped worktree/ad-hoc target, or a worktree/target containing a current-user Cargo, rustc, rust-analyzer, or build-script process cwd. -- 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. +- Queue liveness comes from a claims source, picked per run and named in + the plan output/record (`claims_source`): the repo-queue helper's + transient Bitwarden credential path when that helper file still exists + (broker task ids + states), otherwise the GitHub fallback source — + `fleet queue fallback scan` live/contested claim markers unioned with + open issues carrying `queue/claimed`, keyed by issue number because + fallback claims live on issues (#6619). The fallback source has no + broker task states, so it never makes a target eligible via the + terminal-task reason; it only ever adds protection. Open PRs are read + with `gh`. If no claims source can be read, cleanup stops — and the + refusal now leaves a run record like every other run (#6812). 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 @@ -38,7 +53,11 @@ ad-hoc targets are considered. wildcard or force-delete command is used. At most 20 targets are planned per invocation; the hourly timer continues later if still over cap. - Logs and run summaries live under - `~/.local/state/cargo-target-janitor/runs/`. + `~/.local/state/cargo-target-janitor/runs/`. Every run writes a record + there, including refusals (`"event": "refused"` with the reason): a + janitor that cannot run must be visible in its own state, not only in + the systemd journal (#6812 — the helper-path failure ran hourly, + unrecorded, while the disk filled). - If protected/open-PR or younger targets alone exceed the cap, the report and systemd journal say `over_cap`; they are deliberately kept rather than violating the safety exclusions. A maximum of 20 exact target paths is diff --git a/infra/cargo-target-janitor/bin/cargo_target_janitor.py b/infra/cargo-target-janitor/bin/cargo_target_janitor.py index b669f2a0b..5c39e3e92 100755 --- a/infra/cargo-target-janitor/bin/cargo_target_janitor.py +++ b/infra/cargo-target-janitor/bin/cargo_target_janitor.py @@ -41,6 +41,7 @@ class Target: task_status: str | None = None protected: str | None = None reason: str | None = None + issue_id: int | None = None def task_id_from(value: str) -> int | None: @@ -48,6 +49,44 @@ def task_id_from(value: str) -> int | None: return int(match.group(1)) if match else None +# Fallback-era and broker-era names carry the issue number as well as +# (for broker tasks) the task id: branches queue/-- +# and queue/fallback-- / queue/fb--; fleet +# dirs --, -issue--, and +# fb-- / fallback--. Fallback claims are +# keyed by issue (there are no task ids in fallback mode, #6619), so +# protection needs the issue identity too (#6812). +BRANCH_TASK_ISSUE_RE = re.compile(r"^queue/(\d+)-(\d+)(?:-|$)") +BRANCH_FALLBACK_RE = re.compile(r"^queue/(?:fallback|fb)-(\d+)(?:-|$)") +DIR_TASK_ISSUE_RE = re.compile(r"^(\d+)-(\d+)(?:-|$)") +DIR_TASK_ISSUE_ALT_RE = re.compile(r"^(\d+)-issue-(\d+)(?:-|$)") +DIR_FALLBACK_RE = re.compile(r"^(?:fallback|fb)-(\d+)(?:-|$)") + + +def issue_id_from(value: str) -> int | None: + match = BRANCH_FALLBACK_RE.search(value) + if match: + return int(match.group(1)) + for pattern in (BRANCH_TASK_ISSUE_RE, DIR_TASK_ISSUE_ALT_RE, DIR_TASK_ISSUE_RE): + match = pattern.search(value) + if match: + return int(match.group(2)) + match = DIR_FALLBACK_RE.search(value) + if match: + return int(match.group(1)) + return None + + +def dir_task_id(value: str) -> int | None: + # First numeric segment of a -- fleet dir name; + # task_id_from only recognises the queue/task-/target- prefixes. + for pattern in (DIR_TASK_ISSUE_RE, DIR_TASK_ISSUE_ALT_RE): + match = pattern.search(value) + if match: + return int(match.group(1)) + return None + + def is_adhoc_target(entry: Path, registered: set[Path]) -> bool: return ( ADHOC_TARGET_RE.fullmatch(entry.name) is not None @@ -56,16 +95,56 @@ def is_adhoc_target(entry: Path, registered: set[Path]) -> bool: def worktree_root_for_target(path: Path) -> Path | None: - """The checkout owning a /pkgs/id/target path, else None.""" + # The checkout owning a /pkgs/id/target path, or a + # repo-root /target path (#6812: root targets are real + # cargo output when a build runs at the checkout root or with + # CARGO_TARGET_DIR=/target). An ad-hoc target- dir + # is its own target, never a checkout root. if ( path.name == "target" and path.parent.name == "id" and path.parent.parent.name == "pkgs" ): return path.parent.parent.parent + if path.name == "target" and ADHOC_TARGET_RE.fullmatch(path.parent.name) is None: + return path.parent return None +def branch_for_unregistered(path: Path, cache: dict) -> str | None: + # Current branch of a checkout the primary does not register + # (e.g. the fleet/queue/* worktrees), read from the checkout + # itself. None when unreadable — the caller treats the worktree + # as unmapped, which protects its targets. + resolved = path.resolve() + if resolved in cache: + return cache[resolved] + branch = None + if (path / ".git").exists(): + try: + proc = subprocess.run( + ["git", "-C", str(path), "rev-parse", "--abbrev-ref", "HEAD"], + capture_output=True, + text=True, + timeout=30, + ) + name = proc.stdout.strip() + if proc.returncode == 0 and name and name != "HEAD": + branch = name + except (OSError, subprocess.SubprocessError): + branch = None + cache[resolved] = branch + return branch + + +def looks_like_cargo_target(path: Path) -> bool: + # A repo-root target/ is cargo output only when it holds build + # products; a stray dir named target is not the janitor's concern. + return any( + (path / marker).is_dir() for marker in ("debug", "release", ".fingerprint") + ) + + def owner_changed(target: Target, branches_now: dict[Path, str | None]) -> bool: """Whether the checkout owning a worktree target has moved to a different branch/task since discovery. A switch between plan and @@ -76,7 +155,11 @@ def owner_changed(target: Target, branches_now: dict[Path, str | None]) -> bool: if root is None: return False current_branch = branches_now.get(root.resolve()) - current_task = task_id_from(current_branch or "") or task_id_from(root.name) + current_task = ( + task_id_from(current_branch or "") + or task_id_from(root.name) + or dir_task_id(root.name) + ) return current_branch != target.branch or current_task != target.task_id @@ -266,6 +349,136 @@ def queue_task_states(client, task_ids: set[int]) -> dict[int, str]: return states +class ClaimsSource: + # One readable source of queue liveness for a janitor run. + # claims() returns (claimed_task_ids, claimed_issue_numbers): + # the broker source keys protection by task id, the GitHub + # fallback source by issue number, because fallback claims live + # on issues (there are no task ids in fallback mode, #6619). + # states() returns broker task states, or {} when the source + # has none — a source with no states never makes a target + # eligible via the terminal-task reason; it never weakens a + # protection. + name = "abstract" + + def claims(self): + raise NotImplementedError + + def states(self, task_ids): + return {} + + +class HelperClaimsSource(ClaimsSource): + name = "repo-queue-helper" + + def __init__(self, helper: Path): + self._client = load_queue_client(helper) + + def claims(self): + return queue_claims(self._client), set() + + def states(self, task_ids): + return queue_task_states(self._client, task_ids) + + +def parse_fallback_scan(scan: dict) -> set[int]: + # Issue numbers with a live fallback claim in a scan document. + # Live and contested both protect: a contested issue has two + # workers who believe they hold it, and the #6619 protocol says + # neither proceeds — but the work is claimed, so never delete + # under it. Stale/released/free do not protect here; the + # queue/claimed label union in FallbackClaimsSource covers the + # ambiguous broker-era residue separately. + issues = set() + for item in scan.get("items", []): + claim = item.get("claim") or {} + if claim.get("state") in {"live", "contested"}: + issues.add(int(item["number"])) + return issues + + +def labelled_claimed_issues() -> set[int]: + # Open issues carrying queue/claimed, read completely via gh. + # A broker-era claim leaves this label but no fallback marker; + # the scan fold calls such an issue free, but its claim state + # is genuinely unknown (a parked broker task can resume), so + # the label alone protects. Paginated like open_pr_branches: + # complete or fail closed. + issues = set() + for page_no in range(1, MAX_PR_PAGES + 1): + proc = subprocess.run( + [ + "gh", + "api", + f"repos/{REPO}/issues?state=open&labels=queue%2Fclaimed" + f"&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("issues response is not a list") + for row in rows: + if "pull_request" not in row: + issues.add(int(row["number"])) + except (ValueError, KeyError, TypeError) as exc: + raise SafetyError(f"invalid gh issues response: {exc}") from exc + if len(rows) < PR_PAGE: + return issues + raise SafetyError( + f"claimed-issue read exceeded {MAX_PR_PAGES} pages of {PR_PAGE}; " + "refusing to trust a possibly-truncated set" + ) + + +def fleet_binary() -> str: + found = shutil.which("fleet") + if found: + return found + local = Path.home() / ".local" / "bin" / "fleet" + if local.is_file(): + return str(local) + raise SafetyError("fleet binary not found on PATH or in ~/.local/bin") + + +class FallbackClaimsSource(ClaimsSource): + name = "github-fallback" + + def claims(self): + proc = subprocess.run( + [fleet_binary(), "queue", "fallback", "scan", "--repo", REPO], + capture_output=True, + text=True, + timeout=300, + ) + if proc.returncode != 0: + raise SafetyError( + f"fallback scan failed (exit {proc.returncode}): " + f"{proc.stderr.strip()[:200]}" + ) + try: + scan = json.loads(proc.stdout) + except ValueError as exc: + raise SafetyError(f"invalid fallback scan output: {exc}") from exc + return set(), parse_fallback_scan(scan) | labelled_claimed_issues() + + +def load_claims_source(helper: Path) -> ClaimsSource: + # The repo-queue helper stays the first choice where it still + # exists, but its absence is no longer fatal (#6812): the + # helper was retired in the fleet-binary migration, and a + # janitor that refuses every run enforces nothing. The GitHub + # fallback source needs only gh + the fleet binary and works + # while the queue backend is down. If neither source can be + # read, claims() raises and the run fails closed as before. + if helper.is_file(): + return HelperClaimsSource(helper) + return FallbackClaimsSource() + + PR_PAGE = 100 MAX_PR_PAGES = 200 @@ -309,6 +522,46 @@ def open_pr_branches(repo: str = REPO) -> set[str]: ) +def scan_entries(root: Path): + # (entry, is_top_level) for every dir that can own targets: the + # fleet children, plus the queue/ sub-worktrees one level down + # (#6812: queue/ alone held ~90 GiB the old top-level-only scan + # never saw). + for entry in sorted(root.iterdir()): + yield entry, True + queue_dir = root / "queue" + if queue_dir.is_dir() and not queue_dir.is_symlink(): + for entry in sorted(queue_dir.iterdir()): + yield entry, False + + +def target_paths_for_entry(entry: Path, registered: set, top_level: bool): + # (target_path, owning_worktree_or_None) pairs owned by one + # fleet entry: its pkgs/id target, its repo-root cargo target + # (#6812), or the entry itself when it is an ad-hoc target-. + if top_level and is_adhoc_target(entry, registered): + return [(entry, None)] + paths = [] + pkgs_target = entry / "pkgs" / "id" / "target" + if not pkgs_target.is_symlink() and pkgs_target.is_dir(): + paths.append((pkgs_target, entry.resolve())) + root_target = entry / "target" + if ( + not root_target.is_symlink() + and root_target.is_dir() + and looks_like_cargo_target(root_target) + ): + # A checkout's root target belongs to the checkout. A + # non-checkout dir's root target (lane probe/scratch trees — + # ~113 GiB of them, #6812) belongs to no checkout: it is + # returned with worktree None and handled like an ad-hoc + # target, except that its owning dir still exists, so the + # worktree-gone reason must not fire for it (see discover). + checkout = (entry / ".git").exists() or entry.resolve() in registered + paths.append((root_target, entry.resolve() if checkout else None)) + return paths + + def discover_targets( fleet_root: Path, branches: dict[Path, str | None], @@ -317,7 +570,10 @@ def discover_targets( prs: set[str], process_cwds: list[Path], stale_before: float, + claimed_issues: set[int] | None = None, ) -> list[Target]: + if claimed_issues is None: + claimed_issues = set() root = fleet_root.resolve(strict=True) registered = {path.resolve() for path in branches} worktree_task_ids = { @@ -325,29 +581,40 @@ def discover_targets( for branch in branches.values() if (task_id := task_id_from(branch or "")) is not None } - candidates: list[tuple[Path, Path | None, str | None, int | None]] = [] - for entry in sorted(root.iterdir()): + candidates = [] + branch_cache: dict = {} + for entry, top_level in scan_entries(root): if entry.is_symlink() or not entry.is_dir(): continue - if is_adhoc_target(entry, registered): - candidates.append((entry, None, None, task_id_from(entry.name))) - continue - target = entry / "pkgs" / "id" / "target" - if target.is_symlink() or not target.is_dir(): - continue - worktree = entry.resolve() - branch = branches.get(worktree) - candidates.append( - ( - target, - worktree, - branch, - task_id_from(branch or "") or task_id_from(entry.name), + for target, worktree in target_paths_for_entry(entry, registered, top_level): + if worktree is None and target == entry: + # Ad-hoc target-: the entry IS the target. + candidates.append( + (target, None, None, task_id_from(entry.name), None, None, True) + ) + continue + if worktree is None: + # Scratch root target: no checkout, but the owning + # dir exists and a build inside it must protect it. + task_id = task_id_from(entry.name) or dir_task_id(entry.name) + issue_id = issue_id_from(entry.name) + candidates.append( + (target, None, None, task_id, issue_id, entry.resolve(), False) + ) + continue + branch = branches.get(worktree) + if branch is None: + branch = branch_for_unregistered(entry, branch_cache) + task_id = ( + task_id_from(branch or "") + or task_id_from(entry.name) + or dir_task_id(entry.name) ) - ) + issue_id = issue_id_from(branch or "") or issue_id_from(entry.name) + candidates.append((target, worktree, branch, task_id, issue_id, worktree, False)) result = [] - for path, worktree, branch, task_id in candidates: + for path, worktree, branch, task_id, issue_id, owner_dir, adhoc in candidates: resolved = path.resolve(strict=True) if not resolved.is_relative_to(root) or resolved == root: continue @@ -355,12 +622,16 @@ def discover_targets( size, newest = target_stats(resolved) except OSError as exc: result.append( - Target(path, 0, 0, branch, task_id, protected=f"stat-failed: {exc}") + Target( + path, 0, 0, branch, task_id, + protected=f"stat-failed: {exc}", issue_id=issue_id, + ) ) continue status = statuses.get(task_id) if task_id is not None else None if ( worktree is None + and adhoc and task_id is not None and task_id not in worktree_task_ids ): @@ -370,21 +641,19 @@ def discover_targets( else: reason = "older-than-threshold" if newest <= stale_before else None protection = None - if worktree is None and task_id is None: + if worktree is None and adhoc and task_id is None: protection = "unmapped-ad-hoc-target" elif task_id is not None and task_id in claimed: protection = "live-claimed-task" + elif issue_id is not None and issue_id in claimed_issues: + protection = "live-claimed-issue" elif branch and branch in prs: protection = "open-pr-worktree" elif task_id is not None and any(task_id_from(pr) == task_id for pr in prs): protection = "open-pr-worktree" elif worktree is not None and branch is None: protection = "unmapped-worktree" - elif any( - cwd == worktree or cwd.is_relative_to(worktree) - for cwd in process_cwds - if worktree is not None - ): + elif owner_dir is not None and cwd_inside(process_cwds, owner_dir): protection = "process-in-worktree" elif worktree is None and any(cwd.is_relative_to(root) for cwd in process_cwds): # target-* may be shared via CARGO_TARGET_DIR, so preserve it @@ -406,6 +675,7 @@ def discover_targets( status, protected=protection, reason=reason, + issue_id=issue_id, ) ) return result @@ -418,15 +688,10 @@ def measure_total( root = fleet_root.resolve(strict=True) registered = {path.resolve() for path in (branches or {})} total = 0 - for entry in root.iterdir(): + for entry, top_level in scan_entries(root): if entry.is_symlink() or not entry.is_dir(): continue - paths = ( - [entry] - if is_adhoc_target(entry, registered) - else [entry / "pkgs" / "id" / "target"] - ) - for path in paths: + for path, _worktree in target_paths_for_entry(entry, registered, top_level): if path.is_symlink() or not path.is_dir(): continue resolved = path.resolve(strict=True) @@ -482,11 +747,13 @@ def main() -> int: if args.cap_gib < 1 or args.stale_hours < 1: parser.error("cap and stale threshold must be positive") + run_id = datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%SZ") + log = args.state_dir / "runs" / f"run-{run_id}-{os.getpid()}.jsonl" try: # Snapshot every independent liveness source before producing a plan. branches = worktree_branches(args.primary) - queue_client = load_queue_client(args.queue_helper) - claimed = queue_claims(queue_client) + source = load_claims_source(args.queue_helper) + claimed, claimed_issues = source.claims() prs = open_pr_branches() cwds = active_process_cwds() task_ids = set() @@ -500,7 +767,7 @@ def main() -> int: task_id = task_id_from(branch or "") or task_id_from(entry.name) if task_id is not None and (entry / "pkgs/id/target").is_dir(): task_ids.add(task_id) - statuses = queue_task_states(queue_client, task_ids) + statuses = source.states(task_ids) now = time.time() targets = discover_targets( args.fleet_root, @@ -510,15 +777,15 @@ def main() -> int: prs, cwds, now - args.stale_hours * 3600, + claimed_issues=claimed_issues, ) total = sum(t.bytes for t in targets) selected, projected = build_plan(targets, args.cap_gib * GIB) - run_id = datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%SZ") - log = args.state_dir / "runs" / f"run-{run_id}-{os.getpid()}.jsonl" print( json.dumps( { "mode": "apply" if args.apply else "dry-run", + "claims_source": source.name, "cap_gib": args.cap_gib, "total_gib": round(total / GIB, 2), "projected_gib": round(projected / GIB, 2), @@ -554,6 +821,7 @@ def main() -> int: "event": "plan", "at": datetime.now(timezone.utc).isoformat(), "mode": "apply" if args.apply else "dry-run", + "claims_source": source.name, "total_bytes": total, "cap_bytes": args.cap_gib * GIB, "selected": [ @@ -576,7 +844,7 @@ def main() -> int: remaining_estimate = total for target in selected: # Fresh queue, PR, and process state immediately before each removal. - fresh_claimed = queue_claims(queue_client) + fresh_claimed, fresh_issues = source.claims() fresh_prs = open_pr_branches() fresh_cwds = active_process_cwds() path = target.path @@ -589,8 +857,12 @@ def main() -> int: raise SafetyError( f"task {target.task_id} became live; stopping before {path}" ) + if target.issue_id is not None and target.issue_id in fresh_issues: + raise SafetyError( + f"issue {target.issue_id} became claimed; stopping before {path}" + ) if target.reason == "terminal-task": - fresh_status = queue_task_states(queue_client, {target.task_id}).get( + fresh_status = source.states({target.task_id}).get( target.task_id ) if fresh_status not in {"done", "failed", "cancelled"}: @@ -688,7 +960,28 @@ def main() -> int: ) ) return 0 - except (SafetyError, OSError, subprocess.CalledProcessError, SystemExit) as exc: + except ( + SafetyError, + OSError, + subprocess.CalledProcessError, + subprocess.TimeoutExpired, + SystemExit, + ) as exc: + # A refusal is a run too (#6812): until it left a record, + # an hourly-dead janitor was visible only in the systemd + # journal while its state dir stayed empty. + try: + append_log( + log, + { + "event": "refused", + "at": datetime.now(timezone.utc).isoformat(), + "mode": "apply" if args.apply else "dry-run", + "reason": str(exc), + }, + ) + except OSError: + pass print(f"cargo-target-janitor: refusing cleanup: {exc}", file=sys.stderr) return 2 diff --git a/infra/cargo-target-janitor/tests/test_cargo_target_janitor.py b/infra/cargo-target-janitor/tests/test_cargo_target_janitor.py index 7c94ccfcd..0de179145 100755 --- a/infra/cargo-target-janitor/tests/test_cargo_target_janitor.py +++ b/infra/cargo-target-janitor/tests/test_cargo_target_janitor.py @@ -343,5 +343,214 @@ def test_queue_task_states_chunks_beyond_1000_ids(self): self.assertEqual(len(stub.queries), 3) +class JanitorFallbackSourceTests(unittest.TestCase): + """#6812: the janitor's claims source must survive the helper's + retirement — GitHub fallback claims protect by issue, discovery + covers queue/ sub-worktrees and repo-root targets, and a refusal + leaves a run record.""" + + def setUp(self): + self.tmp = tempfile.TemporaryDirectory() + self.root = Path(self.tmp.name) / "fleet" + self.root.mkdir() + + def tearDown(self): + self.tmp.cleanup() + + def make_target(self, name, size=10, age=72): + path = self.root / name + path.mkdir(parents=True) + data = path / "artifact" + data.write_bytes(b"x" * size) + stamp = time.time() - age * 3600 + import os + + os.utime(data, (stamp, stamp)) + return path + + def test_issue_and_dir_task_identity(self): + self.assertEqual(janitor.issue_id_from("queue/10528-5743-generic"), 5743) + self.assertEqual(janitor.issue_id_from("queue/fallback-6812-janitor"), 6812) + self.assertEqual(janitor.issue_id_from("queue/fb-6757-check"), 6757) + self.assertEqual(janitor.issue_id_from("fb-6615-records"), 6615) + self.assertEqual(janitor.issue_id_from("6635-issue-6635-exec"), 6635) + self.assertEqual(janitor.dir_task_id("10747-1727-built"), 10747) + self.assertIsNone(janitor.issue_id_from("queue/42-fix")) + # fb-- is the fallback worktree convention, + # so a same-issue tools dir resolves to that issue too (it can + # only ever add protection, never remove it). + self.assertEqual(janitor.issue_id_from("fb-5743-tools"), 5743) + self.assertIsNone(janitor.issue_id_from("fb-tools")) + + def test_parse_fallback_scan_protects_live_and_contested_only(self): + scan = { + "items": [ + {"number": 1, "claim": {"state": "live", "claimable": False}}, + {"number": 2, "claim": {"state": "contested", "claimable": False}}, + {"number": 3, "claim": {"state": "stale", "claimable": True}}, + {"number": 4, "claim": {"state": "released", "claimable": True}}, + {"number": 5, "claim": {"state": "free", "claimable": True}}, + ] + } + self.assertEqual(janitor.parse_fallback_scan(scan), {1, 2}) + + def test_fallback_claimed_issue_protects_fb_worktree(self): + target = self.make_target("fb-6757/pkgs/id/target") + found = janitor.discover_targets( + self.root, + {}, + set(), + {}, + set(), + [], + time.time() - 48 * 3600, + claimed_issues={6757}, + ) + self.assertEqual(len(found), 1) + self.assertEqual(found[0].protected, "live-claimed-issue") + self.assertEqual(found[0].issue_id, 6757) + + def test_queue_subworktree_target_is_discovered(self): + target = self.make_target("queue/1234-9876-x/pkgs/id/target") + # Real queue/ worktrees carry a .git file; the branch is read + # from the checkout itself when the primary does not register + # it. Stub that read (the tmp dir is not a git checkout). + real = janitor.branch_for_unregistered + janitor.branch_for_unregistered = lambda p, c: "queue/1234-9876-x" + try: + found = self._discover_queue_target() + finally: + janitor.branch_for_unregistered = real + self.assertEqual(len(found), 1) + self.assertEqual(found[0].task_id, 1234) + self.assertEqual(found[0].issue_id, 9876) + self.assertIsNone(found[0].protected) + self.assertEqual(found[0].reason, "terminal-task") + self.assertGreater(janitor.measure_total(self.root, {}), 0) + + def _discover_queue_target(self): + return janitor.discover_targets( + self.root, + {}, + set(), + {1234: "done"}, + set(), + [], + time.time() - 48 * 3600, + claimed_issues=set(), + ) + + def test_repo_root_target_discovered_and_pr_protected(self): + wt = self.root / "wt-1" + (wt / "target" / "debug").mkdir(parents=True) + (wt / "target" / "debug" / "artifact").write_bytes(b"x" * 10) + (wt / ".git").write_text("gitdir: elsewhere") + plain = self.root / "wt-2" + (plain / "target").mkdir(parents=True) + (plain / "target" / "not-cargo").write_text("x") + found = janitor.discover_targets( + self.root, + {wt.resolve(): "queue/55-x"}, + set(), + {}, + {"queue/55-x"}, + [], + time.time() - 48 * 3600, + ) + self.assertEqual(len(found), 1) + self.assertEqual(found[0].path, (wt / "target").resolve()) + self.assertEqual(found[0].protected, "open-pr-worktree") + self.assertEqual( + janitor.worktree_root_for_target((wt / "target").resolve()), wt.resolve() + ) + + def test_load_claims_source_falls_back_when_helper_missing(self): + source = janitor.load_claims_source(Path(self.tmp.name) / "nope.py") + self.assertIsInstance(source, janitor.FallbackClaimsSource) + + def test_helper_source_round_trip_when_helper_exists(self): + helper = Path(self.tmp.name) / "helper.py" + helper.write_text( + "def get_service_key():\n return 'k'\n" + "def http(method, query, key):\n" + " return [{'id': 7, 'queue': 'repo-health-code-pilot'," + " 'status': 'claimed'," + " 'payload': {'repo': 'developing-today/code'}}]\n" + ) + source = janitor.load_claims_source(helper) + self.assertIsInstance(source, janitor.HelperClaimsSource) + claimed, issues = source.claims() + self.assertEqual(claimed, {7}) + self.assertEqual(issues, set()) + + def test_scratch_root_target_ages_out_without_a_checkout(self): + # A probe/scratch dir (no .git) with a cargo-looking root + # target: not a checkout, so no worktree-gone shortcut — it + # becomes eligible only by age, like any loose target. + probe = self.root / "probe-2026-10-29-x" + target_dir = probe / "target" / "debug" + target_dir.mkdir(parents=True) + artifact = target_dir / "artifact" + artifact.write_bytes(b"x" * 10) + import os + + stamp = time.time() - 72 * 3600 + os.utime(artifact, (stamp, stamp)) + os.utime(target_dir, (stamp, stamp)) + os.utime(probe / "target", (stamp, stamp)) + found = janitor.discover_targets( + self.root, {}, set(), {}, set(), [], time.time() - 48 * 3600, + ) + self.assertEqual(len(found), 1) + self.assertEqual(found[0].path, (probe / "target").resolve()) + self.assertIsNone(found[0].protected) + self.assertEqual(found[0].reason, "older-than-threshold") + + def test_scratch_root_target_protected_by_build_in_owning_dir(self): + probe = self.root / "fb-9999-probe" + target_dir = probe / "target" / "debug" + target_dir.mkdir(parents=True) + (target_dir / "artifact").write_bytes(b"x" * 10) + found = janitor.discover_targets( + self.root, + {}, + set(), + {}, + set(), + [probe], + time.time() - 48 * 3600, + claimed_issues=set(), + ) + self.assertEqual(found[0].protected, "process-in-worktree") + claimed = janitor.discover_targets( + self.root, + {}, + set(), + {}, + set(), + [], + time.time() - 48 * 3600, + claimed_issues={9999}, + ) + self.assertEqual(claimed[0].protected, "live-claimed-issue") + + def test_refusal_writes_a_run_record(self): + state_dir = Path(self.tmp.name) / "state" + argv = [ + "janitor", + "--fleet-root", str(self.root), + "--primary", str(Path(self.tmp.name) / "not-a-repo"), + "--queue-helper", str(Path(self.tmp.name) / "nope.py"), + "--state-dir", str(state_dir), + ] + with mock.patch.object(sys, "argv", argv): + rc = janitor.main() + self.assertEqual(rc, 2) + records = list((state_dir / "runs").glob("*.jsonl")) + self.assertEqual(len(records), 1) + self.assertIn('"event": "refused"', records[0].read_text()) + + + if __name__ == "__main__": unittest.main()