Repository navigation
Description
Summary
Observed two distinct conflict errors while chatting with the Astra TUI against the moi-qa deployment (image idc-20260925T081911Z-e4febd0a..., built from main@e4febd0a). Both are boundary races around run lifecycle, but they are different bugs with different fixes.
Issue A: Cannot submit input to run in 'completed' state has no dedicated error_code, so the client can't auto-requeue it
Observed
› hi
█ Hi. ...
✖ Error · HTTP 409 Conflict: {"detail":"Cannot submit input to run in 'completed' state","request_id":"bdf2d58e521a46de78d71c3ecc5fdf8e"}
12s total · ttft 9.3s · ≥9.1k tokens · ≥8.3k cached · 91% of known input · (16.7k overall)
Server log confirms: POST /chat/runs/efa2e838.../intents → 409 in 109ms (not a timeout/slow-query issue).
Root cause
submit_run_user_intent(crates/runtime/src/server/run/lifecycle/mod.rs:19269) returnsAtomicRunGuidanceAdmission::Inactive{status}→Self::run_state_conflict("submit input to", &status)(mod.rs:13344), which formatsCannot {action} run in '{status}' statewith noerror_code(confirmed:domain_error_codeis empty in the server-side warn log for this request).- The TUI decides whether new input still targets the current run (
GuideCurrentRundelivery) purely from local signals —output_settled_at(set bysettle_visible_replyonAssistantOutputSettled/TurnStreamClosed),foreground_lifecycle_transferred,guidance_admission_closed,follow_up_deferred_before_bind(crates/astra-cli/src/tui/event_loop.rs:2758active_submission_routes_to_next_turn). None of these observe the durable run status directly. - If the server durably completes the run in the gap between the client's last observed stream-lifecycle signal and the next Enter, the client still addresses the input to that run and gets bounced.
- The
Inactivebranch already special-cases two other conflicts with dedicated codes that the client recognizes and auto-recovers from:run_intent_settlement_fenced→RUN_INTENT_SETTLEMENT_FENCED_ERROR_CODE(event_loop.rs:3572) →release_settlement_fenced_guidancerequeues the text to the next turn automatically.run_intent_consumer_not_live.
- The
completed-status conflict falls through to the generic, uncodedrun_state_conflictpath instead. Client-side,GuidanceSubmissionError::from_thin_client(event_loop.rs:3617) can't match any knownerror_code, classifies it asRejected, and just restores the text to the composer — the user has to notice the error and resend manually.
Suggested direction
Give the "run already completed" conflict its own stable error_code (parallel to run_intent_settlement_fenced) and have the client treat it the same way — requeue the rejected text to the next-turn queue instead of a bare rejection.
Issue B: new-run start (/chat/stream) can be wrongly rejected with session already has an active run when the previous run's terminal DB writes are slow
Observed
› 今天星期几
6.6s total · (16.7k overall)
✖ Error · ✗ [invalid_request] Error: session already has an active run
Server log confirms: POST /chat/stream at 09:16:01 emitted an SSE error frame (astra_runtime::sse, error_kind: invalid_request, domain_error_code empty, run_id empty — rejected before a new run id was even allocated).
Root cause
/chat/streamstarts a new run and guards against concurrent runs via an in-memoryHashMap<String, RunState>(self.runs), checked atcrates/runtime/src/server/run/lifecycle/mod.rs:15043(session_has_blocking_run). This is a process-local cache, not a direct durable-state check.- An entry only leaves
self.runsonce the previous run's terminal handling (completion/failure/cancel) has fully finished — there are 30+ call sites ofself.runs.write().await.remove(&run_id), all inside terminal-handling code that also persists several DB writes (run status,agent_events,agent_sessions.event_count,session_context_heads, etc.) before the removal happens. - In this incident window (09:11–09:15, same pod), the DB was logging repeated slow-statement warnings on exactly those tables:
COMMIT— 1.44sUPDATE agent_sessions SET event_count …— 3.9sUPDATE session_context_heads SET head_json …— 5.5sSELECT delete_requested_at, database_deleted_at …— up to 9.76s
- So the previous run's
self.runsentry plausibly outlived its true completion because terminal cleanup was stuck behind these slow writes, and the next/chat/streamcall for the following user turn was rejected by the stale in-memory guard. - Corroborating evidence:
run_recovery_sweeper(crates/runtime/src/server/run/engine.rs:4700,recover_expired_active_runs) logged"reconciled orphaned durable runs", recovered: 1at 09:12:05 in the same window — this sweeper exists specifically to reconcile runs whose blocking state outlives normal completion, i.e. the same failure shape. - Client-side, this 409 has no
error_codeeither, so it renders as a raw[invalid_request] Error: session already has an active runinstead of the friendlier handling the CLI already has for other coded conflicts (e.g.session_writer_conflict→ "Another run still owns this session..." withastra session cancel/--resumehints inturn_failure_reporting.rs).
Suggested direction
- Investigate whether the in-memory
self.runsremoval can be decoupled from (or made resilient to) slow terminal-write latency — e.g. release the blocking guard as soon as the run's status is durably terminal, without waiting on secondary bookkeeping writes (agent_events,session_context_heads, etc.) that aren't required to answer "is this session free to start a new run". - Consider a dedicated
error_codefor this conflict too, distinct from a genuinely stuck/orphaned run (which the sweeper should keep handling), so the client can decide whether a short retry is worthwhile instead of surfacing a raw, unclassified error. - Separately: the underlying slow queries (
agent_sessions,session_context_heads,edge_agent_registryheartbeat updates) are worth their own performance look in themoi-qaMatrixOne instance.
Environment
- Deployment:
moi-qaKubernetes namespace, imageidc-20260925T081911Z-e4febd0a5a764afda0a5a7859bdacfcca088d540-... - Client:
astra 0.2.9
Activity
loveRhythm1990 commentedon Sep 25, 2026
Correction on Issue B's root-cause theory, found while preparing a fix:
I originally guessed the in-memory
self.runsguard entry for the previous run stayed blocking because its removal was gated behind the slow terminal-write DB commits observed in the same log window. That's not what the code does: the foreground/background completion path (crates/runtime/src/server/run/lifecycle/mod.rs, around the// Publish terminal run state before best-effort post-run side effectscomment) explicitly flips the in-memoryRunState.statusto its final value before the slower secondary persistence (event append,agent_sessions/session_context_headsupdates) — specifically so a slow write can't leave an observer thinking the run is still "running". So the DB-latency correlation I drew was circumstantial, not proven, and I can't confirm from a shared, multi-tenant pod's logs which specific run object was still occupying the slot at 09:16:01 (the pod serves many concurrent users/sessions).What I could confirm and am fixing instead: none of the five "session already has an active run" 409s in this file carry a stable
error_code— the in-memory guard increate_run/stream_chat, the durable-insert conflict inpersist_run_start, and the two durable session-execution-slot conflicts inresume_run. All five represent the same product-facing condition (this session's execution slot is currently held by another run) at different layers, and all five render client-side as a bare, unclassified[invalid_request]string today. Giving them one shared, stablesession_execution_slot_occupiedcode doesn't require knowing the exact timing root cause — it's correct regardless of why the slot was occupied, and it's a prerequisite for the client to eventually treat this class of conflict as retryable instead of a dead end.Fix for that, plus the matching
run_intent_run_terminalcode for Issue A, is in #886.Second correction, on the follow-up I raised above: I went and checked whether the in-memory guard should exclude non-root runs the way
run_requires_session_execution_slotexcludesparent_run_id/retry_of/delegation_id/agent_iddurably. It doesn't apply here, for two separate reasons:parent_run_id/retry_of/delegation_idnever reachself.runsat all. The only two insertion points into that map are increate_run/stream_chat, both driven byChatRequestData, which has none of those three fields — a run bearing any of them is created through an internal orchestration path, not these two HTTP entry points.agent_idis aChatRequestDatafield, but it isn't the same thing asDurableRunRecord.agent_id. The former is "which agent this session is bound to" (consumed byresolve_or_create_chat_sessionto build session metadata) and can be set on an entirely ordinary interactive session; the latter is "which agent profile executed this run" and is only set by the internal sub-run/delegation path above —create_run/stream_chatnever populate it (confirmed:RunStartContext, the struct that feeds the durable insert, has noagent_idfield to carry it through). So every run created via these two entry points durably hasagent_id: Noneregardless of what the request'sagent_idsaid, andrun_requires_session_execution_slotcorrectly requires the slot for all of them. The in-memory guard and the durable authority already agree here — there's no gap on this axis.So Issue B's actual trigger (why that specific run was still occupying the slot at 09:16:01) is still open, and I don't have a third theory queued up. The most actionable next step I can suggest, without more guessing:
session_has_blocking_runcurrently only returns a bool, so the rejection carries no identity for whatever run is still blocking (the warn log for this class of 409 even hasrun_id: "", since it fires before the new run is allocated one). Surfacing the blocking run'srun_id/status/waiting_forin that log line would make the next occurrence diagnosable without needing to reconstruct it from a shared pod's general request log the way I did this time.fix(run-lifecycle): complete the pre-admission rejection contract for…
fix(run-lifecycle): give conflict 409s stable error codes (matrixorig…