Repository navigation
fix(streaming): avoid cosmetic edit race against finalize delivery - #1599
Conversation
ttmuse
left a comment
There was a problem hiding this comment.
Thanks — this matches the failure mode exactly, and the direction is right: the fix is to settle the in-flight edit before finalize writes, not to abort harder. Two things I verified while reading: buf_tx is never cloned (only borrowed), so drop genuinely closes the watch channel and the closure branch of the select! will fire; and with the bounded await, PATCH #B is only sent after PATCH #A's response returns, which restores server-side ordering in the common case (RTT ≪ 3s).
Two comments:
- The >3s timeout path still contains the original race in principle: after
abort_handle.abort()there is no further await, and finalize proceeds immediately — if that request was already on the wire, it can still land last. I agree it's an acceptable residual risk, but please state it in the code comment at the abort site, so the comment doesn't repeat PR #1122's mistake of describing the residual window as merely cosmetic. - I'd prefer the deterministic regression test (paused time + barrier in TestAdapter) to land with this PR rather than as a follow-up — race fixes without a test tend to regress silently. If maintainers are fine deferring it, I won't block on it.
CI note: check is green so far; smoke tests still running at the time of this review.
There was a problem hiding this comment.
Review of 41ab4d6 — changes requested
The main change is right: before finalizing, wait up to 3 s for an in-flight cosmetic edit instead of aborting it straight away. In the normal case this fixes the ordering on Discord, Slack and the gateway, and it cannot add or drop messages. The points below still need work before LGTM.
1. The timeout path does not wait for the task to stop — crates/openab-core/src/adapter.rs:1107-1115
tokio::time::timeout(Duration::from_secs(3), handle) takes ownership of the JoinHandle. When it times out, the handle is dropped, and abort_handle.abort() only requests cancellation. Final delivery then starts without confirming that the task has stopped. Slack's HTTP client allows 30 s, and Discord can sit in rate-limit handling, so this branch can actually be hit. A stale …<tail> preview can then land after the final edit, which is the bug this PR is meant to fix. The comment says "without detaching a stale task", but the code does detach it.
Suggested fix:
let mut handle = handle;
if tokio::time::timeout(Duration::from_secs(3), &mut handle).await.is_err() {
tracing::warn!(/* … */);
handle.abort();
let _ = handle.await; // confirm termination before final delivery
}Please also bring back a sentence explaining that on the >3 s path, a request already sent over the network cannot be recalled and may still land after finalize. That leaves a stale preview as the final view until a later edit.
2. No regression test, and Acceptance Criteria 1 and 2 have no evidence
This is a race fix whose correctness depends on the scheduler, and the PR changes only production code. docs/review-contract.md requires every AC to be satisfied for LGTM. One cheap way to get a deterministic test:
- Extract the edit loop and the join into small functions, for example
spawn_cosmetic_edit_loop(...) -> JoinHandle<()>andsettle_edit_task(handle, Duration). - Use a hand-written
ChatAdaptertest double whoseedit_messagerecords each call and waits on atokio::sync::Notifygate. Run it with#[tokio::test(start_paused = true)]. - Cover three cases:
- (a) An edit is in flight when the sender is dropped. Settle returns only after the edit finishes, and no second edit happens.
- (b) The gate is never released. Settle returns at 3 s, and the task has stopped when it returns.
- (c) The sender is dropped during the sleep. There are zero edits, and settle returns immediately.
3. Root cause #1 does not exist in the old code
In tokio 1.52.3 (the version in Cargo.lock), watch::Receiver::has_changed() returns Err once the sender is dropped, even when an unseen value is still pending (tokio/src/sync/watch.rs ~L738). So when the old sleep → has_changed().unwrap_or(false) loop ticked after drop(buf_tx), it did not edit and exited on the next check. The old code never sent an edit after close.
The select! on closure is still worth keeping, but for a different reason. Without abort(), a task parked in the 1.5 s sleep would hold up the bounded join, and the closure branch makes it exit promptly. Please update the comment at adapter.rs:829-830 and the "What problem does this solve?" section to match. The first paragraph there also mentions rx.changed(), which the old loop never called.
4. Review Contract
The 3 s cap with its remaining risk, and the deferred test, both say "pending maintainer sign-off". A maintainer needs to accept or revise them, and the freeze should be recorded per the contract doc.
Minor
- CI
checkpasses at this head. The failingsmoke-test (Dockerfile.mimocode…)job is an ACP handshake failure in that agent image, and the unified mimocode smoke job passes, so it does not appear related to this change. - CI does not check formatting, so please run
cargo fmt --check.
This comment has been minimized.
This comment has been minimized.
This comment has been minimized.
This comment has been minimized.
…tests Address review feedback on the finalize settle path: - On the timeout path, abort and then join the edit task, so it can no longer write after finalize starts. Document the residual risk of a request that was already on the wire. - Extract the loop into spawn_cosmetic_edit_loop and the join into settle_cosmetic_edit_task, with named COSMETIC_EDIT_INTERVAL and COSMETIC_EDIT_SETTLE_TIMEOUT constants. - Correct the biased select comment: it makes the loop exit promptly on close so the settle join is not padded by the sleep. The old loop already skipped edits after close. - Add paused-time tests for close during sleep, an in-flight edit that settles before finalize, and a stalled edit that is aborted and joined at the cap.
This comment has been minimized.
This comment has been minimized.
This comment has been minimized.
This comment has been minimized.
This comment has been minimized.
This comment has been minimized.
The finalize call-site comment said a stale preview "cannot" overwrite the final write. On the settle-timeout path an edit already on the wire can still land last (documented at settle_cosmetic_edit_task), so say "in the normal case" and point to the helper. Also apply rustfmt to adapter.rs, the only file this PR touches. No behavior change. Verified on macmini (rustfmt 1.10.0, clean rsync copy of this tree): - rustfmt --edition 2021 --check crates/openab-core/src/adapter.rs: pass - cargo fmt --check (workspace): fails on 36 files this PR does not touch (pre-existing on main; CI does not run fmt); left unchanged - cargo clippy -- -D warnings: pass - cargo test -p openab-core: 706 passed, 1 failed. The failure is secrets::tests::resolve_exec_nonzero_exit, which execs /bin/false; macOS has no /bin/false (only /usr/bin/false). Unrelated to this PR, passes on Linux CI. cosmetic_edit_tests (3 tests) pass.
Review Contract freezeRecorded by chaodu-agent on behalf of @pahud (maintainer), per
The hash covers the PR description text from the Maintainer decision on residual risk: Accepted Residual Risk 1 (on the >3 s settle-timeout path, a cosmetic edit already on the wire, such as a Slack Any change to the contract text after this point is a contract revision and needs maintainer approval. Frozen contract text (pr1599-contract-r3)## Review Contract
### Goal
Ensure cosmetic streaming edits in `stream_prompt_blocks` stop as soon as the content channel closes at turn end, without issuing a post-close edit and without waiting out the 1.5 s interval, and let any in-flight cosmetic `edit_message` settle (bounded to 3 seconds) before final delivery edits or sends the final message.
### Non-goals
- Eliminating the residual race on the >3 s timeout path (see Accepted Residual Risks); a single-writer design is tracked in #1600.
- Changing HTTP retry/cancellation behavior inside `DiscordAdapter`, `SlackAdapter`, or `GatewayAdapter`.
- Altering the 1500 ms cosmetic debounce cadence or `truncate_chars_tail` preview truncation format.
### Accepted Residual Risks
1. **Stale preview on the >3 s timeout path.** If an in-flight cosmetic `edit_message` does not finish within `COSMETIC_EDIT_SETTLE_TIMEOUT` (3 s), `settle_cosmetic_edit_task` logs `tracing::warn!`, aborts the task and joins it, so the task cannot start or resume an edit after finalize begins and turn completion is not blocked. A request already written to the wire cannot be recalled: a Slack `chat.update`, or a Discord edit retried after a 429, may land after the final edit and leave a stale `...<tail>` preview visible. For gateway platforms, openab → gateway ordering is fixed over one WebSocket, but the gateway's downstream HTTP calls have no ordering guarantee. Impact is cosmetic; the full answer was produced. Mitigation: the `cosmetic edit task did not settle at finalize; aborting` warning identifies affected turns. Recovery: a later edit or a resend of the answer replaces the preview. Accepted by the maintainer as a known limitation, tracked in #1600.
### Acceptance Criteria
- [x] Dropping `buf_tx` exits the cosmetic edit loop during its sleep without executing another cosmetic `edit_message`, and without waiting out the 1500 ms interval. Test: `cosmetic_edit_tests::close_during_sleep_exits_without_edit`.
- [x] At turn end, finalize waits up to 3 s for an in-flight cosmetic `edit_message` to finish before final delivery, and only on timeout warns, aborts and joins the task so it never records an edit afterwards. Tests: `cosmetic_edit_tests::in_flight_edit_settles_before_finalize`, `cosmetic_edit_tests::stalled_edit_is_aborted_and_joined_at_cap`.
- [x] GitHub Actions `CI / check` passes (`cargo check --workspace`, `cargo clippy --workspace -- -D warnings`, and workspace tests).
### Follow-ups
- #1600: remove the >3 s residual risk, either by re-sending the final edit after a timed-out cosmetic edit settles, or with a per-message writer task that is the only writer for a message. Must never re-write after the placeholder was deleted or replaced. |
|
Note LGTM ✅ - At What This PR DoesAt turn end, How It Works
Findings
Finding Details🟢 F1: Abort and join on the timeout path
🟢 F2: Deterministic tests
🟢 F3: Accurate finalize commentThe call-site comment now says a stale preview does not overwrite the final write "in the normal case", and that on the >3s timeout path an edit already sent can still land last, pointing to 🟢 F4: Review Contract freezeThe SHA-256 of the contract section in the PR description ( Addressing Previous Rounds and External Reviewer FeedbackThere are no inline review threads on this PR. All feedback was left as review bodies and is answered here. Previous round findings (rounds 1-5)
External reviewer (review on
|
| Reviewer | Verdict | Key findings |
|---|---|---|
| Reviewer A (previous round) | No objection once the maintainer accepts the best-effort behavior (now accepted) | Confirmed the earlier fixes and the helper extraction; wire-level ordering is the only remaining point |
| Coordinator baseline (this round) | LGTM | Verified the 74f2a39 comment fix, the contract hash against the freeze record, and CI |
| Reviewer C (previous round) | CHANGES REQUESTED, merge after the comment and contract fixes (both now done) | Confirmed task-level ordering tests; recommended a single per-message writer as follow-up (#1600) |
CI / Status
- Every check passes at
74f2a39, includingcheck(cargo check, clippy-D warnings, workspace tests).operatorandpoll-and-revieware skipped. 74f2a39also reformatsadapter.rswith rustfmt, so the file is formatting-clean. Some of those hunks touch unrelated functions (parse_output_directives,contains_bot_mention,compose_display); they are formatting only and do not change behavior.
Non-blocking Follow-ups
- streaming: stale preview can still land after the final edit when the cosmetic edit settle times out (>3 s) #1600: remove the >3s residual risk with a final-edit resend after a timed-out cosmetic edit settles, or with one writer task per message. It must never rewrite after the placeholder was deleted or replaced.
limit - 100underflow: pre-existing onmain;saturating_sub(100)would avoid a panic if an adapter ever reportsmessage_limit < 100.- PR title: "reduce" describes the change more accurately than "avoid".
Baseline Check
- PR opened: 2026-11-15
- Base:
main(default branch, not stacked); head74f2a39d794230151aaacb05b076f95e1f548a26 - Commit since the previous round:
74f2a39(finalize comment wording plus rustfmt ofcrates/openab-core/src/adapter.rs, +38 / -17) - Main already has:
drop(buf_tx)followed byabort()+handle.awaitat finalize (fix(streaming): recover from Feishu 20-edit cap (errcode 230072) #1122) - Net-new value: an in-flight cosmetic edit may finish (up to 3s) before finalize, the loop exits immediately on close, the timeout path still joins, and the lifecycle has deterministic tests
What's Good (🟢)
- The loop and the shutdown join are separate helpers with one job each, which made the race testable and keeps them easy to replace in streaming: stale preview can still land after the final edit when the cosmetic edit settle times out (>3 s) #1600.
- The residual risk is written down in code, in the frozen contract, and in a tracking issue.
5. Three Reasons We Might Not Need This PR
- Main already had a join barrier - The net gain is that a slow edit can finish instead of being cancelled, at the cost of up to 3s of extra finalize latency when an edit is stalled. A normal close exits immediately.
- The remaining stale-tail case is display-only and rare - It needs an HTTP edit still in flight for more than 3s when the turn ends.
- A real ordering guarantee needs a different design - streaming: stale preview can still land after the final edit when the cosmetic edit settle times out (>3 s) #1600 may replace these helpers with a single writer per message, which makes this PR a stepping stone.
What problem does this solve?
At the end of a streamed turn in
stream_prompt_blocks(crates/openab-core/src/adapter.rs), the background cosmetic streaming edit task can complete out of order relative to finalization, overwriting the authoritative finalized reply with a stale, tail-truncated streaming preview (…<tail>viaformat::truncate_chars_tail(&content, limit - 100)).Two points about the old code at finalize (
conn.prompt_done().await):buf_txis dropped,buf_rx.has_changed()returnsErr, so the post-sleep check skipped the edit and the loop exited. But it only noticed closure after its 1.5 ssleepfinished, so withoutabort()the finalize join would wait out that sleep. Abiased;tokio::select!with the closure branch first makes the loop exit as soon as the channel closes.handle.abort()followed bylet _ = handle.await;cancels the task at an arbitrary await point. An edit already sent to the platform cannot be recalled, so it races the finalize write on the network and can land last. Letting the in-flightedit_messagesettle first (bounded) fixes the common case.Discord Discussion URL: https://discord.com/channels/1491295327620169908/1571524487881687181
Review Contract
Goal
Ensure cosmetic streaming edits in
stream_prompt_blocksstop as soon as the content channel closes at turn end, without issuing a post-close edit and without waiting out the 1.5 s interval, and let any in-flight cosmeticedit_messagesettle (bounded to 3 seconds) before final delivery edits or sends the final message.Non-goals
DiscordAdapter,SlackAdapter, orGatewayAdapter.truncate_chars_tailpreview truncation format.Accepted Residual Risks
edit_messagedoes not finish withinCOSMETIC_EDIT_SETTLE_TIMEOUT(3 s),settle_cosmetic_edit_tasklogstracing::warn!, aborts the task and joins it, so the task cannot start or resume an edit after finalize begins and turn completion is not blocked. A request already written to the wire cannot be recalled: a Slackchat.update, or a Discord edit retried after a 429, may land after the final edit and leave a stale...<tail>preview visible. For gateway platforms, openab → gateway ordering is fixed over one WebSocket, but the gateway's downstream HTTP calls have no ordering guarantee. Impact is cosmetic; the full answer was produced. Mitigation: thecosmetic edit task did not settle at finalize; abortingwarning identifies affected turns. Recovery: a later edit or a resend of the answer replaces the preview. Accepted by the maintainer as a known limitation, tracked in streaming: stale preview can still land after the final edit when the cosmetic edit settle times out (>3 s) #1600.Acceptance Criteria
buf_txexits the cosmetic edit loop during its sleep without executing another cosmeticedit_message, and without waiting out the 1500 ms interval. Test:cosmetic_edit_tests::close_during_sleep_exits_without_edit.edit_messageto finish before final delivery, and only on timeout warns, aborts and joins the task so it never records an edit afterwards. Tests:cosmetic_edit_tests::in_flight_edit_settles_before_finalize,cosmetic_edit_tests::stalled_edit_is_aborted_and_joined_at_cap.CI / checkpasses (cargo check --workspace,cargo clippy --workspace -- -D warnings, and workspace tests).Follow-ups
At a Glance
Prior Art & Industry Research
OpenClaw:
src/channels/draft-stream-loop.tsandsrc/channels/draft-stream-controls.ts,createFinalizableDraftStreamControlsprovidesseal()/stopPending(), which marks the stream final, stops pending scheduled timer flushes (loop.stop()), and explicitly awaitsloop.waitForInFlight()before handing control back to the caller that owns final delivery so an in-flight preview edit cannot race finalization.Hermes Agent:
gateway/platforms/base.py(BasePlatformAdapter.edit_message(..., *, finalize=False)) andgateway/run_turn_final_reconcile.py, preview streaming updates are separated fromfinalize=Truedelivery and explicitly reconciled in-place rather than leaving uncoordinated background edits racing final state.Proposed Solution
In
stream_prompt_blocks(crates/openab-core/src/adapter.rs), with the loop and the join extracted intospawn_cosmetic_edit_loopandsettle_cosmetic_edit_task:watch::Receiverintobuf_rx(content reads) andclose_rx(closure detection).COSMETIC_EDIT_INTERVAL) sleep in the cosmetic loop with abiased;tokio::select!whose first branch waits for channel closure, so the loop exits as soon asbuf_txis dropped instead of finishing the sleep. The old loop already skipped edits after close (has_changed()returnsErronce the channel is closed); the select exists so the finalize join does not wait out the interval.conn.prompt_done().await),drop(buf_tx)first, thensettle_cosmetic_edit_taskawaits the task for up to 3 s (COSMETIC_EDIT_SETTLE_TIMEOUT) viatokio::time::timeout. Only if it times out does it logtracing::warn!, abort the task and join it, so the task is gone before finalize writes.Why this approach?
Minimal, localized change: the close-first
select!lets the loop stop promptly at turn end, and the bounded 3 s settle replaces an unconditionalabort()(which cancels an edit that may already be on the wire) without risking an unbounded wait on long 429 retry backoffs. It handles the common case, where the in-flight edit finishes within 3 s, and avoids refactoring outsidestream_prompt_blocks. Removing the remaining >3 s case needs a single-writer design, tracked in #1600.Alternatives Considered
handle.abort()+handle.await: Leaves an in-flight HTTP edit ambiguous or abruptly dropped depending on driver buffering rather than letting normal edits finish cleanly before finalize.handle.awaitafterdrop(buf_tx): Eliminates cancellation mid-edit, but risks stalling final message delivery indefinitely if an upstream platform edit hangs on long 429 retry backoffs.Validation
cosmetic_edit_testsincrates/openab-core/src/adapter.rs, three paused-time tests (close_during_sleep_exits_without_edit,in_flight_edit_settles_before_finalize,stalled_edit_is_aborted_and_joined_at_cap).CI / check(cargo check --workspace,cargo clippy --workspace -- -D warnings, workspace tests) on the PR head.rustfmt --edition 2021 --check crates/openab-core/src/adapter.rs: pass (rustfmt applied toadapter.rs, the only file this PR changes).cargo fmt --check: fails on 36 other files this PR does not touch; pre-existing onmainand not run by CI, so left unchanged.cargo clippy -- -D warnings: pass.cargo test -p openab-core: 706 passed, 1 failed. All threecosmetic_edit_testspass. The failure issecrets::tests::resolve_exec_nonzero_exit, which execs/bin/false; macOS has no/bin/false, so it fails there regardless of this PR and passes on Linux CI.Maintainer update (f230c43, 74f2a39)
Pushed on top of the author's commit to address review feedback:
settle_cosmetic_edit_task), so the task cannot write after finalize starts. The residual risk of a request that was already on the wire is documented at the helper.spawn_cosmetic_edit_loop/settle_cosmetic_edit_task, with namedCOSMETIC_EDIT_INTERVALandCOSMETIC_EDIT_SETTLE_TIMEOUTconstants, andcosmetic_edit_testswere added.adapter.rs. No behavior change.