Skip to content

fix(ui): say when a restart cut a reply or an index short - #5386

Merged
kovtcharov-amd merged 8 commits into
amd:mainfrom
kovtcharov:claude/rel-restart-recovery
Oct 20, 2026
Merged

kovtcharov-amd merged 8 commits into
amd:mainfrom
kovtcharov:claude/rel-restart-recovery

Conversation

@kovtcharov

@kovtcharov kovtcharov commented Oct 19, 2026 •

Copy link
Copy Markdown
Contributor

Before: if the Agent UI backend restarted, crashed or shut down mid-answer, the question sat in the chat with no reply and no explanation, forever, and a document caught mid-index read "indexing" forever. After: the next start shows the reply as far as it got, which tools it had started, then "This answer was interrupted when GAIA closed. Send again to retry.", and the document shows Failed with Retry. A scheduled run cut short says the same in its chat. Nothing is re-run on its own, since a half-finished turn may already have run tools. Lands after v0.25.0.

Reproduced by tests/unit/chat/ui/test_restart_recovery.py: on main, test_app_start_runs_the_recovery finds no reply after a restart and the document still "indexing"; the other cases fail for want of the turn marker. All pass here.

Test plan

  • pytest tests/unit/chat/ui/test_restart_recovery.py (22 cases): streamed, non-streamed and scheduled turns cut off; a shutdown mid-turn; a turn that ends on an error; a policy block saved mid-turn; two servers with turns in one chat; another server's reply not ending this turn; the 30 s sweep closing a turn once its server exits; tools named in the recovered reply; a clock step on Linux; indexing cut off
  • The two-server case on the previous head (6940982), with the reviewer's two_servers.py: B's question got A's streamed text plus the notice. Here each turn keeps its own text.
  • pytest tests/unit/chat/ui tests/unit/test_chat_preflight.py tests/unit/test_ui_warmup.py tests/integration/test_chat_ui_integration.py tests/unit/test_scheduler.py tests/unit/test_scheduler_api.py tests/integration/test_scheduler_e2e.py with an isolated GAIA_HOME: all pass except test_issue_841_custom_python_agent_model_id_respected and test_custom_agent_model_id_honored_through_api (they patch HOME, and fail the same way on main whenever GAIA_HOME is set), and three folder-indexing tests that fail on main too under -n 6 and pass run on their own
  • python util/lint.py --black --isort --pylint --flake8 --test-lanes
  • Live, with Gemma 4 E4B on Lemonade and the built web UI against a fresh GAIA_HOME: force-killed the backend mid-answer (145 chunks in) and mid-index (6.2 MB file), restarted it, and reopened the chat. The reply shows its streamed text plus the interrupted notice, the chat is marked failed and unread, and the document shows Failed / Retry (screenshots in the PR comments). Not run through the desktop app's own Quit.
🔍 Technical details
  • unfinished_turns: one row per question (question_id primary key, cascading from the message), written with the question in one transaction (begin_turn). TurnJournal saves the cleaned streamed text and the tools started every 2 s into this process's own row. Saving the reply (add_message/upsert_message(ends_turn=True)) deletes the row in the same transaction, so a row left behind is always a turn that never saved a reply; there is no "is there a later assistant message" guess.
  • Every update and delete is scoped to the row's owner. Another server closes a row only once its owner has exited (recover_interrupted_work, at create_app and every 30 s).
  • An owner is pid:start:token (gaia.utils.process_owner, shared with fix(gaia-agent): save a turn the TUI's closing cut short as interrupted #5390's session history; both PRs add the identical file). On Linux, start is the boot id plus the start tick from /proc/<pid>/stat, so an NTP step can't make a live server look gone; on Windows and macOS it is create_time(), which those keep as recorded.
  • A turn that ends without saving a reply is closed with what it showed: its final answer as is, or its text plus the last error it showed, or else "This answer ended before GAIA could save a reply." A non-streamed turn whose request is cancelled gets "This answer was interrupted before it finished."
  • Scheduled runs: _execute_task saves the prompt with begin_turn and the reply with ends_turn=True. This touches a different part of scheduler.py from fix(schedule): show runs missed while the PC was off or asleep #5391.
  • Builds on fix(ui): chat survives a busy, slow or dropped backend connection #5316: after a restart its re-attach gets a 404 and loads the saved chat, which now holds the interrupted reply.
  • Merging with fix(ui): one chat no longer holds the model away from every other chat #5337:
    • It moves the non-streamed question save ahead of the turn queue. Save it with question_id = db.begin_turn(sid, request.message) there, and on its "Cancelled." replies use add_message(..., ends_turn=True).
    • Its except BaseException branch should db.discard_turn(question_id) before releasing the lock.
    • If journal.observe moves into its _emit, keep the TurnJournal per run. Its _RunOutcome/TurnCancelled path must not close the turn on a shutdown cancel, or the next start can't report it.
    • Main's chat-list state (last_run_status, unread) is set by recovery too: a recovered turn's chat shows failed and unread. A turn withdrawn from the turn queue, or stopped by the spending limit, saves its reply as the turn's end.
  • Docs: a "PC sleeps" row in the Close/Quit table belongs with fix(llm): a PC that sleeps mid-answer no longer wakes to a stall error #5387, which also edits agent-ui.mdx, so expect a textual conflict there.
  • Not LLM-affecting: no prompt, tool or model change. A recovered reply enters the model's history cleaned the same way a finished one is.

A chat turn interrupted by a backend restart, crash or shutdown used to
leave the question with no reply and no explanation, and a document caught
mid-index read "indexing" forever. A turn now records that it started and
saves its streamed text every 2 s; when the server starts (and every 30 s
after), turns and indexes whose server process has ended are closed: the
reply keeps what was written plus "This answer was interrupted when GAIA
closed. Send again to retry.", and the document is marked failed with
Retry. Nothing is re-run, since a half-finished turn may already have run
tools.

Each in-progress row names its owner process, so a server sharing the
database never closes another live server's work.
@github-actions github-actions Bot added documentation Documentation changes tests Test changes labels Oct 19, 2026
@github-actions

Copy link
Copy Markdown
Contributor

Verdict: Request changes (evidence only). The code looks correct; what's missing is proof on the real app.

After a crash, quit or restart, the Agent UI now shows a reply that was cut off: the text it got to, followed by "This answer was interrupted when GAIA closed. Send again to retry." A document caught mid-index shows Failed with Retry. Each in-progress record names the process that owns it, so a second server sharing the database never closes another server's live turn. Nothing is re-run on its own, which is the right call when a turn may already have run tools.

  • Show it working in the desktop app. The PR's own "quit mid-answer, reopen" item is still unchecked. Before merge, run it once and add a screenshot of the reopened chat, plus a document left mid-index showing Failed / Retry.
  • Two small hardening items are below. Neither blocks merge.

Real-world evidence

N/A: no evidence bundle was produced for this run. The verdict rests on static review alone. I couldn't run the new tests either, because this runner has no pytest. The restart behaviour in the Agent UI hasn't been exercised outside unit tests.

🔍 Technical details

Issues

🟡 No live evidence for a UI-visible change. The test plan's live item is unchecked, and the description has no screenshot or real /api/chat/send → kill → restart → GET /api/sessions/{id}/messages capture. Per the rubric, a UI-backed change needs either the screenshot or the underlying-route evidence. A curl transcript of that sequence would be enough for merge, with the screenshot added afterwards.

🟢 Recovered text is the raw stream, not the cleaned reply (restart_recovery.py TurnJournal.observe, database.py close_turn). A normal turn passes full_response through _clean_answer_json, _TOOL_CALL_JSON_SUB_RE and the other cleaners before saving. partial_content is the uncleaned chunk concatenation. If the model streams {"thought": …} or tool-call JSON, a crash-recovered reply shows it verbatim. This is worth confirming. Applying the same cleaning pipeline before save_turn_partial (or in close_turn) would make a recovered reply look like a normal one.

🟢 journal.close() in finally can mask the turn's own error (_chat_helpers.py _run_chat_lifecycle). close() calls flush() and close_turn() unguarded. If the DB raises there, that exception replaces whatever _stream_chat_impl raised, and _notify_loop is skipped. Guard it the same way the CancelledError branch guards flush():

    finally:
        if not shutting_down:
            try:
                journal.close()
            except (RuntimeError, sqlite3.Error) as exc:
                # The marker stays; the next start closes the turn.
                logger.warning("Could not close the finished turn: %s", exc)

Strengths

  • Owner identity is pid:create_time:token, and an AccessDenied process is treated as alive. A live turn is never wrongly closed, and pid reuse is handled.
  • A policy block saved mid-turn is marked as a placeholder in the same transaction, so it is never mistaken for the reply.
  • The tests reproduce the real failure modes (a streamed turn cut mid-answer, shutdown cancellation, a non-streamed cancel, a live peer server) against a real SQLite DB rather than mocks.

kovtcharov-amd and others added 2 commits October 18, 2026 23:05
A reply recovered after a restart was the raw stream, so leaked thought or
tool-call JSON could show in it; it is now cleaned the same way a finished
reply is, through one shared helper. A database error while closing a
finished turn no longer replaces the error the turn itself raised; the
marker stays and the next start closes the turn.
Two servers on one chat database could corrupt each other's turns: the
in-progress marker was one row per chat, so one server's streamed text
landed in another's marker, its ending erased the other's live marker, and
any later reply counted as "already answered". Each turn is now a row keyed
by its question, saved with the question in one transaction, and only its
owner (or another server, once that owner has exited) updates or closes it.
Saving a turn's reply deletes its row in the same transaction, so recovery
no longer guesses which reply belongs to which question.

A recovered reply now also says which tools the turn had started. Scheduled
runs are marked the same way, so a restart mid-run says so in the run's
chat. On Linux an owner is the boot id plus the start tick from /proc, which
an NTP clock step cannot move.
The TUI's session history needs the same pid/start/token identity to tell a
live process's running turn from a dead one's (amd#5390), and agents/base must
not import from gaia.ui. Same module, same behaviour, now shared.
kovtcharov-amd added a commit to kovtcharov/gaia that referenced this pull request Oct 19, 2026
…ed (amd#5390)

Before: closing the TUI in the middle of a turn left the session
transcript wrong either way. If the agent stopped within the TUI's
2-second grace, the turn was saved as an ordinary "The request was
stopped" answer; if the TUI had to kill it, the question was never saved
at all. After: the question is saved the moment the turn starts, and a
turn the TUI's closing cut short ends with "This answer was interrupted
when GAIA closed." (the Agent UI's wording), so a resumed session
(`GAIA_HISTORY_FILE`) and the model both know that turn never finished.
Lands after v0.25.0.

Reproduced by `hub/agents/gaia/python/tests/test_stdio_host_close.py`:
on main the killed turn leaves no entry and the closed one is saved as a
plain "stopped" answer. Both pass here; failed turns and questions
queued before the close are saved as before.
`tests/unit/test_session_history_pending.py` adds two cases that fail on
this PR's previous head: a finished turn lost when another process
cleared the history mid-turn, and another live process's running turn
shown as interrupted.

## Test plan
- [x] `pytest hub/agents/gaia/python/tests/test_stdio_host_close.py
tests/unit/test_session_history_pending.py
hub/agents/gaia/python/tests/test_stdio.py
hub/agents/gaia/python/tests/test_stdio_wire_contract.py
tests/unit/test_memory_router.py`: 300 passed
- [x] `pytest hub/agents/gaia/python/tests tests/unit/agents` with an
isolated `GAIA_HOME`: 4400 passed. The 4 tool-registry failures
(`test_manifest_tools_count_matches_real_registry`,
`test_broken_agent_dir_records_load_error`, two in
`test_full_tool_bundles.py`) fail the same way on main here.
`test_real_python_test_runner_output_is_recognized[pytest]` failed once
under `-n 6` and passes run alone.
- [x] `python util/lint.py --black --isort --pylint --flake8
--test-lanes --doc-versions`
- [x] Killed mid-turn with `GAIA_HISTORY_FILE` set. The TUI has no
resume path of its own, so this drives the agent's stdio run loop
(`_pump_stdin` and `dispatch_query`, with the real `SessionHistory`) in
a subprocess. A stand-in agent streams a sentence, then works. The
script sends a question, kills the process after the first streamed
event, and reloads the file in a new process:
  ```
  agent event: token
  killed mid-turn, exit code 1
model view: [{"role": "user", "content": "summarize my inbox"}, {"role":
"assistant", "content": "This answer was interrupted when GAIA
closed."}]
  ```
- [x] Live, real agent against a real model (Gemma-4-E4B on Lemonade):
ran `python -m gaia_agent.stdio --history-file <file>` the way the TUI
does, asked for a 600-word story, and after 20 streamed tokens either
closed stdin (what the TUI's close does) or killed the process (what the
TUI does after its grace). Then dumped the file's `turns` table:
  ```
  close stdin:  agent exited on its own in 0.1s, code 0
row 1: owner=none user: 'Write a 600-word story ...' assistant: 'This
answer was interrupted when GAIA closed.'
  kill:         exit code 1
row 1: owner=dead user: 'Write a 600-word story ...' assistant: 'This
answer was interrupted when GAIA closed.'
  ```
A second session opened on the killed file read row 1 as part of its
model view and appended its own turn as row 2.
- [ ] The `gaia` TUI binary itself closed mid-answer (the run above
drives the same stdin/stdout contract the TUI uses, not the TUI)

<details>
<summary>🔍 Technical details</summary>

- `SessionHistory.begin()` inserts a stand-in row (question plus the
note) owned by this process. The next `record()` replaces it in place,
or inserts the turn if the row is gone (another process cleared the
session). `discard_pending()` drops it; `keep_pending()` makes it a
finished entry.
- `prepare()` leaves out stand-ins whose owner is alive: this process's
running turn, or another process's. A dead owner's stand-in reads as
interrupted. The owner identity is `gaia.utils.process_owner` (pid,
start, token), boot-relative on Linux so an NTP step can't make a live
process look gone; amd#5386 uses the same module. The `owner` column is
added to existing history files on open.
- The stdin pump's cancel marks only the turn it cuts short
(`closed_by_host`, under the same lock as the turn's own end), so
questions queued before the close are saved as they ended. The note is
folded into the last reply, so roles still alternate. A broken output
pipe counts as the host leaving.
- A turn that ends unrecorded (an error, a crash) while the host is
still there drops its stand-in, so "a failure is not replayed as an
answer" still holds. The cleanup runs after the console is restored and
logs a database error instead of raising a second terminal event.
- Daemon-relayed agents keep their transcript in the TUI's memory only
(`SSEClient.transcript`), which nothing saves, so there is nothing to
mark there.
- Not LLM-affecting beyond the one note a resumed session sees in place
of a turn that never finished.
</details>

---------

Co-authored-by: Kalin Ovtcharov <[email protected]>
Carries the unfinished-turn marker through main's turn queue, turn summaries
and undo recording. A turn withdrawn from the queue and a turn stopped by the
spending limit now save their reply as the turn's end, so neither leaves a
marker or a duplicate reply behind. A recovered turn marks its chat failed and
unread in the chat list, as a turn that errors does.
Main's amd#5337 saves a non-streamed question before it waits for the model.
That save now opens the turn, and every way the wait can end closes it: a
Stop or a client that left saves "Cancelled." as the turn's reply, and any
other failure drops the marker. The streamed run keeps its turn journal
through main's turn slot.
github-merge-queue Bot pushed a commit that referenced this pull request Oct 19, 2026
Before: a scheduled run that came due while the PC was off or asleep, or
while GAIA or the schedule daemon was closed, vanished without a trace.
In the Agent UI, every restart also reset each task's timer, so a daily
task on a PC restarted daily could never run. After: Agent UI tasks keep
their next run time across a restart. The latest run, if under an hour
late, still runs once; every other one shows in the task's run history
as "Missed 3 runs due … while the PC was off or asleep, or GAIA was
closed". `gaia schedule show` and `list` count the runs the daemon never
made. Nothing is run twice, including with two GAIA servers on one chat
database. Lands after v0.25.0.

Reproduced by `tests/unit/test_scheduler_missed_runs.py`: on main a task
three runs overdue at startup gets no history entry, a run that just
came due never fires, and a task restarted before its time loses it. On
this PR's first commit two servers both run the catch-up, a stretch past
the count cap skips the run due seconds ago, and an older build's stale
time is blamed on the PC; on the second commit an old dense windowed
task first met outside its window crashed the timer, and a pause on one
server was undone by the other. All pass here, as does
`tests/unit/test_schedule_missed_runs.py` for `gaia schedule`.

## Test plan
- [x] `pytest tests/unit/test_scheduler_missed_runs.py
tests/unit/test_schedule_missed_runs.py`: missed at startup; a sleep
while waiting (fake clock); a late run that still runs; a restart before
the due time; two servers on one database; a clock-face stretch past the
cap ("at least 3", latest still runs); every-second for three days
counted exactly; a task left by an older build; an old every-minute
9-to-5 task first met in the evening; a pass that raises is logged and
retried; a pause on one server holds on the other; for `gaia schedule`,
the latest due time past the cap, runs a sleep folded together, a run
dropped as too late counted once, a paused schedule, a store saved
before this change
- [x] `pytest tests/unit/test_scheduler*.py
tests/unit/test_schedule_*.py tests/unit/cli/test_cli_schedule.py
tests/unit/cli/test_cli_docs_drift.py
tests/integration/test_scheduler_e2e.py
tests/unit/chat/ui/test_server.py tests/unit/chat/ui/test_database.py`:
529 passed
- [x] `python util/lint.py --black --isort --pylint --flake8
--test-lanes`
- [x] Real CLI, with `USERPROFILE`/`HOME`/`GAIA_HOME` on a scratch
folder (the schedule store follows `USERPROFILE`, not `GAIA_HOME`):
`gaia schedule add`, then the daemon's scheduler started once after
backdating the expected run 3 hours:
  ```
  next_fire:  2026-10-19T01:00:00-07:00
missed: 4 runs in all while the PC was off or asleep, or the schedule
daemon wasn't running (latest due 2026-10-19T00:00:00-07:00)
brief [enabled] cron='0 * * * *' sink=stdout
next=2026-10-19T01:00:00-07:00 missed=4
  ```
- [x] Two Agent UI schedulers on one scratch database, an
every-10-minutes task 21 minutes overdue:
  ```
  runs: ['A']
  history: done
history: Missed 2 runs due 2026-10-18 23:41 PDT to 2026-10-18 23:51 PDT
while the PC was off or asleep, or GAIA was closed.
  ```

<details>
<summary>🔍 Technical details</summary>

- Agent UI (`ui/scheduler.py`): `_run_loop` waits for the stored
`next_run_at` in naps of at most 30 s, re-reading the wall clock, so a
sleep is noticed within 30 s of waking. At the due time it claims the
run with `claim_scheduled_run` (`UPDATE … WHERE id = ? AND next_run_at
IS ?`); a server that loses the claim re-reads the stored time and waits
again. The winner alone records misses and runs.
- `_plan` works out what came due. Interval tasks are counted exactly,
by arithmetic. Clock-face schedules walk up to 100,000 due times; past
that, the latest is found from the last 8 days and the count reads "at
least N". The latest runs if it is within `MISSED_RUN_GRACE_SECONDS`
(3600, the daemon's misfire grace).
- Each pass (`_take_due_run`) that raises is logged with the task and
due time and retried after 30 s, so one bad pass can't end a schedule
until restart. The claim requires `status = 'active'`, so a pause on one
server holds on the others; a server whose claim finds the task paused
stops its timer.
- Clock-face walks start at the floor, so due times before it are never
walked or counted.
- `scheduler_missed_runs_since` (a settings key) records when this build
first started. Due times before it, or before a task's creation, are
never counted, so an older build's stale `next_run_at` is not reported
as missed.
- An unreadable `next_run_at` fails at load, like a bad
`schedule_config`.
- `gaia schedule` (`schedule/daemon.py`, `store.py`): new fields
`missed_count`, `last_missed`, `resumed_at`, `missed_since`. At start,
`catch_up_missed_runs` counts cron fires from the expected `next_run`,
never before creation, the last run, the last resume, or `missed_since`.
While running, only `EVENT_JOB_SUBMITTED` is used: APScheduler drops the
runs a sleep folded together without an event, and decides "too late" in
another thread, so this listener counts the folded ones and decides
lateness itself, once, inside `store_lock` (`account_missed`). Past
100,000 in one stretch, `last_missed` is the latest due time and `show`
says "at least". `show` prints every time in local time.
- `gaia schedule run` still moves `next_run` to now, so runs missed
before a manual run are not counted.
- The daemon's own job clock (`daemon/scheduler/`) is untouched. #5386
marks scheduled runs as unfinished turns in `_execute_task`, a different
part of `scheduler.py`.
- Not LLM-affecting.
</details>

---------

Co-authored-by: Kalin Ovtcharov <[email protected]>
@kovtcharov-amd

Copy link
Copy Markdown
Collaborator

Ran it live: after the backend was killed mid-answer and mid-index and started again, the chat shows the partial reply with "This answer was interrupted when GAIA closed. Send again to retry.", and the document shows Failed with Retry. Both hardening suggestions were already fixed in 6940982, with tests.

Reopened chat with the interrupted reply

Document library showing Failed / Retry

🔍 Technical details

Setup: head d5af50c (main merged in), npm run build web UI, python -m gaia.ui.server on a fresh GAIA_HOME, Gemma 4 E4B on Lemonade. Before the kill, a 1500-word essay prompt via /api/chat/send had streamed 145 chunks, and /api/documents/upload-path on a 6.2 MB text file had status indexing. The server was then stopped with taskkill /F.

After restart:

  • Server log: Closed work an ended GAIA process left unfinished: 1 chat turn(s), 1 document index(es)
  • GET /api/sessions/{id}/messages: the assistant reply starts with the streamed text and ends with the interrupted notice
  • GET /api/sessions/{id}: last_run_status: failed, unread: true
  • GET /api/documents: indexing_status: failed, last_error: "Indexing was interrupted when GAIA closed. Click Retry to index it again."

This was a crash (force-kill), not the desktop app's own Quit. A graceful shutdown mid-turn is covered by test_a_shutdown_mid_turn_keeps_the_marker_and_the_text.

Hardening items:

  • Raw stream in the recovered reply: TurnJournal now saves clean_reply_text(...), the same cleaner a finished reply goes through (test_recovered_text_is_cleaned_like_a_finished_reply).
  • journal.close() masking the turn's error: it is now guarded for RuntimeError/sqlite3.Error and logs a warning (test_a_failed_close_does_not_mask_the_turns_own_error).

@kovtcharov-amd
kovtcharov-amd added this pull request to the merge queue Oct 20, 2026
Merged via the queue into amd:main with commit a73c784 Oct 20, 2026
35 checks passed
@kovtcharov-amd
kovtcharov-amd deleted the claude/rel-restart-recovery branch October 20, 2026 22:07
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

documentation Documentation changes tests Test changes

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants