Repository navigation
perf(runtime): reduce live run observation load - #891
Conversation
XuPeng-SH
left a comment
There was a problem hiding this comment.
Review recommendation: changes requested before merge.
This is submitted as COMMENT because GitHub does not allow the connected PR author to submit REQUEST_CHANGES on their own pull request.
Reviewed base eff4c9e through head 2ae7a7d, including all 16 changed files and the associated persistence, SSE, WebSocket, and reconnect/interaction paths.
The smaller owner-scoped head query, caught-up fast path, and reuse of delta status are sound ways to reduce observer read cost. Keeping durable execution independent of a failed observer is also the right lifecycle direction. Two integration gaps need to be addressed before merging:
- The new captured-watermark bound can exclude an Explain publication that the WebSocket consumer will never fetch, because that consumer exits on run_finished.
- Preserving a run when the WebSocket closes is not paired with a way for the existing WebSocket client to reattach and restore interaction routing.
Details and suggested regression cases are in the inline comments.
Validation: traced the production write/read and completion paths; compared the actual base/head tail SQL under a deterministic publication interleaving using SQLite; exercised the existing SDK reconnect implementation with a mock WebSocket; git diff --check passed. These probes are not MatrixOne or server end-to-end tests. Rust checks and MatrixOne integration tests were not independently run because this environment has neither the Rust toolchain nor a configured MatrixOne test instance. The PR appropriately describes its QPS estimates as source-derived rather than measured capacity.
| "SELECT payload_json, event_idx FROM agent_run_events | ||
| WHERE user_id = ? AND run_id = ? AND event_idx > ? AND event_idx <= ? | ||
| ORDER BY event_idx ASC", | ||
| ) | ||
| .bind(user_id) | ||
| .bind(run_id) | ||
| .bind(after_event_idx) | ||
| .bind(last_event_idx) |
There was a problem hiding this comment.
[P2] Preserve Explain publication delivery when bounding the WebSocket tail
This new upper bound is incompatible with the WebSocket consumer's existing completion rule. The non-streaming create_run path commits its terminal settlement before publish_explain_artifact_bounded (lifecycle/mod.rs around 14733), while stream_run_over_websocket returns immediately after a batch containing run_finished (ws_handler.rs:1872-1892).
A concrete regression interleaving is: the head SELECT captures completed/watermark N for run_finished; the owner commits artifact_publication at N+1; then this tail SELECT runs. The base query returned both events in that interleaving, but the new query returns only run_finished. The WebSocket observer exits, so the excluded publication is never delivered on a later poll. The report can exist durably while the attached client receives neither its handle nor a publication-unavailable outcome. This widens the pre-existing early-completion race on WebSocket.
Please reuse the bounded Explain publication reconciliation already implemented for live SSE, or otherwise keep the WebSocket observer attached until the publication outcome is delivered or its bounded wait expires. Add a regression test that commits publication between the head read and the tail read; retain the watermark bound itself.
| &WsServerMessage::Error { | ||
| message: terminal_message.clone(), | ||
| message: terminal_message, | ||
| code: "UPSTREAM_ERROR".into(), | ||
| retryable: false, | ||
| }, | ||
| ) | ||
| .await; | ||
| best_effort_cancel_run(state, conn, run_id).await; | ||
| send_msg( | ||
| socket, | ||
| &WsServerMessage::RunFinished { | ||
| run_id: run_id.to_string(), | ||
| status: STATUS_FAILED.to_string(), | ||
| error: Some(terminal_message), | ||
| retryable: true, | ||
| }, | ||
| ) | ||
| .await; | ||
| let _ = socket.send(Message::Close(None)).await; |
There was a problem hiding this comment.
[P2] Provide a recovery path for the run retained after observer closure
After this retry-exhaustion path closes the connection without cancelling the run, a replacement WebSocket cannot resume observing or interacting with that run. authenticate_with_token initializes session_id and active_run_id to None; WsClientMessage has no attach-by-run/cursor operation; and handle_resume_run changes lifecycle state without starting stream_run_over_websocket or restoring those bindings. Consequently, handle_shared_tool_approval and handle_shared_user_prompt_response silently return on the replacement connection, even when the retained run is still waiting for that response. The same gap applies to an ordinary disconnect now that it also preserves the run.
The existing AstraWebSocket reconnect implementation only opens another socket: a source-level mock probe retained runId but sent no subscription/cursor on reconnect. Thus an observer failure can leave execution continuing with no live updates, or leave a waiting interaction unanswerable through the reconnected WebSocket. An explicit HTTP/SSE recovery is available in the server, but this client path does not perform that handoff.
Please connect this behavior to an owner-validated reattachment flow that restores run/session binding and the durable cursor, or implement an explicit client handoff to the existing SSE/HTTP observation and interaction APIs. Extend the new disconnect tests through reconnect, event replay, and resolution of an outstanding approval/ask_user request; checking only that cancel_run was not called does not cover recovery.
XuPeng-SH
left a comment
There was a problem hiding this comment.
Re-review recommendation: changes requested before merge.
Reviewed head 2e75d50 against base eff4c9e, with particular attention to the six-file follow-up since the previously reviewed 2ae7a7d. Submitted as COMMENT because the connected account is the PR author and GitHub prohibits self REQUEST_CHANGES reviews.
The follow-up addresses the two earlier server-side gaps: terminal WebSocket delivery now invokes the shared publication reconciliation, and owner-validated attach_run restores the run/session binding for interactions. Moving SDK authentication to the typed first frame also matches the server contract. However, the new server and SDK behaviors do not yet compose correctly:
- P1: publication is delivered at a higher durable index before the deferred run_finished frame, and the new SDK cursor filter silently drops that terminal frame.
- P2: a failed attach has no recovery/rollback transition. A transient status-read failure leaves an authenticated but unsubscribed connection indefinitely, while a terminal attach failure retains an unusable runId and blocks a subsequent attach.
Both are detailed inline. The new Rust tests inspect raw frames, and the SDK reconnect test covers monotonically ordered successful replay; neither exercises the publication-before-terminal sequence through the actual SDK or an attach rejection.
Additional performance observation, not a separate blocking finding: finish_ws_run_after_publication now calls stream_run_live for every WS terminal, including ordinary non-Explain runs. Its initial metadata path calls load_run, whose database implementation fetches and decodes the entire agent_run_events history without a cursor or LIMIT (runs.rs:15791-15819). This introduces an O(history) read and allocation on the completion path even for an observer that is already caught up. Include long-run terminal latency, tail bytes, peak memory, and multiple subscribers in the capacity measurements; consider bounded shared publication facts to avoid hydrating history merely to decide whether publication is owed.
Validation: inspected the full follow-up diff and relevant storage, lifecycle, wire projection, auth, and interaction paths. Ran Node probes against the current SDK source with a mock WebSocket: publication(index=1) followed by run_finished(index=0) emitted no terminal callback and retained runId; a retryable attach error scheduled no recovery; a NOT_FOUND attach followed by a valid attach threw 'a run is already attached'. git diff --check passed. These are source-level SDK probes, not server/MatrixOne end-to-end executions. Rust and MatrixOne tests were not independently run because the environment has no Rust toolchain or configured test database.
| if (typeof event.index === "number" && Number.isSafeInteger(event.index)) { | ||
| if (event.index < this.replayEventIndex) return; |
There was a problem hiding this comment.
[P1] Do not discard the deferred terminal frame after publication
The server added in this same commit deliberately sends higher-index publication events before the original lower-index run_finished payload: ws_handler.rs buffers the terminal at 1932-1934 and sends it only at the end of finish_ws_run_after_publication. The new Rust publication tests themselves produce artifact_publication(index=1) followed by run_finished(index=0).
Feeding that sequence through the actual SDK makes replayEventIndex advance to 1, so this check returns before emitting run_finished or clearing runId. A successful Explain completion therefore remains active from the SDK consumer's perspective, even on the first connection with no replay or network failure. The same loss occurs for any public indexed event sent after the durable terminal but before its deferred wire frame.
Please make deferred terminal delivery and cursor/deduplication semantics agree, preserving the terminal's run/generation identity without regressing partial-event replay. Add a test that passes the real publication-before-terminal wire order through AstraWebSocket and asserts exactly one run_finished callback plus cleared run state. The raw-socket server tests alone cannot catch this integration failure.
| Ok(record) => record, | ||
| Err((status, err)) => { | ||
| send_msg(socket, &ws_error_from_status(status, err.0.detail)).await; | ||
| return; |
There was a problem hiding this comment.
[P2] Complete the recovery state transition when attach_run fails
If the reconnect authenticates while the database is still recovering, get_run_status can return a retryable 503 here. This branch sends the error and returns to the idle message loop without binding or closing the connection. Meanwhile the SDK has already resolved connect(), marked itself connected, and retained runId; its error handler only emits the error, and automatic retry is driven by socket.onclose. No observer is running and no further attach is scheduled, so restoring the database does not restore updates or approval/ask_user routing.
The non-retryable variant also leaves bad client state: attachRun assigns runId before the server accepts it (websocket.ts:293), but a 404/403 never clears it. After a failed attach, calling attachRun for a valid owned run throws 'a run is already attached' even though the server has no attachment. Both behaviors reproduce with the current SDK source.
Please distinguish pending, accepted, and rejected attachments. Retry transient attach failures within a bound (or close the failed observation socket so the supported recovery path runs), and clear/reject the pending attachment on terminal failure so another attach is possible. Cover a status lookup that fails once and then succeeds, plus NOT_FOUND followed by a successful attach on the same client.
XuPeng-SH
left a comment
There was a problem hiding this comment.
Deep re-review of 7041abb.
Review recommendation: changes requested before merge. One remaining P2 is documented inline: a cursor reattachment can replay a durably failed run as completed when the disconnect splits the terminal event's usage and run_finished projections.
The previous deferred-terminal delivery/deduplication and rejected-attachment recovery findings are addressed in this head. The ordinary non-Explain terminal path also avoids the extra full-history live-attach read.
Validation: reviewed the latest changes against the previous reviewed head and traced the affected persistence, event projection, WebSocket, and SDK paths. Ran executable probes directly against the current SDK TypeScript source (Node type stripping with a mock WebSocket): publication -> disconnect -> retryable attach failure -> successful reattach preserves deduplication and terminal delivery; missing-run rejection allows a subsequent attachment; maxReconnectAttempts bounds failed attachment retries. A separate probe confirms that disconnect after terminal usage@11 sends attach_run(last_index=11), excluding run_error@10; source tracing confirms the incorrect terminal classification on that replay.
Limitations: Rust tests and MatrixOne integration were not executed in this environment, which has no Rust toolchain or configured MatrixOne instance. This is submitted as COMMENT because the authenticated account is the PR author and GitHub disallows requesting changes on one's own PR.
| let terminal_payload = terminal_payload.unwrap_or_else(|| { | ||
| serde_json::to_value(WsServerMessage::RunFinished { | ||
| run_id: run_id.to_string(), | ||
| status, | ||
| &message, | ||
| ) | ||
| { | ||
| send_msg( | ||
| socket, | ||
| &ws_error_from_status(status, message.clone()), | ||
| ) | ||
| .await; | ||
| } | ||
| if policy.cancel_run { | ||
| best_effort_cancel_run(state, conn, run_id).await; | ||
| } | ||
| if policy.emit_failed_terminal { | ||
| send_msg( | ||
| socket, | ||
| &WsServerMessage::RunFinished { | ||
| run_id: run_id.to_string(), | ||
| status: STATUS_FAILED.to_string(), | ||
| error: Some(message.clone()), | ||
| }, | ||
| ) | ||
| .await; | ||
| } | ||
| if policy.continue_polling { | ||
| continue; | ||
| } | ||
| error: terminal_error, | ||
| }) | ||
| .expect("run_finished is serializable") | ||
| }); |
There was a problem hiding this comment.
[P2] Preserve the durable failure status when replay starts at the terminal event
The new cursor reattach path can report a failed run as completed. finalize_run_events persists ordinary error outcomes as run_error@10 followed by run_finished@11 containing usage/error fields but no status. If the socket drops after the usage@11 projection and before the corresponding terminal frame (including while Explain publication is pending), the SDK reconnects with last_index: 11; the executable SDK probe confirms this cursor. The fresh observer therefore does not replay run_error@10. transform_stream_run_events_for_client_with_pending starts with an empty pending_run_error and supplies status: "completed" even though the terminal itself contains an error and delta.status is "failed". This unwrap_or_else keeps that existing, incorrectly classified payload instead of using the durable status; the Explain helper likewise keeps it.
Make terminal classification independent of pre-cursor events, for example by carrying an authoritative status in each durable terminal or correcting the bound terminal projection from its own error/status facts. Add a regression that disconnects between usage and run_finished for a failed run and verifies the reattached terminal remains failed (ordinary and Explain paths).
XuPeng-SH
left a comment
There was a problem hiding this comment.
Deep re-review of 3144f07.
Code-review recommendation: approve. No remaining actionable findings identified at this head.
The last reported P2 is addressed in the shared event projection: a replayed run_finished now derives failure from its own durable error/error_code fields without requiring the preceding run_error. Explicit status, cancellation, and interrupted/paused precedence remain intact. The terminal keeps its error details, index, and owner generation. The added projection regression and ordinary/Explain WebSocket replay cases cover the reported boundary.
I also revisited the surrounding changes beyond that fix:
- Cursor replay and deferred Explain terminal delivery, including deduplication of multiple wire frames from one durable event.
- Pending attachment acceptance/rejection, disconnect before acknowledgement, authentication failures, and preservation of the bound run when a foreign terminal arrives.
- Owner/session checks and durable interaction resolution for approvals and ask_user responses.
- Execution after observer disconnect: the process-local approval, prompt, and progress notification queues use nonblocking try_send, so retaining their receivers does not stall execution when they fill.
- The owner-scoped head/watermark query, bounded event tail, idle polling backoff, publication reconciliation, and ordinary terminal path avoiding the extra full-history read.
Validation: git diff --check passed. Six Node probes executed against the current SDK TypeScript source with a mock WebSocket: failed-terminal wire replay after partial usage delivery with and without Explain publication; disconnect before manual attachment acknowledgement; stale foreign terminal isolation; authentication rejection; protocol-major mismatch. The failed-terminal fixtures match the corrected Rust projection, but these probes do not execute Rust or constitute a server/SDK end-to-end test.
Rust tests and MatrixOne integration were not independently executed because this environment has no Rust toolchain or configured test database. The source-derived query reductions are reasonable; the documented multi-pod QPS, pool-wait, and visibility-latency measurements remain necessary before making a production capacity claim.
Submitted as COMMENT because the authenticated account is the PR author and GitHub does not allow approving one's own pull request.
## Summary Synchronize the workspace version from `0.2.9` to `0.2.10`. This pull request only updates release metadata. It does not change runtime behavior, create a tag, publish container images, or create a GitHub Release. `main` already contains the fixes and features that this version names: - Run-lifecycle 409 conflicts carry stable, structured error codes, and the pre-admission rejection contract is complete for session-slot conflicts (#886). - Bounded session recovery is hardened (#883). - Explain artifact recovery and introspection scope is clarified (#885). - Client-owned skills are routed with the server catalog (#881). - Execution evidence and progress feedback are grounded for judgment (#880). - MCP bindings are preserved across chat turns (#887). - The composer no longer goes stale after a coalesced resize (#889). - Next-turn assessments are persisted for observability (#888). - Live run observation load is reduced (#891). - Partial usage summary output is simplified (#890). - Web dependency patch/minor updates (#895). Pinned MatrixOne and Memoria image digests are unchanged. MOI publishes the client from the selected Astra commit. After this change is on `matrixorigin/Astra`, a MOI source build can set `astra_version` to `0.2.10` and check it against this commit's `Cargo.toml`. Publishing the GitHub Release is a separate step: after merge, run `make release-publish VERSION=0.2.10` from a clean `main` checkout. This pull request does not do that. ## Related issue No related issue. ## Change type - [x] Build, CI, or maintenance ## User and compatibility impact Installed clients do not change until a bundle or GitHub Release is built from this commit. There is no configuration migration. The source version becomes `0.2.10`. ## Architecture and complexity delta N/A - Canonical owner changed or extended: none - Existing implementations and callers searched: the version surfaces covered by `make release-prepare` - Superseded code, states, tables, shims, or self-only tests removed: none - If parallel implementations remain, their boundary and retirement condition: none ## Verification - Commands and results: `make release-prepare VERSION=0.2.10` succeeded. `LC_ALL=C make release-check VERSION=0.2.10` passed. - Public entrypoint exercised: not published. - Unhappy paths exercised: `validate-release-version.sh` confirmed the `0.2.10` version surfaces are internally consistent. - Database verification: not applicable. `make check` and `make test-offline` were not run because this change only rewrites version metadata. ## Final checklist - [x] I added or updated tests at the layer that owns the behavior, or explained why no test is needed. - [x] I updated public or design documentation for contract changes, or the change needs no documentation update. - [x] I checked the diff for credentials, private URLs, customer data, generated files, and other sensitive information. - [x] The PR title follows the repository's Conventional Commit format. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Approved-by: XuPeng-SH <[email protected]>
Summary
Stored historical sessions do not poll. The recurring read budget follows concurrently attached live runs, including waiting runs. Based on the SQL paths, an empty SSE attachment drops from about eight SELECTs per second to about one; an empty WebSocket poll drops from seven or eight SELECTs to one. These are source-derived estimates, not a MatrixOne benchmark.
Verification
cargo check -p astra-runtime --testscargo clippy -p astra-services -p astra-runtime --all-targets -- -D warningscargo clippy -p astra-runtime --all-targets -- -D warningscargo test -p astra-runtime --lib stream_run_ -- --nocapturecargo test -p astra-runtime --lib durable_live_attach_ -- --nocapturecargo test -p astra-runtime --test session_scoped_full_capture_e2emake format-checkmake test-contractThe opt-in MatrixOne integration lane was not run because no isolated test database is configured in this workspace. The remaining capacity claim requires measuring observer QPS, pool wait, and visibility delay with realistic concurrently attached runs and multiple pods.