Skip to content

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

Closed

Description

@loveRhythm1990

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) returns AtomicRunGuidanceAdmission::Inactive{status} → Self::run_state_conflict("submit input to", &status) (mod.rs:13344), which formats Cannot {action} run in '{status}' state with no error_code (confirmed: domain_error_code is empty in the server-side warn log for this request).
  • The TUI decides whether new input still targets the current run (GuideCurrentRun delivery) purely from local signals — output_settled_at (set by settle_visible_reply on AssistantOutputSettled/TurnStreamClosed), foreground_lifecycle_transferred, guidance_admission_closed, follow_up_deferred_before_bind (crates/astra-cli/src/tui/event_loop.rs:2758 active_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 Inactive branch 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_guidance requeues the text to the next turn automatically.
    • run_intent_consumer_not_live.
  • The completed-status conflict falls through to the generic, uncoded run_state_conflict path instead. Client-side, GuidanceSubmissionError::from_thin_client (event_loop.rs:3617) can't match any known error_code, classifies it as Rejected, 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/stream starts a new run and guards against concurrent runs via an in-memory HashMap<String, RunState> (self.runs), checked at crates/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.runs once the previous run's terminal handling (completion/failure/cancel) has fully finished — there are 30+ call sites of self.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.44s
    • UPDATE agent_sessions SET event_count … — 3.9s
    • UPDATE session_context_heads SET head_json … — 5.5s
    • SELECT delete_requested_at, database_deleted_at … — up to 9.76s
  • So the previous run's self.runs entry plausibly outlived its true completion because terminal cleanup was stuck behind these slow writes, and the next /chat/stream call 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: 1 at 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_code either, so it renders as a raw [invalid_request] Error: session already has an active run instead of the friendlier handling the CLI already has for other coded conflicts (e.g. session_writer_conflict → "Another run still owns this session..." with astra session cancel/--resume hints in turn_failure_reporting.rs).

Suggested direction

  • Investigate whether the in-memory self.runs removal 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_code for 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_registry heartbeat updates) are worth their own performance look in the moi-qa MatrixOne instance.

Environment

  • Deployment: moi-qa Kubernetes namespace, image idc-20260925T081911Z-e4febd0a5a764afda0a5a7859bdacfcca088d540-...
  • Client: astra 0.2.9

Activity

  1. loveRhythm1990 commented on Sep 25, 2026

    @loveRhythm1990
    CollaboratorAuthor

    Correction on Issue B's root-cause theory, found while preparing a fix:

    I originally guessed the in-memory self.runs guard 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 effects comment) explicitly flips the in-memory RunState.status to its final value before the slower secondary persistence (event append, agent_sessions/session_context_heads updates) — 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 in create_run/stream_chat, the durable-insert conflict in persist_run_start, and the two durable session-execution-slot conflicts in resume_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, stable session_execution_slot_occupied code 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_terminal code 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_slot excludes parent_run_id/retry_of/delegation_id/agent_id durably. It doesn't apply here, for two separate reasons:

    • parent_run_id/retry_of/delegation_id never reach self.runs at all. The only two insertion points into that map are in create_run/stream_chat, both driven by ChatRequestData, 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_id is a ChatRequestData field, but it isn't the same thing as DurableRunRecord.agent_id. The former is "which agent this session is bound to" (consumed by resolve_or_create_chat_session to 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_chat never populate it (confirmed: RunStartContext, the struct that feeds the durable insert, has no agent_id field to carry it through). So every run created via these two entry points durably has agent_id: None regardless of what the request's agent_id said, and run_requires_session_execution_slot correctly 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_run currently 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 has run_id: "", since it fires before the new run is allocated one). Surfacing the blocking run's run_id/status/waiting_for in 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.

  2. added a commit that references this issue on Sep 25, 2026
    af36152
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions