diff --git a/infra/worktree-reaper/bin/worktree_reaper.py b/infra/worktree-reaper/bin/worktree_reaper.py index 9cbd64df24..c1ee546784 100755 --- a/infra/worktree-reaper/bin/worktree_reaper.py +++ b/infra/worktree-reaper/bin/worktree_reaper.py @@ -600,9 +600,20 @@ def main(argv=None): run_git(primary, "worktree", "prune") summary["kept_total"] = sum(summary["kept"].values()) - log_path = os.path.join(state_dir, "runs", f"run-{ts}-{os.getpid()}.jsonl") + # The log name must be unique per run: ts has only second resolution, + # so same-second runs from one process (the gate suite drives main() + # in-process) would otherwise share a path and the later run would + # truncate the earlier run's audit log (#5716). Add the microsecond + # fraction and create exclusively, suffixing on any residual clash. + log_stamp = f"{ts}-{int((now - int(now)) * 1_000_000):06d}" + log_path = os.path.join(state_dir, "runs", f"run-{log_stamp}-{os.getpid()}.jsonl") + suffix = 2 + while os.path.exists(log_path): + log_path = os.path.join( + state_dir, "runs", f"run-{log_stamp}-{os.getpid()}-{suffix}.jsonl") + suffix += 1 try: - with open(log_path, "w") as fh: + with open(log_path, "x") as fh: for rec in records: fh.write(json.dumps({"type": "decision", **rec}) + "\n") fh.write(json.dumps({"type": "summary", **summary}) + "\n") diff --git a/infra/worktree-reaper/tests/test_worktree_reaper.py b/infra/worktree-reaper/tests/test_worktree_reaper.py index 31185724f9..55ec0ec8ac 100755 --- a/infra/worktree-reaper/tests/test_worktree_reaper.py +++ b/infra/worktree-reaper/tests/test_worktree_reaper.py @@ -255,6 +255,25 @@ def test_04_quiet_gate(self): self.assertFalse(os.path.isdir(tree)) +class RunLogCollisionTests(unittest.TestCase): + """#5716: two runs in the same second must not share a run log.""" + + def test_two_runs_same_second_both_logged(self): + tmp = tempfile.mkdtemp(prefix="wtreaper-collision-") + try: + repo = SyntheticRepo(tmp) + runner = ReaperRun(repo, os.path.join(tmp, "state")) + tree = repo.branch_tree("t/fresh", push=True) + first = runner.run(quiet_hours=100000) + second = runner.run(quiet_hours=100000) + self.assertEqual(first[tree]["reason"], "active") + self.assertEqual(second[tree]["reason"], "active") + logs = os.listdir(os.path.join(tmp, "state", "runs")) + self.assertEqual(len(logs), 2, logs) + finally: + shutil.rmtree(tmp, ignore_errors=True) + + class UnitTests(unittest.TestCase): def test_porcelain_parser(self): raw = (