Repository navigation
fix(cli): report callback detach without promising cancellation - #867
mergify[bot] merged 3 commits into
Conversation
Approval callback transport failure told users the run would be cancelled, but the interactive client only detached. Resume then hit an opaque writer conflict while the old run still owned the session. Co-authored-by: Cursor <[email protected]>
XuPeng-SH
left a comment
There was a problem hiding this comment.
Request changes — reviewed 72690b436431ac357734981a2f811ccb369a5157 against main 14ccc9cd6e7f2e3160addbc5e01cc92ff2c643d2.
Three P2 findings are attached:
- The advertised session-cancel-and-retry sequence omits the resume step required to reactivate the Session.
- The headless cancellation-unknown path still asserts that the server run was not cancelled.
- The new active-run recovery metadata also covers cursor-only conflicts with no active writer.
The direction and scope are otherwise reasonable. The shared callback sentence no longer promises cancellation; interactive failure continues to detach without adding a DELETE, while headless settlement retains its existing exact-run cancellation path. The typed callback flag avoids applying callback-specific copy to unrelated stdout or binding failures. The added admission metadata reaches the existing pre-admission rejection branch, which restores the unsent draft without recording a fictitious failed model turn. No new database queries, model calls, polling loops, or cancellation requests are introduced by this diff, and I found no need for a new lifecycle abstraction.
Read every changed hunk and traced the relevant callers/consumers through callback propagation, both outer settlement owners, admission classification, session cancellation/resume, execution-slot admission, and the canonical coordinator's conflict variants. Local Cargo/Rust tooling is unavailable, so I did not run the Rust/MatrixOne suites or claim an end-to-end reproduction. GitHub Static Checks and Test Suite are successful for this exact head; the added tests do not cover the three cross-boundary scenarios above.
Session cancel settles the Session to cancelled, so recovery must resume before the next message. An unacknowledged headless DELETE must not claim the run was not cancelled, and a writer conflict without a live lease is a cursor retry. Co-authored-by: Cursor <[email protected]>
XuPeng-SH
left a comment
There was a problem hiding this comment.
Approve on code review at 0f1ef429b174cc1d6a6508f66e79f47c1eb147a5. No remaining actionable blocking findings identified.
Read every changed hunk across the 11 files and traced the relevant production consumers. The three findings from the previous review are addressed:
- Session cancellation recovery now includes the required resume step in both CLI recovery paths and the server's live-writer response. I checked the actual command:
astra session cancelwaits for execution-settlement evidence; the server then marks the Session cancelled, and resume explicitly restores active status. An already-bound interactive turn does not silently reactivate the Session. - An unacknowledged headless DELETE now reports an unconfirmed outcome and allows for the run already being cancelled. The confirmed branch requires
execution_settled=true, reports settlement of the exact run, and clears the existing cleanup obligation. The shared callback text makes no promise that detachment itself cancels execution. - Writer-conflict recovery now consumes the coordinator's typed lease field. The coordinator filters expired leases when reporting a changed cursor, so a cursor-only conflict selects retry guidance without a cancel command; a live writer selects wait/cancel/resume guidance. The canonical single-writer checks and distributed-permit release remain intact.
Also checked callback-error propagation through SSE accumulation, interactive versus headless settlement, the metadata-driven admission-rejection path, restored drafts, and stdout/binding-failure handling. Admission rejection still requires no observed physical run and does not record a fictitious failed model turn. Interactive internal failure still performs no public cancellation request; headless cleanup keeps its pre-existing exact-run cancellation behavior.
The implementation remains scoped to reporting and recovery guidance. It introduces no new database query, model call, polling loop, authorization bypass, or automatic session cancellation. It does not implement reattachment, and neither the code nor the review treats that as delivered functionality.
Validation: inspected the added unit/mock tests and surrounding lifecycle code. Local cargo/rustc and a live MatrixOne environment are unavailable, so I did not run those suites. The new tests cover the recovery messages and headless success/503 outcomes; they do not constitute an end-to-end lost-acknowledgement reproduction. Static Checks is successful for this exact head. Several CLI lanes have passed, while the overall Test Suite, including runtime and online lanes, remains in progress.
Merge Queue Status
This pull request spent 24 seconds in the queue, including 3 seconds running CI. Required conditions to merge
|
## Summary Fix the interactive cancellation/admission race reported in #1078. This does not publish a binary or change a running environment. - Retain the original physical response until its first accepted run identity is observed, then settle cancellation of that exact run within the existing ten-second total deadline. Never look up a cancellation target through the Session's active run. - Stop the opted-in SSE consumer at that identity before executing tools or approvals, including events in the same network chunk. Ordinary transport/callback detach still does not authorize Server cancellation. - Preserve visible recovery guidance for unconfirmed cancellation and retain drafts rejected by a busy execution slot. - Address the authenticated-send review finding: resolve credentials before invoking the existing per-attempt payload factory, so cancellation checks, budget refresh and sticky dispatch evidence occur after the asynchronous bearer wait, immediately before sending. Stopping during credential preparation cannot dispatch a new admission or retry; an already dispatched request retains its original response and ambiguous-delivery evidence. Rebased onto upstream `main` at `c08cf4bb2bb0a458d1fd8d923212f12e91b979a7`. The three existing commits replayed without conflicts or patch changes. ## Related issue Closes #1078 Related contracts: #867, #987 and #1064. This addresses explicit interactive cancellation, not automatic cancellation on internal failure. ## Change type - [ ] Feature - [x] Bug fix - [x] Documentation - [ ] Refactor or performance improvement - [x] Test - [ ] Build, CI, or maintenance ## User and compatibility impact Interactive Ctrl+C/TUI cancellation waits for confirmation of the exact admitted run within the existing ten-second budget. A second interrupt may force an unverified exit; that is not presented as confirmed cancellation. Cancellation while admission credentials are pending does not start a new Server execution when they resolve. No Server API, database schema, dependency, release version or configuration changes. Other SSE hosts retain default immediate-cancellation behavior. The existing public ThinClient method signatures are unchanged. No production/QA sessions were modified or cancelled. ## Architecture and complexity delta - Canonical owner changed or extended: the interactive stream owner coordinates drain and exact-run cancellation; shared `SseStreamHost` exposes an opt-in identity-only drain, defaulting to zero. ThinClient's existing authenticated send path owns the final per-attempt preparation boundary. - Existing implementations and callers searched: signal/TUI cancellation, shared SSE ingestion, incremental state, exact-run cancellation and captured auth owner, one-shot cancellation, failure accounting, admission rejection and ThinClient admission/retry callers. - Superseded code, states, tables, shims, or self-only tests removed: the detached interactive cancellation notifier and its one-time run-ID snapshot. No new state machine, table, global registry, Session-lookup fallback or cancellation protocol. - If parallel implementations remain, their boundary and retirement condition: none added. Single-attempt and retry admission share one private authenticated send helper; interactive cancellation reuses `cancel_exact_run_until_settled_with_deadline` and the existing recovery text. ## Verification Current rebased tree, using the canonical macOS temporary directory (`TMPDIR=/private/tmp`): - `cargo test --locked -p astra-cli --lib server_admission_ -- --nocapture`: **37 passed**, including the new real-entry HTTP regression. - `cargo test --locked -p astra-thin-client --lib`: **200 passed**. - `cargo build --locked -p astra-cli --bin mock_mcp_server`: passed; prepares the existing MCP fixture before the complete library inventory. - `cargo nextest run --locked -p astra-cli -p astra-thin-client -p astra-turn-core --lib --profile ci --test-threads 2 --retries 0 --status-level fail --final-status-level fail`: **8,500 passed, 23 skipped**; retries disabled. - `cargo clippy --locked -p astra-cli -p astra-thin-client -p astra-turn-core --all-targets -- -D warnings`: passed. - `cargo fmt --all -- --check`: passed. - `python3 -m unittest discover -s scripts/ci -p 'test_*.py'`: **132 tests, OK with 5 existing skips**. The first run without canonical `TMPDIR` had two macOS `/var` versus `/private/var` path comparisons fail; rerunning with the canonical directory passed without changing tests or assertions. - `python3 scripts/ci/validate_repository.py`: passed. - `git diff --check`: passed. Public entrypoint: the new regression calls the real `stream_chat_sse` against a local HTTP peer and a gated BearerProvider. It cancels while the first admission's bearer is pending (zero POSTs remain zero, with positive not-dispatched evidence), and while a retry's bearer is pending (one earlier POST remains one, with sticky dispatched evidence). It continues polling the same future after cancellation instead of dropping and recreating it. Other covered unhappy paths include delayed run identity, same-chunk tool/approval suppression, absolute grace deadline despite keepalives, unknown identity, rejected and pending cancellation, completion racing cancellation, and busy admission with draft recovery. Existing HTTP/SSE settlement coverage requires only the original response plus exact-run cancellation, with no local tool effect, Session lookup or replay. Earlier local runs disclosed an absent MCP fixture and an intermittent transcript-persistence assertion; neither was hidden by weakening assertions or adding skips. The fixture is now explicitly built before the full inventory. The prior optional live harness run reported 17/18, failing `flash_missing_child_model_fail_closed`; this follow-up does not claim that live run passed or rerun it. Database verification is not applicable: Server transitions, schema, queries and transactions are unchanged. Real Server/DB execution-slot, QA/production, native OS-signal/TUI, Windows/WSL, load and paid-provider validation were not run. Full-workspace and platform gates remain CI responsibilities. The existing macOS compact-unwind linker warning is not treated as a passing or failing assertion. ## 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. Approved-by: XuPeng-SH <[email protected]>
Fixes #854
Problem
After approval or tool-result callback transport retries are exhausted, the interactive CLI told the user that the affected run would be cancelled fail-closed. The actual path only detaches the client:
report_server_run_detach_after_internal_failurelogs a warning and does not sendDELETE /chat/runs/{id}. The server run keeps executing and holds the canonical writer lease.A later
astra --resume <session>plus a new message is rejected withsession_writer_conflict(HTTP 409). The CLI presented that as[invalid_request] Error: another controller owns this canonical session branch, without saying that the previous run still owns the session or offering a recovery action.The single-writer guard is behaving correctly. A transport failure must not be rewritten as user cancellation, and a timed-out acknowledgement does not prove that the server rejected the approval.
Solution
The shared callback-failure sentence states only the fact: the client detached, and that detachment is not itself a cancellation of the server run. A timed-out acknowledgement does not prove the server rejected the operation. The outer lifecycle owner then adds the outcome it actually observed.
cancel_run. The final notice says the server run was not cancelled. Wait for it to finish, or stop it withastra session cancel <session_id>, then runastra --resume <session_id>before sending another message. Session cancel settles the Session tocancelled, and the same interactive process keeps its current session id, so the next turn cannot be admitted until the user resumes.Exact server run <id> cancellation settled.and does not tell the user to wait or cancel manually. When the DELETE is not acknowledged, it says cancellation could not be confirmed and the run may still be active. It does not claim the run was not cancelled, because the server may already have committed the cancel. Stdout closure and session-binding failures do not use this callback copy.session_writer_conflict. A live writer includesrecovery_action: wait_or_cancel_sessionand the cancel-then-resume commands. A conflict with no live lease is only a cursor mismatch:recovery_action: retry_session, with no cancel command. The CLI treats both as admission rejections and no longer presents the classified[invalid_request]text as the recovery guidance.This change does not reattach to the still-running run, and it does not turn an internal failure into the public user-cancel command.
Tests
cargo test -p astra-runtime --lib session_writer_conflict_tells_the_caller_to_wait_or_cancelcargo test -p astra-runtime --lib cursor_conflict_without_a_live_writer_asks_for_retrycargo test -p astra-cli --lib callback_detachcargo test -p astra-cli --lib stdout_closure_cancels_exact_run_once_before_becoming_pipeline_terminalcargo test -p astra-cli --lib writer_conflict_names_the_active_session_and_explicit_cancelcargo test -p astra-cli --lib cursor_only_writer_conflict_asks_for_retry_without_cancellationcargo test -p astra-cli --lib bound_interactive_session_is_not_resumed_before_the_next_turnThese cover the callback fact, interactive detach with cancel-then-resume, headless cancellation settled, headless cancellation unconfirmed, active-writer recovery, and cursor-only retry. The database integration test
db_multi_user_sessions_keep_provider_capacity_isolated_and_reusablewas updated to expect the active-writer response, but it requiresASTRA_TEST_DB_IT=1and was not run.make test-offlinewas not run.