Skip to content

fix(native-chat): drain the reaped child's journal writes before an attach reports - #17160

Closed
brennanb2025 wants to merge 1 commit into
mainfrom
fix/structured-session-attach-drain
Closed

brennanb2025 wants to merge 1 commit into
mainfrom
fix/structured-session-attach-drain

Conversation

@brennanb2025

@brennanb2025 brennanb2025 commented Aug 29, 2026 •

Copy link
Copy Markdown
Contributor
Files Added Deleted Net
Test 2 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​166 $\color{#cf222e}{\Huge{\mathbf{−}}}$​1 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​165
Prod 3 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​10 $\color{#cf222e}{\Huge{\mathbf{−}}}$​3 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​7

The failure

structured-agent-session-integration.test.ts intermittently reported seven journal rows where
six were expected, on test / tests node 24 2/8:

- Expected            + Received
  [                     [
    "message",            "message",
                        + "status",      ← the extra element
    "message",            "message",

The extra element is the Codex turn-lifecycle row — legacy:codex:<session>:turn-lifecycle:turn-1,
body text "Codex is working…" — still present in history after the takeover that should have ended it.

Mechanism

turn/started journals a turn-lifecycle status row; the matching tombstone is written when the
provider child is closed. On a takeover (agentSession.ensure), that close happens inside
adapter.acquire
— at which point the attach has already called eventSink.unbind(), so the
tombstone is only buffered on the deferred sink.

eventSink.bind() in onAttached re-queues the buffered writes onto the sink's async chain, but
nothing awaited that chain. The attach then read its hydration page, published the new fence and
released the session lock while the tombstone was still in flight. Whether a reader saw the stale
row came down to an unrelated race between the tombstone's journal write and the attach's own
store.recordOperationOutcome write.

The attach already establishes the symmetric barrier on the way in
(beforeJournalOpen: unbind() + await drained()). The barrier on the way out was missing.

This is not cosmetic. The stale row is what activeStructuredAgentSessionTurnId() reads, so a
session whose child was just reaped could hydrate as "Codex is working…" — and in the main process
isTurnActive uses the same signal to gate eviction.

Fix

Await the rebound sink before the attach reports: performAttach now awaits onAttached, and the
orchestration drains the sink after bind(). The same rule is applied to the handoff restart path,
which binds and then immediately fans out a snapshot.

Not the PR it failed on

All the implicated files are byte-identical to main, and the same failure occurred independently on
#17115 (an unrelated Windows PowerShell polling PR). Rate across enumerated attempts: 2 / 85.

Verification

Ablation, 12 runs per arm (local load 10–15):

arm pin result
baseline (fix in place) 12/12 green
flow drops await onAttached 0/12 green
orchestration drops await eventSink.drained() 0/12 green
restored 12/12 green

The failure was also reproduced byte-for-byte against the CI diff by delaying the
tombstone 150ms on pristine main — extra "status" at index 1, row
legacy:codex:<session>:turn-lifecycle%3Aturn-1, text "Codex is working…" —
and that same probe passes with the fix.

Gates: pnpm tc (all projects) clean; oxlint, both --deny-warnings plugin
audits, the max-lines ratchet and check-changed-code-quality.mjs all clean;
git diff --check clean; formatted with npx oxfmt --write on changed paths only.

@greptile-apps

greptile-apps Bot commented Aug 29, 2026 •

Copy link
Copy Markdown

Greptile Summary

The PR adds the missing exit-side journal barrier so attach and native-handoff results are emitted only after deferred writes from a reaped provider child have landed.

  • Makes the attach callback awaitable and waits for it before recording success and hydrating the response.
  • Drains the rebound event sink before returning an attach result or publishing a handoff snapshot.
  • Adds focused regression and integration coverage for stale turn-lifecycle rows.

Confidence Score: 5/5

The PR appears safe to merge.

No blocking failure remains.

Important Files Changed

Filename Overview
src/main/native-chat/agent-session-wire/structured-agent-session-attach-flow.ts Makes post-attachment publication awaitable so hydration cannot overtake deferred journal writes.
src/main/native-chat/agent-session-wire/structured-agent-session-attach-orchestration.ts Drains buffered writes after rebinding the event sink and before attach completion.
src/main/native-chat/agent-session-wire/structured-agent-session-host-handoff.ts Applies the same drain-before-snapshot ordering to native handoff recovery.
src/main/native-chat/agent-session-wire/structured-agent-session-attach-drain.test.ts Adds a gated regression test proving attach waits for a buffered reap-time write.
src/main/runtime/structured-agent-session-integration.test.ts Verifies takeover hydration no longer retains the superseded child’s active turn-lifecycle row.

Sequence Diagram

sequenceDiagram
  participant A as Attach or handoff
  participant S as Deferred event sink
  participant P as Superseded provider child
  participant J as Replacement journal
  participant C as Client or subscriber
  A->>S: unbind()
  A->>P: acquire replacement and reap child
  P->>S: buffer final journal writes
  A->>S: bind(J)
  S->>J: replay buffered writes
  A->>S: await drained()
  S-->>A: writes settled
  A->>C: hydration page or snapshot
Loading

Reviews (2): Last reviewed commit: "fix(native-chat): drain the reaped child..." | Re-trigger Greptile

@coderabbitai

coderabbitai Bot commented Aug 29, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 245051c9-e5a2-40f4-93b8-2b64814df29a

📥 Commits

Reviewing files that changed from the base of the PR and between 51ed7d4 and 3af3f64.

📒 Files selected for processing (5)
  • src/main/native-chat/agent-session-wire/structured-agent-session-attach-drain.test.ts
  • src/main/native-chat/agent-session-wire/structured-agent-session-attach-flow.ts
  • src/main/native-chat/agent-session-wire/structured-agent-session-attach-orchestration.ts
  • src/main/native-chat/agent-session-wire/structured-agent-session-host-handoff.ts
  • src/main/runtime/structured-agent-session-integration.test.ts

Included review availability: Your plan provides up to 10 included reviews per hour; 5 remain after this review.


📝 Walkthrough

Walkthrough

The attach flow now supports asynchronous onAttached callbacks and records success after the callback completes. Structured attachment and host handoff paths wait for buffered event-sink writes to drain before reporting pages or snapshots. New and updated tests verify that reaped-child status events appear and that resumed journal items show the turn-ending sequence.

Merge Risk: 🔵 Low · up to 3af3f

This change prevents stale turn-status rows from being reported during session attach and handoff, improving session state consistency. It is mergeable with explicit owner awareness that journal-write failures may still leave stale lifecycle state and should have a defined recovery policy.

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Description check ⚠️ Warning The description provides strong technical detail about the failure, mechanism, fix, and verification. However, it omits required template sections, including the always-required Linked Issue, Visual P… Add the missing template sections. Provide a linked issue after “Fixes #”. For this non-UI behavior change, include “N/A” with a brief reason under Visual Proof. Complete or explicitly mark the remaining sections and checklist items, includ…
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 3 functions across 5 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and concisely describes the main change: draining reaped-child journal writes before attach reports completion.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Full details: Description check

Explanation

The description provides strong technical detail about the failure, mechanism, fix, and verification. However, it omits required template sections, including the always-required Linked Issue, Visual Proof or an explicit N/A explanation, AI Disclosure, Review, Agent skill upstream boundary, Notes, and Checklist.

Resolution

Add the missing template sections. Provide a linked issue after “Fixes #”. For this non-UI behavior change, include “N/A” with a brief reason under Visual Proof. Complete or explicitly mark the remaining sections and checklist items, including testing and cross-platform considerations.

  • Fix all pre-merge checks with AI
✨ Finishing Touches 💡 2
📝 Generate docstrings 💡
  • Create stacked PR
  • Commit on current branch
🛠️ Fix failing CI checks 💡
  • Create stacked PR
  • Commit on current branch

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

…ttach reports

A takeover reaps the superseded provider child from inside `adapter.acquire`,
and the reap journals its end-of-turn bookkeeping — for Codex, the tombstone
that ends the `turn-lifecycle` row. The sink is unbound by then, so those
writes only buffer; `bind()` re-queues them onto the sink's async chain and
nothing awaited it. The attach then read its hydration page, published the new
fence and released the session lock while the tombstone was still in flight, so
`agentSession.ensure` could hand back — and `agentSession.history` could serve —
a page still showing the turn that same attach had just ended.

The attach already fences the way in (`unbind()` + `await drained()` before the
journal opens); this adds the missing fence on the way out, in both the attach
and handoff-restart paths.
@brennanb2025
brennanb2025 force-pushed the fix/structured-session-attach-drain branch from 3af3f64 to 47c7664 Compare August 30, 2026 02:01
@brennanb2025

Copy link
Copy Markdown
Contributor Author

Closing as obsolete: main no longer has the code this PR changes, or already behaves as it intended. Main already drains the event sink before an attach publishes: structured-agent-session-attach-orchestration.ts:305 awaits eventSink.drained() in beforePublish (from #16729/#17707). The handoff file it patches was deleted by #22783

(Stale-PR cleanup 2026-10-20, approved by Brennan. Reopen if something here is still missing on main.)

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant