Skip to content

fix(gateway): eliminate SSE history double-read race — derive sanitized and raw views from single transcript snapshot - #61855

Merged
steipete merged 2 commits into
openclaw:mainfrom
electricsheephq:fix/sse-history-double-read-race
Apr 6, 2026
Merged

steipete merged 2 commits into
openclaw:mainfrom
electricsheephq:fix/sse-history-double-read-race

Conversation

@100yenadmin

@100yenadmin 100yenadmin commented Apr 6, 2026 •

Copy link
Copy Markdown
Contributor

What this fixes (plain English)

The SSE (Server-Sent Events) session history endpoint was reading the session transcript twice — once for the sanitized view and once for the raw view. If a write happened between the two reads, the sanitized and raw views could be inconsistent, causing seq ordering errors in real-time history events.

Technical details

Root cause: Two separate transcript reads in the SSE history handler created a race window. A concurrent write between reads could produce mismatched sanitized/raw snapshots, leading to incorrect seq values in downstream events.

Fix: Read the session transcript once and derive both sanitized and raw views from the same snapshot. Also fixes rawTranscriptSeq initialization to use the single-read raw snapshot.

Files changed:

  • src/gateway/sessions-history-http.ts — single-read pattern for transcript, derive both views from snapshot

Related

Test plan

  • Single-file change, minimal blast radius
  • SSE history events maintain correct seq ordering (no double-read race)
  • No regression in sanitized vs raw transcript views
  • sessions-history-http integration tests have 2 pre-existing infra failures (also fail on upstream/main)

Copilot AI review requested due to automatic review settings April 6, 2026 12:17
@openclaw-barnacle openclaw-barnacle Bot added gateway Gateway runtime size: XS labels Apr 6, 2026
@greptile-apps

greptile-apps Bot commented Apr 6, 2026 •

Copy link
Copy Markdown
Contributor

Greptile Summary

This PR eliminates a theoretical race window in the SSE history endpoint by reading the session transcript exactly once (rawSnapshot) and deriving both the sanitized message view (via sanitizeChatHistoryMessages) and the rawTranscriptSeq initializer from that single snapshot, rather than issuing two separate readSessionMessages calls that could diverge under concurrent writes. The approach is sound and the change is minimal.

  • Single-snapshot read for initial history load correctly prevents seq/content divergence between sanitized and raw views
  • rawTranscriptSeq is now initialized from the same rawSnapshot, keeping seq numbering consistent even when sanitization drops messages
  • Minor: messages: [...sentHistory.items, sanitizedMsg] on line 290 should reference sentHistory.messages for consistency (both are currently identical in content, so no functional impact today)

Confidence Score: 4/5

Safe to merge — the core race fix is correct and the one flagged inconsistency has no functional impact today.

The change is focused and the logic is straightforward. The only identified issue is a P2 style inconsistency (.items vs .messages in the sentHistory update) that doesn't affect current behavior. No regressions to critical paths are expected.

src/gateway/sessions-history-http.ts line 290 — minor field name inconsistency in sentHistory accumulation.

Comments Outside Diff (1)

  1. src/gateway/sessions-history-http.ts, line 290 (link)

    P2 messages spreads from items instead of messages

    On line 290, the messages field is built from sentHistory.items rather than sentHistory.messages. Although both fields currently hold identical content (they are always initialised to the same array in paginateSessionMessages), this is semantically incorrect and could silently diverge if that invariant ever changes.

    Prompt To Fix With AI
    This is a comment left during a code review.
    Path: src/gateway/sessions-history-http.ts
    Line: 290
    
    Comment:
    **`messages` spreads from `items` instead of `messages`**
    
    On line 290, the `messages` field is built from `sentHistory.items` rather than `sentHistory.messages`. Although both fields currently hold identical content (they are always initialised to the same array in `paginateSessionMessages`), this is semantically incorrect and could silently diverge if that invariant ever changes.
    
    
    
    How can I resolve this? If you propose a fix, please make it concise.
Prompt To Fix All With AI
This is a comment left during a code review.
Path: src/gateway/sessions-history-http.ts
Line: 290

Comment:
**`messages` spreads from `items` instead of `messages`**

On line 290, the `messages` field is built from `sentHistory.items` rather than `sentHistory.messages`. Although both fields currently hold identical content (they are always initialised to the same array in `paginateSessionMessages`), this is semantically incorrect and could silently diverge if that invariant ever changes.

```suggestion
          messages: [...sentHistory.messages, sanitizedMsg],
```

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

Reviews (1): Last reviewed commit: "fix(gateway): eliminate SSE history doub..." | Re-trigger Greptile

@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: 32b155050c

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

Comment thread src/gateway/sessions-history-http.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

Updates the gateway’s session history HTTP/SSE handler to avoid reading the session transcript twice, ensuring both sanitized and raw-derived state are computed from a single transcript snapshot (preventing potential seq/content divergence across reads).

Changes:

  • Read the session transcript once into a rawSnapshot and derive sanitized history from it.
  • Initialize rawTranscriptSeq from the same rawSnapshot (instead of performing a second transcript read).

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

Copilot reviewed 1 out of 1 changed files in this pull request and generated no new comments.

…ed and raw views from single transcript snapshot
@steipete
steipete merged commit c7c0550 into openclaw:main Apr 6, 2026
6 checks passed
@steipete

steipete commented Apr 6, 2026

Copy link
Copy Markdown
Contributor

Landed via temp rebase onto main.

  • Gate: pnpm test src/gateway/session-history-state.test.ts ✅; pnpm test src/gateway/sessions-history-http.test.ts hit the same 3 pre-existing infra failures called out in the PR body; pnpm check and pnpm build are currently red on unrelated upstream issues (for example acpx/runtime resolution and broader extension/CLI type errors).
  • Land commit: bac32d3
  • Merge commit: c7c0550

Thanks @100yenadmin!

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

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

maxChars: effectiveMaxChars,
limit,
cursor,
initialRawMessages: rawSnapshot,

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 Seed SSE sequence after registering transcript listener

Passing initialRawMessages: rawSnapshot seeds rawTranscriptSeq from a pre-subscription snapshot, so any message appended between that read and onSessionTranscriptUpdate(...) registration is missed while still advancing the real transcript; the next inline update then reuses a stale sequence and emits shifted messageSeq/__openclaw.seq values for SSE clients. Fresh evidence in this commit is src/gateway/session-history-state.test.ts, which now asserts no second transcript read occurs, locking in pre-subscription seeding behavior.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Thanks for the careful read — I traced through the actual code on upstream/main and I'm confident this is not a real race condition (~98% confidence).

Why the window doesn't exist in Node.js

The sequence in handleSessionHistoryHttpRequest (sessions-history-http.ts, lines 166–219) is:

  1. rawSnapshot = readSessionMessages(...) — synchronous disk read
  2. sanitizeChatHistoryMessages, paginateSessionMessages, resolveSessionTranscriptCandidates, new SessionHistorySseState({initialRawMessages: rawSnapshot}), sseState.snapshot(), setSseHeaders, res.write, sseWrite, setInterval — all synchronous, no await
  3. unsubscribe = onSessionTranscriptUpdate(...) — listener registered

onSessionTranscriptUpdate / emitSessionTranscriptUpdate (transcript-events.ts) are plain synchronous in-process functions — they iterate a Set with a for...of loop, no async boundary.

Because Node.js is single-threaded with a cooperative event loop, no I/O callback or emit can fire during synchronous execution. The event loop cannot yield between steps 1 and 3. A message appended by any other coroutine would queue as a microtask or I/O event and only run after the current synchronous frame completes — which is after the listener is already registered.

Re: seq seeding

rawTranscriptSeq is seeded from rawSnapshot.at(-1).__openclaw.seq ?? rawSnapshot.length (session-history-state.ts line 113). The first inline appendInlineMessage call increments this before stamping the next message. If a message somehow landed in the window (which can't happen, as above), the refresh() fallback path (triggered when update.message === undefined) re-reads disk and resets rawTranscriptSeq from the fresh file — so even hypothetically, seq would self-correct on the next non-inline event.

Verdict: Not a real race. No fix needed. The design is sound and the test (session-history-state.test.ts line 51, asserting readSpy is never called) locks in the intent correctly. No new PR required.

steipete added a commit to leoleedev/openclaw that referenced this pull request Apr 6, 2026
Mlightsnow pushed a commit to Mlightsnow/openclaw that referenced this pull request Apr 6, 2026
lovewanwan pushed a commit to lovewanwan/openclaw that referenced this pull request Apr 28, 2026
ogt-redknie pushed a commit to ogt-redknie/OPENX that referenced this pull request May 2, 2026
YoshiaKefasu pushed a commit to YoshiaKefasu/DennouAibou that referenced this pull request May 18, 2026
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request May 24, 2026
vixco pushed a commit to vixco/openclaw that referenced this pull request Aug 16, 2026
globalcaos pushed a commit to globalcaos/tinkerclaw that referenced this pull request Sep 29, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

gateway Gateway runtime size: S

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants