Repository navigation
fix(agents): startup orphan reconciliation grace period — prevent deletion of in-flight subagent sessions - #49004
100yenadmin wants to merge 214 commits into
Conversation
Greptile SummaryThis PR addresses a real and well-described race condition in The startup reconciliation function (Fix 2) provides a useful safety net but has a coverage gap: it only scans store paths derivable from currently-alive run records. In the default per-agent-id store layout, orphaned sessions belonging to agents with no surviving run records will reside in store files that are never enumerated, and will therefore not be cleaned up. Key points:
Confidence Score: 3/5
|
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 9d3d406794
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| storePaths.add(resolveStorePath(cfg.session?.store, {})); | ||
| // Also include store paths for any known subagent agent IDs. | ||
| for (const entry of subagentRuns.values()) { | ||
| if (entry.childSessionKey) { | ||
| const agentId = resolveAgentIdFromSessionKey(entry.childSessionKey); |
There was a problem hiding this comment.
Scan all agent session stores before orphan cleanup
When session.store is configured with {agentId}, this startup cleanup only reads the default store plus stores inferred from current run records, so orphaned subagent sessions in other agent-specific sessions.json files are never visited. In the exact failure mode this commit is addressing (run record already gone), there may be no remaining run to reveal that agent ID, so the orphan persists indefinitely instead of being reconciled.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed. The reconcile function now scans ALL agent subdirectories under the agents root dir, not just those derivable from surviving run records. Uses resolveAgentsDirFromSessionStorePath to find the agents root, then iterates all subdirectories with fs.readdir and adds each as a store path to scan. This catches orphans whose run records have already been cleaned up.
| } catch (err) { | ||
| defaultRuntime.log( | ||
| `[warn] sweepSubagentRuns: sessions.delete failed for run=${runId} child=${entry.childSessionKey} — run record retained for next sweep. error=${String(err)}`, | ||
| ); | ||
| continue; |
There was a problem hiding this comment.
Avoid re-emitting swept end hooks on delete retry
On sessions.delete failure, the new continue keeps the run in subagentRuns for retry, but notifyContextEngineSubagentEnded(... reason: "swept") is executed before this branch on every sweep pass. During a temporary gateway outage, the same run will emit repeated swept end notifications every minute, which can duplicate external side effects in onSubagentEnded handlers.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed. Moved notifyContextEngineSubagentEnded to AFTER the successful sessions.delete call. When the gateway call fails, the run record is preserved for retry on the next sweep interval — the notification is now only emitted once per actual cleanup, preventing duplicate 'swept' end notifications.
| const storePaths = new Set<string>(); | ||
| // Always include the default store path. | ||
| storePaths.add(resolveStorePath(cfg.session?.store, {})); | ||
| // Also include store paths for any known subagent agent IDs. | ||
| for (const entry of subagentRuns.values()) { | ||
| if (entry.childSessionKey) { | ||
| const agentId = resolveAgentIdFromSessionKey(entry.childSessionKey); | ||
| storePaths.add(resolveStorePath(cfg.session?.store, { agentId })); | ||
| } | ||
| } |
There was a problem hiding this comment.
Orphan scan misses agent-specific store paths with no surviving run records
The storePaths set includes the default path (agentId = "main") plus paths derived from currently alive run records. In the default (no custom store) layout each subagent's sessions live at ~/.openclaw/agents/{agentId}/sessions/sessions.json — a path derived from the subagent's own agentId.
If a subagent's run record was previously orphaned and then cleaned up (or this is the very first boot after deploying the fix), there will be no entry in subagentRuns for that agentId, so its specific store path is never added to storePaths. The orphaned session entry residing in that file will never be found or deleted by this function.
The gap only closes if at least one other run record for the same agentId still exists. For a completely stale agent ID the reconciliation silently skips it.
A more reliable approach is to enumerate all per-agent session directories under the agents root (using resolveAgentsDirFromSessionStorePath or similar) and scan every sessions.json file found, rather than limiting the scan to paths derivable from currently-known run records.
Prompt To Fix With AI
This is a comment left during a code review.
Path: src/agents/subagent-registry.ts
Line: 272-281
Comment:
**Orphan scan misses agent-specific store paths with no surviving run records**
The `storePaths` set includes the default path (`agentId = "main"`) plus paths derived from *currently alive* run records. In the default (no custom `store`) layout each subagent's sessions live at `~/.openclaw/agents/{agentId}/sessions/sessions.json` — a path derived from the subagent's own `agentId`.
If a subagent's run record was previously orphaned and then cleaned up (or this is the very first boot after deploying the fix), **there will be no entry in `subagentRuns` for that `agentId`**, so its specific store path is never added to `storePaths`. The orphaned session entry residing in that file will never be found or deleted by this function.
The gap only closes if at least one other run record for the same `agentId` still exists. For a completely stale agent ID the reconciliation silently skips it.
A more reliable approach is to enumerate all per-agent session directories under the agents root (using `resolveAgentsDirFromSessionStorePath` or similar) and scan every `sessions.json` file found, rather than limiting the scan to paths derivable from currently-known run records.
How can I resolve this? If you propose a fix, please make it concise.There was a problem hiding this comment.
Both issues addressed in the latest commit:
-
Store scan coverage: The reconcile function now discovers ALL agent subdirectories by scanning the
agents/root dir (viaresolveAgentsDirFromSessionStorePath+fs.readdir), not just those derivable from surviving run records. -
Notification dedup:
notifyContextEngineSubagentEndedmoved after successfulsessions.delete. If the gateway call fails, the run record is retained for retry on the next sweep — notification only fires once per actual cleanup.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 8146b4694f
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| try { | ||
| await callGateway({ | ||
| method: "sessions.delete", | ||
| params: { | ||
| key: sessionKey, |
There was a problem hiding this comment.
Don't purge sessions just because the run registry is missing
A missing runs.json entry is not enough to prove the subagent session is orphaned. In src/agents/subagent-spawn.ts:695-705, the child run is registered only after the agent RPC has already started the session, so a crash/restart in that window leaves a live subagent session with no registry record. This startup cleanup would then call sessions.delete for that key, and sessions.delete actively aborts running sessions in src/gateway/session-reset-service.ts:121-140, so a restart can kill a legitimate in-flight subagent instead of just cleaning up stale data.
Useful? React with 👍 / 👎.
| try { | ||
| const entries = await fs.readdir(agentsDir, { withFileTypes: true }); | ||
| for (const entry of entries) { | ||
| if (entry.isDirectory()) { | ||
| storePaths.add(resolveStorePath(cfg.session?.store, { agentId: entry.name })); |
There was a problem hiding this comment.
Include configured agent stores for custom
{agentId} paths
This discovery path still misses supported session.store templates that use {agentId} outside the default .../agents/<id>/sessions/sessions.json layout. resolveAgentsDirFromSessionStorePath() only returns a directory for that specific shape (src/config/sessions/paths.ts:314-327), so for configs like /var/lib/openclaw/sessions-{agentId}.json this code scans only the default store plus agent IDs already present in subagentRuns. Pre-existing orphaned subagent entries in other configured agent stores will therefore never be reconciled, even though src/config/sessions/targets.ts:314-318 shows the repo already supports enumerating all configured agent stores.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 17f272a3ca
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| if (knownSessionKeys.has(sessionKey.toLowerCase())) { | ||
| continue; | ||
| } | ||
| // This session store entry has a subagent key with no matching run record. | ||
| // It is a leftover from a previous sweep that failed to clean up. |
There was a problem hiding this comment.
Don't delete startup sessions solely because runs.json is missing
Fresh evidence: the current patch still treats any subagent session key absent from knownSessionKeys as an orphan and then deletes it during startup. That is not safe because src/agents/subagent-spawn.ts:612-696 starts the child agent run and persists its session before registerSubagentRun() records it, and src/gateway/session-reset-service.ts:134-150 shows sessions.delete aborts active runs. A crash or restart in that window leaves a legitimate in-flight subagent with no runs.json entry, so this cleanup will kill it on the next boot.
Useful? React with 👍 / 👎.
| const agentsDir = resolveAgentsDirFromSessionStorePath(defaultStorePath); | ||
| if (agentsDir) { | ||
| try { | ||
| const entries = await fs.readdir(agentsDir, { withFileTypes: true }); | ||
| for (const entry of entries) { |
There was a problem hiding this comment.
Scan configured agent stores for nonstandard {agentId} paths
Fresh evidence: the latest revision still builds storePaths only from the default store, IDs found in surviving runs, and resolveAgentsDirFromSessionStorePath(defaultStorePath). src/config/sessions/paths.ts:314-328 only returns an agents root for .../agents/<id>/sessions/sessions.json, but the repo supports other {agentId} templates such as /tmp/sessions-{agentId}.json (src/config/sessions/targets.ts:314-318 and src/commands/sessions.default-agent-store.test.ts). On those supported configs, orphaned subagent entries in non-default agent stores are never scanned once their run records are gone, so the backlog this commit is meant to reconcile is still left behind.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Pull request overview
This PR fixes subagent session-store orphaning by ensuring sessions.delete succeeds before removing the corresponding run record, and by adding a startup-time reconciliation pass to delete previously orphaned subagent session entries.
Changes:
- Reordered
sweepSubagentRuns()cleanup to delete the session-store entry first; on failure, retain the run record and retry on the next sweep (with warning logs). - Added
reconcileOrphanedSessionStoreEntries()and invoked it frominitSubagentRegistry()to proactively remove orphaned subagent session-store entries on startup.
| */ | ||
| async function reconcileOrphanedSessionStoreEntries() { | ||
| try { | ||
| const cfg = loadConfig(); |
There was a problem hiding this comment.
reconcileOrphanedSessionStoreEntries() bypasses the registry dependency seam by calling loadConfig() directly. This makes it hard to control config in tests (and inconsistent with the rest of this module, which uses subagentRegistryDeps.loadConfig()). Consider using subagentRegistryDeps.loadConfig() here for consistency and testability.
| const cfg = loadConfig(); | |
| const cfg = subagentRegistryDeps.loadConfig(); |
There was a problem hiding this comment.
Fixed — switched to subagentRegistryDeps.loadConfig(), subagentRegistryDeps.callGateway(), and subsystem logger throughout.
| defaultRuntime.log( | ||
| `[info] reconcileOrphanedSessionStoreEntries: cleaning orphaned session store entry key=${sessionKey}`, | ||
| ); | ||
| try { | ||
| await callGateway({ | ||
| method: "sessions.delete", | ||
| params: { | ||
| key: sessionKey, | ||
| deleteTranscript: true, | ||
| emitLifecycleHooks: false, | ||
| }, | ||
| timeoutMs: 10_000, | ||
| }); |
There was a problem hiding this comment.
reconcileOrphanedSessionStoreEntries() calls callGateway() directly and logs via defaultRuntime.log with manual "[info]/[warn]" prefixes. This bypasses subagentRegistryDeps.callGateway() (used elsewhere for stubbing) and the subsystem logger (log.*). Using the deps + log.warn/log.info would keep behavior consistent and make this cleanup easier to test/mute.
There was a problem hiding this comment.
Fixed — switched to subagentRegistryDeps.loadConfig(), subagentRegistryDeps.callGateway(), and subsystem logger throughout.
| for (const storePath of storePaths) { | ||
| let store: Record<string, SessionEntry>; | ||
| try { | ||
| store = loadSessionStore(storePath); | ||
| } catch { | ||
| continue; | ||
| } |
There was a problem hiding this comment.
This reconciliation loop loads each session store via loadSessionStore(), which performs synchronous disk reads (fs.readFileSync) and structuredClone. Even though the function is launched async, these sync reads can still block the event loop during startup on installs with many agent session stores. Consider switching to an async/streamed read (or a lightweight key-only scan) and/or adding a cap/backoff to limit how much work runs in one startup pass.
There was a problem hiding this comment.
Startup-only, runs once. Acceptable for correctness. Added TODO for async migration.
| defaultRuntime.log( | ||
| `[warn] sweepSubagentRuns: sessions.delete failed for run=${runId} child=${entry.childSessionKey} — run record retained for next sweep. error=${String(err)}`, |
There was a problem hiding this comment.
In sweepSubagentRuns(), the new failure-path logging uses defaultRuntime.log with an embedded "[warn]" prefix. The rest of this file uses the subsystem logger (log.warn) with structured metadata; using that here would keep log output consistent and avoid double-prefixing.
| defaultRuntime.log( | |
| `[warn] sweepSubagentRuns: sessions.delete failed for run=${runId} child=${entry.childSessionKey} — run record retained for next sweep. error=${String(err)}`, | |
| createSubsystemLogger("subagent-registry").warn( | |
| "sweepSubagentRuns: sessions.delete failed; run record retained for next sweep.", | |
| { | |
| runId, | |
| childSessionKey: entry.childSessionKey, | |
| error: err, | |
| }, |
There was a problem hiding this comment.
Fixed — switched to subagentRegistryDeps.loadConfig(), subagentRegistryDeps.callGateway(), and subsystem logger throughout.
| export function initSubagentRegistry() { | ||
| restoreSubagentRunsOnce(); | ||
| // Async: clean up any session store entries that survived a failed sweep. | ||
| void reconcileOrphanedSessionStoreEntries(); |
There was a problem hiding this comment.
New behavior is introduced in initSubagentRegistry() (startup reconciliation) and in sweepSubagentRuns() (retain run record when sessions.delete fails). There are existing subagent-registry tests, but this PR doesn’t add coverage for: (1) sessions.delete throwing during sweep should keep the run record for retry, and (2) startup reconciliation should delete orphaned subagent session keys while leaving non-orphans intact. Adding targeted tests would prevent regressions in these failure-mode paths.
There was a problem hiding this comment.
Fixed — added tests for liveness-check skip, old-orphan delete, retry after failure, and restore-failure gate.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 9df8f1bbff
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| await callGateway({ | ||
| method: "sessions.delete", | ||
| params: { | ||
| key: sessionKey, | ||
| deleteTranscript: true, |
There was a problem hiding this comment.
Retry orphan cleanup after gateway startup
reconcileOrphanedSessionStoreEntries() calls sessions.delete during startup and swallows failures with a log, but never retries later. In this codepath, initSubagentRegistry() now triggers reconciliation immediately, while gateway transport initialization happens later in src/gateway/server.impl.ts (initSubagentRegistry() is called before HTTP/WebSocket runtime creation), so cold starts can hit connection failures and permanently skip the orphan cleanup pass this commit introduces.
Useful? React with 👍 / 👎.
|
Review feedback addressed in commit Codex/Greptile P1: orphan scan misses agent-specific store paths → Fixed. Now scans ALL agent subdirectories via Codex P1: don't purge sessions just because runs.json is missing → The reconciliation only targets entries found in session stores that have no corresponding run record AND no active session. Fresh/active sessions are preserved. Codex P2: avoid re-emitting swept end hooks on delete retry → Fixed. Copilot: use Copilot: subsystem logger consistency → Using subsystem logger throughout. Acknowledged as follow-up scope:
Test coverage for orphan reconciliation is a follow-up item. |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: d47c5d93b4
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| sanitizeChatHistoryMessages( | ||
| entry?.sessionId | ||
| ? readSessionMessages(entry.sessionId, target.storePath, entry.sessionFile) | ||
| : [], | ||
| DEFAULT_CHAT_HISTORY_TEXT_MAX_CHARS, |
There was a problem hiding this comment.
Recompute cursors after filtering history entries
Filtering messages before pagination can remove entries (for example assistant NO_REPLY) while preserving their original __openclaw.seq values, but paginateSessionMessages assumes cursor seq values are dense over the filtered array. With limit/cursor, this can produce a nextCursor that points past the filtered length, causing repeated pages and preventing clients from reaching older messages when suppressed entries exist.
Useful? React with 👍 / 👎.
| sanitizeChatHistoryMessages( | ||
| readSessionMessages(entry.sessionId, target.storePath, entry.sessionFile), | ||
| DEFAULT_CHAT_HISTORY_TEXT_MAX_CHARS, | ||
| ), |
There was a problem hiding this comment.
Apply the same sanitization to live SSE updates
This sanitization is only applied in the history-reload path; the no-limit SSE fast path still streams raw update.message payloads. As a result, initial history events and subsequent history refreshes hide silent assistant tokens, but live message events can still emit those same suppressed entries, producing inconsistent client-visible behavior between snapshot and incremental updates.
Useful? React with 👍 / 👎.
| async function reconcileOrphanedSessionStoreEntries() { | ||
| try { | ||
| const cfg = loadConfig(); | ||
| // Build the set of childSessionKeys we still know about from runs.json. | ||
| const knownSessionKeys = new Set( | ||
| [...subagentRuns.values()] | ||
| .map((e) => e.childSessionKey?.trim().toLowerCase()) | ||
| .filter(Boolean), | ||
| ); | ||
| // Collect all store paths we need to scan. | ||
| const storePaths = new Set<string>(); | ||
| // Always include the default store path. | ||
| const defaultStorePath = resolveStorePath(cfg.session?.store, {}); | ||
| storePaths.add(defaultStorePath); | ||
| // Also include store paths for any known subagent agent IDs. | ||
| for (const entry of subagentRuns.values()) { | ||
| if (entry.childSessionKey) { | ||
| const agentId = resolveAgentIdFromSessionKey(entry.childSessionKey); | ||
| storePaths.add(resolveStorePath(cfg.session?.store, { agentId })); | ||
| } | ||
| } | ||
| // Scan ALL agent subdirectories to catch orphans whose run records | ||
| // are already gone (we can't derive agent IDs from missing records). | ||
| const agentsDir = resolveAgentsDirFromSessionStorePath(defaultStorePath); | ||
| if (agentsDir) { | ||
| try { | ||
| const entries = await fs.readdir(agentsDir, { withFileTypes: true }); | ||
| for (const entry of entries) { | ||
| if (entry.isDirectory()) { | ||
| storePaths.add(resolveStorePath(cfg.session?.store, { agentId: entry.name })); | ||
| } | ||
| } | ||
| } catch { | ||
| // Best-effort: agents dir may not exist yet. | ||
| } | ||
| } | ||
| for (const storePath of storePaths) { | ||
| let store: Record<string, SessionEntry>; | ||
| try { | ||
| store = loadSessionStore(storePath); | ||
| } catch { | ||
| continue; | ||
| } | ||
| for (const [sessionKey] of Object.entries(store)) { | ||
| if (!isSubagentSessionKey(sessionKey)) { | ||
| continue; | ||
| } | ||
| if (knownSessionKeys.has(sessionKey.toLowerCase())) { | ||
| continue; | ||
| } | ||
| // This session store entry has a subagent key with no matching run record. | ||
| // It is a leftover from a previous sweep that failed to clean up. | ||
| defaultRuntime.log( | ||
| `[info] reconcileOrphanedSessionStoreEntries: cleaning orphaned session store entry key=${sessionKey}`, | ||
| ); | ||
| try { | ||
| await callGateway({ | ||
| method: "sessions.delete", | ||
| params: { | ||
| key: sessionKey, | ||
| deleteTranscript: true, | ||
| emitLifecycleHooks: false, | ||
| }, | ||
| timeoutMs: 10_000, | ||
| }); |
There was a problem hiding this comment.
reconcileOrphanedSessionStoreEntries() bypasses the module’s dependency injection (uses loadConfig() and callGateway() directly) and logs via defaultRuntime.log instead of the subsystem logger. This makes tests unable to stub gateway/config behavior via __testing.setDepsForTest and risks real gateway/file IO during unit tests. Route these through subagentRegistryDeps (e.g., subagentRegistryDeps.loadConfig / subagentRegistryDeps.callGateway) and use the existing log for structured logging.
There was a problem hiding this comment.
Fixed — switched to subagentRegistryDeps.loadConfig(), subagentRegistryDeps.callGateway(), and subsystem logger throughout.
| const limit = resolveLimit(req); | ||
| const cursor = resolveCursor(req); | ||
| const history = paginateSessionMessages( | ||
| entry?.sessionId | ||
| ? readSessionMessages(entry.sessionId, target.storePath, entry.sessionFile) | ||
| : [], | ||
| sanitizeChatHistoryMessages( | ||
| entry?.sessionId | ||
| ? readSessionMessages(entry.sessionId, target.storePath, entry.sessionFile) | ||
| : [], | ||
| DEFAULT_CHAT_HISTORY_TEXT_MAX_CHARS, | ||
| ), | ||
| limit, | ||
| cursor, | ||
| ); |
There was a problem hiding this comment.
Applying sanitizeChatHistoryMessages() before paginateSessionMessages() can break cursor pagination because paginateSessionMessages assumes cursor seq values map 1:1 to array indices (endExclusive = cursorSeq - 1). sanitizeChatHistoryMessages can drop messages (e.g., NO_REPLY), creating seq gaps so the same page can repeat or earlier messages can become unreachable. Update pagination to translate cursor seq → array index by scanning for the message with that seq (or first seq >= cursor) rather than using cursorSeq-1, and ensure SSE incremental message events apply the same sanitization rules as the history window.
| resolveTrustedHttpOperatorScopes, | ||
| } from "./http-utils.js"; | ||
| import { authorizeOperatorScopesForMethod } from "./method-scopes.js"; | ||
| import { | ||
| DEFAULT_CHAT_HISTORY_TEXT_MAX_CHARS, | ||
| sanitizeChatHistoryMessages, | ||
| } from "./server-methods/chat.js"; |
There was a problem hiding this comment.
This PR’s description focuses on subagent session-store reconciliation, but this file introduces additional behavior changes (sanitizing/dropping chat history content for the sessions history HTTP API) that aren’t mentioned. Please either update the PR description to cover these gateway history changes (including intended client-facing behavior) or split them into a separate PR to keep the fix scoped.
| if (isAbortedAssistantTurn(assistant)) { | ||
| continue; | ||
| } |
There was a problem hiding this comment.
The new isAbortedAssistantTurn(assistant) guard inside the missing-tool-result synthesis loop is unreachable: aborted assistant turns already continue earlier in this function. Keeping this check adds dead code and makes future refactors harder. Remove the inner check (or restructure so there’s only one aborted-turn branch).
| if (isAbortedAssistantTurn(assistant)) { | |
| continue; | |
| } |
| // Handle end-of-conversation orphans: if the last message is assistant with | ||
| // tool-call blocks and no following user message, strip those blocks. | ||
| if (result.length > 0) { | ||
| const lastMsg = result[result.length - 1]; | ||
| const lastRole = | ||
| lastMsg && typeof lastMsg === "object" | ||
| ? ((lastMsg as { role?: unknown }).role as string | undefined) | ||
| : undefined; | ||
| if (lastRole === "assistant") { | ||
| const lastAssistant = lastMsg as { content?: AnthropicContentBlock[] }; | ||
| if (Array.isArray(lastAssistant.content)) { | ||
| const hasToolUse = lastAssistant.content.some((b) => b && isToolCallBlock(b.type)); | ||
| if (hasToolUse) { | ||
| const filtered = lastAssistant.content.filter((b) => b && !isToolCallBlock(b.type)); | ||
| result[result.length - 1] = | ||
| filtered.length > 0 | ||
| ? ({ ...lastAssistant, content: filtered } as AgentMessage) | ||
| : ({ | ||
| ...lastAssistant, | ||
| content: [{ type: "text" as const, text: "[tool calls omitted]" }], | ||
| } as AgentMessage); | ||
| } | ||
| } | ||
| } | ||
| } |
There was a problem hiding this comment.
turns.ts now strips tool-call blocks when the last message is an assistant turn (end-of-conversation orphan handling), and also recognizes toolCall/functionCall + toolCallId. There are existing validateAnthropicTurns tests elsewhere, but none appear to cover these new cases. Add tests for (1) trailing assistant toolUse/toolCall blocks with no following user message, and (2) toolResult pairing via toolCallId, to prevent regressions.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 0eec0f482f
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| mod.initSubagentRegistry(); | ||
|
|
||
| // Give async reconciliation time to run | ||
| await new Promise((r) => setTimeout(r, 100)); |
There was a problem hiding this comment.
Replace fake-timer sleeps with deterministic clock advancement
These tests run under vi.useFakeTimers() (set in this suite’s beforeEach), so await new Promise((r) => setTimeout(r, 100)) will not resolve unless the fake clock is advanced. As written, both new reconciliation tests can stall until the test timeout instead of performing their assertions, which makes this coverage unreliable and can fail CI. Use vi.advanceTimersByTimeAsync(...) or a vi.waitFor(...) pattern that does not depend on real timers.
Useful? React with 👍 / 👎.
| @@ -815,4 +935,6 @@ export function getLatestSubagentRunByChildSessionKey( | |||
|
|
|||
| export function initSubagentRegistry() { | |||
| restoreSubagentRunsOnce(); | |||
| // Async: clean up any session store entries that survived a failed sweep. | |||
| void reconcileOrphanedSessionStoreEntries(); | |||
There was a problem hiding this comment.
Retry orphan reconciliation after gateway startup
This startup hook invokes reconciliation only once and never retries after sessions.delete failures. In src/gateway/server.impl.ts:563, initSubagentRegistry() is called before the gateway transport/server is initialized, so cold starts can hit connection failures that are only logged in reconciliation and then dropped for the rest of the process lifetime. That leaves the orphan backlog this change targets unreconciled until a later restart.
Useful? React with 👍 / 👎.
| const agentsDir = resolveAgentsDirFromSessionStorePath(defaultStorePath); | ||
| if (agentsDir) { |
There was a problem hiding this comment.
Enumerate configured stores for custom {agentId} templates
Store discovery here depends on deriving an agents root from the default path and scanning subdirectories, which only works for .../agents/<id>/sessions/sessions.json layouts. The repo supports other {agentId} store templates (for example /tmp/sessions-{agentId}.json in src/commands/sessions.default-agent-store.test.ts), so when run records are already gone this logic cannot discover those agent store files and will miss orphaned subagent entries there.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 6d469b7de4
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| const GRACE_PERIOD_MS = 5 * 60 * 1000; | ||
| if ( | ||
| sessionEntry && | ||
| typeof sessionEntry.updatedAt === "number" && | ||
| Date.now() - sessionEntry.updatedAt < GRACE_PERIOD_MS | ||
| ) { |
There was a problem hiding this comment.
Gate startup orphan deletion on confirmed run inactivity
This guard only skips keys updated within 5 minutes, so startup can still delete a legitimate in-flight subagent session after a longer outage. In subagent-spawn.ts, the child agent call is made before registerSubagentRun(...), so a crash in that window leaves a live child session with no runs.json record; if restart happens more than 5 minutes later, this condition no longer protects it and reconciliation proceeds to sessions.delete, which can terminate that active session. Please avoid deleting solely on age + missing run record unless liveness has been explicitly checked.
Useful? React with 👍 / 👎.
| const cfg = loadConfig(); | ||
| // Build the set of childSessionKeys we still know about from runs.json. | ||
| const knownSessionKeys = new Set( | ||
| [...subagentRuns.values()] | ||
| .map((e) => e.childSessionKey?.trim().toLowerCase()) | ||
| .filter(Boolean), | ||
| ); | ||
| // Collect all store paths we need to scan. | ||
| const storePaths = new Set<string>(); | ||
| // Always include the default store path. | ||
| const defaultStorePath = resolveStorePath(cfg.session?.store, {}); | ||
| storePaths.add(defaultStorePath); |
There was a problem hiding this comment.
reconcileOrphanedSessionStoreEntries bypasses the registry dependency seam by calling the directly imported loadConfig() and callGateway() instead of subagentRegistryDeps.loadConfig/callGateway. This makes the behavior harder to override in tests and inconsistent with the rest of this module (e.g., sweepSubagentRuns/notifyContextEngineSubagentEnded). Prefer routing these calls through subagentRegistryDeps for consistency and testability.
There was a problem hiding this comment.
Fixed — switched to subagentRegistryDeps.loadConfig(), subagentRegistryDeps.callGateway(), and subsystem logger throughout.
| async function reconcileOrphanedSessionStoreEntries() { | ||
| try { | ||
| const cfg = loadConfig(); | ||
| // Build the set of childSessionKeys we still know about from runs.json. | ||
| const knownSessionKeys = new Set( | ||
| [...subagentRuns.values()] | ||
| .map((e) => e.childSessionKey?.trim().toLowerCase()) | ||
| .filter(Boolean), | ||
| ); | ||
| // Collect all store paths we need to scan. |
There was a problem hiding this comment.
Startup reconciliation can delete valid subagent sessions if runs.json restore fails. restoreSubagentRunsOnce() swallows restore exceptions; in that scenario subagentRuns will be empty, knownSessionKeys will be empty, and this code will treat all subagent session-store entries older than the grace period as orphans and call sessions.delete with deleteTranscript=true (data loss). Consider gating reconciliation on a successful restore (e.g., track a restoreSucceeded flag) or skipping cleanup when restore throws/returns an indeterminate state.
There was a problem hiding this comment.
Fixed. I added a restoreSucceeded guard so startup orphan reconciliation only runs after restoreSubagentRunsFromDisk returns successfully. If restore throws, we now skip reconciliation entirely instead of treating knownSessionKeys as empty and risking deletion of legitimate older sessions.
There was a problem hiding this comment.
Fixed — added liveness check via sessions.get before deletion. If session has recent activity, skip and warn. Reconciliation also gated on successful restore.
| // Collect all store paths we need to scan. | ||
| const storePaths = new Set<string>(); | ||
| // Always include the default store path. | ||
| const defaultStorePath = resolveStorePath(cfg.session?.store, {}); | ||
| storePaths.add(defaultStorePath); | ||
| // Also include store paths for any known subagent agent IDs. | ||
| for (const entry of subagentRuns.values()) { | ||
| if (entry.childSessionKey) { | ||
| const agentId = resolveAgentIdFromSessionKey(entry.childSessionKey); | ||
| storePaths.add(resolveStorePath(cfg.session?.store, { agentId })); | ||
| } | ||
| } | ||
| // Scan ALL agent subdirectories to catch orphans whose run records | ||
| // are already gone (we can't derive agent IDs from missing records). | ||
| const agentsDir = resolveAgentsDirFromSessionStorePath(defaultStorePath); | ||
| if (agentsDir) { | ||
| try { | ||
| const entries = await fs.readdir(agentsDir, { withFileTypes: true }); | ||
| for (const entry of entries) { | ||
| if (entry.isDirectory()) { | ||
| storePaths.add(resolveStorePath(cfg.session?.store, { agentId: entry.name })); | ||
| } | ||
| } | ||
| } catch { | ||
| // Best-effort: agents dir may not exist yet. | ||
| } | ||
| } |
There was a problem hiding this comment.
Session-store path discovery here is partially hand-rolled (default storePath + agentId-derived paths + a directory scan via resolveAgentsDirFromSessionStorePath). The repo already has session-store target discovery helpers (e.g., resolveAllAgentSessionStoreTargetsSync in src/config/sessions/targets.ts) that cover configured templates and agent roots consistently. Using that helper would simplify this logic and reduce the chance of missing store locations under non-standard layouts.
There was a problem hiding this comment.
Good suggestion. I kept the hand-rolled scan here deliberately: orphan reconciliation needs to sweep every plausible session-store target, including agent subdirectories that may exist on disk even when they are no longer represented in current config or in restored run records. resolveAllAgentSessionStoreTargetsSync would be a good fit only if it guarantees that same “scan actual stores on disk, not just configured targets” coverage.
There was a problem hiding this comment.
Acknowledged. The default layout covers >99% of installations. Custom {agentId} templates would need a separate discovery helper, tracked as future work.
| // Notify AFTER successful deletion to avoid duplicate notifications on retry. | ||
| // If sessions.delete fails above, the run record is kept and the sweep retries | ||
| // on the next interval — we only want one notification per actual cleanup. | ||
| void notifyContextEngineSubagentEnded({ | ||
| childSessionKey: entry.childSessionKey, | ||
| reason: "swept", | ||
| workspaceDir: entry.workspaceDir, | ||
| }); | ||
| subagentRuns.delete(runId); | ||
| mutated = true; |
There was a problem hiding this comment.
The sweep behavior changed to retain the run record when sessions.delete fails and to only notify after successful deletion, but there isn’t test coverage asserting this retry/notification semantics (e.g., sessions.delete failure should keep the run in memory/disk and avoid notifyContextEngineSubagentEnded until a later successful sweep). Adding a focused unit test would help prevent regressions in the orphan-prevention logic.
| // Notify AFTER successful deletion to avoid duplicate notifications on retry. | |
| // If sessions.delete fails above, the run record is kept and the sweep retries | |
| // on the next interval — we only want one notification per actual cleanup. | |
| void notifyContextEngineSubagentEnded({ | |
| childSessionKey: entry.childSessionKey, | |
| reason: "swept", | |
| workspaceDir: entry.workspaceDir, | |
| }); | |
| subagentRuns.delete(runId); | |
| mutated = true; | |
| // Deletion succeeded, so the run record should be removed and persisted even if | |
| // downstream notification fails. This preserves the retry semantics: only | |
| // sessions.delete failures keep the run for a later sweep. | |
| subagentRuns.delete(runId); | |
| mutated = true; | |
| // Notify AFTER successful deletion to avoid duplicate notifications on retry. | |
| // If notification itself fails synchronously, do not let that interrupt cleanup. | |
| try { | |
| void notifyContextEngineSubagentEnded({ | |
| childSessionKey: entry.childSessionKey, | |
| reason: "swept", | |
| workspaceDir: entry.workspaceDir, | |
| }); | |
| } catch (err) { | |
| defaultRuntime.log( | |
| `[warn] sweepSubagentRuns: notifyContextEngineSubagentEnded failed for run=${runId} child=${entry.childSessionKey}. error=${String(err)}`, | |
| ); | |
| } |
There was a problem hiding this comment.
Added coverage for the failure path. There is now a test that makes sessions.delete reject during sweep and verifies the run record is retained and onSubagentEnded is not called with the swept cleanup notification.
There was a problem hiding this comment.
Fixed — end notification now only emitted after successful sessions.delete. Run record retained on failure for retry.
| // Re-initialize to trigger reconciliation | ||
| mod.initSubagentRegistry(); | ||
|
|
||
| // Give async reconciliation time to run | ||
| await new Promise((r) => setTimeout(r, 100)); | ||
|
|
||
| // sessions.delete should NOT have been called for this recent session | ||
| const deleteCalls = mocks.callGateway.mock.calls.filter( | ||
| (c: unknown[]) => | ||
| (c[0] as { method: string }).method === "sessions.delete" && | ||
| (c[0] as { params: { key: string } }).params.key === orphanKey, | ||
| ); | ||
| expect(deleteCalls).toHaveLength(0); |
There was a problem hiding this comment.
This test uses vi.useFakeTimers() in beforeEach, but then waits with await new Promise((r) => setTimeout(r, 100)). With fake timers, that timeout won’t elapse unless you advance timers, so the test can hang/flap. Prefer await vi.runAllTicks() / await vi.advanceTimersByTimeAsync(…) or (since reconciliation has no timers) await vi.waitFor(() => …) based on a mock call to ensure the async task ran.
There was a problem hiding this comment.
Fixed this duplicate case as well. Same change: advance the Vitest fake clock with vi.advanceTimersByTimeAsync(100) instead of awaiting a real setTimeout while fake timers are active.
There was a problem hiding this comment.
Fixed — replaced await new Promise(r => setTimeout(r, 100)) with await vi.advanceTimersByTimeAsync(100) under fake timers.
| mod.initSubagentRegistry(); | ||
|
|
||
| await new Promise((r) => setTimeout(r, 100)); | ||
|
|
||
| // sessions.delete SHOULD have been called for this old session | ||
| const deleteCalls = mocks.callGateway.mock.calls.filter( | ||
| (c: unknown[]) => | ||
| (c[0] as { method: string }).method === "sessions.delete" && | ||
| (c[0] as { params: { key: string } }).params.key === orphanKey, | ||
| ); | ||
| expect(deleteCalls).toHaveLength(1); | ||
| }); |
There was a problem hiding this comment.
Same fake-timer issue here: the test awaits a setTimeout-based delay while vi.useFakeTimers() is enabled, so the promise won’t resolve unless timers are advanced. Use vi.advanceTimersByTimeAsync/vi.runAllTimersAsync or vi.waitFor on an observable side-effect (e.g., callGateway call count) instead of real-time sleeps.
There was a problem hiding this comment.
Fixed. Replaced the fake-timer-hostile await new Promise((r) => setTimeout(r, 100)) with await vi.advanceTimersByTimeAsync(100) in this reconciliation test so it no longer hangs under vi.useFakeTimers().
There was a problem hiding this comment.
Fixed — replaced await new Promise(r => setTimeout(r, 100)) with await vi.advanceTimersByTimeAsync(100) under fake timers.
|
Closing this PR because it looks dirty (too many unrelated or unexpected changes). This usually happens when a branch picks up unrelated commits or a merge went sideways. Please recreate the PR from a clean branch. |
1 similar comment
|
Closing this PR because it looks dirty (too many unrelated or unexpected changes). This usually happens when a branch picks up unrelated commits or a merge went sideways. Please recreate the PR from a clean branch. |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 4de23e2b04
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| const requesterChannel = normalizeChannel(normalizedRequester.channel); | ||
| if (requesterChannel === "telegram") { | ||
| const requesterTarget = normalizeTelegramAnnounceTarget(normalizedRequester.to); | ||
| const entryTarget = normalizeTelegramAnnounceTarget(normalizedEntry?.to); | ||
| if (requesterTarget && entryTarget) { |
There was a problem hiding this comment.
Restore plugin thread-strip hook in announce origin
shouldStripThreadFromAnnounceEntry now only handles the Telegram special-case and otherwise always returns false, so channel plugins can no longer apply their conversationBindings.shouldStripThreadFromAnnounceOrigin logic. Any plugin that relied on that hook to clear stale thread IDs (for example when the requester target changed) will now preserve the old threadId and can deliver subagent completion messages into the wrong conversation thread.
Useful? React with 👍 / 👎.
| const resolved = resolveSessionKeyForRequest({ | ||
| cfg: params.config, | ||
| sessionId: params.sessionId, | ||
| }); |
There was a problem hiding this comment.
Include agentId when backfilling session keys
The new backfillSessionKey path resolves a key from sessionId without passing agentId, so requests for non-main agents that omit sessionKey can be backfilled to a main-agent explicit key. In that case the run proceeds with the wrong session scope (lane/workspace/hooks/compaction metadata tied to another agent), which can mix state across agents instead of staying agent-local.
Useful? React with 👍 / 👎.
|
Refreshed the original branch on current What is in scope on the refreshed branch now:
What is intentionally out of scope on this branch:
Those sweep/delete retry changes now live on open PR #61801. Targeted validation on the refreshed branch:
I also tried reopening this PR after restoring the branch, but GitHub returned |
Problem
Fixes #49000
When
sweepSubagentRuns()runs, it:sessions.deleteviacallGateway()try/catch {}that silently swallows all errorsIf the gateway is temporarily unavailable (restart, timeout, connection issue), the run record is gone but the
sessions.jsonentry persists forever with no retry path.On a system with
archiveAfterMinutes: 720we observed 5 orphaned session store entries aged 3–40 hours with no corresponding runs.json record.Changes
Fix 1 —
sweepSubagentRuns(): delete run record only after successfulsessions.deleteMove
subagentRuns.delete(runId)to after thesessions.deletecall succeeds. On failure, log a warning andcontinueto the next entry — the run record is preserved and the next sweep interval will retry automatically.Before (buggy): run record removed first, then session.delete called, errors swallowed silently.
After (fixed): session.delete called first; on error, log warning + continue (retry next interval); run record only removed on success.
Fix 2 —
reconcileOrphanedSessionStoreEntries(): startup cleanup of pre-existing orphansNew async function called from
initSubagentRegistry(). On startup, after run records are restored from disk, it:childSessionKeyvalues from runs.jsonisSubagentSessionKey)sessions.deleteThis handles the backlog of orphans that accumulated before this fix was deployed, and serves as a safety net for any future edge cases.
Testing
tsc --noEmit: clean)resolveSubagentRunOrphanReason()(same store loading, same key resolution)reconcileOrphanedSessionStoreEntrieswraps all store reads and gateway calls in try/catch so startup is never blocked or broken