Repository navigation
fix(acp): order new session response before updates - #110455
fuller-stack-dev merged 25 commits into
Conversation
|
Codex review: needs maintainer review before merge. Reviewed September 16, 2026, 11:20 PM ET / September 17, 2026, 03:20 UTC (Revision 40). ClawSweeper reviewWhat this changesThe PR orders ACP session-creation responses before initial updates, connects buffer cleanup and output failures to bridge shutdown, and synchronizes an update-report cleanup test. Merge readiness✅ Ready for maintainer review This remains a useful fix: current main and v2026.9.4 retain the reported ordering problem. Prior tracking findings are resolved, the accepted transport proof remains applicable, and no new blocking defect was found. Priority: P1 Review scores
Verification
How this fits togetherThe ACP bridge connects editor clients over standard input/output to OpenClaw Gateway sessions. Its transport boundary orders session responses and streaming updates before sending them back to the client. flowchart LR
A[Editor client] --> B[Inbound request tracking]
B --> C[ACP bridge and Gateway]
C --> D[Outbound ordering boundary]
D --> E{Session introduced?}
E -->|No| F[Buffer initial updates]
F --> D
E -->|Yes| G[Response then session updates]
G --> A
Before mergeNone. Agent review detailsSecurityNone. PR surfaceSource +284, Tests +1106. Total +1390 across 8 files. View PR surface stats
Review metrics
Root-cause clusterRelationship: Members:
Proposal only: this assessment does not dispatch repair, suppress jobs, mutate sibling items, close, or merge anything. Technical reviewBest possible solution: Keep ordering at the stdio boundary, preserve independent session streaming, and let the existing session store own lifecycle cleanup. Do we have a high-confidence way to reproduce the issue? Yes: current-main lifecycle code emits initial notifications before returning, and the inspected SDK serializes the result afterward. Recorded transport traces corroborate the mechanism; this review did not execute a new reproduction. Is this the best way to solve the issue? Yes: enforcing order at the serialization boundary avoids timer assumptions, preserves existing-session replay, and uses the existing store for cleanup rather than creating another session owner. AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning medium; reviewed against 26d2daa2c294. LabelsLabel justifications:
EvidenceWhat I checked:
Likely related people:
Rating scale
Overall follows the weaker of proof and patch quality. Workflow
HistoryReview history (39 earlier review cycles; latest 8 shown)
|
|
Added current-head ACP stdio-boundary behavior proof in d8df408. The new startup integration test drives messages through Observed frame order (redacted): {
"sessionLoad": [
{"method":"session/update","params":{"sessionId":"existing-session"}}
],
"sessionNew": [
{"id":2,"result":{"sessionId":"new-session"}},
{"method":"session/update","params":{"sessionId":"new-session"}}
]
}The test first waits until the existing-session update reaches the NDJSON boundary, then verifies the unknown new-session update is still buffered, writes the matching result, and verifies result-before-update ordering. Validation on Node 24.18.0 / pnpm 11.2.2:
|
d8df408 to
72c55bd
Compare
|
Added unmocked current-head behavior proof after rebasing onto upstream Setup:
Redacted stdout frame order: [
{"id":1},
{"id":2,"sessionId":"<new-session>"},
{"method":"session/update","sessionId":"<new-session>"},
{"method":"session/update","sessionId":"<new-session>"},
{"method":"session/update","sessionId":"existing-proof-session"},
{"method":"session/update","sessionId":"existing-proof-session"},
{"id":3}
]This shows the The temporary unmocked proof harness passed in 55.1s and was removed after capture. The committed focused suites also pass after the rebase: 2 files, 24 tests. @clawsweeper re-review |
|
🦞🧹 I asked ClawSweeper to review this item again. |
|
Addressed the remaining P3: replaced the helper-local @clawsweeper re-review |
|
🦞🧹 I asked ClawSweeper to review this item again. Re-review progress:
|
|
Both remaining P2s are addressed in 01beed5d6db. Track only protocol-established session IDs (
All three collections are peer-driven, so all three are bounded (64 sessions, 256 updates per session, 64 in-flight Route outbound pipe failures through shutdown (
Coverage — 7 new tests, each aimed at one of the two findings:
The teardown test drives a rejecting NDJSON sink and asserts the agent, Gateway, and state database are all closed — it fails against the previous Verification on Node 26.5.0 / pnpm 11.15.1, current head Test count went 24 → 31 with the 7 additions above. @clawsweeper re-review |
|
🦞🧹 I asked ClawSweeper to review this item again. Re-review progress:
|
|
🦞🧹 I asked ClawSweeper to review this item again. Re-review progress:
|
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.
|
Fixed in f203c69. My retirement path was too broad: it retired the session named by any failing load or resume, including one that merely reloaded a session already live. That session then lost recognition and its next update waited behind an unrelated pending creation — the exact delay this boundary promises never to impose on an existing session. Only recognition a request introduces is provisional now: const alreadyEstablished = this.establishedSessionIds.has(sessionId);
this.establish(sessionId);
const requestId = readRequestId(messageObject?.id);
if (!alreadyEstablished && requestId !== undefined) {
this.provisionalSessions.set(requestId, sessionId);
}A reload of a live session records nothing, so its rejection retires nothing. Coverage — Negative control, I have not re-captured the wire trace for this commit. The change is a condition on which requests are recorded for retirement; the @clawsweeper re-review |
|
🦞🧹 I asked ClawSweeper to review this item again. Re-review progress:
|
…s 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.
|
Both fixed in 39052af. Both were introduced by my own earlier repairs, and I want to name the mechanism, because it explains why this PR has taken as many rounds as it has. [P1] A session overtaking its own backlog. Strict front-of-queue draining was my fix for cross-session reordering. It preserved that, and created intra-session reordering: with The rule now: a session with updates still queued keeps queuing, recognized or not. [P2] Overlapping loads erasing each other. Provisional claims and confirmed sessions shared one set, so Coverage — 2 new tests, both failing on
Negative control, On the pattern. Rounds 3 through 13 of this PR have each fixed the finding named and introduced the next one, and every one of those was in code I added, not in the original fix. The root cause is not any single finding: it is that I kept deriving one invariant at a time under review pressure instead of laying out the full ordering contract before writing. I do not think the two rules now in the file — queue only while a creation can release you and never let a session pass its own backlog — have a further hole in the concurrency space you have been probing, but I have been wrong about that before on this PR and would rather say so than assert it. The @clawsweeper re-review |
|
🦞🧹 I asked ClawSweeper to review this item again. |
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.
|
Fixed in 8d1632b, and this one taught me something about the shape of the problem rather than just about a bug. I had been treating cross-session ordering as a guarantee worth defending — that was the point of the front-only drain. It is not one. Sessions are independent streams, so ordering A's updates against B's buys nothing a client can observe, while it does hold A behind B, and frames that carry no session ID bypass the queue entirely. A prompt's A session's queue is now released whole when its own result is written. Within a session the order is exact and unchanged. The shared queue keeps global arrival order on exactly one path — where no creation can introduce anything, so every queued session is one that was never introduced — which is the only place a cross-session rule means anything. This also answers your note about the production-line growth: session-local release removes the connection-wide coupling rather than adding to it. Coverage — 3 tests, all failing on
The third had encoded cross-session blocking as the expected behaviour; it now asserts each session releasing on its own result, which is what the boundary actually promises. Negative control, I have not re-captured the wire trace. The @clawsweeper re-review |
|
🦞🧹 I asked ClawSweeper to review this item again. Re-review progress:
|
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.
|
Captured in 113b0b7. This is the wire trace I said I had skipped — the Scenario. Two Outbound frames on 113b0b7: Same scenario, The chatty session's text moves from frame 2 to frame 5. A client that renders Why one assertion over the whole sequence. My first version checked frame by frame, and on the reverted build it stopped at frame 2 — proving the backlog was not released, but never showing where the displaced frame lands, which is the part that matters. Asserting the five-frame sequence as a unit makes the failure print the actual wire order.
What this harness does and does not cover, so it is not read as more than it is: it drives the real @clawsweeper re-review |
|
🦞🧹 I asked ClawSweeper to review this item again. Re-review progress:
|
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.
|
Two things in The description was stale and I have rewritten it. It still described the first design — a single global buffer that holds updates until the matching
@clawsweeper re-review |
|
🦞🧹 I asked ClawSweeper to review this item again. Re-review progress:
|
|
@steipete — asking for a ruling rather than another review round. Pinging you specifically because you wrote 24 of the last 40 commits under The one open design question. The boundary holds a single cap ( ClawSweeper labelled that Size, in the units that matter. Current state. 59 tests across 3 files, green; Glad to keep changing it if you want changes. I would rather iterate against your call than keep re-deriving the contract one round at a time, which is honestly what most of this PR's length is. |
|
@clawsweeper re-review Current-source repair is published at |
|
🦞🧹 I asked ClawSweeper to review this item again. Re-review progress:
|
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]>
Resolve the file-preview locale conflict by retaining the exact landed openclaw#150491 UI implementation and removing the earlier consumed alternative. Slack, native manifest, and cold fixture now match canonical main. The seven ACP source/test files and pinned SDK inputs remain unchanged. The UI loading regression and canonical fixed-input performance comparison pass (362561B <= 362588B); scoped P0-P2 review has no findings.
|
This assigned pull request has been automatically marked as stale after being open for 27 days. |
|
Merged via squash.
|
What Problem This Solves
Fixes #109961.
ACP
session/newemits its initialsession/updatenotifications before returning the JSON-RPC result that introduces the newsessionId. A client that requires the result before accepting updates discards those notifications, and the new session cannot proceed.Why This Change Was Made
AcpGatewayAgent.newSession()has to gather and emit the initial snapshot through the ACP connection before its handler can return, and the SDK serializes the request result only after that handler resolves. No arrangement of awaits inside the translator can fix the wire order, so the invariant is enforced at the stdio boundary instead:src/acp/server.tswraps the NDJSON stream in a transform pair that observes inbound requests and orders outbound frames.Two invariants carry the design:
session/newresponse can still release it. Nothing else introduces a session ID, so queuing outside that window would strand the update for the life of the process.Within a session the order is exact. A session with updates still queued keeps queuing, recognized or not, so a newer update can never pass an older one from the same session.
Client-supplied session IDs are handled separately.
session/loadandsession/resumeregister a claim on the session, counted per session and recognized immediately so their updates are never delayed; acceptance confirms the session, and a rejection retires only its own claim, so one failing load cannot erase recognition another established. Responses are identified by shape — nomethod, carryingresultorerror— so an agent-initiated request such asrequestPermissioncannot settle a correlation and release a session's updates ahead of its result.The boundary also has to stay in step with session lifetime. Idle reaping and capacity eviction remove sessions without any ACP request the boundary could observe, so
packages/acp-core/src/session.tsgains anonSessionRemovedhook that reports every removal it performs, and the server wires it to the boundary'sforget.One bound remains:
MAX_QUEUED_UPDATES_PER_SESSION = 256. It fails open by releasing that session's backlog in order and writing the overflowing update through — cross-session order degrades there, intra-session order does not. Dropping an update would lose session content permanently, whereas emitting one early only restores the ordering that existed before this boundary.User Impact
ACP clients receive the
session/newresult before any update referencing the returnedsessionId, and receive a session's text before the prompt response that completes it. Existing-session flows (session/load,session/resume) keep their current streaming behaviour with no added delay.Evidence
The final candidate passed 18 real-SDK/NDJSON acceptance cases, 21 ordering regressions, 12 session-store tests, and all 26 server startup/shutdown cases (including the corrected async-close mock). The original correlation code failed 11 acceptance cases; the separate null-ID protocol-error regression also failed before its repair. The actual mixed-session byte-stream transcript and exact commands follow. Fresh independent review found no actionable P0–P2 issues; remaining static checks and exact-head CI are required before native landing.
Test-type correction and CI disposition
The three CI test-type errors are corrected without production changes: use the existing guarded Gateway accessor, the repository typed deferred helper, and checked burst-test entries. All 18 SDK/NDJSON acceptance cases and the two affected ordering/shutdown cases pass again. The complete changed-file check passed, including both core typecheck lanes, all three dead-export scans, lint (zero warnings/errors), and the native/runtime/auth guards; the fresh P0–P2 review of this test-only delta is scoped-clean.
ClawSweeper revision 38 reviewed production head
5542e6bb0f70and found no blocking code/security findings; it explicitly accepted the actual mixed-session SDK/NDJSON proof and closed both prior tracking findings. The typing-only follow-up does not change production behavior.The original hosted run also exposed baseline Slack cycle/lint, UI-startup budget, and cold/native-fixture failures. Existing canonical owners #150026 and #114032 are repairing those scopes. No assertions, budgets, trust checks, or CI gates are weakened here; required exact-head CI must be green before native preparation/landing.
Current-source integration and acceptance
Integrated current main
a90b969ae261de04052c029e3c24e543b5786be1while retaining contributor headc5e1a1b5dbdf8f50e4dd80dde2cc28ed696870cfas an ancestor. Both conflicts were resolved in the lifecycle owners: current retry-safe asynchronous shutdown and the simplified session registry remain intact.Root cause and repair
The translator emits initial snapshots before returning, while the ACP SDK serializes the creation result only after that return. The stdio boundary is therefore the ordering owner; a translator timer or microtask cannot guarantee response-before-update wire order. The repair preserves per-session backlog release, prompt text before completion, and independent overlapping load/resume claims.
Request tracking now matches the installed SDK 1.4.0 envelope contract and retains native JSON-RPC ID types, including empty strings and null. Malformed envelopes create no correlation. SDK uncorrelated null-ID invalid-request errors cannot retire a valid null-ID creation. Parameter-validation errors still retire their own admitted requests. The SDK does not publicly export its envelope predicates; this narrow predicate matches the directly inspected implementation without importing a private subpath.
Fresh actual SDK/NDJSON evidence
src/acp/session-new-ordering.sdk.test.tsuses the real installed AgentSideConnection, real ndJsonStream, byte streams, and real in-memory session store. The upstream agent handlers are synthetic deterministic fixtures; this is not an authenticated provider or Rabbit R1 test. Previous real Gateway/spawned-ACP traces remain relevant and were not replayed.Negative controls: 11 failures / 6 passes on the original correlation implementation after current-main integration. A separate null-ID/protocol-error collision failed before its repair. The final 18-case SDK acceptance suite passes, covering empty/null/numeric/string IDs, concurrent slow/chatty creation and prompt completion, load/resume replay, malformed envelopes, SDK parameter failures, store eviction, output failure, and the stable SDK's actual rejection of NDJSON batches. Stable v1 disables batches; no new batch support or protocol version change is introduced.
Actual accepted mixed-session output (captured from the NDJSON byte sink):
The slow creation is still outstanding when the chatty prompt and both replay flows complete. Its initial update follows its own response.
Scope and compatibility
No config/default, authentication, Gateway request, schema/version, cache identity, persisted-data format, or provider behavior change. Current main's event-ledger and async shutdown semantics are preserved. The only session-store addition is a removal callback for the transport projection, used by explicit deletion, idle reaping, capacity eviction, and disposal.
Production delta against integrated main: +286/-2 (net +284); tests +1102/-1 (net +1101). This is down from the incoming net +369 production lines. Remaining growth implements a missing wire-ordering responsibility and its removal lifecycle, not a second session authority. Historical repetitive commentary was reduced; the existing fail-open 256-update per-session overflow behavior is retained.
Commands/evidence:
node scripts/run-vitest.mjs src/acp/session-new-ordering.sdk.test.ts packages/acp-core/src/session.test.ts: 18 + 12 passed.node scripts/run-vitest.mjs src/acp/session-new-ordering.test.ts: 21 passed as part of the initial focused run.src/acp/server.startup.test.ts: 25 cases passed; the final output-failure case passed after adapting its mock to current async database-close API. No unchanged case was replayed.967a6925fdf1df8ec60f69117418797eb2448b13.Known bound: when a session exceeds 256 queued initial updates, its backlog is released in order (fail-open) rather than dropping content. This is unchanged from the contributor implementation. No live provider calls, memory indexing writes, or operator Gateway restart were used.
Earlier contributor proof (retained; not replayed)
oxlintandoxfmt --checkare clean across all six changed files.Wire-level proof of the ordering guarantee, recorded through the real
serveAcpGatewayplumbing with twosession/newrequests outstanding at once and a prompt running on one of them:With
session-new-ordering.tsalone reverted to39052af4, the same scenario puts the completion response at frame 2 and the text it completes at frame 5. Each behavioural commit in this PR carries a test that fails on its parent; the negative controls are recorded in the review thread.AI-assisted with Codex. The implementation and tests were reviewed and run locally by the contributor.
Current CI prerequisite integration
Candidate:
d09745f88eaedd3e188c7b3d305ec0a5b409dd89, integrating current main90b421ae252ceaea5bf5a9f106eab51bf384431bto resolve a real locale conflict.The seven ACP source/test files and their pinned SDK inputs are unchanged from the accepted
967a6925qualification above; the 77-case genuine SDK/NDJSON proof is retained, not replayed. The remaining diff against integrated main is those seven files plus the update-report test synchronization repair.The original exact-head CI run exposed shared baseline failures. Their canonical fixes are now on main: the native manifest closure owned by #114032, the cold fixture dependency, and the exact landed Slack implementation from #111148 including #150457. The superseded #150482 classifier alternative is not retained.
For UI, the earlier published #150026 prerequisite was replaced completely by the exact landed #150491 implementation when main advanced. The UI subtree and catalog loader match that main commit. The cold loading/language-fallback regression and full
pnpm ui:i18n:verifypassed; fresh scoped independent review found no actionable P0-P2 findings. The actual hosted fixed-input comparison command (pnpm ui:check-performance:base 90b421ae252ceaea5bf5a9f106eab51bf384431b) passed at 362,561 B gzip <= 362,588 B, with unchanged thresholds and baseline. An ordinary developer-metadata build measured 362,615 B; it is not the fixed-input CI measurement and is not represented as a passing budget check.The only additional test repair awaits the existing second-validation callback after asynchronous artifact staging in the delayed update-report cleanup test. Explicit call-count, successor-content, cleanup assertions, and timeout settings remain unchanged; production code is untouched. Its 20-case suite and scoped independent review passed.
Retained prerequisite validation: 54 tooling tests passed, 1 platform-specific skip; 31 Slack tests passed on the landed implementation; 208 unchanged callback/preview tests passed. Applicable types/export scans, targeted lint, and both import-cycle checks passed. Broad local extension lint stopped before analysis at the nested-install declaration boundary (
qrcodein the ancestor install); the boundary was preserved without modifying shared dependencies. The priorf3c466i18n log reported fallback-baseline drift despite success metadata; it is not counted as passing evidence. The canonical replacement passes the actual local verification command. Required exact-head CI35177138475 passed ond09745f88eaedd3e188c7b3d305ec0a5b409dd89: 109 successful jobs, 17 skips, no error annotations. Native prepare also passed on that same head without a rebase or redundant push.