fix(gc): recheck owner status and mounts before scratch deletes
CI / security-codeql (push) Canceled after 0s
CI / test-unit (push) Canceled after 0s
CI / test-integration (push) Canceled after 0s
CI / test-env-virtual (push) Canceled after 0s
CI / test-env-nix (push) Canceled after 0s
CI / test-e2e (push) Canceled after 0s
CI / test-virgin-user (push) Canceled after 0s
CI / test-virgin-root (push) Canceled after 0s
CI / lint-shell (push) Canceled after 0s
CI / lint-python (push) Canceled after 0s
CI / lint-docker (push) Canceled after 0s
CI / quality (push) Canceled after 0s

CodeRabbit on PR 21: the scratch delete trusted the owner status read at plan time, and walk skipped mounts below a scratch directory that rmtree would cross. The owner file is now read again before every scratch delete; walk counts entries on another filesystem and a counted mount keeps the item above low.

PR: https://github.com/kevinveenbirkenbach/package-manager/pull/21
Created-with: https://s.veen.world/skills
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Kevin Veen-BirkenbachandClaude Opus 5.5 committed 2026-12-01 19:23:17 +00:00
1 parent 4c603a0087
commit babc977cfe
5 files changed
+102 -13

No files matched your search

+5 -1
View File
@@ -15,6 +15,7 @@ class TreeStats:
newest_mtime: float = 0.0
foreign_entries: int = 0
unreadable: int = 0
mounts: int = 0
cores: list[str] = field(default_factory=list)
@@ -55,7 +56,8 @@ def walk(path: str, dev: int | None = None) -> TreeStats:
Returns:
Allocated bytes (st_blocks * 512, each hard-linked inode once), the
newest mtime, entries not owned by the current uid (none counted below a
foreign one), directories that could not be listed, and the regular
foreign one), directories that could not be listed, entries on
another filesystem (counted, never descended into), and the regular
files named `core` or `core.<digits>`.
"""
stats = TreeStats()
@@ -83,4 +85,6 @@ def walk(path: str, dev: int | None = None) -> TreeStats:
continue
if child.st_dev == dev:
stack.append((entry.path, child, pruned or foreign))
else:
stats.mounts += 1
return stats
+9 -5
View File
@@ -93,14 +93,16 @@ def _render(plan: dict) -> str:
def _delete(
entry: dict,
git_by_name: dict,
owners: dict[str, str],
owners_file: str | None,
now: float,
) -> str:
try:
if entry["kind"] in DOCKER_KINDS:
return delete_docker(entry)
if entry["kind"] == "tmp":
return delete_tmp(entry, owners, now, _process_cwds())
return delete_tmp(
entry, read_owners(owners_file), now, _process_cwds()
)
if entry["kind"] == "worktree":
repo, it = git_by_name[(entry["repo"], entry["name"])]
return delete_worktree(repo, it)
@@ -139,11 +141,13 @@ def _host_items(
return [*docker, *scratch], [*notes, *docker_warnings]
def _apply(entries: list[dict], git: list, owners: dict[str, str], now: float) -> None:
def _apply(
entries: list[dict], git: list, owners_file: str | None, now: float
) -> None:
git_by_name = {(e["repo"], e["name"]): (repo, it) for repo, it, e in git}
for entry in entries:
if entry["risk"] == LOW:
entry["result"] = _delete(entry, git_by_name, owners, now)
entry["result"] = _delete(entry, git_by_name, owners_file, now)
print(
f"[gc] {entry['kind']} {entry['name']}: {entry['result']}",
file=sys.stderr,
@@ -204,5 +208,5 @@ def risk_cleanup(repo_roots: list[str], request: RiskRequest) -> int:
host, host_warnings = _host_items(request, owners, now, host_ns)
entries = [*(entry for _, _, entry in git), *host]
if request.apply:
_apply(entries, git, owners, now)
_apply(entries, git, request.owners_file, now)
return _report(request, host_ns, now, entries, [*git_warnings, *host_warnings])
+10 -6
View File
@@ -43,6 +43,15 @@ def _measure(path: str, st: os.stat_result) -> tuple[TreeStats | None, int, floa
return stats, stats.size_bytes, max(stats.newest_mtime, st.st_mtime)
def _contents(path: str, stats: TreeStats, cwds: dict) -> tuple[str, str] | None:
if stats.mounts:
return MEDIUM, "holds a mount point"
if stats.foreign_entries or stats.unreadable:
return MEDIUM, "holds foreign or unreadable entries"
busy = _busy(cwds, path)
return (MEDIUM, busy) if busy else None
def _held(
path: str, stats: TreeStats | None, status: str | None, cwds: dict
) -> tuple[str, str] | None:
@@ -50,12 +59,7 @@ def _held(
return HIGH, "holds a git checkout: remove it as a worktree"
if status is not None and status not in ENDED:
return HIGH, f"owner task is {status}"
if stats is not None and (stats.foreign_entries or stats.unreadable):
return MEDIUM, "holds foreign or unreadable entries"
busy = _busy(cwds, path) if stats is not None else None
if busy:
return MEDIUM, busy
return None
return _contents(path, stats, cwds) if stats is not None else None
def _settled(status: str | None, age: float) -> tuple[str, str]:
@@ -3,6 +3,7 @@ from __future__ import annotations
import os
import tempfile
import unittest
from types import SimpleNamespace
from unittest.mock import patch
from pkgmgr.actions.gc.report import walk as walk_module
@@ -108,6 +109,28 @@ class TestWalk(unittest.TestCase):
self.assertEqual(stats.size_bytes, 0)
def test_child_on_another_filesystem_is_counted_not_walked(self) -> None:
self._write("mnt/inner", b"x" * 8192)
mnt = os.path.join(self.root, "mnt")
fields = list(os.lstat(mnt))
fields[2] += 1
moved = os.stat_result(fields)
real_children = walk_module._children
def children(path, stats):
return [
SimpleNamespace(path=e.path, stat=lambda follow_symlinks: moved)
if e.path == mnt
else e
for e in real_children(path, stats)
]
with patch.object(walk_module, "_children", side_effect=children):
stats = walk(self.root)
self.assertEqual(stats.mounts, 1)
self.assertEqual(stats.size_bytes, allocated(self.root))
if __name__ == "__main__":
unittest.main()
@@ -1,10 +1,11 @@
from __future__ import annotations
import json
import os
import unittest
from unittest.mock import patch
from pkgmgr.actions.gc.risk import git_items, plan
from pkgmgr.actions.gc.risk import git_items, plan, tmp_items
from tests.unit.pkgmgr.actions.gc.risk.risk_fixture import (
BARE_CONTAINER,
DANGLING_ID,
@@ -113,6 +114,59 @@ class TestApplyLow(RiskPlanFixture, unittest.TestCase):
self.assertTrue(os.path.isdir(self.wt["done"]))
self.assertTrue(os.path.isfile(self.t["old-done.log"]))
def _owners_after_plan(self, content: str | None) -> tuple[int, dict]:
real_apply = plan._apply
def rewrite_then_apply(*args):
if content is None:
os.unlink(self.owners)
else:
with open(self.owners, "w") as fh:
fh.write(content)
return real_apply(*args)
with patch.object(plan, "_apply", side_effect=rewrite_then_apply):
code, printed, _ = self.run_gc(level="low", apply=True)
return code, printed
def test_owner_status_changed_after_plan_keeps_the_scratch(self) -> None:
running = json.dumps({self.t["old-stopped"]: "running"})
code, printed = self._owners_after_plan(running)
stopped = self.entry(printed, self.t["old-stopped"])
self.assertEqual(code, 0)
self.assertEqual(
stopped["result"], "skipped: changed since plan (owner task is running)"
)
self.assertTrue(os.path.isdir(self.t["old-stopped"]))
def test_owner_file_gone_after_plan_fails_and_keeps_the_scratch(self) -> None:
code, printed = self._owners_after_plan(None)
self.assertEqual(code, 1)
for name in ("old-stopped", "old-done.log"):
self.assertTrue(
self.entry(printed, self.t[name])["result"].startswith("failed:"), name
)
self.assertTrue(os.path.lexists(self.t[name]), name)
def test_mount_below_scratch_is_never_low(self) -> None:
real_walk = tmp_items.walk
def mounted(path, *args):
stats = real_walk(path, *args)
if path == self.t["old-stopped"]:
stats.mounts = 1
return stats
with patch.object(tmp_items, "walk", side_effect=mounted):
code, printed, _ = self.run_gc(level="low", apply=True)
self.assertEqual(code, 0)
self.assertNotIn(self.t["old-stopped"], self.risks(printed))
self.assertTrue(os.path.isdir(self.t["old-stopped"]))
if __name__ == "__main__":
unittest.main()