Skip to content

feat(gateway): queue inbound messages during drain and recover interrupted turns on restart - #49407

Closed
amittell wants to merge 1 commit into
openclaw:mainfrom
amittell:feat/inbound-drain-queue-v3
Closed

amittell wants to merge 1 commit into
openclaw:mainfrom
amittell:feat/inbound-drain-queue-v3

Conversation

@amittell

Copy link
Copy Markdown
Contributor

Summary

Closes and supersedes #41597 (rebased onto current upstream/main).

Adds a pending-inbound store and active-turn tracking to support lossless gateway restarts and crash recovery. When the gateway restarts, messages that were queued before the shutdown are re-delivered, and interrupted turns can be recovered.

Changes

Core infrastructure

  • src/infra/pending-inbound-store.ts (new): File-backed store with two tables:
    • pending-inbound: written by channel plugins before processing; cleared on delivery
    • active-turn: written at turn start; cleared on completion (for crash recovery)
  • src/infra/pending-inbound-store.test.ts (new): Full test coverage

Gateway startup recovery

  • src/gateway/server-startup.ts: On startup, read pending-inbound store and re-deliver any messages queued before the shutdown; read active-turn records to recover interrupted session state

Supporting changes

  • src/infra/system-events.ts: ActiveTurnState events for turn lifecycle
  • src/process/command-queue.ts: Drain lifecycle integration
  • src/infra/json-files.ts: Atomic JSON file helpers
  • src/agents/pi-embedded-runner/run/attempt.ts: Write active-turn record before run; clear on completion

Note

Channel-specific drain routing (telegram topic/replyThreadId passthrough) will follow as a separate commit once ported to the current extensions/telegram/ layout.

…upted turns on restart

Adds a pending-inbound store and active-turn tracking to support lossless
gateway restarts and crash recovery.

Key changes:
- src/infra/pending-inbound-store.ts: file-backed store for pending inbound
  messages (written by channel plugins before processing, cleared on delivery)
  and active-turn records (written at turn start, cleared on completion)
- src/gateway/server-startup.ts: on startup, read pending-inbound store and
  deliver any unprocessed messages queued before restart; read active-turn
  records to recover interrupted turns
- src/infra/system-events.ts: ActiveTurnState events for turn lifecycle tracking
- src/process/command-queue.ts: integrate with drain lifecycle
- src/infra/json-files.ts: atomic JSON file helpers used by pending-inbound store
- src/agents/pi-embedded-runner/run/attempt.ts: write active-turn record before
  run starts; clear on completion (for crash recovery)

Note: Channel-specific drain routing (telegram topic/thread replyThreadId
passthrough) will be applied separately as it requires porting to the current
extensions/telegram/ layout.
Copilot AI review requested due to automatic review settings March 18, 2026 03:25
@aisle-research-bot

aisle-research-bot Bot commented Mar 18, 2026 •

Copy link
Copy Markdown

🔒 Aisle Security Analysis

We found 2 potential security issue(s) in this PR:

# Severity Title
1 🔵 Low Symlink-following chmod in atomic writer can change permissions of attacker-chosen directory
2 🔵 Low Prototype pollution via attacker-controlled sessionId in active-turn on-disk store

1. 🔵 Symlink-following chmod in atomic writer can change permissions of attacker-chosen directory

Property Value
Severity Low
CWE CWE-59
Location src/infra/json-files.ts:39-46

Description

writeTextAtomic() now calls fs.chmod(path.dirname(filePath), ensureDirMode) after fs.mkdir(..., { recursive: true }).

On POSIX platforms, chmod(2) follows symlinks (Node’s fs.chmod() does not provide a no-follow guarantee), so if an attacker can influence filePath or can create/replace a path component (e.g., the leaf directory) with a symlink, the gateway may chmod the symlink target rather than the intended state directory.

Impact depends on deployment, but can include:

  • Arbitrary permission changes on directories writable/owned by the gateway user (or worse, if running with elevated privileges).
  • Local DoS / data loss by locking down permissions (e.g., chmod to 0o700) on an unexpected directory.

Vulnerable code (new behavior):

await fs.mkdir(path.dirname(filePath), mkdirOptions);
if (typeof options?.ensureDirMode === "number") {
  try {
    await fs.chmod(path.dirname(filePath), options.ensureDirMode);
  } catch {
    ​// ignore
  }
}

This is a classic link-following / TOCTOU class issue when directory paths are not guaranteed to be trusted and immutable.

Recommendation

Avoid chmod’ing a path that could be a symlink, and (where possible) constrain writes to a trusted root.

Minimum hardening:

  1. Detect and refuse symlink directories before chmod:
const dir = path.dirname(filePath);
const st = await fs.lstat(dir);
if (st.isSymbolicLink()) {
  throw new Error(`Refusing to chmod symlink directory: ${dir}`);
}
if (!st.isDirectory()) {
  throw new Error(`Expected directory for atomic write: ${dir}`);
}
await fs.chmod(dir, options.ensureDirMode);
  1. If filePath should always live under a specific trusted directory (e.g., resolved state dir), enforce containment using realpath:
const root = await fs.realpath(trustedRoot);
const dirReal = await fs.realpath(path.dirname(filePath));
if (!dirReal.startsWith(root + path.sep)) {
  throw new Error("Refusing to chmod/write outside trusted root");
}
  1. Consider only applying chmod when you are confident you just created the directory (or document that filePath must be trusted and not attacker-controlled).

These changes reduce symlink/hardlink and TOCTOU risk around permission-setting operations.


2. 🔵 Prototype pollution via attacker-controlled sessionId in active-turn on-disk store

Property Value
Severity Low
CWE CWE-1321
Location src/infra/pending-inbound-store.ts:234-239

Description

The active-turn tracking store uses a plain object ({}) as a dictionary and indexes it with entry.sessionId.

  • sessionId can be supplied by gateway API callers (e.g. agent RPC takes sessionId?: string with no key restrictions) and is forwarded into runEmbeddedAttempt.
  • writeActiveTurn() assigns existing.activeTurns[entry.sessionId] = entry on a normal object.
  • If an attacker uses a special key such as "__proto__", this triggers JavaScript's __proto__ setter and mutates the prototype of activeTurns (prototype pollution).
  • This can corrupt in-memory state during the locked read-modify-write, potentially causing incorrect pruning/serialization or other logic issues, and is a common class of vulnerability whenever untrusted keys are used on plain objects.

Vulnerable code:

if (!existing.activeTurns) {
  existing.activeTurns = {};
}
existing.activeTurns[entry.sessionId] = entry;

Recommendation

Prevent prototype pollution by not using plain objects with untrusted keys.

Recommended fixes (pick one):

  1. Use a null-prototype dictionary and validate reserved keys:
const FORBIDDEN_KEYS = new Set(["__proto__", "prototype", "constructor"]);

function assertSafeKey(key: string) {
  if (FORBIDDEN_KEYS.has(key)) {
    throw new Error(`invalid sessionId key`);
  }
}

​// When creating:
existing.activeTurns = Object.create(null) as Record<string, ActiveTurnEntry>;

​// Before setting:
assertSafeKey(entry.sessionId);
existing.activeTurns[entry.sessionId] = entry;
  1. Alternatively, store activeTurns as an array of entries (and search by sessionId), or use a Map internally and serialize safely.

Also consider applying the same protection to any other record-like objects keyed by identifiers coming from requests or external systems.


Analyzed PR: #49407 at commit c4b49d2

Last updated on: 2026-03-18T04:21:22Z

@openclaw-barnacle openclaw-barnacle Bot added gateway Gateway runtime agents Agent runtime and tooling size: XL r: too-many-prs Auto-close: author has more than twenty active PRs. labels Mar 18, 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.

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

Adds crash/restart resilience by persisting (a) inbound messages captured during gateway drain and (b) in-flight “active turns”, then replaying/notifying on startup.

Changes:

  • Export gateway draining state and system event queue cap (MAX_EVENTS) for reuse.
  • Introduce pending-inbound-store (disk-backed pending inbound + active turn tracking) with extensive tests.
  • Harden atomic JSON/text writes (directory/file permissions) and add startup replay + stale-turn recovery flows.

Reviewed changes

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

Show a summary per file
File Description
src/process/command-queue.ts Exposes isGatewayDraining() to query restart-drain state.
src/infra/system-events.ts Exports MAX_EVENTS so other modules can cap per-session queues consistently.
src/infra/system-events.test.ts Updates tests to align with MAX_EVENTS export and dedupe/cap behavior.
src/infra/pending-inbound-store.ts New disk-backed store for drain-captured inbound messages + active turn crash recovery.
src/infra/pending-inbound-store.test.ts Adds coverage for persistence, dedupe, pruning, concurrency, and permissions.
src/infra/json-files.ts Improves permission enforcement for atomic writes (dir chmod + temp-file mode).
src/gateway/server-startup.ts Replays pending inbound system events before channels start; recovers stale active turns after startup.
src/agents/pi-embedded-runner/run/attempt.ts Persists/clears active turn records around embedded runs for crash recovery.

const rawSenderLabel =
payload.senderName ?? payload.senderUsername ?? payload.senderId ?? "unknown";
const senderLabel = sanitizeInboundSystemTags(String(rawSenderLabel));
const rawPreview = (payload.text ?? "").slice(0, 200).replace(/\n/g, "\\n");

/**
* Remove the pending inbound file entirely.
* @deprecated Use `clearPendingInboundEntries` or `clearActiveTurns` to avoid
Comment on lines +648 to +677
it("pending-inbound.json is written with mode 0o600", async () => {
await writePendingInbound(stateDir, {
channel: "telegram",
id: "perm-test-1",
payload: { text: "secret" },
capturedAt: Date.now(),
});

const filePath = path.join(stateDir, "pending-inbound.json");
const stat = await fsp.stat(filePath);
// Mask to the low 9 permission bits (strip file type bits)
const mode = stat.mode & 0o777;
expect(mode).toBe(0o600);
});

it("state dir is created with mode 0o700", async () => {
// Use a sub-directory that does not yet exist
const subDir = path.join(stateDir, "sub-state-dir");

await writePendingInbound(subDir, {
channel: "telegram",
id: "perm-test-2",
payload: { text: "secret" },
capturedAt: Date.now(),
});

const stat = await fsp.stat(subDir);
const mode = stat.mode & 0o777;
expect(mode).toBe(0o700);
});
@greptile-apps

greptile-apps Bot commented Mar 18, 2026

Copy link
Copy Markdown
Contributor

Greptile Summary

This PR introduces a lossless gateway restart mechanism by adding a file-backed pending-inbound-store.ts with two tables — one for messages captured during drain and one for active turns — plus startup recovery logic in server-startup.ts that replays queued messages and notifies users of interrupted turns.

The core infrastructure (store design, atomic writes, file-lock + in-process queue composition, pruning, and the attempt.ts integration) is well-executed. Key concerns:

  • P1 – Stale-turn recovery runs after startChannels(): The pending-inbound replay block is correctly placed before channels start, but the active-turn recovery block runs after. Between the readActiveTurn re-validation and the clearActiveTurn call, a fast inbound message handled by an already-live channel could write a fresh active-turn entry under the same sessionId, which the recovery loop would then incorrectly delete. Moving the recovery block before startChannels() would close this race without any other changes.
  • P2 – clearActiveTurn unnecessary write: When called with a sessionId that is absent from activeTurns, the function still acquires the file lock, reads, and rewrites the file unchanged. Adding an early-return guard (if (!(sessionId in existing.activeTurns)) return) removes the wasted I/O.
  • P2 – Test coverage regression in system-events.test.ts: Tests for isSystemEventContextChanged, drainSystemEventEntries, hasSystemEvents, and peekSystemEventEntries are removed, but all four functions remain exported and in active use. Keeping or migrating those test cases would preserve the existing coverage baseline.

Confidence Score: 3/5

  • Mergeable with caution — the stale-turn recovery placement after channel startup introduces a narrow but real race condition that could silently delete a live active-turn record.
  • The core store infrastructure and attempt.ts integration are solid. The P1 concern (stale-turn recovery running after channels are live) is a genuine race condition whose probability is low in practice but non-zero — a fast channel that starts processing a message before the recovery loop finishes could have its active-turn record incorrectly cleared. The test coverage regression for system-events functions and the minor clearActiveTurn unnecessary-write issue are worth addressing before merge, but are not blocking on their own.
  • Pay close attention to src/gateway/server-startup.ts (stale-turn recovery block placement relative to startChannels()) and src/infra/pending-inbound-store.ts (clearActiveTurn early-return guard).
Prompt To Fix All With AI
This is a comment left during a code review.
Path: src/infra/pending-inbound-store.ts
Line: 247-260

Comment:
**Unnecessary file write when entry is absent**

`clearActiveTurn` takes out a file lock, reads the file, performs a no-op `delete`, and writes the file back unchanged whenever `activeTurns` exists but doesn't contain the target `sessionId`. This shows up on every normal turn completion path (the `finally` block in `attempt.ts`) if `writeActiveTurn` previously failed and never persisted an entry.

Adding an early-return guard avoids the wasted I/O:

```suggestion
      const existing = await readPendingInboundFile(filePath);
      if (!existing.activeTurns || !(entry.sessionId in existing.activeTurns)) {
        return; // nothing to clear
      }
      delete existing.activeTurns[sessionId];
```

Actually, since the parameter name is `sessionId` not `entry.sessionId`, the fix should be:

```
      if (!existing.activeTurns || !(sessionId in existing.activeTurns)) {
        return; // nothing to clear
      }
```

How can I resolve this? If you propose a fix, please make it concise.

---

This is a comment left during a code review.
Path: src/infra/system-events.test.ts
Line: 4-11

Comment:
**Test coverage regression for retained exports**

This PR removes tests for `isSystemEventContextChanged`, `drainSystemEventEntries`, `hasSystemEvents`, and `peekSystemEventEntries`. All four functions are still exported from `system-events.ts` and remain part of the public API used by the rest of the codebase.

The deleted test cases covered meaningful behaviour: context-key normalisation (`isSystemEventContextChanged`), clone-on-drain and duplicate-reset semantics (`drainSystemEventEntries`), and event presence (`hasSystemEvents` / `peekSystemEventEntries`). Removing them leaves a gap that makes it easier for regressions in those functions to go undetected.

Consider keeping the existing tests alongside the new ones, or migrating them to a dedicated `system-events-legacy.test.ts` if the file felt too large.

How can I resolve this? If you propose a fix, please make it concise.

---

This is a comment left during a code review.
Path: src/gateway/server-startup.ts
Line: 264-361

Comment:
**Stale-turn recovery runs after `startChannels()`, creating a narrow TOCTOU window**

The pending-inbound replay block correctly runs *before* `startChannels()`, but the stale active-turn recovery block runs *after* channels are already live. Once `startChannels()` returns, a fast inbound message could trigger `writeActiveTurn` for a session whose stale record is still being processed by the recovery loop. The re-validation (`readActiveTurn`) and the subsequent `clearActiveTurn` are not atomic — if a fresh `writeActiveTurn` from the new channel handler completes between those two calls (both async awaits), the recovery loop will delete the new, live entry.

The `processStartedAt` guard at the top of the loop handles the most common case (turns where `startedAt >= processStartedAt`), but is not a complete fence: `writeActiveTurn` uses `Date.now()` at call time, which must be called *after* `processStartedAt` was captured for the guard to fire. If a very fast channel handler writes its turn before the loop reaches that `sessionId`, and the clock hasn't advanced enough, both `turn.startedAt` (stale snapshot) and the fresh entry's `startedAt` could compare equal, causing the guard to pass and the live entry to be silently cleared.

Moving the entire stale-turn recovery block to *before* `startChannels()` — similar to the pending-inbound replay — would eliminate the race entirely without requiring any logic changes.

How can I resolve this? If you propose a fix, please make it concise.

Last reviewed commit: "feat(gateway): queue..."

Comment on lines +247 to +260
for (let i = 0; i < pruneCount; i++) {
delete existing.activeTurns[sorted[i]];
}
}
await writeJsonAtomic(filePath, existing, {
mode: 0o600,
trailingNewline: true,
ensureDirMode: 0o700,
});
}),
);
}

/**

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 Unnecessary file write when entry is absent

clearActiveTurn takes out a file lock, reads the file, performs a no-op delete, and writes the file back unchanged whenever activeTurns exists but doesn't contain the target sessionId. This shows up on every normal turn completion path (the finally block in attempt.ts) if writeActiveTurn previously failed and never persisted an entry.

Adding an early-return guard avoids the wasted I/O:

Suggested change
for (let i = 0; i < pruneCount; i++) {
delete existing.activeTurns[sorted[i]];
}
}
await writeJsonAtomic(filePath, existing, {
mode: 0o600,
trailingNewline: true,
ensureDirMode: 0o700,
});
}),
);
}
/**
const existing = await readPendingInboundFile(filePath);
if (!existing.activeTurns || !(entry.sessionId in existing.activeTurns)) {
return; // nothing to clear
}
delete existing.activeTurns[sessionId];

Actually, since the parameter name is sessionId not entry.sessionId, the fix should be:

      if (!existing.activeTurns || !(sessionId in existing.activeTurns)) {
        return; // nothing to clear
      }
Prompt To Fix With AI
This is a comment left during a code review.
Path: src/infra/pending-inbound-store.ts
Line: 247-260

Comment:
**Unnecessary file write when entry is absent**

`clearActiveTurn` takes out a file lock, reads the file, performs a no-op `delete`, and writes the file back unchanged whenever `activeTurns` exists but doesn't contain the target `sessionId`. This shows up on every normal turn completion path (the `finally` block in `attempt.ts`) if `writeActiveTurn` previously failed and never persisted an entry.

Adding an early-return guard avoids the wasted I/O:

```suggestion
      const existing = await readPendingInboundFile(filePath);
      if (!existing.activeTurns || !(entry.sessionId in existing.activeTurns)) {
        return; // nothing to clear
      }
      delete existing.activeTurns[sessionId];
```

Actually, since the parameter name is `sessionId` not `entry.sessionId`, the fix should be:

```
      if (!existing.activeTurns || !(sessionId in existing.activeTurns)) {
        return; // nothing to clear
      }
```

How can I resolve this? If you propose a fix, please make it concise.

Comment on lines 4 to 11
import { resolveMainSessionKey } from "../config/sessions.js";
import { isCronSystemEvent } from "./heartbeat-runner.js";
import {
drainSystemEventEntries,
enqueueSystemEvent,
hasSystemEvents,
isSystemEventContextChanged,
peekSystemEventEntries,
MAX_EVENTS,
peekSystemEvents,
resetSystemEventsForTest,
} from "./system-events.js";

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 Test coverage regression for retained exports

This PR removes tests for isSystemEventContextChanged, drainSystemEventEntries, hasSystemEvents, and peekSystemEventEntries. All four functions are still exported from system-events.ts and remain part of the public API used by the rest of the codebase.

The deleted test cases covered meaningful behaviour: context-key normalisation (isSystemEventContextChanged), clone-on-drain and duplicate-reset semantics (drainSystemEventEntries), and event presence (hasSystemEvents / peekSystemEventEntries). Removing them leaves a gap that makes it easier for regressions in those functions to go undetected.

Consider keeping the existing tests alongside the new ones, or migrating them to a dedicated system-events-legacy.test.ts if the file felt too large.

Prompt To Fix With AI
This is a comment left during a code review.
Path: src/infra/system-events.test.ts
Line: 4-11

Comment:
**Test coverage regression for retained exports**

This PR removes tests for `isSystemEventContextChanged`, `drainSystemEventEntries`, `hasSystemEvents`, and `peekSystemEventEntries`. All four functions are still exported from `system-events.ts` and remain part of the public API used by the rest of the codebase.

The deleted test cases covered meaningful behaviour: context-key normalisation (`isSystemEventContextChanged`), clone-on-drain and duplicate-reset semantics (`drainSystemEventEntries`), and event presence (`hasSystemEvents` / `peekSystemEventEntries`). Removing them leaves a gap that makes it easier for regressions in those functions to go undetected.

Consider keeping the existing tests alongside the new ones, or migrating them to a dedicated `system-events-legacy.test.ts` if the file felt too large.

How can I resolve this? If you propose a fix, please make it concise.

Comment on lines 264 to 361
);
}

// Recover stale active turns — runs that were in-flight when the process died.
// Notify the originating session so the user knows to resend.
try {
const stateDir = resolveStateDir(process.env);
const staleTurns = await readStaleActiveTurns(stateDir);
if (staleTurns.length > 0) {
params.log.warn(
`active-turn recovery: found ${staleTurns.length} stale turn(s) from previous process`,
);
for (const turn of staleTurns) {
// Skip turns started by THIS process — they raced ahead of the
// recovery loop (channel startup created a new turn before we got
// here). Only turns from the PREVIOUS process are truly stale.
if (turn.startedAt >= processStartedAt) {
params.log.warn(
`active-turn recovery: skipping live turn ${turn.sessionId} (startedAt=${turn.startedAt} >= processStartedAt=${processStartedAt})`,
);
continue;
}

// Re-validate the current store entry before clearing. Between the
// snapshot (readStaleActiveTurns) and now, a fresh turn could have
// been written under the same sessionId — e.g. if a channel handler
// started a new turn whose sessionId collides with a stale one.
// Only clear if the on-disk entry still has the same startedAt we
// saw in the snapshot (i.e. it has NOT been refreshed by this process).
const currentEntry = await readActiveTurn(stateDir, turn.sessionId);
if (!currentEntry) {
// Already cleared by something else — nothing to do.
continue;
}
if (currentEntry.startedAt !== turn.startedAt) {
// A fresh turn was written under the same sessionId after our snapshot.
// The startedAt guard above already protects against this case when the
// new turn's startedAt >= processStartedAt, but a recycled sessionId
// whose new startedAt still happens to be < processStartedAt (due to
// clock imprecision or test-injected timestamps) would slip through.
// Comparing startedAt values is the most reliable way to detect staleness.
params.log.warn(
`active-turn recovery: skipping refreshed turn ${turn.sessionId} (snapshot startedAt=${turn.startedAt}, current startedAt=${currentEntry.startedAt})`,
);
continue;
}

// Consume first to prevent infinite retry on crash.
await clearActiveTurn(stateDir, turn.sessionId);

// Skip probe sessions — they are synthetic health-check runs.
if (turn.sessionId.startsWith("probe-")) {
continue;
}

// Attempt to resolve a delivery target for the session. Sessions without
// a resolvable channel target (isolated scheduler sessions, orphaned sessions,
// or any session with no channel mapping) are skipped — the originating system
// (e.g. a scheduler's drain-retry) handles recovery for those.
const { baseSessionKey } = parseSessionThreadInfo(turn.sessionKey);
const parsedTarget = resolveAnnounceTargetFromKey(baseSessionKey ?? turn.sessionKey ?? "");
const { entry: turnEntry } = loadSessionEntry(turn.sessionKey ?? "");
let deliveryCtx = deliveryContextFromSession(turnEntry);
if (!deliveryCtx && baseSessionKey && baseSessionKey !== turn.sessionKey) {
const { entry: baseEntry } = loadSessionEntry(baseSessionKey);
deliveryCtx = deliveryContextFromSession(baseEntry);
}
const origin = mergeDeliveryContext(deliveryCtx, parsedTarget ?? undefined);
const resolvedChannel = origin?.channel ? normalizeChannelId(origin.channel) : null;
const resolvedTo = origin?.to;
if (!resolvedChannel || !resolvedTo) {
continue;
}

try {
const recoveryMessage =
"⚠️ I was restarted mid-conversation. Please resend your last message.";
enqueueSystemEvent(`[active-turn-recovery] ${recoveryMessage}`, {
sessionKey: turn.sessionKey,
contextKey: `active-turn-recovery:${turn.sessionId}`,
});
params.log.warn(
`active-turn recovery: notified session ${turn.sessionKey} (sessionId=${turn.sessionId}, channel=${turn.channel})`,
);
} catch (err) {
params.log.warn(
`active-turn recovery: notify failed for session ${turn.sessionKey}: ${String(err)}`,
);
}
}
}
} catch (err) {
params.log.warn(`active-turn recovery: startup failed: ${String(err)}`);
}

if (params.cfg.hooks?.internal?.enabled) {
setTimeout(() => {
const hookEvent = createInternalHookEvent("gateway", "startup", "gateway:startup", {

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 Stale-turn recovery runs after startChannels(), creating a narrow TOCTOU window

The pending-inbound replay block correctly runs before startChannels(), but the stale active-turn recovery block runs after channels are already live. Once startChannels() returns, a fast inbound message could trigger writeActiveTurn for a session whose stale record is still being processed by the recovery loop. The re-validation (readActiveTurn) and the subsequent clearActiveTurn are not atomic — if a fresh writeActiveTurn from the new channel handler completes between those two calls (both async awaits), the recovery loop will delete the new, live entry.

The processStartedAt guard at the top of the loop handles the most common case (turns where startedAt >= processStartedAt), but is not a complete fence: writeActiveTurn uses Date.now() at call time, which must be called after processStartedAt was captured for the guard to fire. If a very fast channel handler writes its turn before the loop reaches that sessionId, and the clock hasn't advanced enough, both turn.startedAt (stale snapshot) and the fresh entry's startedAt could compare equal, causing the guard to pass and the live entry to be silently cleared.

Moving the entire stale-turn recovery block to before startChannels() — similar to the pending-inbound replay — would eliminate the race entirely without requiring any logic changes.

Prompt To Fix With AI
This is a comment left during a code review.
Path: src/gateway/server-startup.ts
Line: 264-361

Comment:
**Stale-turn recovery runs after `startChannels()`, creating a narrow TOCTOU window**

The pending-inbound replay block correctly runs *before* `startChannels()`, but the stale active-turn recovery block runs *after* channels are already live. Once `startChannels()` returns, a fast inbound message could trigger `writeActiveTurn` for a session whose stale record is still being processed by the recovery loop. The re-validation (`readActiveTurn`) and the subsequent `clearActiveTurn` are not atomic — if a fresh `writeActiveTurn` from the new channel handler completes between those two calls (both async awaits), the recovery loop will delete the new, live entry.

The `processStartedAt` guard at the top of the loop handles the most common case (turns where `startedAt >= processStartedAt`), but is not a complete fence: `writeActiveTurn` uses `Date.now()` at call time, which must be called *after* `processStartedAt` was captured for the guard to fire. If a very fast channel handler writes its turn before the loop reaches that `sessionId`, and the clock hasn't advanced enough, both `turn.startedAt` (stale snapshot) and the fresh entry's `startedAt` could compare equal, causing the guard to pass and the live entry to be silently cleared.

Moving the entire stale-turn recovery block to *before* `startChannels()` — similar to the pending-inbound replay — would eliminate the race entirely without requiring any logic changes.

How can I resolve this? If you propose a fix, please make it concise.

@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: c4b49d2521

ℹ️ 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".

// is required at this point.
try {
const stateDir = resolveStateDir(process.env);
const pending = await readPendingInbound(stateDir);

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 Wire pending-inbound writes into the drain path

This startup replay path assumes inbound messages were persisted during shutdown drain, but in this commit there is still no production caller of writePendingInbound (repo-wide search in src/ and extensions/ only finds the declaration/tests). As a result, pending will remain empty here and messages arriving after markGatewayDraining() are still lost across restarts, so the new lossless-drain behavior does not actually activate.

Useful? React with 👍 / 👎.

Comment on lines +311 to +312
// Consume first to prevent infinite retry on crash.
await clearActiveTurn(stateDir, turn.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.

P1 Badge Atomically verify-and-clear stale active turns

The stale-turn check is not atomic: readActiveTurn and clearActiveTurn happen in separate awaited operations, so a new run can write a fresh record for the same sessionId in between (see writeActiveTurn usage in src/agents/pi-embedded-runner/run/attempt.ts). In that interleaving this code can delete the live record after passing the earlier startedAt comparison, which removes crash-recovery coverage for the active turn and can lead to incorrect recovery behavior.

Useful? React with 👍 / 👎.

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: XL

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants