Skip to content

fix(restart): wait for session event queue before clearing active run - #41547

Closed
pingfanfan wants to merge 1 commit into
openclaw:mainfrom
pingfanfan:codex/fix-restart-event-queue-drain-41538
Closed

pingfanfan wants to merge 1 commit into
openclaw:mainfrom
pingfanfan:codex/fix-restart-event-queue-drain-41538

Conversation

@pingfanfan

Copy link
Copy Markdown
Contributor

Summary

Fixes a restart race where embedded runs could be removed from the active-run registry before the pi-coding-agent session event queue had finished draining. That let update.run / gateway restart emit SIGUSR1 while transcript/session persistence was still settling.

Root cause

runEmbeddedAttempt() cleared ACTIVE_EMBEDDED_RUNS in its cleanup path immediately after unsubscribing. But AgentSession persists transcript/session updates through its internal _agentEventQueue, and that queue can still be draining after the run itself looks finished.

That meant restart deferral could observe getActiveEmbeddedRunCount() === 0 too early and restart the gateway before transcript writes had finished.

Changes

  • add waitForAgentSessionEventQueue() to wait for the pi-coding-agent session event queue to settle with a bounded timeout
  • call that drain helper in runEmbeddedAttempt() before clearActiveEmbeddedRun(...)
  • add unit coverage for the drain helper's normal, missing-queue, and timeout paths

Testing

  • corepack pnpm exec vitest run src/agents/pi-embedded-runner/session-event-queue.test.ts src/agents/pi-embedded-runner/run/attempt.test.ts src/agents/pi-embedded-runner/runs.test.ts
  • corepack pnpm exec oxlint --type-aware src/agents/pi-embedded-runner/run/attempt.ts src/agents/pi-embedded-runner/session-event-queue.ts src/agents/pi-embedded-runner/session-event-queue.test.ts

AI-assisted. I reviewed the changed code and ran the targeted tests and lint above locally.

Fixes #41538

@openclaw-barnacle openclaw-barnacle Bot added the agents Agent runtime and tooling label Mar 10, 2026
@greptile-apps

greptile-apps Bot commented Mar 10, 2026

Copy link
Copy Markdown
Contributor

Greptile Summary

This PR fixes a restart race condition where runEmbeddedAttempt() could remove a session from ACTIVE_EMBEDDED_RUNS before the pi-coding-agent internal _agentEventQueue had finished draining, allowing gateway restart to fire SIGUSR1 while transcript/session writes were still in-flight.

The fix introduces a new waitForAgentSessionEventQueue() helper that races the session's internal queue promise against a bounded 5 s timeout, and calls it inside the finally cleanup block of runEmbeddedAttempt() — after unsubscribe() but before clearActiveEmbeddedRun().

  • session-event-queue.ts: Clean, self-contained helper. Handles all expected edge cases (falsy session, no queue property, queue rejection via .catch(() => undefined), timeout via Promise.race). The clearTimeout in the finally block correctly prevents the timer from firing after the queue has already settled.
  • attempt.ts: Placement in the finally block is correct. The await in a finally is valid JS/TS and the helper is designed to never throw, so original exception propagation is unaffected.
  • session-event-queue.test.ts: Tests cover the three documented paths (normal, missing queue, timeout). One path — a rejecting queue — has defensive code in the implementation but no corresponding test case, leaving the .catch(() => undefined) guard unverified by the test suite.

Confidence Score: 4/5

  • Safe to merge; correctly fixes the race condition with no observable regressions.
  • The logic is sound, the helper is defensive, the placement in the finally block is correct, and three of four test paths are covered. The only gap is a missing test for a rejecting queue, which is a low-risk coverage omission rather than a functional bug.
  • src/agents/pi-embedded-runner/session-event-queue.test.ts — consider adding a rejected-queue test case.

Last reviewed commit: 4dc806c

Comment on lines +4 to +64
describe("waitForAgentSessionEventQueue", () => {
it("waits for the queued session event work to finish", async () => {
const resolved: string[] = [];
let releaseQueue: (() => void) | undefined;
const queue = new Promise<void>((resolve) => {
releaseQueue = () => {
resolved.push("queue");
resolve();
};
});

const waitPromise = waitForAgentSessionEventQueue({
session: { _agentEventQueue: queue },
onTimeout: () => {
resolved.push("timeout");
},
}).then(() => {
resolved.push("wait");
});

await Promise.resolve();
expect(resolved).toEqual([]);

releaseQueue?.();
await waitPromise;

expect(resolved).toEqual(["queue", "wait"]);
});

it("returns immediately when no event queue is exposed", async () => {
await expect(
waitForAgentSessionEventQueue({
session: {},
}),
).resolves.toBeUndefined();
});

it("times out instead of hanging forever on a stuck queue", async () => {
vi.useFakeTimers();
try {
const events: string[] = [];
const waitPromise = waitForAgentSessionEventQueue({
session: { _agentEventQueue: new Promise(() => {}) },
timeoutMs: 250,
onTimeout: () => {
events.push("timeout");
},
}).then(() => {
events.push("wait");
});

await vi.advanceTimersByTimeAsync(250);
await waitPromise;

expect(events).toEqual(["timeout", "wait"]);
} finally {
await vi.runOnlyPendingTimersAsync();
vi.useRealTimers();
}
});
});

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.

Missing test for rejected queue

waitForAgentSessionEventQueue explicitly guards against a rejecting queue with .catch(() => undefined) (line 27 of session-event-queue.ts), but there is no test covering that path. Without a test, a future refactor could silently remove that guard and introduce an unhandled rejection at cleanup time.

Consider adding a case like:

it("resolves without throwing when the event queue rejects", async () => {
  await expect(
    waitForAgentSessionEventQueue({
      session: { _agentEventQueue: Promise.reject(new Error("queue error")) },
    }),
  ).resolves.toBeUndefined();
});
Prompt To Fix With AI
This is a comment left during a code review.
Path: src/agents/pi-embedded-runner/session-event-queue.test.ts
Line: 4-64

Comment:
**Missing test for rejected queue**

`waitForAgentSessionEventQueue` explicitly guards against a rejecting queue with `.catch(() => undefined)` (line 27 of `session-event-queue.ts`), but there is no test covering that path. Without a test, a future refactor could silently remove that guard and introduce an unhandled rejection at cleanup time.

Consider adding a case like:

```ts
it("resolves without throwing when the event queue rejects", async () => {
  await expect(
    waitForAgentSessionEventQueue({
      session: { _agentEventQueue: Promise.reject(new Error("queue error")) },
    }),
  ).resolves.toBeUndefined();
});
```

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

@pingfanfan

Copy link
Copy Markdown
Contributor Author

Closing this to reduce my active PR queue and keep review load focused. I may resubmit later after the current set is resolved.

@pingfanfan pingfanfan closed this Mar 10, 2026
@benclawbot

Copy link
Copy Markdown

For skills not loading - check skill path exists and has SKILL.md file. Happy to help debug - email [email protected]

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

Labels

agents Agent runtime and tooling

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: update.run (and gateway restart) should flush open session JSONL transcripts before SIGTERM

2 participants