Skip to content

Commit f92449f

Browse files
committed
refactor(sessions): retire runtime transcript sidecars
1 parent b0b708d commit f92449f

27 files changed

Lines changed: 1374 additions & 3600 deletions

‎config/max-lines-baseline.txt‎

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -459,8 +459,6 @@ src/agents/runtime-plan/prepare-auth.test.ts
459459
src/agents/sandbox/ssh.ts
460460
src/agents/session-tool-result-guard.ts
461461
src/agents/session-transcript-repair.test.ts
462-
src/agents/session-write-lock.test.ts
463-
src/agents/session-write-lock.ts
464462
src/agents/sessions/extensions/runner.ts
465463
src/agents/sessions/extensions/types.ts
466464
src/agents/sessions/model-registry.ts

‎docs/.generated/plugin-sdk-api-baseline.sha256‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ cbf4e2c3088f8886a7c9ea91325a66e0f0846cea21f0b2891f36399b4811306c module/account
44
8e985f345f21a1c9a2b0e94304aaaad6a326bec1c1ce3b26027d2862804a366e module/account-resolution
55
e5e67ddf3cab38fcbf9220bc3160715897e2709d9a9ff6ff36f1ecc9453c2367 module/agent-config-primitives
66
74daa746deb548379d3f0d6eac3c4d082df1034c4360cc03bf51fee0f10a2e4d module/agent-harness
7-
c706f6f39070110ad2ac9140e2962249f95aee7d4e2a2fa2f7276beb1dfc7efc module/agent-harness-runtime
7+
98c427c987ed9ed54c8ba82c54b9ff0d019d87d7b52066de79aa7f34c449adee module/agent-harness-runtime
88
5168648cd946abad8a92822889f13ceacc87ed502314a66190d0b1eb8ebe76ea module/agent-media-payload
99
2dcb4d62d90e5d71594f6b843c97534509a154784e378fb1c75bd86b5122b710 module/agent-runtime
1010
56b6d5fb6af3d95af1200065aca2e7d4f59e5fa59740505fe6ff433077ef6646 module/allow-from

‎src/agents/main-session-restart-recovery-marking.ts‎

Lines changed: 0 additions & 92 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,10 @@
11
import { randomUUID } from "node:crypto";
2-
import fs from "node:fs";
32
import path from "node:path";
43
import { resolveStateDir } from "../config/paths.js";
54
import {
65
type InternalSessionEntry as SessionEntry,
76
type RestartRecoveryRun,
87
resolveAllAgentSessionStoreTargetsSync,
9-
resolveSessionFilePath,
10-
resolveSessionTranscriptPathInDir,
118
} from "../config/sessions.js";
129
import { applySessionEntryReplacements } from "../config/sessions/session-accessor.js";
1310
import type { OpenClawConfig } from "../config/types.openclaw.js";
@@ -33,41 +30,6 @@ import {
3330
shouldSkipMainRecovery,
3431
} from "./main-session-restart-recovery-shared.js";
3532
import { resolveAgentSessionDirs } from "./session-dirs.js";
36-
import type { SessionLockInspection } from "./session-write-lock.js";
37-
38-
function normalizeTranscriptLockPath(lockPath: string): string | undefined {
39-
const trimmed = lockPath.trim();
40-
if (!path.basename(trimmed).endsWith(".jsonl.lock")) {
41-
return undefined;
42-
}
43-
const resolved = path.resolve(trimmed);
44-
try {
45-
return path.join(fs.realpathSync(path.dirname(resolved)), path.basename(resolved));
46-
} catch {
47-
return resolved;
48-
}
49-
}
50-
51-
function resolveEntryTranscriptLockPaths(params: {
52-
entry: SessionEntry;
53-
sessionsDir: string;
54-
}): string[] {
55-
const paths = new Set<string>();
56-
const push = (resolvePath: () => string) => {
57-
try {
58-
paths.add(path.resolve(`${resolvePath()}.lock`));
59-
} catch {
60-
// Keep restart recovery best-effort when session metadata is stale.
61-
}
62-
};
63-
push(() =>
64-
resolveSessionFilePath(params.entry.sessionId, params.entry, {
65-
sessionsDir: params.sessionsDir,
66-
}),
67-
);
68-
push(() => resolveSessionTranscriptPathInDir(params.entry.sessionId, params.sessionsDir));
69-
return [...paths];
70-
}
7133

7234
export async function markRestartAbortedMainSessions(params: {
7335
cfg?: OpenClawConfig;
@@ -305,57 +267,3 @@ export async function markStartupOrphanedMainSessionsForRecovery(params: {
305267
}
306268
return result;
307269
}
308-
309-
export async function markRestartAbortedMainSessionsFromLocks(params: {
310-
sessionsDir: string;
311-
cleanedLocks: SessionLockInspection[];
312-
}): Promise<{ marked: number; skipped: number }> {
313-
const result = { marked: 0, skipped: 0 };
314-
const sessionsDir = path.resolve(params.sessionsDir);
315-
const interruptedLockPaths = new Set(
316-
params.cleanedLocks
317-
.map((lock) => normalizeTranscriptLockPath(lock.lockPath))
318-
.filter((lockPath): lockPath is string => Boolean(lockPath)),
319-
);
320-
if (interruptedLockPaths.size === 0) {
321-
return result;
322-
}
323-
324-
const storePath = path.join(sessionsDir, "sessions.json");
325-
const storeResult = await applySessionEntryReplacements({
326-
storePath,
327-
statuses: ["running"],
328-
update: (entries) => {
329-
const replacements: Array<{ sessionKey: string; entry: SessionEntry }> = [];
330-
const counts = { marked: 0, skipped: 0 };
331-
for (const { sessionKey, entry } of entries) {
332-
if (entry.status !== "running") {
333-
continue;
334-
}
335-
if (shouldSkipMainRecovery(entry, sessionKey)) {
336-
counts.skipped++;
337-
continue;
338-
}
339-
const entryLockPaths = resolveEntryTranscriptLockPaths({ entry, sessionsDir });
340-
if (!entryLockPaths.some((lockPath) => interruptedLockPaths.has(lockPath))) {
341-
continue;
342-
}
343-
transitionMainSessionRecovery(entry, {
344-
kind: "mark_interrupted",
345-
cycleId: randomUUID(),
346-
now: Date.now(),
347-
});
348-
replacements.push({ sessionKey, entry });
349-
counts.marked++;
350-
}
351-
return { result: counts, replacements };
352-
},
353-
});
354-
result.marked += storeResult.marked;
355-
result.skipped += storeResult.skipped;
356-
357-
if (result.marked > 0) {
358-
log.warn(`marked ${result.marked} interrupted main session(s) from stale transcript locks`);
359-
}
360-
return result;
361-
}

‎src/agents/main-session-restart-recovery.test.ts‎

Lines changed: 0 additions & 102 deletions
Original file line numberDiff line numberDiff line change
@@ -65,7 +65,6 @@ import * as recoveryOwnerRelease from "./main-session-recovery-owner-release.js"
6565
import { claimMainSessionRecoveryOwner } from "./main-session-recovery-store.js";
6666
import {
6767
markRestartAbortedMainSessions,
68-
markRestartAbortedMainSessionsFromLocks,
6968
markStartupOrphanedMainSessionsForRecovery,
7069
recoverStartupOrphanedMainSessions as recoverStartupOrphanedMainSessionsBase,
7170
recoverRestartAbortedMainSessions as recoverRestartAbortedMainSessionsBase,
@@ -75,7 +74,6 @@ import {
7574
scheduleRestartAbortedMainSessionRecovery as scheduleRestartAbortedMainSessionRecoveryBase,
7675
} from "./main-session-restart-recovery.js";
7776
import { AGENT_RUN_RESTART_ABORT_ERROR_CODE } from "./run-termination.js";
78-
import type { SessionLockInspection } from "./session-write-lock.js";
7977
import {
8078
createAssistantToolCallMessage,
8179
createSessionEntry,
@@ -358,26 +356,6 @@ function unresumableAssistantMessage(text = "provider failed") {
358356
};
359357
}
360358

361-
function cleanedLockForPath(lockPath: string): SessionLockInspection {
362-
// Simulates lock cleanup after process restart: stale lock removed, owning
363-
// PID dead, and the transcript path available for recovery.
364-
return {
365-
lockPath,
366-
pid: 999_999,
367-
pidAlive: false,
368-
createdAt: new Date(Date.now() - 1_000).toISOString(),
369-
ageMs: 1_000,
370-
stale: true,
371-
staleReasons: ["dead-pid"],
372-
removable: true,
373-
removed: true,
374-
};
375-
}
376-
377-
function cleanedLock(sessionsDir: string, sessionId: string): SessionLockInspection {
378-
return cleanedLockForPath(path.join(sessionsDir, `${sessionId}.jsonl.lock`));
379-
}
380-
381359
describe("main-session-restart-recovery", () => {
382360
it("marks only matching running main sessions by active session key", async () => {
383361
// Only top-level running main sessions are restart-recoverable. Completed,
@@ -768,86 +746,6 @@ describe("main-session-restart-recovery", () => {
768746
expect(store["agent:main:custom-by-id"]?.abortedLastRun).toBe(true);
769747
});
770748

771-
it("marks only main running sessions whose transcript lock was cleaned", async () => {
772-
const sessionsDir = await makeSessionsDir();
773-
await writeStore(sessionsDir, {
774-
"agent:main:main": {
775-
...runningSessionEntry("main-session"),
776-
},
777-
"agent:main:subagent:child": {
778-
...runningSessionEntry("child-session"),
779-
spawnDepth: 1,
780-
},
781-
"agent:main:other": {
782-
...runningSessionEntry("other-session"),
783-
},
784-
});
785-
786-
const result = await markRestartAbortedMainSessionsFromLocks({
787-
sessionsDir,
788-
cleanedLocks: [
789-
cleanedLock(sessionsDir, "main-session"),
790-
cleanedLock(sessionsDir, "child-session"),
791-
],
792-
});
793-
794-
const store = readStore(path.join(sessionsDir, "sessions.json"));
795-
expect(result).toEqual({ marked: 1, skipped: 1 });
796-
expect(store["agent:main:main"]?.abortedLastRun).toBe(true);
797-
expect(store["agent:main:subagent:child"]?.abortedLastRun).toBeUndefined();
798-
expect(store["agent:main:other"]?.abortedLastRun).toBeUndefined();
799-
});
800-
801-
it.each([
802-
{
803-
name: "does not mark a session for an unrelated topic lock that only shares its id prefix",
804-
sessionKey: "agent:main:main",
805-
sessionId: "main-session",
806-
sessionFile: "main-session.jsonl",
807-
lockKind: "unrelated",
808-
marked: 0,
809-
},
810-
{
811-
name: "falls back to the session id transcript lock when persisted sessionFile is outside the sessions dir",
812-
sessionKey: "agent:main:main",
813-
sessionId: "main-session",
814-
sessionFile: "../stale/outside.jsonl",
815-
lockKind: "session-id",
816-
marked: 1,
817-
},
818-
{
819-
name: "falls back to the session id transcript lock when persisted sessionFile belongs to another generated session",
820-
sessionKey: "agent:main:main",
821-
sessionId: "11111111-1111-4111-8111-111111111111",
822-
sessionFile: "22222222-2222-4222-8222-222222222222.jsonl",
823-
lockKind: "session-id",
824-
marked: 1,
825-
},
826-
])("$name", async ({ sessionKey, sessionId, sessionFile, lockKind, marked }) => {
827-
const sessionsDir = await makeSessionsDir();
828-
await writeStore(sessionsDir, {
829-
[sessionKey]: runningSessionEntry(sessionId, { sessionFile }),
830-
});
831-
const lockFile =
832-
lockKind === "unrelated"
833-
? "main-session-topic-unrelated.jsonl.lock"
834-
: `${sessionId}.jsonl.lock`;
835-
const lockPath = path.join(sessionsDir, lockFile);
836-
837-
const result = await markRestartAbortedMainSessionsFromLocks({
838-
sessionsDir,
839-
cleanedLocks: [cleanedLockForPath(lockPath)],
840-
});
841-
842-
const store = readStore(path.join(sessionsDir, "sessions.json"));
843-
expect(result).toEqual({ marked, skipped: 0 });
844-
if (marked === 1) {
845-
expect(store[sessionKey]?.abortedLastRun).toBe(true);
846-
} else {
847-
expect(store[sessionKey]?.abortedLastRun).toBeUndefined();
848-
}
849-
});
850-
851749
it("resumes marked sessions with a tool-result transcript tail", async () => {
852750
const sessionsDir = await makeSessionsDir();
853751
await writeStore(sessionsDir, mainSessionStore());

‎src/agents/main-session-restart-recovery.ts‎

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,6 @@
44

55
export {
66
markRestartAbortedMainSessions,
7-
markRestartAbortedMainSessionsFromLocks,
87
markStartupOrphanedMainSessionsForRecovery,
98
} from "./main-session-restart-recovery-marking.js";
109
export {

‎src/agents/sandbox/registry.ts‎

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -8,14 +8,14 @@ import fs from "node:fs/promises";
88
import path from "node:path";
99
import type { Insertable, Selectable, Updateable } from "kysely";
1010
import { z } from "zod";
11+
import { acquireFileLock } from "../../infra/file-lock.js";
1112
import { executeSqliteQuerySync, getNodeSqliteKysely } from "../../infra/kysely-sync.js";
1213
import { withOpenClawStateDatabaseReadOnly } from "../../state/openclaw-state-db-readonly.js";
1314
import { tableExists } from "../../state/openclaw-state-db-schema-helpers.js";
1415
import type { DB as OpenClawStateKyselyDatabase } from "../../state/openclaw-state-db.generated.js";
1516
import { runOpenClawStateWriteTransaction } from "../../state/openclaw-state-db.js";
1617
import { resolveOpenClawStateSqlitePath } from "../../state/openclaw-state-db.paths.js";
1718
import { safeParseJsonWithSchema } from "../../utils/zod-parse.js";
18-
import { acquireSessionWriteLock } from "../session-write-lock.js";
1919
import {
2020
SANDBOX_BROWSER_REGISTRY_PATH,
2121
SANDBOX_BROWSERS_DIR,
@@ -365,9 +365,9 @@ function normalizeSandboxRegistryEntry(entry: SandboxRegistryEntry): SandboxRegi
365365
}
366366

367367
async function withRegistryLock<T>(registryPath: string, fn: () => Promise<T>): Promise<T> {
368-
const lock = await acquireSessionWriteLock({
369-
sessionFile: registryPath,
370-
timeoutMs: 60_000,
368+
const lock = await acquireFileLock(registryPath, {
369+
stale: 30_000,
370+
retries: { retries: 59, factor: 1, minTimeout: 1_000, maxTimeout: 1_000 },
371371
});
372372
try {
373373
return await fn();
Lines changed: 19 additions & 49 deletions
Original file line numberDiff line numberDiff line change
@@ -1,74 +1,44 @@
1-
/**
2-
* Session write-lock error types and guards.
3-
*
4-
* Session persistence uses stable error codes so callers can distinguish lock
5-
* contention or stale lock cleanup from ordinary write failures.
6-
*/
7-
const SESSION_WRITE_LOCK_TIMEOUT_CODE = "OPENCLAW_SESSION_WRITE_LOCK_TIMEOUT";
8-
const SESSION_WRITE_LOCK_STALE_CODE = "OPENCLAW_SESSION_WRITE_LOCK_STALE";
1+
/** Stable session ownership errors shared by runtime and public harness adapters. */
2+
const TIMEOUT_CODE = "OPENCLAW_SESSION_WRITE_LOCK_TIMEOUT";
3+
const STALE_CODE = "OPENCLAW_SESSION_WRITE_LOCK_STALE";
94

10-
/** Error thrown when a session write lock cannot be acquired before timeout. */
115
export class SessionWriteLockTimeoutError extends Error {
12-
readonly code = SESSION_WRITE_LOCK_TIMEOUT_CODE;
13-
readonly timeoutMs: number;
14-
readonly owner: string;
15-
readonly lockPath: string;
6+
readonly code = TIMEOUT_CODE;
7+
declare readonly timeoutMs: number;
8+
declare readonly owner: string;
9+
declare readonly lockPath: string;
1610

1711
constructor(params: { timeoutMs: number; owner: string; lockPath: string }) {
1812
super(
1913
`session file locked (timeout ${params.timeoutMs}ms): ${params.owner} ${params.lockPath}`,
2014
);
2115
this.name = "SessionWriteLockTimeoutError";
22-
this.timeoutMs = params.timeoutMs;
23-
this.owner = params.owner;
24-
this.lockPath = params.lockPath;
16+
Object.assign(this, params);
2517
}
2618
}
2719

28-
/** Error thrown when an existing session write lock is stale and needs cleanup. */
2920
export class SessionWriteLockStaleError extends Error {
30-
readonly code = SESSION_WRITE_LOCK_STALE_CODE;
31-
readonly owner: string;
32-
readonly lockPath: string;
33-
readonly staleReasons: string[];
21+
readonly code = STALE_CODE;
22+
declare readonly owner: string;
23+
declare readonly lockPath: string;
24+
declare readonly staleReasons: string[];
3425

3526
constructor(params: { owner: string; lockPath: string; staleReasons?: string[] }) {
3627
const staleReasons = params.staleReasons?.length ? params.staleReasons : ["unknown"];
3728
super(
3829
`session file lock stale (${staleReasons.join(", ")}): ${params.owner} ${params.lockPath}`,
3930
);
4031
this.name = "SessionWriteLockStaleError";
41-
this.owner = params.owner;
42-
this.lockPath = params.lockPath;
43-
this.staleReasons = staleReasons;
32+
Object.assign(this, params, { staleReasons });
4433
}
4534
}
4635

47-
/** Returns whether an error is a session write-lock timeout. */
48-
function isSessionWriteLockTimeoutError(err: unknown): boolean {
36+
export function isSessionWriteLockAcquireError(error: unknown): boolean {
37+
const code = (error as { code?: unknown } | null)?.code;
4938
return (
50-
err instanceof SessionWriteLockTimeoutError ||
51-
Boolean(
52-
err &&
53-
typeof err === "object" &&
54-
(err as { code?: unknown }).code === SESSION_WRITE_LOCK_TIMEOUT_CODE,
55-
)
39+
error instanceof SessionWriteLockTimeoutError ||
40+
error instanceof SessionWriteLockStaleError ||
41+
code === TIMEOUT_CODE ||
42+
code === STALE_CODE
5643
);
5744
}
58-
59-
/** Returns whether an error is a stale session write-lock failure. */
60-
function isSessionWriteLockStaleError(err: unknown): boolean {
61-
return (
62-
err instanceof SessionWriteLockStaleError ||
63-
Boolean(
64-
err &&
65-
typeof err === "object" &&
66-
(err as { code?: unknown }).code === SESSION_WRITE_LOCK_STALE_CODE,
67-
)
68-
);
69-
}
70-
71-
/** Returns whether an error is any session write-lock acquisition failure. */
72-
export function isSessionWriteLockAcquireError(err: unknown): boolean {
73-
return isSessionWriteLockTimeoutError(err) || isSessionWriteLockStaleError(err);
74-
}

0 commit comments

Comments
 (0)