Skip to content
Merged
Show file tree
Hide file tree
Changes from 11 commits
Commits
Show all changes
46 commits
Select commit Hold shift + click to select a range
8dd0812
Delete mutation run snapshots when they are finished with
claude Jul 27, 2026
2e8a9b9
Make the automatic mutation clear-up safer and louder
claude Jul 27, 2026
26139fb
Say when a mutation run record is cleared out
claude Jul 27, 2026
26e0555
Split run clear-up out of the mutation supervisor
claude Jul 27, 2026
e22d816
Swap a mutation run record into place in one step
claude Jul 27, 2026
95665aa
Merge remote-tracking branch 'origin/main' into claude/temp-dir-clean…
claude Jul 27, 2026
ac4504b
Tighten the mutation run clear-up after review
claude Jul 27, 2026
c15d68a
Split run records and the run lock out of isolation-state
claude Jul 27, 2026
93306be
Look at the run record again after waiting on its lock
claude Jul 27, 2026
7a125db
Treat a held run folder as busy whatever its record says
claude Jul 27, 2026
7ac103d
Delete a run's folder only while holding its lock
claude Jul 27, 2026
2bbe57a
Wait for the record swap to start before reading it
claude Jul 27, 2026
5543372
Merge remote-tracking branch 'origin/main' into claude/temp-dir-clean…
claude Jul 27, 2026
f9b37a0
Only clear away folders this runner really named
claude Jul 27, 2026
7160d25
Merge remote-tracking branch 'origin/main' into claude/temp-dir-clean…
claude Jul 27, 2026
2c85a6a
Leave a folder alone unless we can tell it is finished
claude Jul 27, 2026
1db7e21
Check a run record is whole before trusting it
claude Jul 27, 2026
8be3687
Note the folders every command should leave alone
claude Jul 27, 2026
21f8ee6
Merge remote-tracking branch 'origin/main' into claude/temp-dir-clean…
claude Jul 27, 2026
60b3791
Treat a vanished run folder as nobody's, and mirror the new test paths
claude Jul 27, 2026
13c9ef0
Check the lock is still the file at the run's path before using it
claude Jul 27, 2026
7b15569
Merge remote-tracking branch 'origin/main' into claude/temp-dir-clean…
claude Jul 27, 2026
3e92f0a
Check the run's own lock is the file at its path too, and stop hiding…
claude Jul 27, 2026
a46db75
Treat a folder that goes before the lock opens as another go
claude Jul 27, 2026
a92f53d
Make every lock in the repo one mechanism
claude Jul 27, 2026
f48e0b4
Merge remote-tracking branch 'origin/main' into claude/temp-dir-clean…
claude Jul 27, 2026
7670e5b
Merge main, and note the migration lock in the stripe-mock lock TODO
claude Jul 27, 2026
8f8734e
Keep the lock helpers that only lock-file.ts uses private
claude Jul 27, 2026
cea09c3
Join the wait helper back onto one line
claude Jul 27, 2026
3d51572
Merge remote-tracking branch 'origin/main' into claude/temp-dir-clean…
claude Jul 27, 2026
3e1e541
Let a job that gives up on a lock really stop waiting
claude Jul 27, 2026
fb9b7a8
Start the give-up clock when the child is queueing, not when it starts
claude Jul 27, 2026
69f6206
Let the child keep its own deadline, and share the same-file check
claude Jul 27, 2026
3575635
Fold the one-go helper into the lock it serves
claude Jul 27, 2026
482a9a3
Test the lock whose file has gone from its path
claude Jul 27, 2026
e994301
Merge remote-tracking branch 'origin/main' into claude/temp-dir-clean…
claude Jul 27, 2026
c002fed
Tell a lock that could not be taken from one that was busy
claude Jul 27, 2026
469e343
Clear runs away a few at a time
claude Jul 27, 2026
732549e
Tell a lock check that could not answer from one that says nobody
claude Jul 27, 2026
636989c
Test the lock file that outlives the run that made it
claude Jul 27, 2026
63e2367
Only believe a whole line from the child holding a lock
claude Jul 27, 2026
28c53c3
Name the held lock's type in the test instead of exporting it
claude Jul 27, 2026
2aed858
Treat a lock file that has gone as nobody holding one
claude Jul 27, 2026
c1db784
Share one way of making a stat say something else
claude Jul 27, 2026
e0d6567
Let the child say its folder went, rather than guessing afterwards
claude Jul 27, 2026
f27fb64
Merge remote-tracking branch 'origin/main' into claude/temp-dir-clean…
claude Jul 28, 2026
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
8 changes: 6 additions & 2 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -932,8 +932,12 @@ file. The normal `deno task mutation` command first copies the current checkout
(including dirty source/test edits, excluding `.git`, cache/report folders,
local databases, secrets, and generated assets) to `.mutation-runs/<id>/work`;
all in-place writes and per-mutant bundle rebuilds happen inside that copy, not
the live files. Each run leaves `.mutation-runs/<id>/run.json` with the child
PID/status, so a stray run is easy to find and stop:
the live files. That copy is deleted as soon as the run ends, so
`.mutation-runs/` does not fill up with checkout copies. While a run is going —
and until the *next* run starts — it has a small `.mutation-runs/<id>/run.json`
holding the child PID/status, so a stray run is easy to find and stop. Starting
a run clears out the folders of every earlier run that is no longer going,
including any whose `run.json` is unreadable because it was killed mid-write:

```bash
deno task mutation --list
Expand Down
2 changes: 1 addition & 1 deletion scripts/mutation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,12 +20,12 @@
import { globToRegExp, join, normalize, SEPARATOR } from "@std/path";
import { DEFAULT_TIMEOUT, parseArgs } from "./mutation/args.ts";
import { runIsolatedMutationCommand } from "./mutation/isolation.ts";
import { withMutationRunLock } from "./mutation/isolation-lock.ts";
import {
MUTATION_RUN_ID_ENV,
MUTATION_RUN_ROOT_ENV,
MUTATION_SNAPSHOT_CHILD_ENV,
MUTATION_WORK_ROOT_ENV,
withMutationRunLock,
} from "./mutation/isolation-state.ts";

const USAGE = `Usage:
Expand Down
196 changes: 196 additions & 0 deletions scripts/mutation/isolation-cleanup.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,196 @@
/**
* Which mutation runs are still going, and deleting the ones that are not.
*
* The supervisor in isolation.ts uses this both to clear up before a new run
* and to serve the explicit list/kill/clean commands.
*/

import { join } from "@std/path";
import { rethrowUnlessNotFound } from "#scripts/not-found.ts";
import { processExists, removeTree } from "#scripts/process.ts";
import { errorMessage } from "#shared/error-message.ts";
import { runLockIsHeld, withRunLockIfFree } from "./isolation-lock.ts";
import {
readRunRecord,
readRunRecords,
runDirectoryNames,
} from "./isolation-records.ts";
import {
MUTATION_RECORD_FILE,
MUTATION_RUN_ID_PREFIX,
type MutationRunRecord,
newRunRecord,
runRoot,
runStartedRecently,
withinStartupGrace,
} from "./isolation-state.ts";

/** Is this record's run started, and its process still alive? */
const runProcessIsUp = (record: MutationRunRecord): boolean =>
record.status === "running" &&
record.pid !== undefined &&
processExists(record.pid);

export const processBelongsToRun = async (
record: MutationRunRecord,
): Promise<boolean> => runProcessIsUp(record) && (await runLockIsHeld(record));

/** The record as it reads on disk right now, if it can be read at all. */
const freshRecord = async (
record: MutationRunRecord,
): Promise<MutationRunRecord | null> => {
const latest = await readRunRecord(join(record.root, MUTATION_RECORD_FILE));
return latest === null ? null : { ...latest, root: record.root };
};

export const liveRunIdSet = async (
records: MutationRunRecord[],
): Promise<Set<string>> => {
const live = await Promise.all(
records.map(async (record) =>
(await processBelongsToRun(record)) ? record.id : null,
),
);
return new Set(live.filter((id): id is string => id !== null));
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
};

export type RemoveRunResult =
| { record: MutationRunRecord; removed: true }
| { error: unknown; record: MutationRunRecord; removed: false };

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Remove cleanup-only exports

A repo-wide search finds no caller outside this module for RemoveRunResult, CleanedRuns, or removeRun; exporting these implementation details creates a dead public surface that internal callers can begin depending on. Keep the types and helper private by removing their export modifiers.

AGENTS.md reference: AGENTS.md:L81-L81

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Agreed — fixed in 1db7e21. RemoveRunResult, CleanedRuns, and removeRun are private again; only removeFinishedRuns, removeWorkSnapshot, removeInactiveRuns, reportRemoveFailure, processBelongsToRun, and liveRunIdSet are exported, and each has a caller outside the file.


Generated by Claude Code


/** Delete one folder of a run, treating an already-missing folder as done. */
const removeRunPath = async (
record: MutationRunRecord,
path: string,
): Promise<RemoveRunResult> => {
try {
await removeTree(path);
return { record, removed: true };
} catch (error) {
const missing = error instanceof Deno.errors.NotFound;
return missing
? { record, removed: true }
: { error, record, removed: false };
}
};

/**
* Judged from the record alone: the caller already holds the folder's lock, so
* a live run is one whose child is up, or one so young its record may not have
* caught up yet.
*/
const activeByRecord = (record: MutationRunRecord): boolean =>
record.status === "copying"
? runStartedRecently(record)
: runProcessIsUp(record) && runStartedRecently(record);
Comment on lines +84 to +87

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Revisit young unlocked runs before finishing

When a supervisor is killed during snapshot copying and a replacement starts within 30 seconds, the replacement can acquire the abandoned run's lock but this branch still classifies the copying record as active solely because its timestamp is recent. Because removeInactiveRuns performs only this one startup sweep, the abandoned checkout remains indefinitely unless a third mutation is started after the grace period; retry the skipped cleanup after the grace period or before the replacement finishes so the next run actually clears stopped-run copies.

AGENTS.md reference: AGENTS.md:L937-L941

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not taking this one. A supervisor killed mid-copy leaves a folder that the next run clears once it is past the 30-second grace, and for a developer-only tool that is soon enough — the disk only matters after another run, which does the sweep. Re-sweeping inside a run would mean a timer racing the run's own copy for very little gain.


Generated by Claude Code


/**
* Delete a run's whole folder, but only while holding its lock, and only if
* the record read under that lock still says the run is over. Holding the lock
* is what stops an owner claiming the folder in the moment between the two.
* `null` means the run is still someone's, so it was left alone.
*/
export const removeRun = (
record: MutationRunRecord,
): Promise<RemoveRunResult | null> =>
withRunLockIfFree(record, async () => {
const latest = (await freshRecord(record)) ?? record;
return activeByRecord(latest)
? null
: await removeRunPath(record, record.root);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Revalidate the lock file after taking it

When cleanup holds run.lock while a delayed supervisor has already opened that file and is waiting, this recursive deletion unlinks the lock inode. After cleanup unlocks, the supervisor can acquire that now-unlinked inode, recreate the run folder in writeRunRecord, and copy under a lock that no longer exists at the folder path; another startup or --clean can then create a new lock and delete the live snapshot, particularly once the original copying timestamp is over the 30-second grace. Fresh evidence beyond the earlier lock-through-deletion thread is that a waiting file descriptor survives unlinking, so revalidate that the acquired lock is still the file at run.lock, or avoid unlinking it while waiters may exist.

AGENTS.md reference: AGENTS.md:L935-L940

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good catch, fixed in 13c9ef0. After taking the lock, withRunLockOrNull compares the held file's inode with whatever now sits at run.lock; a mismatch or a missing path means the wait was won on an unlinked file, so it gives up rather than working under a lock that keeps nobody out. Filesystems that report no inode fall back to trusting the lock. Regression test: "gives up when the folder was deleted while it queued for the lock" in test/scripts/mutation/isolation-lock.test.ts.


Generated by Claude Code

});

export interface CleanedRuns {
failed: Extract<RemoveRunResult, { removed: false }>[];
removed: MutationRunRecord[];
skipped: MutationRunRecord[];
}

/** Delete every run in `records` that is finished with, and say what happened. */
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
export const removeFinishedRuns = async (
records: MutationRunRecord[],
): Promise<CleanedRuns> => {
const results = await Promise.all(
records.map(async (record) => ({
outcome: await removeRun(record),
record,
})),

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Bound concurrency while cleaning accumulated runs

When the first mutation after this upgrade encounters the large backlog this change is meant to remove, this Promise.all starts one removeRun per folder at once, and each one launches a separate Deno lock-holder process through withRunLockOrNull. Hundreds of retained snapshots can therefore create hundreds of Deno processes simultaneously, exhausting memory, file descriptors, or the process limit and aborting startup before the backlog is cleared. Process the records sequentially or with a small concurrency limit.

AGENTS.md reference: AGENTS.md:L935-L941

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good catch, and it lands right where it hurts: the first run after this change is exactly the one that meets the backlog the change exists to clear. Fixed in 469e343 — eight at a time now, through the repo's chunk helper, so a folder full of old runs cannot start hundreds of lock-holder processes at once and stop the run that came to tidy them up.


Generated by Claude Code

);
return {
failed: results
.map(({ outcome }) => outcome)
.filter((outcome) => outcome?.removed === false),
removed: results
.filter(({ outcome }) => outcome?.removed === true)
.map(({ record }) => record),
skipped: results
.filter(({ outcome }) => outcome === null || outcome === undefined)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Treat a stale queued lock as already cleaned

When two --clean commands select the same finished run and the second has already opened run.lock, the first can delete the folder before releasing the lock; the second then acquires the unlinked inode, fails heldLockIsAtPath, and returns null here as though the run were active. removeMatchedRuns consequently prints both “Skipped active” and “No cleanable” and exits 1 even though the requested cleanup succeeded. Fresh evidence beyond the earlier missing-before-open case is this already-open, queued waiter; recheck whether the root disappeared before classifying a null outcome as skipped.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Agreed — fixed in 3e1e541. A null from the lock now gets one more look: if the run's folder is no longer there, another clear-up got there first, which is the outcome we wanted, so it counts as removed rather than "skipped active". A folder that is still there is a genuine skip, as before.


Generated by Claude Code

.map(({ record }) => record),
};
};

export const reportRemoveFailure = (
what: string,
{ error, record }: Extract<RemoveRunResult, { removed: false }>,
): void => {
const subject = [what, record.id].filter(Boolean).join(" ");
console.error(`Failed to remove ${subject}: ${errorMessage(error)}`);
};
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved

/** Drops the snapshot of a run that has ended: it is a whole checkout copy. */
export const removeWorkSnapshot = async (
record: MutationRunRecord,
): Promise<void> => {
const result = await removeRunPath(record, record.workRoot);
if (!result.removed) reportRemoveFailure("the snapshot of", result);
};

/** When a folder last changed, or 0 when that cannot be told. */
const folderChangedAt = async (path: string): Promise<number> => {
const info = await Deno.stat(path).catch((error: unknown) => {
rethrowUnlessNotFound(error);
return null;
});
return info?.mtime?.getTime() ?? 0;
};

/**
* A folder whose record cannot be read belongs to a run that was killed while
* writing it. Stand in for that record so the folder can be checked and
* cleared like any other.
*/
const recordForUnreadableRun = async (
id: string,
root: string,
): Promise<MutationRunRecord> => {
const changedAt = await folderChangedAt(runRoot(id, root));
return {
...newRunRecord(id, [], root),
// Young folders are left alone, in case a run is writing its record now.
updatedAt: withinStartupGrace(changedAt)
? new Date().toISOString()
: new Date(0).toISOString(),

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Recheck unreadable records before deleting their runs

When a snapshot copy lasts over 30 seconds and another run reads run.json while the supervisor is rewriting it to running, readRunRecords drops the partial record and this fallback uses the run directory's old mtime instead of the freshly written status. During the supervisor-to-child lock handoff, the lock probe can then succeed before the child acquires the lock, classify the synthesized record as inactive, and delete the live snapshot. Fresh evidence beyond the earlier lock thread is this unreadable-record path, which discards the timestamp written before the supervisor releases its lock; write records atomically or reread the record before removing the run.

AGENTS.md reference: AGENTS.md:L935-L940

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good spot — this one is real, and the atomic-write half of your suggestion is the fix. Done in e22d816: writeRunRecord now writes to run.json.writing and renames it over run.json, so a reader always sees one whole record, old or new. A live run can no longer be mistaken for an unreadable folder, and the mtime fallback is left for what it was meant for — a folder abandoned before any record was ever written.

Regression test: "keeps the last complete record readable while writing a new one" in test/scripts/mutation/isolation-state/records.test.ts holds the swap half way and reads the record, which returns the previous complete record instead of nothing.


Generated by Claude Code

};
};

const runsToSweep = async (root: string): Promise<MutationRunRecord[]> => {
const records = await readRunRecords(root);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Filter readable records by the generated run ID

When an unrelated directory under .mutation-runs contains a readable run.json—for example, a copied backup of an old run—readRunRecords includes it in records, so it bypasses the isRunId check applied only to unreadable directories and is recursively deleted by startup cleanup. Apply the ownership check to readable records as well so cleanup remains limited to folders created as mutation runs.

AGENTS.md reference: AGENTS.md:L937-L940

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Agreed — fixed in 2c85a6a. The name check now applies to readable records too, so a stray folder under .mutation-runs is left alone whether or not it happens to contain a run.json:

const records = (await readRunRecords(root)).filter((record) => isRunId(record.id));

The startup-cleanup tests now use properly shaped ids throughout, so they exercise the real filter rather than passing by accident.


Generated by Claude Code

const known = new Set(records.map((record) => record.id));
// Only folders this runner named: anything else under .mutation-runs was
// put there by someone else and is not ours to delete.
const unreadable = (await runDirectoryNames(root)).filter(
(name) => !known.has(name) && name.startsWith(MUTATION_RUN_ID_PREFIX),
);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Validate the complete generated run ID before deleting

Fresh evidence after the earlier thread is that the final guard only uses startsWith: an old directory such as .mutation-runs/mutation-backups still passes this filter despite not matching createRunId's timestamp-and-suffix format, and an absent or unreadable run.json causes startup to recursively delete it. Validate the complete generated ID format or a reliable ownership marker so cleanup remains limited to actual earlier runs.

AGENTS.md reference: AGENTS.md:L937-L940

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fair — mutation-backups is a good counter-example. Fixed in f9b37a0: the sweep now checks the whole shape of a name this runner makes, not just the prefix.

export const isRunId = (name: string): boolean =>
  /^mutation-\d{8}T\d{6}Z-[0-9a-f]{8}$/.test(name);

Regression test: "knows which folder names are its own runs" in test/scripts/mutation/isolation-state/records.test.ts checks a real createRunId() passes while mutation-backups and a wrong-suffix name do not. The startup-cleanup tests now use a properly shaped id for their broken folder, so they exercise the real filter.


Generated by Claude Code

return [
...records,
...(await Promise.all(
unreadable.map((id) => recordForUnreadableRun(id, root)),
)),
];
};

/** Clears out whatever earlier runs left behind, so nothing piles up. */
export const removeInactiveRuns = async (root: string): Promise<void> => {
const { failed } = await removeFinishedRuns(await runsToSweep(root));
for (const result of failed) reportRemoveFailure("the earlier run", result);
};
96 changes: 96 additions & 0 deletions scripts/mutation/isolation-lock.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
/**
* The lock each mutation run holds while it owns its folder.
*/

import { join } from "@std/path";
import { openLockFile, withFileLock } from "#scripts/lock-file.ts";
import { denoExitCode } from "./child-process.ts";
import {
MUTATION_RUN_LOCK_FILE,
type MutationRunRecord,
runLockPath,
} from "./isolation-state.ts";

const LOCK_HELD_EXIT_CODE = 124;

const LOCK_PROBE_SCRIPT = `
const [path, timeoutText] = Deno.args;
const timeout = setTimeout(
() => Deno.exit(${LOCK_HELD_EXIT_CODE}),
Number(timeoutText),
);
const file = await Deno.open(path, { read: true, write: true }).catch(() => null);
if (file === null) {
clearTimeout(timeout);
Deno.exit(2);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Treat a probe-time missing lock as free

When a concurrent cleanup removes the run folder after the parent’s statOrNull check but before this subprocess opens run.lock, Deno.open gets NotFound, this branch returns exit code 2, and runLockIsHeld throws. In the inspected listRuns and signalRun paths, a normal concurrent cleanup can therefore make --list or --kill abort instead of reporting that the run is no longer active. Fresh evidence after the prior probe-error fix is that the child still gives an expected missing path the same exit code as permission and I/O failures; give NotFound its own free/missing result while continuing to propagate other failures.

AGENTS.md reference: AGENTS.md:L147-L150

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Right again — fixed in 2aed858. The probe now gives a missing lock file the same answer as a free one, and keeps its own exit code for permission and I/O failures, which still stop the command.

This is the third time round the same distinction on this path — the parent's open, then the probe's failures, now the probe's expected absence — and the rule that settles all three is the same: an absence somebody could reasonably meet is an answer, anything else is worth raising. A clear-up taking the folder away mid-question is squarely the first kind.

Regression test: "reports a lock that goes while being looked at as not held", driven by a stat that claims the file is there when it is not, which is exactly what losing that race looks like from the parent's side.


Generated by Claude Code

}
try {
await file.lock(true);
await file.unlock();
clearTimeout(timeout);
file.close();
Deno.exit(0);
} catch {
clearTimeout(timeout);
file.close();
Deno.exit(2);
}
`;

const lockProbeExitCode = (path: string, timeoutMs: number): Promise<number> =>
denoExitCode(["eval", LOCK_PROBE_SCRIPT, "--", path, String(timeoutMs)], {
stderr: "null",
stdout: "null",
});

export const runLockIsHeld = async (
record: Pick<MutationRunRecord, "root">,
timeoutMs = 50,
): Promise<boolean> => {
const path = runLockPath(record);
const file = await openLockFile(path).catch(() => null);
if (file === null) return false;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Propagate failures while probing the run lock

When run.lock cannot be opened because of PermissionDenied or another I/O failure, this broad catch converts the failure to false; in the inspected listRuns and signalRun paths, --list can therefore label a live child stale and --kill can refuse to signal it instead of reporting the filesystem problem. Fresh evidence after the earlier lock-open fix is that it hardened withRunLockOrNull, while this separate runLockIsHeld probe still catches every exception; reserve the unlocked result for an expected missing lock and propagate other errors.

AGENTS.md reference: AGENTS.md:L115-L117

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Agreed — fixed in 3e92f0a. runLockIsHeld now opens the lock through nullIfNotFound, so only a missing folder reads as "nobody is holding it"; a permission or I/O failure throws instead of quietly making --list call a live run stale.

Regression test: "gives up loudly when the run folder cannot be looked at" in test/scripts/mutation/isolation-lock.test.ts, plus "reports a run whose folder is not there as not held" for the expected-absence case.


Generated by Claude Code

file.close();
return (await lockProbeExitCode(path, timeoutMs)) === LOCK_HELD_EXIT_CODE;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Propagate failures from the lock probe

When the initial open succeeds but the probe subprocess then hits PermissionDenied or another I/O error while opening or locking run.lock, LOCK_PROBE_SCRIPT exits with code 2 and this comparison reports the lock as free. As a result, --list can label a live run stale and --kill can refuse to signal it instead of exposing the filesystem failure. Fresh evidence in 587f003 is that the probe still maps both open and lock failures to exit 2 despite the earlier thread stating that this was fixed; distinguish the expected missing-lock result and propagate other probe failures.

AGENTS.md reference: AGENTS.md:L115-L117

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You're right, and right to point at the earlier thread: that reply overstated it. I fixed the parent's open and left the probe mapping "could not open" and "could not lock" to the same ending as "free". Fixed properly in 732549e.

The check now has three endings — held, free, and could-not-tell — and the last one throws naming the path and how the check ended, instead of quietly answering "nobody".

While there: it no longer opens the lock file just to see whether one exists. Asking a question should not make the thing it asks about, and the file's presence is what the question was really about.

Two tests cover the loud paths (a folder that cannot be read, and a folder sitting where the lock file should be). A third came out of the coverage gate catching a gap I had just made: answering "not held" straight from the disk left nothing reaching the probe's own "free" ending, so a run that takes its lock and lets it go now checks that too.


Generated by Claude Code

};

/**
* Hold a run's lock while `run` works, but only if it is free within
* `timeoutMs`; otherwise give up and answer `null`. Clearing up must never
* queue behind a run that holds its folder for an hour.
*/
export const withRunLockIfFree = async <Result>(
record: Pick<MutationRunRecord, "root">,
run: () => Promise<Result>,
timeoutMs = 250,
): Promise<Result | null> => {
const file = await openLockFile(runLockPath(record)).catch(() => null);
if (file === null) return null;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Propagate failures opening a run lock

When the run lock cannot be opened because of PermissionDenied or another I/O error, this broad catch returns null, so automatic cleanup silently leaves the checkout copy and explicit --clean incorrectly reports the run as active. Reserve the skipped result for a genuinely missing or busy lock and propagate other open failures so the command reports the filesystem problem.

AGENTS.md reference: AGENTS.md:L115-L117

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Agreed — fixed in 2c85a6a. withRunLockIfFree no longer swallows the open failure: a lock file that cannot be opened at all now stops the command instead of reading as "busy". Skipping in silence there would leave a whole checkout copy behind with nothing said about it.

Regression test: "gives up loudly when the folder cannot hold a lock" in test/scripts/mutation/isolation-state/lock.test.ts.

I've left runLockIsHeld as it was: it only reports liveness for --list and never decides a deletion.


Generated by Claude Code

const locked = file.lock(true).then(() => true);
let waited = 0;
const gaveUp = new Promise<false>((resolve) => {
waited = setTimeout(() => resolve(false), timeoutMs);
Deno.unrefTimer(waited);
});
if (!(await Promise.race([locked, gaveUp]))) {
// Closing hands back anything the abandoned wait is later granted.
file.close();
return null;
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
}
clearTimeout(waited);
try {
return await run();
} finally {
await file.unlock();
file.close();
}
};

/** Hold a run's own lock, making its folder first so there is one to lock. */
export const withMutationRunLock = async <Result>(
runRootPath: string,
run: () => Promise<Result>,
): Promise<Result> => {
await Deno.mkdir(runRootPath, { recursive: true });
return await withFileLock(join(runRootPath, MUTATION_RUN_LOCK_FILE), run);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Revalidate the supervisor lock before entering the callback

When a supervisor has opened run.lock but is queued behind cleanup, cleanup can delete the stale folder and release the now-unlinked lock inode; this call then acquires that inode and runs the callback, where writeRunRecord recreates the folder without recreating the lock at its path, allowing another startup to delete the snapshot while it is being copied. Fresh evidence after the prior thread is that stillTheLockFile is called only by cleanup's withRunLockOrNull, while this supervisor path still delegates directly to withFileLock without revalidation; recheck and retry the owner-side acquisition before running the callback.

AGENTS.md reference: AGENTS.md:L935-L940

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Right, the owner side had no revalidation — fixed in 3e92f0a. Both lock paths now go through one underLockFile helper that checks the lock it holds is still the file at run.lock; they differ only in how long they wait for it (the clear-up gives up after a timeout, the owner waits as long as it takes). When the owner's check fails it makes the folder and takes the lock again, so it never copies under a lock nothing points at.

Regression test: "takes its own lock again when the folder is swept mid-wait" in test/scripts/mutation/isolation-lock.test.ts.


Generated by Claude Code

};
Loading