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
60 changes: 60 additions & 0 deletions bin/tine.py
Original file line number Diff line number Diff line change
Expand Up @@ -1886,6 +1886,62 @@ def before_shim(root: Path, settings: dict[str, dict[str, object]], isolation: s
return buck2_argv(*([FLAG_ISOLATION, isolation] if isolation else []))


# Buck loads its whole materializer state when a daemon starts, and tine starts one for every command, so
# every command slows down with the number of outputs the state tracks. A rebuilt output that moved to a new
# content hash keeps its old copy until a stale clean removes it, and Buck only runs one on its own after a
# daemon has run for 12 hours.
CLEAN_STALE_PERIOD = 24 * 60 * 60
CLEAN_STALE_AGE = 3 * 24 * 60 * 60
CLEAN_STALE_STAMP = f"{HOME}/tine-clean-stale"
# The isolation dir Buck uses when neither `--isolation-dir` nor BUCK_ISOLATION_DIR names one.
DEFAULT_ISOLATION = "v2"


def clean_stale_outputs(root: Path, isolation: str | None, now: float) -> None:
"""Delete the outputs of an isolation dir that no command used recently, at most once a period.

The modification time of a stamp per isolation dir records when tine last cleaned it.
"""
import subprocess

stamp = root / f"{CLEAN_STALE_STAMP}.{isolation or DEFAULT_ISOLATION}"
try:
last: float | None = stamp.stat().st_mtime
except FileNotFoundError:
last = None
if last is not None and now - last < CLEAN_STALE_PERIOD:
return
# Every command bumps the access times of the outputs it uses. Counting the age from the last cleaning
# keeps what a checkout used before a break that is longer than the age.
age = CLEAN_STALE_AGE + (now - last if last is not None else 0)
# Before cleaning, so that commands started in the meantime don't clean too.
stamp.parent.mkdir(parents=True, exist_ok=True)
stamp.touch()
os.utime(stamp, (now, now))
print(f"tine: deleting Buck outputs that no command used in {age / 86400:.0f} days", file=sys.stderr)
# Without an event log of its own, the cleaning can't take the place of the command that follows as the
# latest command that `buck log` reports on. Buck orders logs by the second their command started, and by
# command name within a second when the filesystem records no creation time.
clean = buck2_argv(
*([FLAG_ISOLATION, isolation] if isolation else []),
"clean",
"--no-event-log",
"--stale",
f"{age:.0f}s",
)
# A failed cleaning costs disk and startup time, so the command runs anyway.
try:
# Its report would mix into the output of the command that follows.
result = subprocess.run(
clean, stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.PIPE, text=True
)
except OSError as error:
print(f"tine: cleaning stale Buck outputs failed: {error}", file=sys.stderr)
return
if result.returncode != 0:
print(f"tine: cleaning stale Buck outputs failed:\n{result.stderr}", file=sys.stderr)


def buck_command(argv: list[str]) -> None:
# Buck stores no directory mode and creates the directories of its outputs with its own umask.
# Images copy those outputs, so their modes must not depend on the umask of the user.
Expand Down Expand Up @@ -1936,6 +1992,10 @@ def buck_command(argv: list[str]) -> None:
# run, so even an inherited BUCK_ISOLATION_DIR is overridden.
if command.subcommand == "complete" and not command.own_isolation:
argv = [FLAG_ISOLATION, ISOLATION_COMPLETE, *argv]
if command.subcommand not in BUCK_COMMAND_NO_ACTION:
import time

clean_stale_outputs(root, command.isolation, time.time())
buck = buck2_argv(*argv)
try:
os.execv(buck[0], buck)
Expand Down
96 changes: 96 additions & 0 deletions bin/tine_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -1187,6 +1187,84 @@ def test_no_file_to_bind_over(self) -> None:
tine.glibc_loader()


class TestCleanStaleOutputs(unittest.TestCase):
"""tine cleans stale Buck outputs at most once a day, before a command that runs actions."""

NOW = 2_000_000_000.0
DAY = 24 * 60 * 60

@override
def setUp(self) -> None:
self.root = scratch(self)
# A Buck that records each argument vector it runs with, and exits with the status in `status`.
self.buck2 = self.root / "buck2"
self.buck2.write_text(
'#!/bin/sh\necho "$*" >>"$0.calls"\nexit "$(cat "$0.status" 2>/dev/null || echo 0)"\n'
)
self.buck2.chmod(0o755)
patched = unittest.mock.patch.dict(os.environ, {"BUCK2_BINARY": str(self.buck2)})
patched.start()
self.addCleanup(patched.stop)

def calls(self) -> list[str]:
path = self.buck2.with_name("buck2.calls")
return path.read_text().splitlines() if path.exists() else []

def clean(self, isolation: str | None = None, now: float = NOW) -> str:
stderr = io.StringIO()
with contextlib.redirect_stderr(stderr):
tine.clean_stale_outputs(self.root, isolation, now)
return stderr.getvalue()

def stamp(self, isolation: str = tine.DEFAULT_ISOLATION) -> Path:
return self.root / f"{tine.CLEAN_STALE_STAMP}.{isolation}"

def test_first_command_cleans_and_records_it(self) -> None:
# Without a stamp, tine has never cleaned the isolation dir. It must delete what no command used
# within the age and record the time in a stamp.
self.clean()
self.assertEqual(self.calls(), [f"--no-buckd clean --no-event-log --stale {tine.CLEAN_STALE_AGE}s"])
self.assertEqual(self.stamp().stat().st_mtime, self.NOW)

def test_a_recent_cleaning_is_not_repeated(self) -> None:
# A cleaning less than a period ago must keep the next command from running another one.
self.clean()
self.clean(now=self.NOW + tine.CLEAN_STALE_PERIOD - 1)
self.assertEqual(len(self.calls()), 1)

def test_the_age_counts_from_the_last_cleaning(self) -> None:
# After a break of ten days, the cleaning must keep what the commands before the break used, so the
# age it passes grows by the time since the last cleaning.
self.clean()
later = self.NOW + 10 * self.DAY
self.clean(now=later)
self.assertEqual(
self.calls()[1],
f"--no-buckd clean --no-event-log --stale {tine.CLEAN_STALE_AGE + 10 * self.DAY}s",
)
self.assertEqual(self.stamp().stat().st_mtime, later)

def test_each_isolation_dir_is_cleaned_on_its_own(self) -> None:
# Every isolation dir has its own outputs, so a cleaning of the default one must not stand in for
# another, and the other's cleaning must name its isolation dir.
self.clean()
self.clean(isolation="other")
self.assertEqual(
self.calls()[1],
f"--no-buckd --isolation-dir other clean --no-event-log --stale {tine.CLEAN_STALE_AGE}s",
)
self.assertTrue(self.stamp("other").exists())

def test_a_failed_cleaning_is_reported_and_not_retried_at_once(self) -> None:
# A Buck that fails to clean must not fail the command that follows. tine reports the failure and
# tries again a period later rather than on every command.
self.buck2.with_name("buck2.status").write_text("1")
stderr = self.clean()
self.assertIn("cleaning stale Buck outputs failed", stderr)
self.clean(now=self.NOW + 1)
self.assertEqual(len(self.calls()), 1)


class TestNamespaces(MountTestCase):
"""Create and inspect bind mounts in child-process namespaces."""

Expand Down Expand Up @@ -1983,8 +2061,16 @@ def running(self) -> collections.abc.Generator[list[object]]:
execve: list[object] = []
self.served: list[object] = []
self.bound: list[object] = []
self.cleaned: list[str | None] = []
with contextlib.ExitStack() as patches:
patch = unittest.mock.patch.object
patches.enter_context(
patch(
tine,
"clean_stale_outputs",
side_effect=lambda _root, isolation, _now: self.cleaned.append(isolation),
)
)
patches.enter_context(
patch(tine, "bind_glibc_loader", side_effect=lambda: self.bound.append(len(self.served)))
)
Expand Down Expand Up @@ -2250,6 +2336,16 @@ def test_a_run_without_a_home_gets_one(self) -> None:
self.assertEqual(os.environ["HOME"], str(self.root / tine.HOME))
self.assertTrue((self.root / tine.HOME).is_dir())

def test_only_a_command_that_runs_actions_cleans_stale_outputs(self) -> None:
# A build cleans the stale outputs of the isolation dir it runs in. A command that runs no actions,
# such as `targets` or completion, must not wait for a cleaning.
with self.running():
tine.buck_command(["build", "//x"])
tine.buck_command(["--isolation-dir", "other", "build", "//x"])
tine.buck_command(["targets", "//x"])
tine.buck_command(["complete", "--target=//x"])
self.assertEqual(self.cleaned, [None, "other"])

def test_a_run_with_a_home_keeps_it(self) -> None:
home = scratch(self, "tine-home.")
with unittest.mock.patch.dict(os.environ, {"HOME": str(home)}):
Expand Down
Loading