Repository navigation
Clear away mutation run copies, and give every lock one shared mechanism #1957
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from 11 commits
8dd0812
2e8a9b9
26139fb
26e0555
e22d816
95665aa
ac4504b
c15d68a
93306be
7a125db
7ac103d
2bbe57a
5543372
f9b37a0
7160d25
2c85a6a
1db7e21
8be3687
21f8ee6
60b3791
13c9ef0
7b15569
3e92f0a
a46db75
a92f53d
f48e0b4
7670e5b
8f8734e
cea09c3
3d51572
3e1e541
fb9b7a8
69f6206
3575635
482a9a3
e994301
c002fed
469e343
732549e
636989c
63e2367
28c53c3
2aed858
c1db784
e0d6567
f27fb64
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| 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)); | ||
| }; | ||
|
|
||
| export type RemoveRunResult = | ||
| | { record: MutationRunRecord; removed: true } | ||
| | { error: unknown; record: MutationRunRecord; removed: false }; | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. A repo-wide search finds no caller outside this module for AGENTS.md reference: AGENTS.md:L81-L81 Useful? React with 👍 / 👎.
Member
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Agreed — fixed in 1db7e21. 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
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
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 AGENTS.md reference: AGENTS.md:L937-L941 Useful? React with 👍 / 👎.
Member
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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); | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
When cleanup holds AGENTS.md reference: AGENTS.md:L935-L940 Useful? React with 👍 / 👎.
Member
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Good catch, fixed in 13c9ef0. After taking the lock, 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. */ | ||
|
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, | ||
| })), | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
When the first mutation after this upgrade encounters the large backlog this change is meant to remove, this AGENTS.md reference: AGENTS.md:L935-L941 Useful? React with 👍 / 👎.
Member
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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 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) | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
When two Useful? React with 👍 / 👎.
Member
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Agreed — fixed in 3e1e541. A 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)}`); | ||
| }; | ||
|
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(), | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
When a snapshot copy lasts over 30 seconds and another run reads AGENTS.md reference: AGENTS.md:L935-L940 Useful? React with 👍 / 👎.
Member
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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: Regression test: "keeps the last complete record readable while writing a new one" in Generated by Claude Code |
||
| }; | ||
| }; | ||
|
|
||
| const runsToSweep = async (root: string): Promise<MutationRunRecord[]> => { | ||
| const records = await readRunRecords(root); | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
When an unrelated directory under AGENTS.md reference: AGENTS.md:L937-L940 Useful? React with 👍 / 👎.
Member
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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 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), | ||
| ); | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
Fresh evidence after the earlier thread is that the final guard only uses AGENTS.md reference: AGENTS.md:L937-L940 Useful? React with 👍 / 👎.
Member
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Fair — 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 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); | ||
| }; | ||
| 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); | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
When a concurrent cleanup removes the run folder after the parent’s AGENTS.md reference: AGENTS.md:L147-L150 Useful? React with 👍 / 👎.
Member
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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; | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
When AGENTS.md reference: AGENTS.md:L115-L117 Useful? React with 👍 / 👎.
Member
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Agreed — fixed in 3e92f0a. Regression test: "gives up loudly when the run folder cannot be looked at" in Generated by Claude Code |
||
| file.close(); | ||
| return (await lockProbeExitCode(path, timeoutMs)) === LOCK_HELD_EXIT_CODE; | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
When the initial open succeeds but the probe subprocess then hits AGENTS.md reference: AGENTS.md:L115-L117 Useful? React with 👍 / 👎.
Member
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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; | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
When the run lock cannot be opened because of AGENTS.md reference: AGENTS.md:L115-L117 Useful? React with 👍 / 👎.
Member
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Agreed — fixed in 2c85a6a. Regression test: "gives up loudly when the folder cannot hold a lock" in I've left 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; | ||
|
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); | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
When a supervisor has opened AGENTS.md reference: AGENTS.md:L935-L940 Useful? React with 👍 / 👎.
Member
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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 Regression test: "takes its own lock again when the folder is swept mid-wait" in Generated by Claude Code |
||
| }; | ||
Uh oh!
There was an error while loading. Please reload this page.