Skip to content

Commit 2b68918

Browse files
committed
fix(agents): serialize worktree git lock cleanup
1 parent e7a0ef1 commit 2b68918

2 files changed

Lines changed: 116 additions & 44 deletions

File tree

‎src/agents/worktrees/run-lease.test.ts‎

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -277,6 +277,31 @@ describe("worktree run lease", () => {
277277
expect(await lockState(record)).toEqual({ kind: "none" });
278278
});
279279

280+
it("does not let a failed cleanup unlock a newer holder generation", async () => {
281+
const created = await createSessionWorktree();
282+
const first = await acquireWorktreeRunLease(created.id, { env });
283+
const record = getRegistryWorktree(env, created.id)!;
284+
285+
let failUnlock = true;
286+
__testing.setUnlockImplForTest(async (rec) => {
287+
if (failUnlock) {
288+
throw new Error("simulated git unlock failure");
289+
}
290+
await unlockWorktree(rec);
291+
});
292+
293+
await first.release();
294+
expect(await lockState(record)).toEqual({ kind: "live", pid: process.pid });
295+
296+
const second = await acquireWorktreeRunLease(created.id, { env });
297+
failUnlock = false;
298+
await __testing.drainPendingCleanupsForTest();
299+
expect(await lockState(record)).toEqual({ kind: "live", pid: process.pid });
300+
301+
await second.release();
302+
expect(await lockState(record)).toEqual({ kind: "none" });
303+
});
304+
280305
it("fails closed when a session's authoritative worktree binding is removed", async () => {
281306
const created = await createSessionWorktree();
282307
await service.remove({ id: created.id, reason: "manual-delete", force: true });

‎src/agents/worktrees/run-lease.ts‎

Lines changed: 91 additions & 44 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,7 @@ type HeldWorktreeLock = { refcount: number; gitLocked: boolean };
3232
// child that share one worktree refcount it here so a child release does not unlock
3333
// the parent's still-live checkout.
3434
const heldGitLocks = new Map<string, HeldWorktreeLock>();
35+
const gitLockTransitionTails = new Map<string, Promise<void>>();
3536
let ownerChecks: RunLeaseOwnerChecks = {};
3637
let resolveSelfStartTime = getFileLockProcessStartTime;
3738
let releaseRunLeaseRow = releaseWorktreeRunLeaseRow;
@@ -55,6 +56,91 @@ function errorMessage(error: unknown): string {
5556
return error instanceof Error ? error.message : String(error);
5657
}
5758

59+
async function withGitLockTransition<T>(id: string, operation: () => Promise<T>): Promise<T> {
60+
const previous = gitLockTransitionTails.get(id) ?? Promise.resolve();
61+
let finish!: () => void;
62+
const current = new Promise<void>((resolve) => {
63+
finish = resolve;
64+
});
65+
const tail = previous.then(() => current);
66+
gitLockTransitionTails.set(id, tail);
67+
await previous;
68+
try {
69+
return await operation();
70+
} finally {
71+
finish();
72+
if (gitLockTransitionTails.get(id) === tail) {
73+
gitLockTransitionTails.delete(id);
74+
}
75+
}
76+
}
77+
78+
async function retainGitLock(env: NodeJS.ProcessEnv, id: string): Promise<void> {
79+
await withGitLockTransition(id, async () => {
80+
const held = heldGitLocks.get(id) ?? { refcount: 0, gitLocked: false };
81+
const needsLock = held.refcount === 0 && !held.gitLocked;
82+
held.refcount += 1;
83+
heldGitLocks.set(id, held);
84+
if (!needsLock) {
85+
return;
86+
}
87+
const record = getRegistryWorktree(env, id);
88+
if (!record) {
89+
return;
90+
}
91+
try {
92+
await lockWorktreeForProcess(record);
93+
held.gitLocked = true;
94+
} catch (error) {
95+
log.warn(`worktree git lock unavailable for ${id}: ${errorMessage(error)}`);
96+
}
97+
});
98+
}
99+
100+
async function releaseGitLock(cleanup: LeaseCleanup): Promise<boolean> {
101+
return await withGitLockTransition(cleanup.id, async () => {
102+
let held = heldGitLocks.get(cleanup.id);
103+
if (!cleanup.refcountReleased) {
104+
cleanup.refcountReleased = true;
105+
if (held) {
106+
held.refcount -= 1;
107+
}
108+
}
109+
held = heldGitLocks.get(cleanup.id);
110+
if (!held) {
111+
cleanup.gitUnlockPending = false;
112+
return true;
113+
}
114+
if (held.refcount > 0) {
115+
// A newer holder adopted a guard whose prior unlock failed. Its own final
116+
// release now owns the unlock; stale cleanup must not drop that generation.
117+
cleanup.gitUnlockPending = false;
118+
return true;
119+
}
120+
if (!held.gitLocked) {
121+
heldGitLocks.delete(cleanup.id);
122+
cleanup.gitUnlockPending = false;
123+
return true;
124+
}
125+
const record = getRegistryWorktree(cleanup.env, cleanup.id);
126+
if (!record) {
127+
heldGitLocks.delete(cleanup.id);
128+
cleanup.gitUnlockPending = false;
129+
return true;
130+
}
131+
try {
132+
await unlockWorktreeImpl(record);
133+
} catch (error) {
134+
cleanup.gitUnlockPending = true;
135+
log.warn(`failed to unlock worktree ${cleanup.id}: ${errorMessage(error)}`);
136+
return false;
137+
}
138+
heldGitLocks.delete(cleanup.id);
139+
cleanup.gitUnlockPending = false;
140+
return true;
141+
});
142+
}
143+
58144
async function realpathOrSelf(candidate: string): Promise<string> {
59145
try {
60146
return await fs.realpath(candidate);
@@ -128,32 +214,7 @@ async function runLeaseCleanup(cleanup: LeaseCleanup): Promise<boolean> {
128214
}
129215
cleanup.rowDeleted = true;
130216
}
131-
if (!cleanup.refcountReleased) {
132-
cleanup.refcountReleased = true;
133-
const current = heldGitLocks.get(cleanup.id);
134-
if (current) {
135-
current.refcount -= 1;
136-
if (current.refcount > 0) {
137-
heldGitLocks.set(cleanup.id, current);
138-
} else {
139-
heldGitLocks.delete(cleanup.id);
140-
cleanup.gitUnlockPending = current.gitLocked;
141-
}
142-
}
143-
}
144-
if (cleanup.gitUnlockPending) {
145-
const record = getRegistryWorktree(cleanup.env, cleanup.id);
146-
if (record) {
147-
try {
148-
await unlockWorktreeImpl(record);
149-
} catch (error) {
150-
log.warn(`failed to unlock worktree ${cleanup.id}: ${errorMessage(error)}`);
151-
return false;
152-
}
153-
}
154-
cleanup.gitUnlockPending = false;
155-
}
156-
return true;
217+
return await releaseGitLock(cleanup);
157218
}
158219

159220
async function drainPendingLeaseCleanups(): Promise<void> {
@@ -203,24 +264,9 @@ export async function acquireWorktreeRunLease(
203264
now: Date.now(),
204265
checks: ownerChecks,
205266
});
206-
// Reserve the refcount slot synchronously before awaiting the git lock so two
207-
// overlapping same-process acquisitions cannot both store refcount 1 and let the
208-
// first release drop the guard while the other run is still live.
209-
const held = heldGitLocks.get(id) ?? { refcount: 0, gitLocked: false };
210-
const isFirstHolder = held.refcount === 0;
211-
held.refcount += 1;
212-
heldGitLocks.set(id, held);
213-
if (isFirstHolder) {
214-
const record = getRegistryWorktree(env, id);
215-
if (record) {
216-
try {
217-
await lockWorktreeForProcess(record);
218-
held.gitLocked = true;
219-
} catch (error) {
220-
log.warn(`worktree git lock unavailable for ${id}: ${errorMessage(error)}`);
221-
}
222-
}
223-
}
267+
// Serialize refcount and Git transitions so a cleanup retry cannot unlock a
268+
// newer same-process holder after a prior generation's unlock failed.
269+
await retainGitLock(env, id);
224270
const cleanup: LeaseCleanup = {
225271
env,
226272
id,
@@ -294,6 +340,7 @@ const testing = {
294340
},
295341
resetForTest(): void {
296342
heldGitLocks.clear();
343+
gitLockTransitionTails.clear();
297344
pendingLeaseCleanups.clear();
298345
ownerChecks = {};
299346
resolveSelfStartTime = getFileLockProcessStartTime;

0 commit comments

Comments
 (0)