Skip to content
Merged
Show file tree
Hide file tree
Changes from 42 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
9 changes: 7 additions & 2 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -932,8 +932,13 @@ 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. A run deletes that copy as soon as it ends — reporting the
failure if it cannot — 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
113 changes: 82 additions & 31 deletions TODO.md
Original file line number Diff line number Diff line change
Expand Up @@ -1586,37 +1586,6 @@ and `grep -rn "encryptWithOwnerKey\|decryptWithOwnerKey\|hybridEncrypt" src/`.

---

## Make `--clean` synchronize with the run lock before removing a run

*Origin: reviewer suggestion on PR #1951.*

`cleanableRuns` in `scripts/mutation/isolation.ts` decides a `copying` run is
abandoned when its lock is not held, and `removeRun` then deletes
`record.root` recursively. Neither step takes the run lock, so a run can pass
the check while still queueing, take the lock, and start copying — and the
clean, already committed to its decision, removes the record and the
half-copied snapshot underneath it.

PR #1951 narrowed this: the run now writes its record again once it holds the
lock, so a clean that lands entirely *before* the lock leaves a run that is
still findable. That is the common ordering and it is covered by
`recordAroundClean` in `test/scripts/mutation/isolation/helpers.ts`. The
remaining window — clean decides, run takes the lock, clean removes — is not
closed by that write, and no write can close it: the fix has to be that the
clean holds the run lock across both the decision and the removal.

It was left out of #1951 because that PR is about test coverage of
`isolation.ts`, and this is a behaviour change to the clean path with its own
concurrency design to think through (a clean that blocks on every run's lock
must not hang on a genuinely live run — the existing `runLockIsHeld` check
would become a `tryLock`).

Starting point: `cleanableRuns`, `removeRun`, and `cleanRuns` in
`scripts/mutation/isolation.ts`, plus `withMutationRunLock` and `runLockIsHeld`
in `scripts/mutation/isolation-state.ts`.

---

## Decide what happens to undated bookings when a listing starts being booked by the day

*Origin: found while migrating the multi-day tests to stories (PR for batch 8).*
Expand Down Expand Up @@ -1694,3 +1663,85 @@ Starting point: `src/ui/client/scanner.js`, the confirmation branches around its
handling of `wrong_listing` and `verify_id`, and `test/ui/client/order.test.ts`
for how a client script is driven without a real browser.

## Let every mutation command leave folders it did not name alone

*Origin: reviewer suggestion (Codex) on PR #1957.*

`readRunRecords` in `scripts/mutation/isolation-records.ts` reads a record from
every folder under `.mutation-runs`, whatever it is called. So `--clean all`
deletes a stray folder that happens to hold a readable `run.json` — a copied
backup of an old run, say — even though this runner never made it.

The clear-up that runs before each mutation *is* restricted: `runsToSweep` picks
folders by name with `isRunId` before reading anything inside them. The explicit
list/kill/clean commands are the ones still reading everything.

This is older than PR #1957 — `--clean all` has always deleted every folder with
a readable record — and closing it means renaming about twenty fixture ids in
`test/scripts/mutation/` to the real `mutation-<time>-<hex>` shape, which is why
it did not ride along with that change.

Starting point: filter the names in `readRunRecords` with `isRunId` the way
`runsToSweep` does, then work through the fixture ids in
`test/scripts/mutation/isolation/commands.test.ts`,
`test/scripts/mutation/isolation/list-and-kill.test.ts`, and
`test/scripts/mutation/isolation-state/records.test.ts`.

## Give the stripe-mock install lock the same shape as every other file lock

*Origin: noticed while unifying the locks behind `scripts/lock-file.ts`.*

Every lock that is a file — the precommit gate, the browser-asset build, the
stripe-mock start, each mutation run — now goes through `withFileLock`, which
holds one advisory lock and checks that the lock it holds is still the file at
its path. (The database migration lock is not one of these: it is a row in a
table, and is named below for the pattern it shares.)

`scripts/stripe-mock/install.ts` is the exception: it has a second,
hand-rolled protocol underneath (`createNew` to claim the lock, a timestamp
written inside it, and `removeStaleInstallLock` to break a lock whose owner
died), guarded by a `withFileLock` on a separate guard file.

It answers a question the shared lock cannot: "whoever claimed this walked away,
so take it from them". Two other places answer that same question their own way:
the mutation runner uses a record with a status, a pid, and a startup grace plus
`processExists`, and the database migration lock
(`src/shared/db/migrations/lock.ts`) writes an owner into a settings row and
lets anyone break a claim older than `MIGRATION_LOCK_TTL_MS`. Three mechanisms
for one job.

Worth folding into one: either teach `lock-file.ts` about an owner that can go
away, or let the install reuse the run-record shape. It stayed out of PR #1957
because it is a whole protocol, not a shared helper, and the install path has
its own timing tests.

Starting point: `tryAcquireInstallLock`/`removeStaleInstallLock` in
`scripts/stripe-mock/install.ts`; `acquireMigrationLock` in
`src/shared/db/migrations/lock.ts` is the best-worked-out version of the pattern
and the one to copy; `activeByRecord` in `scripts/mutation/isolation-cleanup.ts`
is the third; and `test/scripts/stripe-mock/install/stale-locks.test.ts` and
`waiting.test.ts` say what the timing tests expect.

## Tell a clear-up's hold on a run apart from the run's own

*Origin: reviewer suggestion (Codex) on PR #1957.*

`processBelongsToRun` in `scripts/mutation/isolation-cleanup.ts` decides a run
belongs to the process in its record when that process is alive *and* somebody
is holding the run's lock. A clear-up deleting that run's folder holds the same
lock, so during a deletion the two are indistinguishable.

That matters in one case: the record's process id has since been given to some
unrelated program. `--kill` then reads "alive and locked" as proof and signals a
process that has nothing to do with us. Deleting a whole checkout copy takes
long enough for the window to be real.

It needs the lock evidence tied to the run's own child rather than to whoever
holds the lock — the holder could write who it is, or a clear-up could hold
something a run never holds. Either is a change to what a lock means here, which
is why it did not ride along with PR #1957.

Starting point: `processBelongsToRun` and `removeRun` in
`scripts/mutation/isolation-cleanup.ts`, `signalRun` in
`scripts/mutation/isolation.ts` for what acts on the answer, and
`scripts/held-lock-process.ts` for the process that holds a lock on our behalf.
31 changes: 7 additions & 24 deletions scripts/database-snapshot-lib.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,11 @@ import { load } from "@std/dotenv";
import { basename, dirname, join, resolve, toFileUrl } from "@std/path";
import * as v from "valibot";
import { withCleanup } from "#scripts/cleanup.ts";
import {
lstatOrNull,
statNumberOrNull,
statOrNull,
} from "#scripts/not-found.ts";
import { secureUrlCheck } from "#scripts/secure-url.ts";
import { getEnv } from "#shared/env.ts";

Expand Down Expand Up @@ -152,25 +157,6 @@ export const readSnapshotRequestFromEnvFile = async (
const outputAlreadyExists = (path: string): Error =>
new Error(`Output already exists: ${path}`);

const readOrNullIfMissing = async <Result>(
read: () => Promise<Result>,
): Promise<Result | null> => {
try {
return await read();
} catch (error) {
if (error instanceof Deno.errors.NotFound) return null;
throw error;
}
};

const fileInfoOrNull =
(getRead: () => (path: string) => Promise<Deno.FileInfo>) =>
(path: string): Promise<Deno.FileInfo | null> =>
readOrNullIfMissing(() => getRead()(path));

const statOrNull = fileInfoOrNull(() => Deno.stat);
const lstatOrNull = fileInfoOrNull(() => Deno.lstat);

const requireOutputDirectory = async (path: string): Promise<void> => {
const info = await statOrNull(path);
if (info === null)
Expand Down Expand Up @@ -282,11 +268,8 @@ const SNAPSHOT_QUERY_CHECKS = [
),
];

const fileSizeOrNull = async (path: string): Promise<number | null> => {
const info = await statOrNull(path);
// SQLite can either remove an empty WAL or leave a zero-byte file.
return info?.size ?? null;
};
// SQLite can either remove an empty WAL or leave a zero-byte file.
const fileSizeOrNull = statNumberOrNull((info) => info.size);

const requireEmptyWal = async (path: string): Promise<void> => {
const size = await fileSizeOrNull(`${path}-wal`);
Expand Down
109 changes: 109 additions & 0 deletions scripts/held-lock-process.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,109 @@
/**
* A lock held for us by a child process, so that giving up on the wait really
* does give up.
*
* Waiting for a lock in this process cannot be called off: the wait keeps the
* process alive until the lock arrives, however long that takes, and closing
* the file does not stop it. A command that gave up after a quarter of a second
* would still sit there until the other job finished. So a child does the
* waiting, and gives up by ending itself.
*/

import { dirname } from "@std/path";
import { statOrNull } from "#scripts/not-found.ts";

/**
* Waits for the lock, says which file it got, and holds it until its input
* closes — when we let go, or if we die first. It gives itself the same time
* we would, counted from when it starts waiting, and ends if that runs out.
*/
const HOLD_LOCK_SCRIPT = `
const [path, timeoutText] = Deno.args;
const say = (line) => Deno.stdout.write(new TextEncoder().encode(line + "\\n"));
const file = await Deno.open(path, { create: true, read: true, write: true });
const gaveUp = setTimeout(() => Deno.exit(0), Number(timeoutText));
await file.lock(true);
clearTimeout(gaveUp);
const { ino } = await file.stat();
await say(\`held \${ino}\`);
await Deno.stdin.read(new Uint8Array(1));
await file.unlock();
file.close();
`;

interface HeldLock {
/** The file it locked, or `NaN` when the disk keeps no file numbers. */
fileNumber: number;
letGo: () => Promise<void>;
}

/** The child's `held` line, or `null` if it ends before saying a whole one. */
const heldLine = async (
reader: ReadableStreamDefaultReader<Uint8Array>,
): Promise<string | null> => {
let said = "";
for (;;) {
const { value } = await reader.read();
if (value === undefined) return null;
said += new TextDecoder().decode(value);
// Whole lines only — everything after the last newline is still arriving.
// "held" and its file number can come in two pieces, and half a line taken
// for the whole of one loses the number.
const whole = said.split("\n").slice(0, -1);
const held = whole.find((line) => line.startsWith("held"));
if (held !== undefined) return held;
}
};

/** Wait for the child to stop, leaving none of its pipes open behind us. */
const closeDown = async (
child: Deno.ChildProcess,
): Promise<Deno.CommandStatus> => {
await child.stdin.close();
return await child.status;
};

/**
* Hold the lock at `path` through a child process. `null` means the lock did
* not come free within `timeoutMs`, or its folder is not there to lock in. A
* lock that could not be taken at all throws instead: that is not "busy".
*/
export const holdLockOrNull = async (
path: string,
timeoutMs: number,
): Promise<HeldLock | null> => {
// No folder to make the lock file in means nobody's lock to take.
if ((await statOrNull(dirname(path))) === null) return null;
const child = new Deno.Command(Deno.execPath(), {
args: ["eval", HOLD_LOCK_SCRIPT, "--", path, String(timeoutMs)],
stderr: "piped",
stdin: "piped",
stdout: "piped",
}).spawn();

const reader = child.stdout.getReader();
const line = await heldLine(reader);
reader.releaseLock();
await child.stdout.cancel();

if (line === null) {
// It ends quietly when its own time runs out. Ending any other way means
// the lock could not be taken at all, which is not the same as busy.
const why = await new Response(child.stderr).text();
const stopped = await closeDown(child);
// Its folder can go while it is starting, which is nobody's lock rather
// than a failure to take one.
const folderWent = (await statOrNull(dirname(path))) === null;
if (!(stopped.success || folderWent)) {

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 Preserve the child's missing-folder result

When another cleanup removes the run directory after the parent check but before the helper's Deno.open, the child exits with NotFound; if the run owner recreates that directory before this later statOrNull, folderWent is false and an expected concurrent removal is misreported as a lock failure. In the mutation startup path, that rejection escapes removeInactiveRuns and prevents the new run from starting. The fresh, separate path from the fixed lock probe is holdLockOrNull's post-exit directory check; have the child report NotFound distinctly instead of inferring it from mutable state afterward.

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.

Agreed, and the reasoning is the part worth keeping: I was deciding whether the folder had gone by looking at the disk after the child had exited — a fact read from state that can change underneath it. The owner remaking the folder in that gap turns an ordinary concurrent clear-up into "the lock could not be taken", and on the startup path that rejection stops the next run from starting at all.

Fixed in e0d6567. The child reports a missing folder with an ending of its own rather than dying of it, so the answer comes from the moment it happened. Anything else it dies of still throws, with its own error text attached.

Second time tonight this same shape has bitten on this path, so to say it plainly: when something transient has to be told apart, the party that saw it should say so, instead of somebody re-deriving it later.


Generated by Claude Code

throw new Error(`Could not take the lock at ${path}: ${why.trim()}`);
}
return null;
Comment on lines +100 to +111

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-holder child

When the helper child fails before reporting held—for example, because Deno.open or file.lock gets PermissionDenied or an I/O error—heldLine returns null and this branch treats every child exit as an ordinary timeout. Through withFileLockOrNull, explicit mutation cleanup then reports the run as active and startup cleanup silently leaves its checkout behind instead of exposing the filesystem failure. Inspect the child's exit status and reserve null for the documented timeout or missing-folder outcomes; propagate other 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.

Agreed — a swallowed failure, and the worst kind, since the run would be called active and its copy left behind without a word. Fixed in c002fed.

The child now ends quietly only when its own time runs out, so any other ending means the lock could not be taken at all, and that throws with the child's own error text attached.

Writing the test caught a distinction worth naming: the folder going while the child is starting also kills the child, but that is the documented "nobody's lock", not a failure — so it throws only when the folder is still there. My own deleted-folder test failed until I got that right. New test: "says so loudly when the lock cannot be taken at all", which puts a folder where the lock file should be.


Generated by Claude Code

}
await child.stderr.cancel();
return {
fileNumber: Number(line.split(" ")[1]),
letGo: async () => {
await closeDown(child);
},
};
};
Loading