fix(gc): let worktree holds beat the forge skip, read the mount table and recheck docker before 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
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 architecture review on PR 21: a forge-unavailable skip hid lock, busy, checkout and age holds from the risk plan; a mount at a scratch candidate or a same-device bind mount went unseen; containers and build cache were removed without a fresh check. Tree holds now win over the forge skip and the age check also runs under it, scratch items read /proc/self/mountinfo, and docker items are planned again before each delete. 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:
1 parent
babc977cfe
commit
43a3f9f73d
9 files changed
+102
-75
No files matched your search
@@ -65,6 +65,7 @@ REFUSAL = (
|
||||
)
|
||||
SCOPES = ("worktree", "branch", "all", "purge", "local")
|
||||
NOT_LINKED = "not a linked worktree of this repository"
|
||||
FORGE_UNAVAILABLE = "forge unavailable"
|
||||
NO_REMOTE_DEFAULT = (
|
||||
"refused: no remote-tracking default (origin, else the only remote: "
|
||||
"refs/remotes/<remote>/HEAD, main or master, resolving inside "
|
||||
@@ -518,24 +519,22 @@ def human_size(size: int) -> str:
|
||||
return f"{value / 1024:.1f}T"
|
||||
|
||||
|
||||
def _needs_forge(item: Item, tree: Worktree | None) -> bool:
|
||||
def _forge_skip(repo: Repo, item: Item, tree: Worktree | None) -> str | None:
|
||||
"""
|
||||
Whether deciding the item needs the forge's PR and protection facts.
|
||||
|
||||
Args:
|
||||
repo: the planned repository with its forge facts.
|
||||
item: the classified item.
|
||||
tree: the worktree holding its branch, or None.
|
||||
|
||||
Returns:
|
||||
False only for a branch that no worktree holds, without upstream and
|
||||
remote branch, merged into the default by ancestry; True otherwise.
|
||||
FORGE_UNAVAILABLE when the forge was not read, except for a branch that
|
||||
no worktree holds, without upstream and remote branch, merged into the
|
||||
default by ancestry; None otherwise.
|
||||
"""
|
||||
return not (
|
||||
tree is None
|
||||
and item.merged_by == "ancestor"
|
||||
and item.upstream is None
|
||||
and not item.remotes
|
||||
)
|
||||
if not repo.forge.unavailable:
|
||||
return None
|
||||
local = tree is None and item.upstream is None and not item.remotes
|
||||
return None if local and item.merged_by == "ancestor" else FORGE_UNAVAILABLE
|
||||
|
||||
|
||||
def _skip(
|
||||
@@ -548,10 +547,9 @@ def _skip(
|
||||
number = repo.forge.open_heads.get(item.branch) if item.branch else None
|
||||
if number:
|
||||
return f"open-pr #{number}"
|
||||
if repo.forge.unavailable and _needs_forge(item, tree):
|
||||
return "forge unavailable"
|
||||
forge = _forge_skip(repo, item, tree)
|
||||
if tree is None:
|
||||
return None
|
||||
return forge
|
||||
if tree.main:
|
||||
return "checked out in main worktree"
|
||||
if repo.scope == "local":
|
||||
@@ -576,7 +574,7 @@ def _skip(
|
||||
lock = _lock_skip(tree.locked, repo.host_ns)
|
||||
if lock:
|
||||
return lock
|
||||
return _busy(cwds, tree.path)
|
||||
return _busy(cwds, tree.path) or forge
|
||||
|
||||
|
||||
def _remote_refusal(unsafe: list[str], item: Item) -> str | None:
|
||||
@@ -746,7 +744,7 @@ def _build(
|
||||
)
|
||||
item.skip = _skip(repo, item, tree, checkout, cwds)
|
||||
if (
|
||||
item.skip is None
|
||||
item.skip in (None, FORGE_UNAVAILABLE)
|
||||
and repo.min_age is not None
|
||||
and item.last_activity
|
||||
and (time.time() - item.last_activity) / 3600 < repo.min_age
|
||||
|
||||
@@ -15,7 +15,6 @@ class TreeStats:
|
||||
newest_mtime: float = 0.0
|
||||
foreign_entries: int = 0
|
||||
unreadable: int = 0
|
||||
mounts: int = 0
|
||||
cores: list[str] = field(default_factory=list)
|
||||
|
||||
|
||||
@@ -56,8 +55,7 @@ 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, entries on
|
||||
another filesystem (counted, never descended into), and the regular
|
||||
foreign one), directories that could not be listed, and the regular
|
||||
files named `core` or `core.<digits>`.
|
||||
"""
|
||||
stats = TreeStats()
|
||||
@@ -85,6 +83,4 @@ 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
|
||||
@@ -160,22 +160,27 @@ def docker_items(now: float) -> tuple[list[dict], list[str]]:
|
||||
], []
|
||||
|
||||
|
||||
def delete_docker(entry: dict) -> str:
|
||||
def delete_docker(entry: dict, now: float) -> str:
|
||||
"""
|
||||
Args:
|
||||
entry: a low image, build-cache or container item of the plan.
|
||||
now: as docker_items takes it.
|
||||
|
||||
Returns:
|
||||
done, or skipped with the reason: an image no longer dangling right
|
||||
before its delete, or a kind that is never low.
|
||||
done, or skipped with the reason: an item that docker no longer
|
||||
lists as low right before its delete, or a kind that is never low.
|
||||
|
||||
Raises:
|
||||
subprocess.CalledProcessError: when docker refuses the delete.
|
||||
"""
|
||||
name = entry["name"]
|
||||
fresh, _ = docker_items(now)
|
||||
if not any(
|
||||
i["kind"] == entry["kind"] and i["name"] == name and i["risk"] == LOW
|
||||
for i in fresh
|
||||
):
|
||||
return "skipped: changed since plan"
|
||||
if entry["kind"] == "image":
|
||||
if name not in set(_docker(DANGLING).split()):
|
||||
return "skipped: no longer dangling"
|
||||
_docker(["image", "rm", name])
|
||||
elif entry["kind"] == "build-cache":
|
||||
_docker(
|
||||
|
||||
@@ -3,6 +3,7 @@ from __future__ import annotations
|
||||
from dataclasses import replace
|
||||
|
||||
from pkgmgr.actions.branch.gc import (
|
||||
FORGE_UNAVAILABLE,
|
||||
Item,
|
||||
Repo,
|
||||
_git,
|
||||
@@ -15,7 +16,6 @@ from pkgmgr.actions.worktree.hooks import FINI_HOOK
|
||||
from .levels import HIGH, LOW, MEDIUM, item
|
||||
|
||||
LOCAL_PROOF = ("ancestor", "patch")
|
||||
FORGE_UNAVAILABLE = "forge unavailable"
|
||||
TREE_STEPS = (f"hook:{FINI_HOOK}", "worktree")
|
||||
|
||||
|
||||
|
||||
@@ -98,7 +98,7 @@ def _delete(
|
||||
) -> str:
|
||||
try:
|
||||
if entry["kind"] in DOCKER_KINDS:
|
||||
return delete_docker(entry)
|
||||
return delete_docker(entry, now)
|
||||
if entry["kind"] == "tmp":
|
||||
return delete_tmp(
|
||||
entry, read_owners(owners_file), now, _process_cwds()
|
||||
|
||||
@@ -2,6 +2,7 @@ from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import stat
|
||||
|
||||
from pkgmgr.actions.branch.gc import _busy
|
||||
@@ -11,6 +12,8 @@ from pkgmgr.actions.gc.report.walk import TreeStats, walk
|
||||
from .levels import HIGH, LOW, MEDIUM, TMP_AGE_S, item
|
||||
|
||||
ENDED = ("done", "stopped")
|
||||
MOUNTINFO = "/proc/self/mountinfo"
|
||||
OCTAL = re.compile(r"\\([0-7]{3})")
|
||||
|
||||
|
||||
def read_owners(path: str | None) -> dict[str, str]:
|
||||
@@ -43,9 +46,22 @@ 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 _mount_hold(path: str) -> tuple[str, str] | None:
|
||||
try:
|
||||
with open(MOUNTINFO, encoding="utf-8") as fh:
|
||||
points = [OCTAL.sub(_char, line.split()[4]) for line in fh]
|
||||
except (OSError, IndexError):
|
||||
return MEDIUM, "mount table unreadable"
|
||||
if any(p == path or p.startswith(path + os.sep) for p in points):
|
||||
return MEDIUM, "is or holds a mount point"
|
||||
return None
|
||||
|
||||
|
||||
def _char(match: re.Match) -> str:
|
||||
return chr(int(match.group(1), 8))
|
||||
|
||||
|
||||
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)
|
||||
@@ -59,6 +75,9 @@ 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}"
|
||||
mounted = _mount_hold(path)
|
||||
if mounted:
|
||||
return mounted
|
||||
return _contents(path, stats, cwds) if stats is not None else None
|
||||
|
||||
|
||||
|
||||
@@ -3,7 +3,6 @@ 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
|
||||
@@ -109,28 +108,6 @@ 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()
|
||||
@@ -11,6 +11,7 @@ from tests.unit.pkgmgr.actions.gc.risk.risk_fixture import (
|
||||
DANGLING_ID,
|
||||
OLD_CACHE,
|
||||
RiskPlanFixture,
|
||||
write,
|
||||
)
|
||||
|
||||
|
||||
@@ -114,25 +115,21 @@ 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]:
|
||||
def _after_plan(self, change) -> 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)
|
||||
def change_then_apply(*args):
|
||||
change()
|
||||
return real_apply(*args)
|
||||
|
||||
with patch.object(plan, "_apply", side_effect=rewrite_then_apply):
|
||||
with patch.object(plan, "_apply", side_effect=change_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)
|
||||
code, printed = self._after_plan(lambda: write(self.owners, running))
|
||||
stopped = self.entry(printed, self.t["old-stopped"])
|
||||
|
||||
self.assertEqual(code, 0)
|
||||
@@ -142,7 +139,7 @@ class TestApplyLow(RiskPlanFixture, unittest.TestCase):
|
||||
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)
|
||||
code, printed = self._after_plan(lambda: os.unlink(self.owners))
|
||||
|
||||
self.assertEqual(code, 1)
|
||||
for name in ("old-stopped", "old-done.log"):
|
||||
@@ -151,21 +148,47 @@ class TestApplyLow(RiskPlanFixture, unittest.TestCase):
|
||||
)
|
||||
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 test_docker_items_no_longer_low_after_plan_are_kept(self) -> None:
|
||||
def nothing_low() -> None:
|
||||
df = json.loads(self.docker.df)
|
||||
for row in df["Containers"]:
|
||||
row["LocalVolumes"] = "1"
|
||||
for row in df["BuildCache"]:
|
||||
row["InUse"] = "true"
|
||||
self.docker.df = json.dumps(df)
|
||||
self.docker.calls.clear()
|
||||
|
||||
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)
|
||||
code, printed = self._after_plan(nothing_low)
|
||||
changed = {
|
||||
e["name"]: e["result"]
|
||||
for e in printed["items"]
|
||||
if e["kind"] in ("build-cache", "container")
|
||||
}
|
||||
|
||||
self.assertEqual(code, 0)
|
||||
self.assertNotIn(self.t["old-stopped"], self.risks(printed))
|
||||
self.assertTrue(os.path.isdir(self.t["old-stopped"]))
|
||||
self.assertEqual(
|
||||
changed,
|
||||
dict.fromkeys((OLD_CACHE, BARE_CONTAINER), "skipped: changed since plan"),
|
||||
)
|
||||
self.assertEqual(self.docker.writes(), [["image", "rm", DANGLING_ID]])
|
||||
|
||||
def test_mount_at_or_below_scratch_is_never_low(self) -> None:
|
||||
stopped = self.t["old-stopped"]
|
||||
table = os.path.join(self.root, "mountinfo")
|
||||
for point in (stopped, os.path.join(stopped, "deep"), None):
|
||||
with self.subTest(point=point):
|
||||
if point is None:
|
||||
table_path = os.path.join(self.root, "absent")
|
||||
else:
|
||||
escaped = point.replace(" ", "\\040")
|
||||
write(table, f"36 35 98:0 / {escaped} rw - ext4 /dev/x rw\n")
|
||||
table_path = table
|
||||
with patch.object(tmp_items, "MOUNTINFO", table_path):
|
||||
code, printed, _ = self.run_gc(level="low", apply=True)
|
||||
|
||||
self.assertEqual(code, 0)
|
||||
self.assertNotIn(stopped, self.risks(printed))
|
||||
self.assertTrue(os.path.isdir(stopped))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
@@ -12,6 +12,7 @@ from pkgmgr.actions.branch.gc_forge import ForgeFacts
|
||||
from pkgmgr.actions.gc.risk import plan
|
||||
from pkgmgr.cli.commands.worktree import handle_gc
|
||||
from pkgmgr.cli.parser import create_parser
|
||||
from tests.support.git_sandbox import git
|
||||
from tests.unit.pkgmgr.actions.gc.risk.risk_fixture import (
|
||||
BARE_CONTAINER,
|
||||
BUSY_CACHE,
|
||||
@@ -60,6 +61,14 @@ class TestRiskRules(RiskPlanFixture, unittest.TestCase):
|
||||
self.assertEqual(done["pr"], "unknown")
|
||||
self.assertEqual(done["skip"], "forge unavailable")
|
||||
|
||||
def test_forge_absence_never_hides_a_worktree_hold(self) -> None:
|
||||
self.forge = ForgeFacts(unavailable="no GitHub token")
|
||||
git(self.repo, "worktree", "lock", "--reason", "kept", self.wt["done"])
|
||||
_, printed, _ = self.run_gc(level="high")
|
||||
done = self.entry(printed, self.wt["done"])
|
||||
|
||||
self.assertEqual((done["risk"], done["skip"]), ("medium", "lock: kept"))
|
||||
|
||||
def test_open_pull_request_is_not_low(self) -> None:
|
||||
self.forge = ForgeFacts(open_heads={"done": 9})
|
||||
_, printed, _ = self.run_gc(level="high")
|
||||
|
||||
Reference in new issue
Block a user