Skip to content

fix(discord): rejoin threads on unarchive to restore MESSAGE_CREATE events - #111148

Merged
fuller-stack-dev merged 3 commits into
openclaw:mainfrom
hanamizuki:fix/discord-thread-unarchive-rejoin
Sep 17, 2026
Merged

fuller-stack-dev merged 3 commits into
openclaw:mainfrom
hanamizuki:fix/discord-thread-unarchive-rejoin

Conversation

@hanamizuki

@hanamizuki hanamizuki commented Jul 19, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

When a Discord thread is auto-archived and the gateway later restarts, the bot is no longer a thread member (archived threads are excluded from THREAD_LIST_SYNC). If a user subsequently sends a message — which causes Discord to unarchive the thread — the DiscordThreadUpdateListener receives the THREAD_UPDATE event but returns early because isThreadArchived(data) is false. The bot never rejoins the thread, so all subsequent MESSAGE_CREATE events for that thread are silently lost.

This means the bot becomes permanently unresponsive in any thread that happened to be archived at the time of a gateway restart, even after the thread is unarchived by user activity.

Why This Change Was Made

The existing DiscordThreadUpdateListener only handles the archive transition (closing sessions). It has no handling for the unarchive transition. This is a gap in the thread lifecycle management that causes silent message loss — the hardest kind of bug to diagnose because there are no errors in the logs.

User Impact

Before: Bot silently stops responding in threads that were archived during a gateway restart. Users see no error, no reaction, nothing — messages simply vanish into the void.

After: When a thread is unarchived, the bot automatically rejoins it via PUT /channels/{id}/thread-members/@me (idempotent — Discord returns 204 if already a member). A log line confirms the rejoin for observability.

Changes

  • extensions/discord/src/monitor/listeners.ts — restructured DiscordThreadUpdateListener.handle to branch on archive vs unarchive:
    • Archive (existing behavior, unchanged): close/reset thread sessions
    • Unarchive (new): call Discord REST API to rejoin the thread, log success/failure

Evidence

  • Observed in production: gateway restarted → threads archived at restart time became permanently unresponsive → zero log entries for inbound messages on those threads
  • Gateway log showed thread archived — reset sessions events but no corresponding rejoin on unarchive
  • Fix confirmed: after deploying this patch, Discord thread unarchived — rejoined thread appears in logs and the bot resumes responding

Test plan

  • Gateway restart with archived threads → unarchive by sending a message → bot responds
  • Bot already a member of an unarchived thread → PUT returns 204, no error
  • REST call failure (e.g., permissions) → logged as warning, does not crash the gateway

Maintainer integration — 2026-09-17

Rebound the contributor's repair onto current main while preserving contributor ancestry, current slow-listener/error handling, dynamic reaction policy, account-scoped thread deletion, and unchanged downstream message authorization. Claims remain bounded to 10,000, are acquired before REST, reset on archive/fresh READY, and released only by their own failed request. Production delta is +38 lines; this is the missing lifecycle capability, using the existing REST client and bounded-map helper.

Upstream contract verification

  • Discord: unarchiving a thread explicitly says an app may not have the thread or its member state in memory, then receives a full Thread Update before Thread Member Update. This resolves the previous reviewer-side documentation-access gap.
  • Discord: Join Thread documents PUT /channels/{channel.id}/thread-members/@me, active-thread requirement, and HTTP 204 success.
  • The accepted six-cycle production evidence remains the real Discord proof. It was not rerun or represented as new runtime evidence.

Current-source verification

New regressions run production listener registration through the real Client event queue and REST client, stubbing only transport responses and session closing. They cover ordinary updates/204, overlapping jobs, archive and READY resets, REST failure/retry, stale failures across both resets, and independent account clients. On unmodified current main: eight intended failures and one passing archive control. Integrated candidate: nine owner-boundary tests plus eight startup tests passed.

The 57 sibling message/interaction/deletion/provider tests also passed, for 74 distinct focused tests. The three deferred-concurrency cases passed again after switching to the repository-supported typed helper. Final independent autoreview of the five-file candidate is scoped-clean with zero actionable P0–P2 findings. Required production/test types and remaining local repository guards passed. The nested native worktree cannot complete local declaration-boundary lint because it detects ancestor-checkout dependency resolution; clean-checkout hosted lint and extension-package-boundary checks passed on the first integration head. Exact-head hosted CI remains required before native preparation and landing. No Discord account calls, operator Gateway restart, or historical proof replay.

CI integration prerequisites

The first hosted run exposed two existing Slack failures in its newer-main merge context. This update incorporates that main revision and repairs both without changing Slack policy: the lifecycle type moves to a leaf contract to break the static ingress/thread-resolution cycle, and the approval-event callback retains its receiver instead of passing an unbound method. The static graph reproduced one cycle before and zero after; 54 existing Slack ingress/thread-resolution tests and both extension typechecks passed. The callback is covered by the existing requested/resolved approval-flow test. The existing approval requested/resolved scenario passed (one selected test; 207 unselected), and scoped typed lint passed with zero warnings/errors. Final eleven-file independent review is scoped-clean with zero actionable P0–P2 findings. The update is published as e83454baf984cac8ddcd796e9b52699bbaabc8c1; exact-head CI remains required before native preparation.

@openclaw-barnacle openclaw-barnacle Bot added channel: discord Channel integration: discord size: XS labels Jul 19, 2026
@hanamizuki
hanamizuki force-pushed the fix/discord-thread-unarchive-rejoin branch from 2db0c92 to 4ee9d6b Compare July 19, 2026 03:02
@clawsweeper clawsweeper Bot added rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. P2 Normal backlog priority with limited blast radius. merge-risk: 🚨 message-delivery 🚨 May drop, duplicate, misroute, suppress, or wrongly target messages. labels Jul 19, 2026
@clawsweeper

clawsweeper Bot commented Jul 19, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed September 16, 2026, 9:53 PM ET / September 17, 2026, 01:53 UTC (Revision 12).

ClawSweeper review

What this changes

The Discord plugin rejoins active threads with bounded lifecycle tracking and regression coverage, while accompanying Slack changes separate an internal lifecycle type and preserve an approval callback’s receiver.

Merge readiness

✅ Ready for maintainer review

This repair remains necessary: current main and v2026.9.4 still ignore active-thread updates. The earlier lifecycle concerns are addressed, Discord’s documentation resolves the previous inspection gap, and no actionable introduced defect was found.

Priority: P1
Reviewed head: e83454baf984cac8ddcd796e9b52699bbaabc8c1

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) A useful, focused recovery fix with production evidence and meaningful lifecycle regression coverage; no blocking defect remains in the reviewed changes.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (logs): The contributor’s production Gateway logs and observations show the changed Discord listener rejoining unarchived threads and responses resuming across repeated cycles. That historical proof remains applicable to the bounded recovery implementation; current registration and race tests supplement it without being represented as a fresh live run.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Verified Sufficient (logs): The contributor’s production Gateway logs and observations show the changed Discord listener rejoining unarchived threads and responses resuming across repeated cycles. That historical proof remains applicable to the bounded recovery implementation; current registration and race tests supplement it without being represented as a fresh live run.
Evidence reviewed 10 items Current main still lacks recovery: The current-main thread-update listener returns immediately for non-archived threads; it contains no membership reconciliation.
Latest release retains the same gap: The v2026.9.4 source also returns early for active-thread updates. The release tag was independently resolved to the supplied release commit through GitHub’s tag endpoint.
Lifecycle repair and registration: The introduced listener claims before awaiting REST, bounds tracking to 10,000 entries, resets on archive and fresh READY, and releases only its own failed claim. Startup registers both listeners against the same client-owned instance.
Findings None None.
Security None None.

How this fits together

The Discord monitor receives thread lifecycle events and maintains the bot’s thread membership so messages can reach OpenClaw. Incoming messages then pass through the existing channel and sender authorization checks before agent dispatch.

flowchart TD
  A[Discord thread and READY events] --> B[Thread lifecycle listener]
  B --> C{Thread archived?}
  C -->|Yes| D[Clear claim and close thread sessions]
  C -->|No| E[Bounded per-client rejoin claim]
  E --> F[Discord membership request]
  F --> G[Incoming message authorization]
  G --> H[Authorized agent turns]
  A -->|Fresh READY clears claims| E
Loading

Before merge

None.

Agent review details

Security

None.

PR surface

Source +39, Tests +190. Total +229 across 11 files.

View PR surface stats
Area Files Added Removed Net
Source 7 66 27 +39
Tests 4 191 1 +190
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 11 257 28 +229

Review metrics

Metric Value Why it matters
Production versus regression coverage Production net +39 lines; tests and test support net +190 lines Production growth adds bounded lifecycle recovery through existing owners; most growth exercises reset, retry, and concurrency behavior.

Technical review

Best possible solution:

Keep thread membership recovery in the existing Discord lifecycle listener, with bounded account-local tracking and unchanged downstream authorization.

Do we have a high-confidence way to reproduce the issue?

Yes: restart while a thread is archived, then unarchive it through user activity; current source skips membership recovery, and the contributor supplies production before/after evidence. This review did not independently execute that scenario.

Is this the best way to solve the issue?

Yes: the patch extends the existing lifecycle owner, reuses the REST client, and addresses repeated-update and stale-failure races without introducing configuration or a parallel recovery service.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning medium; reviewed against 1fbb41545ec5.

Labels

Label justifications:

  • P1: The supplied production report describes Discord threads becoming persistently unresponsive after archive and Gateway restart.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🦞 diamond lobster and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Sufficient (logs): The contributor’s production Gateway logs and observations show the changed Discord listener rejoining unarchived threads and responses resuming across repeated cycles. That historical proof remains applicable to the bounded recovery implementation; current registration and race tests supplement it without being represented as a fresh live run.
  • proof: sufficient: Contributor real behavior proof is sufficient. The contributor’s production Gateway logs and observations show the changed Discord listener rejoining unarchived threads and responses resuming across repeated cycles. That historical proof remains applicable to the bounded recovery implementation; current registration and race tests supplement it without being represented as a fresh live run.

Evidence

What I checked:

  • Current main still lacks recovery: The current-main thread-update listener returns immediately for non-archived threads; it contains no membership reconciliation. (extensions/discord/src/monitor/listeners.ts:589, 1fbb41545ec5)
  • Latest release retains the same gap: The v2026.9.4 source also returns early for active-thread updates. The release tag was independently resolved to the supplied release commit through GitHub’s tag endpoint. (extensions/discord/src/monitor/listeners.ts, 3a9d69db306c)
  • Lifecycle repair and registration: The introduced listener claims before awaiting REST, bounds tracking to 10,000 entries, resets on archive and fresh READY, and releases only its own failed claim. Startup registers both listeners against the same client-owned instance. (extensions/discord/src/monitor/listeners.ts:580, e83454baf984)
  • Discord contract resolves the previous review gap: Discord’s thread documentation specifies a full Thread Update on unarchive even without cached thread state. Its Join Thread contract requires an active thread and returns HTTP 204 on success. These are the external contracts directly consumed by the listener; both pages were inspected.
  • Production recovery evidence: The supplied July 19 production evidence reports six natural unarchive cycles after deployment; excerpts show rejoin logs followed by successful message actions and repeated archive/rejoin activity. The captured September integration body explicitly preserves this historical evidence without claiming a new live run.
  • Regression coverage exercises the registered boundary: Nine cases use production registration, the real Client event queue, and the REST client with mocked responses to cover deduplication, overlapping updates, archive/READY resets, failure retry, stale failures, and account separation. The body reports eight pre-fix failures plus a passing archive control and 74 focused Discord tests passing after integration. These are supplemental reported results; this read-only review did not execute tests. (extensions/discord/src/monitor/listeners.thread-update.test.ts:34, e83454baf984)

Likely related people:

  • steipete: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)
  • pash-openai: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)

Rating scale

Score Internal tier Crab rank Meaning
6/6 S 🦀 challenger crab Exceptional readiness
5/6 A 🦞 diamond lobster Very strong readiness
4/6 B 🐚 platinum hermit Good normal PR; ordinary maintainer review
3/6 C 🦐 gold shrimp Useful, but confidence is limited
2/6 D 🦪 silver shellfish Proof or implementation needs work
1/6 F 🧂 unranked krab Not merge-ready
N/A NA 🌊 off-meta tidepool Rating does not apply

Overall follows the weaker of proof and patch quality.
Shiny media proof means a screenshot, video, or linked artifact directly shows the changed behavior. Runtime, network, CSP, and security claims still need visible diagnostics.

Workflow

  • ClawSweeper keeps one durable marker-backed review comment per issue or PR.
  • Re-runs edit this comment so the latest verdict, findings, and automation markers stay together instead of adding duplicate bot comments.
  • A fresh review can be triggered by eligible @clawsweeper re-review comments, exact-item GitHub events, scheduled/background review runs, or manual workflow dispatch.
  • PR/issue authors and users with repository write access can comment @clawsweeper re-review or @clawsweeper re-run on an open PR or issue to request a fresh review only.
  • Maintainers can also comment @clawsweeper review to request a fresh review only.
  • Fresh-review commands do not start repair, autofix, rebase, CI repair, or automerge.
  • Maintainer-only repair and merge flows require explicit commands such as @clawsweeper autofix, @clawsweeper automerge, @clawsweeper fix ci, or @clawsweeper address review.
  • Maintainers can comment @clawsweeper explain to ask for more context, or @clawsweeper stop to stop active automation.

History

Review history (11 earlier review cycles; latest 8 shown)
  • reviewed 2026-07-19T04:14:09.818Z sha 90bd57aad74da6bbdc5b1a476ac73fb097260c43 :: needs changes before merge. :: [P2] Reconcile an active thread only once per archive cycle
  • reviewed 2026-07-31T08:05:09.363Z sha 90bd57aad74da6bbdc5b1a476ac73fb097260c43 :: needs changes before merge. :: [P2] Rejoin only after an observed archive-to-active transition
  • reviewed August 4, 2026, 11:17 AM ET / 15:17 UTC sha unknown :: needs changes before merge. :: [P2] Rejoin only once per recovery cycle
  • reviewed 2026-08-09T07:43:10.592Z sha fc504b9 :: needs maintainer review before merge. :: none
  • reviewed 2026-08-14T10:37:37.550Z sha fc504b9 :: needs maintainer review before merge. :: none
  • reviewed August 21, 2026, 2:07 PM ET / 18:07 UTC sha unknown :: needs maintainer review before merge. :: none
  • reviewed September 5, 2026, 1:07 AM ET / 05:07 UTC sha unknown :: blocked before merge. :: none
  • reviewed September 5, 2026, 2:09 AM ET / 06:09 UTC sha unknown :: blocked before merge. :: none

@hanamizuki
hanamizuki force-pushed the fix/discord-thread-unarchive-rejoin branch from 4ee9d6b to d1d8a2d Compare July 19, 2026 03:16
@hanamizuki

Copy link
Copy Markdown
Contributor Author

Real behavior proof — production deployment

Deployed this patch to a production OpenClaw gateway (Discord channel, mojo agent). Here's the observed lifecycle:

Before patch (2026-07-18): threads archived, never rejoined

2026-07-18T18:02:17+08:00 [discord] thread archived — reset sessions
2026-07-18T23:57:39+08:00 [discord] thread archived — reset sessions
2026-07-18T23:57:42+08:00 [discord] thread archived — reset sessions
2026-07-18T23:57:43+08:00 [discord] thread archived — reset sessions
(... no "rejoined" events — messages in unarchived threads silently lost)

User reported bot unresponsive in thread 1527846824440762429. Gateway log had zero mentions of this thread — MESSAGE_CREATE events never arrived.

After patch deployed (2026-07-19 01:35+08:00): unarchive → rejoin → messages received

2026-07-19T02:05:10+08:00 [discord] thread unarchived — rejoined thread
2026-07-19T02:05:11+08:00 [ws] ⇄ res ✓ message.action 1360ms channel=discord
2026-07-19T02:05:13+08:00 [ws] ⇄ res ✓ message.action 1526ms channel=discord
2026-07-19T02:05:15+08:00 [ws] ⇄ res ✓ message.action 1428ms channel=discord

2026-07-19T02:09:03+08:00 [discord] thread unarchived — rejoined thread
2026-07-19T03:02:25+08:00 [discord] thread archived — reset sessions
2026-07-19T10:19:03+08:00 [discord] thread unarchived — rejoined thread
2026-07-19T11:01:03+08:00 [discord] thread unarchived — rejoined thread
2026-07-19T11:12:24+08:00 [discord] thread unarchived — rejoined thread

Summary

  • Rejoin fires correctly on every THREAD_UPDATE with archived: false
  • MESSAGE_CREATE events resume immediately after rejoin (confirmed by successful message.action responses within 1-2 seconds)
  • Idempotent — multiple rejoin calls for the same thread produce no errors
  • Full archive→unarchive lifecycle working: threads naturally cycle through archived (sessions reset) → unarchived (rejoin) → bot responds → re-archived, repeatedly throughout the day
  • 6 natural unarchive events observed over ~9 hours of production uptime with zero failures

@clawsweeper clawsweeper Bot added proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. and removed rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels Jul 19, 2026
@hanamizuki
hanamizuki force-pushed the fix/discord-thread-unarchive-rejoin branch from d1d8a2d to 90bd57a Compare July 19, 2026 04:09
@clawsweeper clawsweeper Bot added P1 High-priority user-facing bug, regression, or broken workflow. and removed P2 Normal backlog priority with limited blast radius. labels Aug 4, 2026
@hanamizuki
hanamizuki force-pushed the fix/discord-thread-unarchive-rejoin branch from 90bd57a to 1ff1b96 Compare August 9, 2026 07:02
@hanamizuki
hanamizuki force-pushed the fix/discord-thread-unarchive-rejoin branch from 1ff1b96 to fc504b9 Compare August 9, 2026 07:12
@hanamizuki

Copy link
Copy Markdown
Contributor Author

Addressed the lifecycle blocker in fc504b9:

  • Added bounded, listener-owned rejoin claims.
  • Claims are recorded before awaiting REST, collapsing concurrent updates.
  • Archive and fresh READY events reset the matching lifecycle.
  • Failed requests release only their own claim, preserving retries without stale-request races.
  • Added coverage for ordinary updates, concurrency, archive/READY lifecycles, failed retries, and stale failures.

Validation:

  • Focused Discord suite: 3 files, 58 tests passed.
  • pnpm tsgo:extensions:test
  • GitHub CI run 31300611454: 89 checks completed, 0 failures, openclaw/ci-gate passed.

The earlier production proof remains applicable; this update bounds when membership reconciliation runs.

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Aug 9, 2026 •

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event repository_dispatch).
Result: when the review finishes, ClawSweeper will create the durable review comment if needed or update the existing comment in place.

Re-review progress:

@clawsweeper clawsweeper Bot added rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. and removed rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. labels Aug 9, 2026
@clawsweeper clawsweeper Bot removed the merge-risk: 🚨 message-delivery 🚨 May drop, duplicate, misroute, suppress, or wrongly target messages. label Sep 5, 2026
@github-actions

github-actions Bot commented Sep 17, 2026 •

Copy link
Copy Markdown
Contributor

Security-sensitive guard cleared

This PR no longer has blocked security-sensitive file changes. A future security-sensitive change requires a fresh /allow-security-sensitive-change comment after the guard blocks that new head SHA.

  • Current SHA: e83454baf984cac8ddcd796e9b52699bbaabc8c1

@github-actions github-actions Bot removed security-sensitive-changed dependencies-changed PR changes dependency-related files labels Sep 17, 2026
@fuller-stack-dev
fuller-stack-dev merged commit a13ecd2 into openclaw:main Sep 17, 2026
96 of 98 checks passed
@fuller-stack-dev

Copy link
Copy Markdown
Member

Merged via squash.

fuller-stack-dev added a commit to superdiaodiao/openclaw that referenced this pull request Sep 17, 2026
Reuse the published UI and native closure fixes from openclaw#150026 and openclaw#114032.
Match the landed Slack correction from openclaw#111148, including openclaw#150457.
Keep the qualified ACP production code and SDK proof unchanged.

Co-authored-by: pash-openai <[email protected]>
fuller-stack-dev added a commit that referenced this pull request Sep 17, 2026
* fix(acp): order new session response before updates

Change-Id: I162e6670e72e5e2aa9d1b2a70d8a02f18dd82e05

* test(acp): prove stdio session ordering

* test(acp): close startup input before ordering proof

* fix(acp): use canonical record guard for session ordering

* fix(acp): bound session tracking and route sink failures to shutdown

Two lifecycle defects remained on the ordering boundary.

observeInbound recorded params.sessionId for every inbound message, so a
valid-shaped session/prompt naming a session the translator later rejects
still added an ID that was never reaped -- a peer could grow the set for
the lifetime of the process. Only session/load and session/resume assert a
session that already exists; session/new is now correlated by JSON-RPC
request ID so an ID is established by the response that introduces it.
Every collection is peer-driven, so all three are bounded and fail open:
overflow writes the update through in arrival order, because dropping one
loses session content while emitting one early only restores the pre-fix
ordering. session/close releases anything still buffered instead of
stranding it.

pipeTo rejects when the NDJSON writer or stdout fails, and that promise was
discarded. The ACP client is already unreachable at that point, but the
Gateway connection and shared state database stayed open. It now flows
through the same idempotent shutdown owner as EOF and SIGTERM.

* fix(acp): only buffer updates a new-session response can still release

The previous round bounded the collections but not the consequences of
those bounds, leaving two ways an update could be held forever.

Evicting the oldest correlation to admit the 65th session/new dropped the
only thing that could drain that session's buffered initial update: the
client received the result and never received the update, which is the
silent stall this boundary exists to fix. Correlations are no longer
evicted. Past the cap a request is left uncorrelated and its response is
matched by count instead, falling back to the session ID the response
already carries -- our own outbound payload rather than peer input.

establishedSessionIds was never bounded or released, so a long-lived
bridge grew it for every loaded, resumed, and created session. It is now
released on session/close and bounded; past the bound, established and
pending are no longer distinguishable, so buffering stops rather than
holding updates that might never come back out.

Underneath both: an update is only ever buffered while some session/new
response can still release it. Nothing else introduces a session ID, so
buffering outside that window strands it by construction. When the last
correlation resolves, anything still buffered is written through in
arrival order.

* fix(acp): retire an overflow correlation slot on a failed creation

The count-based fallback for session/new requests past the correlation cap
was only consumed by a response that carried a session ID. A creation that
failed returned a JSON-RPC error instead, so its slot stayed behind and the
next unrelated response carrying a session ID was mistaken for it, flushing
a session the protocol never introduced.

The slot is now retired by the first uncorrelated response whatever it
carries: a result establishes the session, an error simply frees the slot.
Retiring it can also remove the last thing able to release a buffered
update, so the reachability check runs on that path too.

* fix(acp): fail open when new-session correlation saturates

The count-based fallback for requests past the correlation cap could be
consumed by any uncorrelated response. An ordinary RPC reply arriving while
the overflowed session/new was still outstanding took its slot, so that
session's own result no longer established it, and its update could ship
ahead of the result -- the ordering failure this boundary exists to prevent,
reached from the other side.

A response is now matched only by its own request ID. Past the cap the
request is simply not correlated and the boundary fails open until the
tracked correlations drain: while saturated no update is buffered, so
ordering degrades to pre-fix behaviour rather than risking either a strand
or a cross-association. Correlations are still never evicted, so every
tracked request resolves and saturation always clears.

This removes the counter and both of its branches rather than adding a
third guard to it.

* fix(acp): keep buffered updates in global arrival order

The buffer was a map keyed by session, so releasing it walked one session
at a time. Two creations emitting A1, B1, A2 and then both failing put
A1, A2, B1 on the wire, reordering updates across sessions against the
arrival-order guarantee this boundary is supposed to provide.

Buffered updates now live in a single array in arrival order, and that
array is the only thing that decides ordering. Draining one session filters
it in place, preserving the order of everything left behind. The per-session
counts that enforce the bounds move to a separate map that is never consulted
for ordering, so there is one ordering path rather than two.

* refactor(acp): rebuild the ordering boundary around two invariants

Six rounds of point fixes each introduced the next defect, so the state
machine is rebuilt rather than patched again. Everything now follows from
two rules:

An update is queued only while some session/new response can still release
it. Nothing else introduces a session ID, so queuing outside that window
strands it by construction.

The queue drains strictly from the front and stops at the first update that
is still blocked, so releasing never emits an update ahead of one that
arrived earlier.

Three defects fall out of that directly. Correlations now settle only on
frames shaped like JSON-RPC responses, so an agent-initiated request whose
client-chosen id collides with an in-flight session/new no longer releases
that session's updates early. Draining no longer lifts one session's entries
out of the middle of the queue, so a later update cannot overtake an earlier
one when its own creation settles first. Tracking saturation is recomputed
rather than latched, so session/close frees capacity and ordering resumes
instead of failing open for the life of the process.

The released-updates side channel is gone: inbound events only change state,
and the next outbound frame drains the one queue.

* fix(acp): never clear correlation saturation

Saturation was cleared once the tracked correlations drained, on the claim
that this was the first provable quiescent point. It is not: an overflowed
session/new is by definition not in that set, so the set emptying says only
that the tracked requests finished. A later tracked creation could then
re-enable queuing and drain the overflowed session's update ahead of its own
result, which is the failure this boundary exists to prevent.

There is no point at which an uncorrelated creation is provably gone, so the
flag is never cleared. Once correlation has overflowed the boundary stays
failed open, trading ordering for a guarantee it can still honour.

* fix(acp): size the ordering bounds above what the bridge admits

The 64-request correlation cap sat below the agent's own admission limit,
which allows well over a hundred creations in its default window. An
ordinary accepted burst therefore overflowed it and, since saturation is
never cleared, permanently disabled ordering for the rest of the process:
the exact-head trace recorded 140 updates ahead of their results.

The correlation set is now uncapped. An entry is one short string, it is
removed by the response to its own request, and every entry costs the peer
a real session creation, so the agent's admission limit bounds it long
before memory does. Saturation and its permanent fail-open go with it.

MAX_QUEUED_SESSIONS had the same defect for the same reason and is raised
above the admission limit; the per-session bound is unchanged.

* fix(acp): track established sessions until they close

The 1,024-session bound was the third instance of the same defect: once a
long-lived bridge reached it, established and pending sessions became
indistinguishable and ordering was given up for the rest of the process.

It is removed rather than raised. Every entry corresponds to a session that
is live on the Gateway side, which costs orders of magnitude more than the
ID string held here, and session/close releases it, so this set can never be
the binding constraint.

Two bounds remain, both on the queue itself, which holds messages rather
than identifiers: MAX_QUEUED_SESSIONS sits above what the agent admits, and
MAX_QUEUED_UPDATES_PER_SESSION bounds a single session's initial burst. Both
fail open in the direction that only degrades ordering, never delivery.

* fix(acp): follow the session store's lifecycle and drop the last cap

Two owner-boundary defects, both at the seam between this boundary and the
work the bridge actually accepts.

MAX_QUEUED_SESSIONS was the fourth cap to sit below accepted traffic. The
admission limit is a rate, not a concurrency bound; a slow backend can hold
more accepted creations outstanding than any fixed number, and update N+1
then bypassed the queue ahead of its own result. It is removed. The number
of sessions with queued updates is the number of accepted creations still
outstanding, which the bridge already bounds. The per-session cap stays: it
is the one bound that holds messages rather than work the bridge admitted.

establishedSessionIds was released only by an inbound session/close, but the
store reaps idle sessions and evicts at capacity without producing any ACP
request, so a long-lived bridge kept recognizing sessions the store had
discarded. The store now reports every removal through onSessionRemoved,
and server.ts injects a store wired to the boundary's forget(), so
recognition follows the store's own lifecycle rather than only the close
requests a client chooses to send. The injected store is disposed on the
bridge's shutdown path since injected stores stay caller-owned.

Rebased onto current main.

* fix(acp): retire a loaded session the agent rejects

session/load and session/resume were established on arrival, before the
agent validated them. A rejected load -- one carrying per-session MCP
servers, for instance -- left its client-chosen ID recognized until close
or store removal. With the established set now uncapped, that is a growth
vector a peer controls.

The ID is still established provisionally on arrival so a loaded session's
updates are never delayed; the request is remembered by JSON-RPC ID, and an
error response retires the session it named. Bounded by in-flight loads,
each of which is real work, and cleared by its own response.

* fix(acp): only retire recognition a rejected request introduced

The previous commit retired the session named by any failing load or
resume. A session that was already established and merely reloaded lost
its recognition when that reload failed, so its later updates waited
behind an unrelated pending creation -- the delay this boundary exists to
avoid, and which it explicitly promises not to impose on existing
sessions.

Only recognition a request introduces is provisional now: the request is
remembered for retirement only when it established the ID itself.

* fix(acp): keep updates behind their session's backlog; separate claims from confirmation

Two concurrency defects at the boundary, both introduced by earlier repairs.

Strict front-of-queue draining preserved cross-session order but let a
session overtake itself: with A1, B1, A2 queued and A's result in, the drain
emitted A1 and stopped at B1, leaving A2; a later A3 then passed straight
through because A was established, so the client saw A3 before A2. A session
with updates still queued now keeps queuing regardless of recognition, so
its later updates wait behind its own backlog. The per-session overflow
fails open by releasing that session's backlog in order first, so even the
overflow path never reorders within a session.

Provisional load/resume claims shared the confirmed set, so "already
established" could not distinguish a succeeded request from a pending one.
Two overlapping loads on one session: the second succeeds, the first is
rejected, and the first's retirement erased the second's valid recognition.
Claims are now counted per session, separately from confirmation. A session
is recognized while confirmed or while any claim is outstanding; a rejection
retires exactly its own claim; acceptance confirms.

* fix(acp): release a session's backlog when its own result is written

Holding one session behind another let a prompt outrun its own output. With
A1, B1, A2 queued and A introduced, the global front-only drain emitted A1
and stopped at B1, so A kept queuing; a prompt's end_turn response carries no
session ID, never enters the queue, and therefore reached the client ahead of
the agent_message_chunk it completed.

A session's queue is now released whole when its own result is written,
rather than only the run at the head of the shared queue. Sessions are
independent streams, so ordering one against another buys nothing the client
can observe, while it does delay a session past frames that bypass the queue
entirely. Order within a session is unchanged and still exact.

The shared queue keeps global arrival order only on the path where no
creation can introduce anything, which spans sessions that were never
introduced and is the one place a cross-session rule is meaningful.

* test(acp): pin the wire order of a prompt response against its own text

Captures the ordering boundary at the ACP stdio boundary itself rather than
through the ordering class alone: two session/new requests are outstanding at
once, so an update for either is held, and the prompt response that completes
one of them carries no session ID and so passes through the boundary untouched.

Asserted as one five-frame sequence. Frame-by-frame assertions stop at the
first divergence, which hides where a displaced frame actually lands - and
where it lands is the defect.

* test(acp-core): stop shadowing the suite store in the removal-hook test

oxlint eslint(no-shadow) flagged the local store in the onSessionRemoved test
against the suite-level one. Renamed rather than reusing the outer store: the
test needs its own maxSessions and idleTtlMs to reach the eviction paths.

* test(acp): keep ordering fixtures type-safe

* fix(ci): consume canonical ACP landing prerequisites

Reuse the published UI and native closure fixes from #150026 and #114032.
Match the landed Slack correction from #111148, including #150457.
Keep the qualified ACP production code and SDK proof unchanged.

Co-authored-by: pash-openai <[email protected]>

* test(update): await report staging before cleanup race

---------

Co-authored-by: Jason (Json) <[email protected]>
Co-authored-by: pash-openai <[email protected]>
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Sep 17, 2026
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Sep 17, 2026
* fix(acp): order new session response before updates

Change-Id: I162e6670e72e5e2aa9d1b2a70d8a02f18dd82e05

* test(acp): prove stdio session ordering

* test(acp): close startup input before ordering proof

* fix(acp): use canonical record guard for session ordering

* fix(acp): bound session tracking and route sink failures to shutdown

Two lifecycle defects remained on the ordering boundary.

observeInbound recorded params.sessionId for every inbound message, so a
valid-shaped session/prompt naming a session the translator later rejects
still added an ID that was never reaped -- a peer could grow the set for
the lifetime of the process. Only session/load and session/resume assert a
session that already exists; session/new is now correlated by JSON-RPC
request ID so an ID is established by the response that introduces it.
Every collection is peer-driven, so all three are bounded and fail open:
overflow writes the update through in arrival order, because dropping one
loses session content while emitting one early only restores the pre-fix
ordering. session/close releases anything still buffered instead of
stranding it.

pipeTo rejects when the NDJSON writer or stdout fails, and that promise was
discarded. The ACP client is already unreachable at that point, but the
Gateway connection and shared state database stayed open. It now flows
through the same idempotent shutdown owner as EOF and SIGTERM.

* fix(acp): only buffer updates a new-session response can still release

The previous round bounded the collections but not the consequences of
those bounds, leaving two ways an update could be held forever.

Evicting the oldest correlation to admit the 65th session/new dropped the
only thing that could drain that session's buffered initial update: the
client received the result and never received the update, which is the
silent stall this boundary exists to fix. Correlations are no longer
evicted. Past the cap a request is left uncorrelated and its response is
matched by count instead, falling back to the session ID the response
already carries -- our own outbound payload rather than peer input.

establishedSessionIds was never bounded or released, so a long-lived
bridge grew it for every loaded, resumed, and created session. It is now
released on session/close and bounded; past the bound, established and
pending are no longer distinguishable, so buffering stops rather than
holding updates that might never come back out.

Underneath both: an update is only ever buffered while some session/new
response can still release it. Nothing else introduces a session ID, so
buffering outside that window strands it by construction. When the last
correlation resolves, anything still buffered is written through in
arrival order.

* fix(acp): retire an overflow correlation slot on a failed creation

The count-based fallback for session/new requests past the correlation cap
was only consumed by a response that carried a session ID. A creation that
failed returned a JSON-RPC error instead, so its slot stayed behind and the
next unrelated response carrying a session ID was mistaken for it, flushing
a session the protocol never introduced.

The slot is now retired by the first uncorrelated response whatever it
carries: a result establishes the session, an error simply frees the slot.
Retiring it can also remove the last thing able to release a buffered
update, so the reachability check runs on that path too.

* fix(acp): fail open when new-session correlation saturates

The count-based fallback for requests past the correlation cap could be
consumed by any uncorrelated response. An ordinary RPC reply arriving while
the overflowed session/new was still outstanding took its slot, so that
session's own result no longer established it, and its update could ship
ahead of the result -- the ordering failure this boundary exists to prevent,
reached from the other side.

A response is now matched only by its own request ID. Past the cap the
request is simply not correlated and the boundary fails open until the
tracked correlations drain: while saturated no update is buffered, so
ordering degrades to pre-fix behaviour rather than risking either a strand
or a cross-association. Correlations are still never evicted, so every
tracked request resolves and saturation always clears.

This removes the counter and both of its branches rather than adding a
third guard to it.

* fix(acp): keep buffered updates in global arrival order

The buffer was a map keyed by session, so releasing it walked one session
at a time. Two creations emitting A1, B1, A2 and then both failing put
A1, A2, B1 on the wire, reordering updates across sessions against the
arrival-order guarantee this boundary is supposed to provide.

Buffered updates now live in a single array in arrival order, and that
array is the only thing that decides ordering. Draining one session filters
it in place, preserving the order of everything left behind. The per-session
counts that enforce the bounds move to a separate map that is never consulted
for ordering, so there is one ordering path rather than two.

* refactor(acp): rebuild the ordering boundary around two invariants

Six rounds of point fixes each introduced the next defect, so the state
machine is rebuilt rather than patched again. Everything now follows from
two rules:

An update is queued only while some session/new response can still release
it. Nothing else introduces a session ID, so queuing outside that window
strands it by construction.

The queue drains strictly from the front and stops at the first update that
is still blocked, so releasing never emits an update ahead of one that
arrived earlier.

Three defects fall out of that directly. Correlations now settle only on
frames shaped like JSON-RPC responses, so an agent-initiated request whose
client-chosen id collides with an in-flight session/new no longer releases
that session's updates early. Draining no longer lifts one session's entries
out of the middle of the queue, so a later update cannot overtake an earlier
one when its own creation settles first. Tracking saturation is recomputed
rather than latched, so session/close frees capacity and ordering resumes
instead of failing open for the life of the process.

The released-updates side channel is gone: inbound events only change state,
and the next outbound frame drains the one queue.

* fix(acp): never clear correlation saturation

Saturation was cleared once the tracked correlations drained, on the claim
that this was the first provable quiescent point. It is not: an overflowed
session/new is by definition not in that set, so the set emptying says only
that the tracked requests finished. A later tracked creation could then
re-enable queuing and drain the overflowed session's update ahead of its own
result, which is the failure this boundary exists to prevent.

There is no point at which an uncorrelated creation is provably gone, so the
flag is never cleared. Once correlation has overflowed the boundary stays
failed open, trading ordering for a guarantee it can still honour.

* fix(acp): size the ordering bounds above what the bridge admits

The 64-request correlation cap sat below the agent's own admission limit,
which allows well over a hundred creations in its default window. An
ordinary accepted burst therefore overflowed it and, since saturation is
never cleared, permanently disabled ordering for the rest of the process:
the exact-head trace recorded 140 updates ahead of their results.

The correlation set is now uncapped. An entry is one short string, it is
removed by the response to its own request, and every entry costs the peer
a real session creation, so the agent's admission limit bounds it long
before memory does. Saturation and its permanent fail-open go with it.

MAX_QUEUED_SESSIONS had the same defect for the same reason and is raised
above the admission limit; the per-session bound is unchanged.

* fix(acp): track established sessions until they close

The 1,024-session bound was the third instance of the same defect: once a
long-lived bridge reached it, established and pending sessions became
indistinguishable and ordering was given up for the rest of the process.

It is removed rather than raised. Every entry corresponds to a session that
is live on the Gateway side, which costs orders of magnitude more than the
ID string held here, and session/close releases it, so this set can never be
the binding constraint.

Two bounds remain, both on the queue itself, which holds messages rather
than identifiers: MAX_QUEUED_SESSIONS sits above what the agent admits, and
MAX_QUEUED_UPDATES_PER_SESSION bounds a single session's initial burst. Both
fail open in the direction that only degrades ordering, never delivery.

* fix(acp): follow the session store's lifecycle and drop the last cap

Two owner-boundary defects, both at the seam between this boundary and the
work the bridge actually accepts.

MAX_QUEUED_SESSIONS was the fourth cap to sit below accepted traffic. The
admission limit is a rate, not a concurrency bound; a slow backend can hold
more accepted creations outstanding than any fixed number, and update N+1
then bypassed the queue ahead of its own result. It is removed. The number
of sessions with queued updates is the number of accepted creations still
outstanding, which the bridge already bounds. The per-session cap stays: it
is the one bound that holds messages rather than work the bridge admitted.

establishedSessionIds was released only by an inbound session/close, but the
store reaps idle sessions and evicts at capacity without producing any ACP
request, so a long-lived bridge kept recognizing sessions the store had
discarded. The store now reports every removal through onSessionRemoved,
and server.ts injects a store wired to the boundary's forget(), so
recognition follows the store's own lifecycle rather than only the close
requests a client chooses to send. The injected store is disposed on the
bridge's shutdown path since injected stores stay caller-owned.

Rebased onto current main.

* fix(acp): retire a loaded session the agent rejects

session/load and session/resume were established on arrival, before the
agent validated them. A rejected load -- one carrying per-session MCP
servers, for instance -- left its client-chosen ID recognized until close
or store removal. With the established set now uncapped, that is a growth
vector a peer controls.

The ID is still established provisionally on arrival so a loaded session's
updates are never delayed; the request is remembered by JSON-RPC ID, and an
error response retires the session it named. Bounded by in-flight loads,
each of which is real work, and cleared by its own response.

* fix(acp): only retire recognition a rejected request introduced

The previous commit retired the session named by any failing load or
resume. A session that was already established and merely reloaded lost
its recognition when that reload failed, so its later updates waited
behind an unrelated pending creation -- the delay this boundary exists to
avoid, and which it explicitly promises not to impose on existing
sessions.

Only recognition a request introduces is provisional now: the request is
remembered for retirement only when it established the ID itself.

* fix(acp): keep updates behind their session's backlog; separate claims from confirmation

Two concurrency defects at the boundary, both introduced by earlier repairs.

Strict front-of-queue draining preserved cross-session order but let a
session overtake itself: with A1, B1, A2 queued and A's result in, the drain
emitted A1 and stopped at B1, leaving A2; a later A3 then passed straight
through because A was established, so the client saw A3 before A2. A session
with updates still queued now keeps queuing regardless of recognition, so
its later updates wait behind its own backlog. The per-session overflow
fails open by releasing that session's backlog in order first, so even the
overflow path never reorders within a session.

Provisional load/resume claims shared the confirmed set, so "already
established" could not distinguish a succeeded request from a pending one.
Two overlapping loads on one session: the second succeeds, the first is
rejected, and the first's retirement erased the second's valid recognition.
Claims are now counted per session, separately from confirmation. A session
is recognized while confirmed or while any claim is outstanding; a rejection
retires exactly its own claim; acceptance confirms.

* fix(acp): release a session's backlog when its own result is written

Holding one session behind another let a prompt outrun its own output. With
A1, B1, A2 queued and A introduced, the global front-only drain emitted A1
and stopped at B1, so A kept queuing; a prompt's end_turn response carries no
session ID, never enters the queue, and therefore reached the client ahead of
the agent_message_chunk it completed.

A session's queue is now released whole when its own result is written,
rather than only the run at the head of the shared queue. Sessions are
independent streams, so ordering one against another buys nothing the client
can observe, while it does delay a session past frames that bypass the queue
entirely. Order within a session is unchanged and still exact.

The shared queue keeps global arrival order only on the path where no
creation can introduce anything, which spans sessions that were never
introduced and is the one place a cross-session rule is meaningful.

* test(acp): pin the wire order of a prompt response against its own text

Captures the ordering boundary at the ACP stdio boundary itself rather than
through the ordering class alone: two session/new requests are outstanding at
once, so an update for either is held, and the prompt response that completes
one of them carries no session ID and so passes through the boundary untouched.

Asserted as one five-frame sequence. Frame-by-frame assertions stop at the
first divergence, which hides where a displaced frame actually lands - and
where it lands is the defect.

* test(acp-core): stop shadowing the suite store in the removal-hook test

oxlint eslint(no-shadow) flagged the local store in the onSessionRemoved test
against the suite-level one. Renamed rather than reusing the outer store: the
test needs its own maxSessions and idleTtlMs to reach the eviction paths.

* test(acp): keep ordering fixtures type-safe

* fix(ci): consume canonical ACP landing prerequisites

Reuse the published UI and native closure fixes from openclaw#150026 and openclaw#114032.
Match the landed Slack correction from openclaw#111148, including openclaw#150457.
Keep the qualified ACP production code and SDK proof unchanged.

Co-authored-by: pash-openai <[email protected]>

* test(update): await report staging before cleanup race

---------

Co-authored-by: Jason (Json) <[email protected]>
Co-authored-by: pash-openai <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

P1 High-priority user-facing bug, regression, or broken workflow. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. size: XL status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants