Repository navigation
fix(llm): a PC that sleeps mid-answer no longer wakes to a stall error - #5387
Conversation
On Windows the monotonic clock keeps counting while the PC sleeps, so the 120 s stream idle limit, the socket read deadline behind it, the retry budget and the Agent UI's no-progress limit all fired the moment the PC woke from a long enough sleep, though the local model server had slept too and was about to carry on. These limits now skip time the process spent suspended, noticed as a jump of more than 5 s between clock reads that happen every second or faster; a server that stays silent while the PC is awake is still caught.
|
Verdict: Approve with suggestions This fixes a real Windows annoyance. A PC that slept mid-answer woke up to "the model stopped sending partway through its answer", because the clock kept counting through the sleep. Time spent asleep no longer counts toward the stream stall limit, the socket read deadline, the retry budget, or the Agent UI's no-progress limit. A server that goes quiet while the PC is awake is still cut off. I found no blocking issues. The approach can only delay a limit, never disable it. The excused time is capped at "now", and the stall check runs right after the sleep is excused on every loop pass, so a dead server is still caught within one window of waking. The tests reproduce the bug on main and check both directions: carry on after a sleep, still stop on real silence. One behaviour change worth knowing: with a hosted model whose connection died silently during the sleep, the user now waits up to a full idle window (120 s by default) after waking before the retry kicks in. Before, the error fired the moment the PC woke. The docs already say this case is "handled like any other dropped connection", so I'm not flagging it as a bug. Real-world evidenceN/A: no evidence bundle was produced for this run. The change is timing behaviour inside the LLM client and Agent UI turn loop, and it can only be exercised by actually sleeping a Windows machine. The PR leaves that live check unticked in its test plan. This verdict rests on static review plus the unit tests the PR describes. It would still be worth running the live "sleep a Windows laptop for 5+ minutes mid-answer" check before the release ships. 🔍 Technical detailsIssues Found 🟢 Socket-read tests patch the global 🟢 🟢 Follow-up noted in the PR, worth an issue ( Strengths
|
…e.monotonic The sleep tests swapped time.monotonic for the whole process, which also fed the fake clock to the shared awake-clock thread and anything else running. The read now takes an injectable clock like the rest of the watchdog, and the Agent UI fixtures no longer use create=True, so renaming the patched helper fails the test instead of silently skipping the guard.
…g sleep The first version noticed a sleep as a jump of more than 5 s between clock reads, which also hid a GIL stall or VM pause without a trace, needed a ticker thread, and left two read-order races. A running tool's 180 s limit also still counted sleep, so a turn that slept mid-tool failed on waking with ToolExecutionTimeout. gaia.utils.awake_clock.monotonic() now reads QueryUnbiasedInterruptTime on Windows, which excludes sleep and hibernation, and time.monotonic() elsewhere, which already stops during suspend. The stream watchdog, socket read deadline, retry budget, tool limit and Agent UI turn clock all read it, and silence is measured from one clock.
The busy-server load wait that main added now reads the same awake clock as the retry budget, so a PC that sleeps while Lemonade loads a model still waits for it on waking.
|
Verdict: Approve with suggestions On Windows, a PC that slept partway through an answer used to wake up to a stall or timeout error. This PR moves those time limits onto a clock that stops while the PC sleeps: the stream idle check, the socket read deadline, the retry and load-wait budgets, a running tool's time limit, and the Agent UI's no-progress limit. A server or tool that stays silent while the PC is awake is still cut off. Nothing blocks merge.
Real-world evidenceN/A: this is a timing change that only shows on a Windows PC going to sleep, which CI can't do, and no evidence bundle was produced for this run. The verdict rests on static review and the PR's simulated-sleep unit tests. The live Windows sleep check is still open in the PR's test plan. 🔍 Technical detailsIssues found 🟢 The same comment appears twice in 🟢 The 🟢 The Checked and fine
Strengths
|
Review follow-up: the sleeping-PC turn tests use the clock fixture directly, and the read-deadline comment lives only where the clock is read.
# Conflicts: # src/gaia/ui/_chat_helpers.py
# Conflicts: # docs/sdk/configuration.mdx
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 - [x] `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 - [x] 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. - [x] `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 - [x] `python util/lint.py --black --isort --pylint --flake8 --test-lanes` - [x] 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. <details> <summary>🔍 Technical details</summary> - `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 amd#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 amd#5391. - Builds on amd#5316: after a restart its re-attach gets a 404 and loads the saved chat, which now holds the interrupted reply. - Merging with amd#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 amd#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. </details> --------- Co-authored-by: Kalin Ovtcharov <[email protected]>
Before: on Windows, a PC that slept mid-answer for longer than two minutes woke to "The model stopped sending partway through its answer", because the monotonic clock there keeps counting through sleep and the stream idle limit read the sleep as a dead server. A longer sleep tripped the socket read deadline, the retry budget, a running tool's 180 s limit (
ToolExecutionTimeout), and the Agent UI's 75-minute no-progress limit the same way. After: every one of those limits runs on a clock that stops while the PC sleeps, so a local model and a running tool pick up where they left off, and a server or tool that goes quiet while the PC is awake is still cut off. Lands after v0.25.0.Reproduced by
tests/unit/test_sleep_aware_timers.pyand the "PC that sleeps mid-turn" cases intests/unit/chat/ui/test_turn_idle_limit.py. They stand in for a Windows PC whosetime.monotonicjumps eight hours during a sleep while the awake clock does not, and run the code with its default clocks. On main the stream raisesStreamStalledError, the socket read raisesReadTimeout, the retry gives up after one attempt, the tool raisesToolExecutionTimeout, and both Agent UI turns are stopped for "no progress". All pass here.Test plan
pytest tests/unit/test_sleep_aware_timers.py tests/unit/test_awake_clock.py tests/unit/chat/ui/test_turn_idle_limit.py, including the guards that a silent server, an overrunning tool and a silent turn are still stopped while the PC is awaketest_a_server_silent_while_the_process_was_paused_is_still_cut_offfails on this PR's first commit (the gap heuristic hid a pause) and passes here; the tool and Agent UI cases also fail on that commitpytest tests/unit/test_stream_stall_watchdog.py tests/unit/test_stream_reader_abandon.py tests/unit/test_llm_retry_adversarial.py tests/unit/agents tests/unit/chat/ui tests/unit/test_lemonade_client_http.py tests/unit/test_lemond_request_budget.pywith an isolatedGAIA_HOME; the only failures also fail on main wheneverGAIA_HOMEis setpython util/lint.py --black --isort --pylint --flake8 --test-lanesEval categories to watch on the next RC:
error_recovery,gaia_resilience.🔍 Technical details
gaia.utils.awake_clock.monotonic()readsQueryUnbiasedInterruptTimeon Windows (excludes sleep and hibernation, Windows 7+, ~16 ms resolution) andtime.monotonic()elsewhere, which already stops during suspend on Linux and macOS. No heuristic and no ticker thread, so a GIL stall or VM pause still counts in full.ByteActivity(and sowatch_streamsilence and_AbortableStream.readdeadlines, from one clock), LemonadeClient's retry budget,_call_tool_boundedand its user-wait clock, and the Agent UI turn clock (_turn_clock). Call sites look it up at call time, so a test can stand in for it.watch_streamand_AbortableStreamno longer take their ownclock(no caller passed one); both read the activity's clock, which is the one injection point.test_sleep_aware_timers.pyswaptime.monotonicfor one test at a time and reload the watchdog, so they fail on any version that measures a limit ontime.monotonic. Nothing in that module starts a thread that outlives a test, and the Agent UI fixtures patch_chat_helpersattributes withoutcreate=True.requests.post(timeout=)inchat_completions) is bounded by the socket's own wait, so whether a sleep cuts it short depends on how Windows times a socket wait across sleep. Not changed here.LemonadeClients.sweepresets every lease after a gap longer than half the TTL;test_a_sleeping_machine_lapses_no_lease).time.monotonic(daemon/broker.py). Permission and question prompts still time out across a sleep, which is defensible since the user was away.