Skip to content

fix(run-lifecycle): give conflict 409s stable error codes - #886

Merged
mergify[bot] merged 3 commits into
matrixorigin:mainfrom
loveRhythm1990:fix/run-lifecycle-conflict-error-codes
Sep 25, 2026
Merged

mergify[bot] merged 3 commits into
matrixorigin:mainfrom
loveRhythm1990:fix/run-lifecycle-conflict-error-codes

Conversation

@loveRhythm1990

@loveRhythm1990 loveRhythm1990 commented Sep 25, 2026 •

Copy link
Copy Markdown
Collaborator

Fixes #884.

Both problems in #884 are the same class of bug: a run-lifecycle 409 that carries no stable error_code, so the TUI can't tell it apart from an arbitrary client error and just drops the user's message back into the composer instead of doing anything useful with it.

What changed

1. Cannot submit input to run in 'completed' state now carries a stable code when the run is genuinely terminal.

submit_run_user_intent's AtomicRunGuidanceAdmission::Inactive branch now checks durable_run_status_is_terminal(&status) and, when true, returns the new run_intent_run_terminal code instead of the generic uncoded conflict — mirroring how run_intent_settlement_fenced is already handled. A non-terminal Inactive status (e.g. a manual pause, which may still resume) keeps the old plain rejection.

Client-side, GuidanceSubmissionError::SettlementFenced is generalized into GuidanceSubmissionError::GuidanceClosed(&'static str) carrying the user-facing notice, and run_intent_run_terminal is matched the same way run_intent_settlement_fenced already was — the rejected text gets requeued to the next turn (via the existing release_settlement_fenced_guidance plumbing) instead of being silently dropped back into the composer as a bare error.

Note on the notice wording: terminal covers cancelled and failed, not just completed, and those are exactly the cases where the turn also settles abnormally — should_start_queued_followups then holds the backlog and the text is restored to the composer instead. So the new notice states what is true when it is printed ("Your message was moved to the next-turn queue.") rather than promising a delivery the settlement path may not make; otherwise a Ctrl+C race would show two contradictory system messages in a row. There are assertions covering both halves of that.

2. Every "session already has an active run" 409 now carries a stable session_execution_slot_occupied code.

There are five call sites producing this exact message across create_run, stream_chat, persist_run_start, and resume_run (two conflict branches) — one in-process guard (self.runs) and two durable-store conflicts (insert-time, and the session-execution-slot check). They're all the same product-facing condition — this session's execution slot is currently held by another run — just detected at different layers. All five now use the same SESSION_EXECUTION_SLOT_OCCUPIED_ERROR_CODE constant.

To be explicit about the blast radius: sse_error_kind deliberately classifies on HTTP status alone and ignores the domain code, so this changes no error_kind and nothing the user sees changes yet for this half. What it does do is populate domain_error_code in the server's SSE-error logs, and deliver a stable code to the client (it reaches PartialTurnData.error_code via the existing extraction in chat_turn_sse_dispatch.rs), so a client-side fix has something to match on.

What I deliberately did not do

While tracing the actual completion path to find where the in-memory self.runs entry is released, I found the run-completion code explicitly flips the in-memory status to terminal before the slower secondary DB writes (event append, agent_sessions/session_context_heads updates) — specifically to avoid exactly the kind of staleness I'd guessed at in #884. So my original "the guard is gated behind slow DB writes" theory doesn't hold up under closer reading, and I can't otherwise confirm from a shared, multi-tenant pod's logs which run object was actually still occupying the slot at the time. I've posted a correction on the issue.

Given that, this PR is scoped to the well-supported half (a stable, shared error code across all five call sites) rather than guessing at a specific timing fix or adding a client-side auto-retry loop for starting a new turn. Known follow-ups, none of them regressions from this change:

  • Teaching the client to treat session_execution_slot_occupied as retryable (bounded, with backoff) — the larger behavioural change this PR unblocks.
  • Whether the in-memory guard should exclude non-root/background runs sharing a session_id — checked, doesn't apply: the only two insertion points into self.runs are create_run/stream_chat, both driven by ChatRequestData, which carries none of parent_run_id/retry_of/delegation_id, and never populates DurableRunRecord.agent_id either (that's a different field with the same name — ChatRequestData.agent_id means "which agent this session is bound to", not "which agent executed this run"). So the in-memory guard and the durable authority already agree on every run these two entry points can produce.
  • The agent-workbench guide path (submit_run_user_intent called directly, every Err mapped to GuideRejected) bypasses from_thin_client, so it gets neither the new code nor the pre-existing fence handling.
  • persist_run_start still discriminates on the literal string "session already has an active run" produced in crates/services/src/runs.rs; a shared const would close that cross-crate coupling.

Testing

  • cargo check -p astra-runtime, cargo check -p astra-cli
  • cargo fmt --check on the touched files
  • cargo clippy -p astra-runtime -p astra-cli --tests -- -D warnings — clean
  • cargo test -p astra-runtime --lib run::lifecycle::tests:: — 508 passed. Existing conflict tests now assert on error_code; added submit_run_user_intent_rejects_paused_durable_run_without_terminal_code as a regression guard that a non-terminal Inactive status keeps the old, uncoded rejection.
  • cargo test -p astra-cli --lib tui::event_loop:: — 211 passed. Updated the from_thin_client coverage for the renamed GuidanceClosed variant; added cases for the new run_intent_run_terminal code, for an unrelated/uncoded conflict staying a plain Rejected, and for the notice/should_start_queued_followups invariant described above.

Verified by reading rather than by test, worth a reviewer's eye: admit_run_guidance checks the idempotency key before the status check ("Retry identity is authoritative before status/liveness"), so a retried intent that already committed still returns Duplicate and is not captured by the new terminal code.

🤖 Generated with Claude Code

Two conflict families in the run lifecycle carried no `error_code`,
so the TUI couldn't distinguish them from an arbitrary client error
and just surfaced a raw message instead of doing anything useful.

1. `submit_run_user_intent`'s `Inactive{status}` branch now returns
   the new `run_intent_run_terminal` code when the run's durable
   status is genuinely terminal (completed/failed/cancelled/
   delegated), instead of the generic uncoded `run_state_conflict`.
   This mirrors the existing `run_intent_settlement_fenced` handling:
   there is no "current run" left to guide either way, so the client
   should requeue the text as the next turn rather than dropping it.
   A non-terminal `Inactive` status (e.g. a manual pause, which may
   still resume) keeps the old plain rejection.

   Client-side, `GuidanceSubmissionError::SettlementFenced` is
   generalized into `GuidanceClosed(&'static str)` carrying the
   user-facing notice, and the new code is matched the same way,
   reusing the existing next-turn-queue plumbing.

2. Every "session already has an active run" 409 — the in-process
   `self.runs` guard in `create_run`/`stream_chat`, the durable
   insert conflict in `persist_run_start`, and the two durable
   session-execution-slot conflicts in `resume_run` — now carries
   the same `session_execution_slot_occupied` code. All five are the
   same product-facing condition (this session's execution slot is
   held by another run) detected at different layers.

Fixes matrixorigin#884.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
@loveRhythm1990 loveRhythm1990 changed the title fix(runtime,cli): give run-lifecycle 409s stable error codes fix(run-lifecycle): give conflict 409s stable error codes Sep 25, 2026

@XuPeng-SH XuPeng-SH left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reviewed head 949dfd196bd50a0dbc708484d68a0ab299e1a5e3, including durable guidance admission, SSE error propagation, TUI ownership/queue handling, and turn failure settlement.

Request changes: the terminal-guidance handling is reasonable, but the session-slot conflict still does not enter the existing pre-admission recovery path. The inline P1 explains how a request rejected before execution is instead recorded as a failed turn, advances the local turn cursor, and bypasses draft restoration. This is an existing defect left unresolved by this PR, not a newly introduced regression; adding a code alone does not complete the unhappy-path fix claimed by “Fixes #884”.

Please complete the existing structured admission contract at the appropriate start-rejection boundaries and reuse the existing settlement/recovery implementation. Do not indiscriminately label resume conflicts as new-turn admission rejections. This fix should require no additional database query, status polling, retry loop, or compatibility shim.

Additional review notes:

  • Do not make all session_execution_slot_occupied responses automatically retryable. The slot predicate includes waiting and paused + waiting_for, which can require explicit user action. Preserve the draft and provide the appropriate recovery action; do not add repeated start requests merely because this code is present.
  • The current patch adds no SQL, polling, or retries for error classification. The durable guidance path checks idempotency before status, and an existing lifecycle test already covers an exact retry returning Duplicate after completion. Preserve this ordering.
  • Add coverage through the actual SSE-to-settlement boundary: a start conflict must restore the draft, leave the turn cursor unchanged, emit no TurnError journal event, and perform no recovery request. For terminal guidance, test completion versus cancellation/failure through the queue/settlement path, including message ordering and exactly-once delivery. The added classifier/notice assertions alone do not exercise that behavior.

Validation: source/call-chain review and inspection of CI results; Cargo tests were not run locally. The runtime and CLI jobs inspected passed; the full Test Suite was still running when checked.

… session-slot conflicts

Addresses XuPeng-SH's review on matrixorigin#886.

The three *start*-rejection sites for `session_execution_slot_occupied`
(`create_run`'s guard, `stream_chat`'s guard, and the durable insert
conflict in `persist_run_start`) now carry `admission_state: "rejected"`
metadata, the same structured contract `session_writer_conflict` and
`execution_workspace_claimed` already use. Without it, the client's
`is_pre_admission_rejection` classifier (which requires that metadata
alongside the error code and an absent run id) could not tell this
409 apart from an executed-and-failed turn: `settle_failed_turn` took
the ordinary-failure branch instead of `report_admission_rejection`,
so the draft was never restored through the recovery path, a TurnError
was journaled, and the local turn cursor advanced for a request that
never started. Adding the error code alone did not fix this half of
matrixorigin#884 — the code review is correct that this was still broken.

`resume_run`'s two conflict sites deliberately do NOT get this
metadata: a resume conflict is not a new-turn admission and must not
be settled through the draft-restoring contract. Both call sites and
the shared error-code doc comment now say so explicitly, and a
lifecycle test locks in the asymmetry.

No SQL, polling, or retry loop is added anywhere in this change. The
existing idempotency-before-status ordering in `admit_run_guidance` is
untouched.

Testing:
- Server: `create_run`/`stream_chat` conflict tests now assert
  `admission_state: "rejected"`; the `resume_run` conflict test asserts
  its *absence*.
- Client: a new test in `turn_settlement` exercises the actual
  boundary — the real `is_pre_admission_rejection` classifier (now
  `pub(crate)` for this test, cfg-gated) feeding `settle_failed_turn` —
  and asserts the draft is restored, the turn cursor does not advance,
  and no journal is created.
- Client: a new test in `event_loop` runs the real
  `should_start_queued_followups` for the terminal-guidance
  (`run_intent_run_terminal`) requeue across completed/cancelled/failed
  outcomes, asserting exactly-once delivery and stable ordering
  alongside an earlier-queued message.
- `cargo fmt --check`, `cargo clippy -p astra-runtime -p astra-cli
  --tests -- -D warnings` (including the plain non-test lib build, to
  catch the cfg-gating this needed) — all clean.
- `cargo test -p astra-runtime --lib run::lifecycle::tests::` — 508
  passed. `cargo test -p astra-cli --lib tui::event_loop::` — 212
  passed. `cargo test -p astra-cli --lib cli::turn::turn_settlement::`
  — 4 passed.

Co-Authored-By: Claude Opus 5 <[email protected]>
@loveRhythm1990

Copy link
Copy Markdown
Collaborator Author

@XuPeng-SH addressed in 24c3c1c — replied inline with specifics: #886 (comment)

Short version: the three start-rejection sites now carry admission_state: "rejected" so is_pre_admission_rejection/settle_failed_turn correctly restore the draft instead of settling this as a failed, executed turn; resume_run's two conflicts deliberately stay outside that contract; new tests exercise the real classifier/settlement functions rather than re-deriving their logic; no SQL/polling/retry added.

Ready for another look whenever convenient.

@XuPeng-SH XuPeng-SH left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Deep re-review of 50d96e312cf8935d7cf261766b87579593d135eb..338f9d1b4aae764eb04c1e49cdbbf06367f276bb: no remaining blocking findings. The previous P1 is resolved.

All three new-start conflict boundaries now attach admission_state: rejected; both resume conflict boundaries correctly omit it. Server SSE conversion preserves the metadata, and client classification reaches draft restoration without ordinary failed-turn settlement, a local turn-cursor advance, or a reconciliation request.

I also checked the terminal-guidance race: both storage implementations resolve the immutable intent identity before checking terminal status, so a lost acknowledgement for an already-committed intent remains a duplicate acknowledgement rather than a new-turn replay. The TUI's pending-submission barrier lets the definitive rejection be processed before turn closure, and the saved queue index preserves order. Successful completion dispatches client-owned follow-ups; cancellation/failure retains them as draft input. This change adds no database query, transaction, polling loop, or automatic session-slot retry.

Nonblocking notes:

  • Update the PR description for the final implementation: the slot-conflict half now changes draft restoration and settlement behavior, so the statement that nothing user-visible changes is stale. The underlying cause of the original occupied slot is still unproven and should remain described that way.
  • The new tests exercise the real classifier and queue/settlement helpers, but construct the wire metadata/outcome inputs themselves. They are useful component regressions, not full SSE/TUI end-to-end coverage. I inspected the intervening production wiring and existing generic SSE coverage; a transport/event-loop integration test remains a useful follow-up.

Local validation at 24c3c1c0: terminal_guidance_followup_delivery_matches_turn_outcome, guidance_submission_errors_preserve_ambiguous_commit_ownership, and settle_failed_turn_restores_draft_without_advancing_cursor_for_session_slot_conflict all passed in the freshly built CLI test executable. The subsequent 338f9d1b update only merged main's non-overlapping #885 changes; the PR diff against its new base is byte-identical to the reviewed/tested patch (diff blob hash 6ec5be73b72893af3a0748d52b50df6a989cecbe). git diff --check passed at the latest head. No live-database or PTY integration run was performed.

Independent judgment: a fresh gpt-6-astra medium reviewer inspected the complete diff and the relevant store, SSE and TUI paths and also found no actionable correctness defect. CI was still running when inspected; its completion is not assumed.

@mergify mergify Bot added the queued label Sep 25, 2026
@mergify

mergify Bot commented Sep 25, 2026 •

Copy link
Copy Markdown
Contributor

Merge Queue Status

  • ✅ Entered queue — 2026-09-25 15:10 UTC · Rule: main · triggered by rule Automatic queue on approval for main
  • ✅ Checks skipped · PR is already up-to-date
  • ✅ Merged — 2026-09-25 15:10 UTC · at af361522ae23edaed3a52a0a56d2ad4a91665310 · squash

This pull request spent 11 seconds in the queue, including 1 second running CI.

Required conditions to merge
  • #review-threads-unresolved = 0 [🛡 GitHub branch protection]
  • github-review-approved [🛡 GitHub branch protection]
  • any of [🛡 GitHub branch protection]:
    • check-success = Check PR title
    • check-neutral = Check PR title
    • check-skipped = Check PR title
  • any of [🛡 GitHub branch protection]:
    • check-success = check
    • check-neutral = check
    • check-skipped = check
  • any of [🛡 GitHub branch protection]:
    • check-success = Test: core crates + bridge hooks
    • check-neutral = Test: core crates + bridge hooks
    • check-skipped = Test: core crates + bridge hooks
  • any of [🛡 GitHub branch protection]:
    • check-success = Test: astra-runtime
    • check-neutral = Test: astra-runtime
    • check-skipped = Test: astra-runtime
  • any of [🛡 GitHub branch protection]:
    • check-success = Test: astra-cli (edge-fs-tools)
    • check-neutral = Test: astra-cli (edge-fs-tools)
    • check-skipped = Test: astra-cli (edge-fs-tools)
  • any of [🛡 GitHub branch protection]:
    • check-success = Test: astra-cli (edge-git-gix)
    • check-neutral = Test: astra-cli (edge-git-gix)
    • check-skipped = Test: astra-cli (edge-git-gix)
  • any of [🛡 GitHub branch protection]:
    • check-success = Test: astra-cli (edge-rest)
    • check-neutral = Test: astra-cli (edge-rest)
    • check-skipped = Test: astra-cli (edge-rest)
  • any of [🛡 GitHub branch protection]:
    • check-success = Test: astra-cli (edge-shell)
    • check-neutral = Test: astra-cli (edge-shell)
    • check-skipped = Test: astra-cli (edge-shell)
  • any of [🛡 GitHub branch protection]:
    • check-success = Test: astra-cli (non-edge)
    • check-neutral = Test: astra-cli (non-edge)
    • check-skipped = Test: astra-cli (non-edge)
  • any of [🛡 GitHub branch protection]:
    • check-success = Test: online (core)
    • check-neutral = Test: online (core)
    • check-skipped = Test: online (core)
  • any of [🛡 GitHub branch protection]:
    • check-success = Test: online (integration)
    • check-neutral = Test: online (integration)
    • check-skipped = Test: online (integration)
  • any of [🛡 GitHub branch protection]:
    • check-skipped = Test: turn-core + services + plan
    • check-neutral = Test: turn-core + services + plan
    • check-success = Test: turn-core + services + plan
  • any of [🛡 GitHub branch protection]:
    • check-skipped = web (typecheck, test, build)
    • check-neutral = web (typecheck, test, build)
    • check-success = web (typecheck, test, build)
  • any of [🛡 GitHub branch protection]:
    • check-skipped = Astra SDK (typecheck, test+coverage, build)
    • check-neutral = Astra SDK (typecheck, test+coverage, build)
    • check-success = Astra SDK (typecheck, test+coverage, build)

@mergify
mergify Bot merged commit af36152 into matrixorigin:main Sep 25, 2026
25 of 27 checks passed
@mergify mergify Bot removed the queued label Sep 25, 2026
@loveRhythm1990 loveRhythm1990 mentioned this pull request Sep 28, 2026
5 tasks done
mergify Bot pushed a commit that referenced this pull request Sep 28, 2026
## 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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

TUI hits two uncoded run-lifecycle 409s: 'completed' guidance rejection and stale-guard new-run rejection

2 participants