Skip to content

Commit 7cd2e48

Browse files
yetvalsteipete
andauthored
fix(agents): lease session worktrees during runs (#103263)
* fix(agents): lease managed worktrees across a run with an exclusive removal claim A resumed session's managed worktree could be removed mid-run by idle GC, a separate remover, or a manual worktrees.gc, destroying in-flight work; a session whose worktree was already removed was admitted anyway and ran without its checkout. Runs now take a shared run-lease and removal takes an exclusive claim, both held as rows in the shared state_leases table so admission and removal serialize through one BEGIN IMMEDIATE transaction. Lease rows carry an opaque token plus pid and process start time; dead or reused-pid owners are pruned inside the same transaction. Removal claims before any cleanliness or snapshot work and rejects while a live run lease exists; a run releases only its own token. The worktree id is resolved from the session binding or by containment over both the run cwd and workspace dir, so a workspace-only child still leases. The git worktree lock is retained as a secondary raw-Git guard and refcounted per process so a parent and a same-process child do not unlock each other. * fix(agents): serialize worktree git lock cleanup * test(agents): seed worktree races in sqlite --------- Co-authored-by: Peter Steinberger <[email protected]>
1 parent 724e90c commit 7cd2e48

8 files changed

Lines changed: 1534 additions & 196 deletions

File tree

‎src/agents/agent-command.ts‎

Lines changed: 124 additions & 98 deletions
Original file line numberDiff line numberDiff line change
@@ -175,6 +175,7 @@ import { resolveCandidateThinkingLevel, resolveEffectiveAgentRuntime } from "./t
175175
import { resolveAgentTimeoutMs } from "./timeout.js";
176176
import { hasNonzeroUsage } from "./usage.js";
177177
import { ensureAgentWorkspace } from "./workspace.js";
178+
import { acquireWorktreeRunLease, resolveWorktreeIdForPath } from "./worktrees/run-lease.js";
178179

179180
const log = createSubsystemLogger("agents/agent-command");
180181

@@ -902,61 +903,77 @@ async function prepareAgentCommandExecution(opts: AgentCommandOpts, runtime: Run
902903
if (opts.thinkingOnce && !thinkOnce) {
903904
throw new Error(`Invalid one-shot thinking level. Use one of: ${thinkingLevelsHint}.`);
904905
}
905-
await ensureAgentWorkspace({
906-
dir: workspaceDirRaw,
907-
ensureBootstrapFiles: !agentCfg?.skipBootstrap,
908-
skipOptionalBootstrapFiles: agentCfg?.skipOptionalBootstrapFiles,
906+
// Lease the managed worktree before any workspace-dependent preparation so idle
907+
// GC or a separate remover cannot delete the checkout while it is being set up;
908+
// a session bound to a removed worktree fails closed here. Released on any prepare
909+
// failure below and in the run's outer cleanup.
910+
const resolvedCwd = cwd ? resolveUserPath(cwd) : undefined;
911+
const worktreeId = await resolveWorktreeIdForPath({
912+
sessionEntry: sessionEntryRaw,
913+
candidatePaths: [resolvedCwd ?? workspaceDir, workspaceDir],
909914
});
910-
const runId = opts.runId?.trim() || sessionId;
911-
const { getAcpSessionManager } = await loadAcpManagerRuntime();
912-
const acpManager = getAcpSessionManager();
913-
const acpResolution = sessionKey
914-
? acpManager.resolveSession({
915-
cfg,
916-
sessionKey,
917-
})
918-
: null;
919-
const body =
920-
!isRawModelRun && acpResolution?.kind === "ready"
921-
? resolveAcpPromptBody(message, opts.internalEvents)
922-
: prependInternalEventContext(message, opts.internalEvents);
923-
const transcriptBody =
924-
opts.transcriptMessage ?? resolveInternalEventTranscriptBody(message, opts.internalEvents);
915+
const runLease = worktreeId ? await acquireWorktreeRunLease(worktreeId) : undefined;
916+
try {
917+
await ensureAgentWorkspace({
918+
dir: workspaceDirRaw,
919+
ensureBootstrapFiles: !agentCfg?.skipBootstrap,
920+
skipOptionalBootstrapFiles: agentCfg?.skipOptionalBootstrapFiles,
921+
});
922+
const runId = opts.runId?.trim() || sessionId;
923+
const { getAcpSessionManager } = await loadAcpManagerRuntime();
924+
const acpManager = getAcpSessionManager();
925+
const acpResolution = sessionKey
926+
? acpManager.resolveSession({
927+
cfg,
928+
sessionKey,
929+
})
930+
: null;
931+
const body =
932+
!isRawModelRun && acpResolution?.kind === "ready"
933+
? resolveAcpPromptBody(message, opts.internalEvents)
934+
: prependInternalEventContext(message, opts.internalEvents);
935+
const transcriptBody =
936+
opts.transcriptMessage ?? resolveInternalEventTranscriptBody(message, opts.internalEvents);
925937

926-
return {
927-
opts: commandOpts,
928-
body,
929-
transcriptBody,
930-
cfg,
931-
configuredThinkingCatalog,
932-
normalizedSpawned,
933-
agentCfg,
934-
thinkOverride,
935-
thinkOnce,
936-
verboseOverride,
937-
timeoutMs,
938-
runTimeoutOverrideMs,
939-
sessionId,
940-
sessionKey,
941-
sessionEntry: sessionEntryRaw,
942-
sessionStore,
943-
storePath,
944-
isNewSession,
945-
persistedThinking,
946-
persistedVerbose,
947-
sessionAgentId,
948-
outboundSession,
949-
workspaceDir,
950-
cwd: cwd ? resolveUserPath(cwd) : undefined,
951-
agentDir,
952-
pluginsEnabled,
953-
manifestMetadataSnapshot,
954-
modelManifestContext,
955-
runId,
956-
isSubagentLane,
957-
acpManager,
958-
acpResolution,
959-
};
938+
return {
939+
opts: commandOpts,
940+
body,
941+
transcriptBody,
942+
cfg,
943+
configuredThinkingCatalog,
944+
normalizedSpawned,
945+
agentCfg,
946+
thinkOverride,
947+
thinkOnce,
948+
verboseOverride,
949+
timeoutMs,
950+
runTimeoutOverrideMs,
951+
sessionId,
952+
sessionKey,
953+
sessionEntry: sessionEntryRaw,
954+
sessionStore,
955+
storePath,
956+
isNewSession,
957+
persistedThinking,
958+
persistedVerbose,
959+
sessionAgentId,
960+
outboundSession,
961+
workspaceDir,
962+
cwd: resolvedCwd,
963+
agentDir,
964+
pluginsEnabled,
965+
manifestMetadataSnapshot,
966+
modelManifestContext,
967+
runId,
968+
isSubagentLane,
969+
acpManager,
970+
acpResolution,
971+
runLease,
972+
};
973+
} catch (error) {
974+
await runLease?.release();
975+
throw error;
976+
}
960977
}
961978

962979
async function agentCommandInternal(
@@ -1008,9 +1025,9 @@ async function agentCommandInternal(
10081025
pluginsEnabled,
10091026
manifestMetadataSnapshot,
10101027
modelManifestContext,
1028+
runLease,
10111029
} = prepared;
10121030
let lifecycleGeneration = opts.lifecycleGeneration ?? captureAgentRunLifecycleGeneration(runId);
1013-
assertAgentRunLifecycleGenerationCurrent(lifecycleGeneration);
10141031
const effectiveCwd = cwd ? resolveUserPath(cwd) : workspaceDir;
10151032
let sessionEntry = prepared.sessionEntry;
10161033
const sessionStateActor = classifySessionStateActor({
@@ -1026,7 +1043,6 @@ async function agentCommandInternal(
10261043
let trackedRestartRecoveryDeliveryContext = false;
10271044
let currentRunDeliveryContext: DeliveryContext | undefined;
10281045
const preparedSessionId = sessionEntry?.sessionId;
1029-
const sessionStoreRuntime = storePath && sessionKey ? await loadSessionStoreRuntime() : undefined;
10301046
const internalModelRunTargets =
10311047
initialOpts.modelRun === true && suppressVisibleSessionEffects
10321048
? new Map<string, AgentRunSessionTarget>()
@@ -1043,49 +1059,56 @@ async function agentCommandInternal(
10431059
);
10441060
}
10451061

1046-
// Reset marks its mutation before interrupting work. An aborted run must not
1047-
// queue behind that mutation or reset would wait on the run holding the queue.
1048-
const sessionWorkAdmission = await beginSessionWorkAdmission({
1049-
scope: storePath ?? `agent:${sessionAgentId}`,
1050-
identities: [sessionKey, sessionId],
1051-
signal: opts.abortSignal,
1052-
onInterrupt: () => lifecycleAbortController.abort(createAgentRunRestartAbortError()),
1053-
assertAllowed: () => {
1054-
const currentEntry =
1055-
sessionStoreRuntime && storePath && sessionKey
1056-
? sessionStoreRuntime.loadSessionEntry({
1057-
storePath,
1058-
sessionKey,
1059-
readConsistency: "latest",
1060-
})
1061-
: sessionEntry;
1062-
if (!currentEntry && preparedSessionId) {
1063-
throw new Error(`Session "${sessionKey ?? sessionId}" changed while starting work. Retry.`);
1064-
}
1065-
const matchesIntentionalRollover =
1066-
isNewSession && currentEntry?.sessionId === preparedSessionId;
1067-
if (currentEntry && currentEntry.sessionId !== sessionId && !matchesIntentionalRollover) {
1068-
throw new Error(`Session "${sessionKey ?? sessionId}" changed while starting work. Retry.`);
1069-
}
1070-
const archivedSessionError = resolveSessionWorkStartError(
1071-
sessionKey ?? sessionId,
1072-
currentEntry,
1073-
);
1074-
if (archivedSessionError) {
1075-
throw new Error(archivedSessionError);
1076-
}
1077-
sessionEntry = currentEntry;
1078-
if (sessionStore && sessionKey) {
1079-
if (currentEntry) {
1080-
sessionStore[sessionKey] = currentEntry;
1081-
} else {
1082-
delete sessionStore[sessionKey];
1083-
}
1084-
}
1085-
},
1086-
});
1087-
1062+
let sessionWorkAdmission: Awaited<ReturnType<typeof beginSessionWorkAdmission>> | undefined;
10881063
try {
1064+
assertAgentRunLifecycleGenerationCurrent(lifecycleGeneration);
1065+
const sessionStoreRuntime =
1066+
storePath && sessionKey ? await loadSessionStoreRuntime() : undefined;
1067+
// Reset marks its mutation before interrupting work. An aborted run must not
1068+
// queue behind that mutation or reset would wait on the run holding the queue.
1069+
sessionWorkAdmission = await beginSessionWorkAdmission({
1070+
scope: storePath ?? `agent:${sessionAgentId}`,
1071+
identities: [sessionKey, sessionId],
1072+
signal: opts.abortSignal,
1073+
onInterrupt: () => lifecycleAbortController.abort(createAgentRunRestartAbortError()),
1074+
assertAllowed: () => {
1075+
const currentEntry =
1076+
sessionStoreRuntime && storePath && sessionKey
1077+
? sessionStoreRuntime.loadSessionEntry({
1078+
storePath,
1079+
sessionKey,
1080+
readConsistency: "latest",
1081+
})
1082+
: sessionEntry;
1083+
if (!currentEntry && preparedSessionId) {
1084+
throw new Error(
1085+
`Session "${sessionKey ?? sessionId}" changed while starting work. Retry.`,
1086+
);
1087+
}
1088+
const matchesIntentionalRollover =
1089+
isNewSession && currentEntry?.sessionId === preparedSessionId;
1090+
if (currentEntry && currentEntry.sessionId !== sessionId && !matchesIntentionalRollover) {
1091+
throw new Error(
1092+
`Session "${sessionKey ?? sessionId}" changed while starting work. Retry.`,
1093+
);
1094+
}
1095+
const archivedSessionError = resolveSessionWorkStartError(
1096+
sessionKey ?? sessionId,
1097+
currentEntry,
1098+
);
1099+
if (archivedSessionError) {
1100+
throw new Error(archivedSessionError);
1101+
}
1102+
sessionEntry = currentEntry;
1103+
if (sessionStore && sessionKey) {
1104+
if (currentEntry) {
1105+
sessionStore[sessionKey] = currentEntry;
1106+
} else {
1107+
delete sessionStore[sessionKey];
1108+
}
1109+
}
1110+
},
1111+
});
10891112
return await sessionWorkAdmission.run(async () => {
10901113
if (opts.deliver === true) {
10911114
const sendPolicy = resolveSendPolicy({
@@ -2821,7 +2844,10 @@ async function agentCommandInternal(
28212844
}
28222845
});
28232846
} finally {
2824-
sessionWorkAdmission.release();
2847+
if (runLease) {
2848+
await runLease.release();
2849+
}
2850+
sessionWorkAdmission?.release();
28252851
if (internalModelRunTargets) {
28262852
// Compaction may rotate a private session identity. Remove every owned
28272853
// SQLite row only after delivery; transcript and trajectory rows cascade.

‎src/agents/worktrees/git-lock.ts‎

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
import path from "node:path";
2+
import { isPidDefinitelyDead } from "../../shared/pid-alive.js";
3+
import { commandError, listGitWorktrees, runGit } from "./git.js";
4+
import type { ManagedWorktreeRecord } from "./types.js";
5+
6+
const OPENCLAW_LOCK_PATTERN = /^openclaw pid=(\d+)$/;
7+
8+
export type LockState =
9+
| { kind: "none" }
10+
| { kind: "live"; pid: number }
11+
| { kind: "dead"; pid: number }
12+
| { kind: "foreign"; reason: string };
13+
14+
export async function lockState(record: ManagedWorktreeRecord): Promise<LockState> {
15+
const entry = (await listGitWorktrees(record.repoRoot)).find(
16+
(candidate) => path.resolve(candidate.path) === path.resolve(record.path),
17+
);
18+
if (!entry || entry.lockedReason === undefined) {
19+
return { kind: "none" };
20+
}
21+
const match = OPENCLAW_LOCK_PATTERN.exec(entry.lockedReason);
22+
if (!match) {
23+
return { kind: "foreign", reason: entry.lockedReason };
24+
}
25+
const pid = Number(match[1]);
26+
// A cross-user (EPERM) OpenClaw lock is treated as live so a run's checkout is
27+
// never removed under it; only an ESRCH/zombie owner counts as dead.
28+
return isPidDefinitelyDead(pid) ? { kind: "dead", pid } : { kind: "live", pid };
29+
}
30+
31+
export async function lockWorktreeForProcess(record: ManagedWorktreeRecord): Promise<void> {
32+
const result = await runGit(record.repoRoot, [
33+
"worktree",
34+
"lock",
35+
"--reason",
36+
`openclaw pid=${process.pid}`,
37+
record.path,
38+
]);
39+
if (result.code !== 0) {
40+
const state = await lockState(record);
41+
if (state.kind !== "live" || state.pid !== process.pid) {
42+
throw commandError("git worktree lock", result);
43+
}
44+
}
45+
}
46+
47+
export async function unlockWorktree(record: ManagedWorktreeRecord): Promise<void> {
48+
const result = await runGit(record.repoRoot, ["worktree", "unlock", record.path]);
49+
if (result.code !== 0) {
50+
throw commandError("git worktree unlock", result);
51+
}
52+
}

0 commit comments

Comments
 (0)