Skip to content

feat(infra): add active turn tracker to recover from silent failures after gateway restart - #41248

Closed
ryan-mt wants to merge 3 commits into
openclaw:mainfrom
ryan-mt:fix/active-turn-recovery
Closed

ryan-mt wants to merge 3 commits into
openclaw:mainfrom
ryan-mt:fix/active-turn-recovery

Conversation

@ryan-mt

@ryan-mt ryan-mt commented Mar 9, 2026

Copy link
Copy Markdown

Summary

When the gateway restarts (crash, SIGUSR1, or compaction failure), in-flight embedded PI runs are lost because ACTIVE_EMBEDDED_RUNS is an in-memory Map. This leaves users in a silent state where the bot never responds until the user sends a new message.

This PR adds a 2-layer defense:

  1. Disk-backed active turn tracker (src/infra/active-turns.ts) — writes marker files to ~/.openclaw/active-turns/{sessionId}.json when a turn starts, removes them when it completes. On startup, server-active-turn-recovery.ts scans for stale markers and sends a recovery message to the user via the same delivery resolution chain used by the restart sentinel.

  2. Stuck turn watchdog (src/infra/stuck-turn-watchdog.ts) — periodic check (every 2 minutes) that cross-references disk markers against in-memory runs. Cleans orphaned markers (disk exists but no in-memory run) and aborts turns stuck >20 minutes.

Design decisions

  • Fire-and-forget writes: marker I/O never blocks the hot path (async write, sync-free on the streaming path)
  • Atomic writes: tmp file + rename to prevent partial reads
  • Consume-then-process: markers are cleared before delivery attempt to prevent infinite retry loops
  • Probe session filtering: sessions with probe- prefix are skipped (health checks)
  • Follows existing patterns: reuses the same delivery context resolution chain as server-restart-sentinel.ts
  • Dynamic imports in startup: avoids oxfmt stripping unused static imports

Files changed

File Change
src/infra/active-turns.ts New — marker file I/O (write/clear/load/remove)
src/infra/stuck-turn-watchdog.ts New — periodic watchdog with configurable thresholds
src/gateway/server-active-turn-recovery.ts New — startup recovery that delivers notification to interrupted users
src/agents/pi-embedded-runner/runs.ts Modified — hooks writeActiveTurn / clearActiveTurn into set/clear lifecycle
src/gateway/server-startup.ts Modified — wires recovery + watchdog on startup (dynamic import, test-guarded)
src/infra/active-turns.test.ts New — 9 unit tests
src/infra/active-turns-crash-scenarios.test.ts New — 8 crash scenario tests
src/infra/stuck-turn-watchdog.test.ts New — 5 watchdog tests

Test plan

  • 22 tests covering unit, crash scenarios, and watchdog behavior
  • Crash recovery: marker survives process exit, detected on next startup
  • Clean completion: marker removed, no false positive recovery
  • Concurrent turns: independent tracking per session
  • Rapid write-clear cycles: no stale markers left behind
  • Watchdog cleans orphaned markers and aborts stuck turns
  • Probe sessions excluded from tracking
  • Manual: kill gateway mid-conversation, restart, verify recovery message delivered
  • Manual: trigger compaction failure, verify watchdog detects and aborts

…after gateway restart

Add a disk-backed active turn tracker that persists in-flight agent session
markers. On unclean restart or crash, stale markers are detected and the
affected user receives a recovery notification. A stuck turn watchdog runs
every 2 minutes and aborts turns that exceed 20 minutes.

New modules:
- src/infra/active-turns.ts: marker file I/O (write/clear/load)
- src/gateway/server-active-turn-recovery.ts: startup recovery
- src/infra/stuck-turn-watchdog.ts: periodic stuck turn detection

Modified:
- src/agents/pi-embedded-runner/runs.ts: hook writeActiveTurn/clearActiveTurn
- src/gateway/server-startup.ts: wire recovery + watchdog after startup
Copilot AI review requested due to automatic review settings March 9, 2026 16:27
@greptile-apps

greptile-apps Bot commented Mar 9, 2026

Copy link
Copy Markdown
Contributor

Greptile Summary

This PR adds a 2-layer disk-backed defense against silent failures from gateway restarts: an active turn marker system (active-turns.ts) that persists per-session state files across crashes, a startup recovery pass (server-active-turn-recovery.ts) that detects and notifies users of interrupted turns, and a periodic watchdog (stuck-turn-watchdog.ts) that prunes stale markers and aborts genuinely stuck turns. The design choices (atomic writes, consume-then-process, probe session filtering, timer.unref()) are thoughtful and the 22-test suite gives solid coverage of the intended scenarios.

Key issues found:

  • Race condition in write/clear lifecycle (src/infra/active-turns.ts): writeActiveTurn is a multi-step async chain (mkdir → writeFile(tmp) → rename), while clearActiveTurn fires a single unlink. On fast turns, the unlink can complete (ENOENT, silently swallowed) before the rename finishes, leaving a permanent stale marker. On the next gateway startup, recoverInterruptedTurns will find this orphan and send a spurious "please resend" notification to a user whose turn already completed. The Scenario 7 test masks this with explicit 300 ms delays between writes and clears.
  • shouldRecoverInterruptedTurns() is dead code (src/gateway/server-active-turn-recovery.ts): The function is exported but never called; server-startup.ts duplicates the same guard inline instead of calling it.
  • startedAt not validated as a number (src/infra/active-turns.ts): loadActiveTurnMarkers validates sessionId and sessionKey but not startedAt. A marker missing this field produces NaN elapsed times in the watchdog, silently bypassing both the warn and abort thresholds.

Confidence Score: 3/5

  • Safe to merge with low risk, but the write/clear race condition can produce spurious recovery notifications for users whose turns completed normally.
  • The overall architecture is sound and well-tested, but the fire-and-forget write/clear race condition is a real production bug: fast turns can leave stale markers that trigger false "please resend" messages on the next restart. The other two issues (dead export, missing startedAt validation) are minor. The race condition should be addressed before this ships to avoid user-visible false positives.
  • src/infra/active-turns.ts — race condition between writeActiveTurn and clearActiveTurn needs resolution before the marker system can be trusted for all turn durations.

Last reviewed commit: 34c532f

Comment thread src/infra/active-turns.ts Resolved
Comment thread src/infra/active-turns.ts Resolved

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

This PR adds a 2-layer defense mechanism to recover from silent failures when the gateway crashes or restarts with in-flight embedded PI runs. When a turn is active, a marker file is written to disk; on startup, stale markers are detected and recovery notifications are sent to users. A periodic watchdog also monitors for stuck turns and stale markers at runtime.

Changes:

  • New disk-backed active turn tracker (active-turns.ts) with fire-and-forget marker file I/O using atomic tmp+rename writes, plus a startup recovery module (server-active-turn-recovery.ts) that delivers notifications for interrupted turns.
  • New stuck-turn watchdog (stuck-turn-watchdog.ts) that periodically cross-references disk markers against in-memory runs, cleaning orphans and aborting turns stuck >20 minutes.
  • Integration into the gateway lifecycle: runs.ts hooks marker write/clear into the embedded run set/clear lifecycle, and server-startup.ts wires recovery + watchdog on startup.

Reviewed changes

Copilot reviewed 8 out of 8 changed files in this pull request and generated 5 comments.

Show a summary per file
File Description
src/infra/active-turns.ts New: marker file I/O — write, clear, load, remove turn markers with path sanitization and probe filtering
src/infra/stuck-turn-watchdog.ts New: periodic watchdog that detects stale/stuck turns via disk marker + in-memory run cross-referencing
src/gateway/server-active-turn-recovery.ts New: startup recovery that sends notifications to users for interrupted turns using the outbound delivery chain
src/agents/pi-embedded-runner/runs.ts Modified: hooks writeActiveTurn/clearActiveTurn into set/clear embedded run lifecycle
src/gateway/server-startup.ts Modified: wires recovery + watchdog on startup with dynamic imports and a 1500ms delay
src/infra/active-turns.test.ts New: 9 unit tests for marker I/O
src/infra/active-turns-crash-scenarios.test.ts New: 8 crash scenario tests
src/infra/stuck-turn-watchdog.test.ts New: 5 watchdog tests

Comment thread src/infra/active-turns.ts Resolved
Comment thread src/gateway/server-startup.ts Resolved
Comment thread src/infra/active-turns.ts Resolved

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 34c532fa6b

ℹ️ About Codex in GitHub

Codex has been enabled to automatically 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 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

Comment thread src/infra/active-turns.ts Resolved
Comment thread src/infra/active-turns.ts Resolved

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: bc80d844a4

ℹ️ About Codex in GitHub

Codex has been enabled to automatically 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 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

Comment thread src/infra/active-turns.ts
Comment on lines +75 to +78
const pending = pendingWrites.get(sessionId);
const doUnlink = () => fs.promises.unlink(filePath).catch(() => {});
if (pending) {
void pending.then(doUnlink);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Prevent clear from deleting a newer run marker

clearActiveTurn captures the current pending write and unlinks afterward without re-checking whether a newer writeActiveTurn has started for the same sessionId; if a turn ends and a new turn starts quickly, the old clear path can delete the new marker file, so the currently active run is no longer crash-recoverable or watchdog-visible. This race is separate from the write-before-clear case because it occurs when a newer write starts after clearActiveTurn has already scheduled its unlink.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed — clearActiveTurn now captures writeGeneration at call time and checks it before unlinking. If a newer writeActiveTurn bumped the generation, the unlink is skipped. Test added (Scenario 8).

Comment on lines +36 to +40
for (const marker of markers) {
// Always clear the marker first (consume-then-process pattern) to prevent
// infinite retry loops if the gateway crashes again during recovery.
await removeActiveTurnMarker(marker.sessionId);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Skip startup recovery for runs that are already active

This loop consumes every marker unconditionally, but startup schedules recovery with a 1.5s delay after channel startup (src/gateway/server-startup.ts), so a user message received during that window can create a fresh marker that gets misclassified as "interrupted" here. The code then removes that live marker and sends a false recovery prompt, and the active turn loses disk tracking until another write happens.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed — recoverInterruptedTurns now checks isEmbeddedPiRunActive() before processing each marker. Live runs are skipped.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: c81f81e11f

ℹ️ About Codex in GitHub

Codex has been enabled to automatically 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 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

})
.finally(() => {
void import("../infra/stuck-turn-watchdog.js").then(({ startStuckTurnWatchdog }) => {
startStuckTurnWatchdog({ deps: params.deps });

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Stop watchdog interval when gateway lifecycle closes

startGatewaySidecars calls startStuckTurnWatchdog but discards the returned stop handle, so shutdown has no way to clear that interval. In the in-process restart path (src/cli/gateway-cli/run-loop.ts, where restart falls back without exiting), sidecars are started again and another watchdog timer is added, causing duplicate marker scans/abort attempts and accumulating background work after each restart.

Useful? React with 👍 / 👎.


// Always clear the marker first (consume-then-process pattern) to prevent
// infinite retry loops if the gateway crashes again during recovery.
await removeActiveTurnMarker(marker.sessionId);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Revalidate activity before deleting startup recovery marker

The loop checks isEmbeddedPiRunActive and then immediately awaits removeActiveTurnMarker, but a new run for the same sessionId can start between those two steps and have its fresh marker unlinked. That race leads to a false "interrupted" recovery notification and removes crash-recovery/watchdog visibility for the now-active run, especially since recovery is intentionally delayed after channel startup.

Useful? React with 👍 / 👎.

@openclaw-barnacle openclaw-barnacle Bot added gateway Gateway runtime agents Agent runtime and tooling size: L r: too-many-prs Auto-close: author has more than twenty active PRs. labels Mar 9, 2026
@openclaw-barnacle

Copy link
Copy Markdown

Closing this PR because the author has more than 10 active PRs in this repo. Please reduce the active PR queue and reopen or resubmit once it is back under the limit. You can close your own PRs to get back under the limit.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling gateway Gateway runtime r: too-many-prs Auto-close: author has more than twenty active PRs. size: L

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants