Skip to content

fix(llm): a PC that sleeps mid-answer no longer wakes to a stall error - #5387

Merged
kovtcharov-amd merged 7 commits into
amd:mainfrom
kovtcharov:claude/rel-sleep-aware-timers
Oct 19, 2026
Merged

kovtcharov-amd merged 7 commits into
amd:mainfrom
kovtcharov:claude/rel-sleep-aware-timers

Conversation

@kovtcharov

@kovtcharov kovtcharov commented Oct 19, 2026 •

Copy link
Copy Markdown
Contributor

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.py and the "PC that sleeps mid-turn" cases in tests/unit/chat/ui/test_turn_idle_limit.py. They stand in for a Windows PC whose time.monotonic jumps eight hours during a sleep while the awake clock does not, and run the code with its default clocks. On main the stream raises StreamStalledError, the socket read raises ReadTimeout, the retry gives up after one attempt, the tool raises ToolExecutionTimeout, 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 awake
  • test_a_server_silent_while_the_process_was_paused_is_still_cut_off fails 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 commit
  • pytest 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.py with an isolated GAIA_HOME; the only failures also fail on main whenever GAIA_HOME is set
  • python util/lint.py --black --isort --pylint --flake8 --test-lanes
  • Live: on a Windows laptop, sleep it for 5+ minutes during a long local answer and see the answer finish after waking

Eval categories to watch on the next RC: error_recovery, gaia_resilience.

🔍 Technical details
  • gaia.utils.awake_clock.monotonic() reads QueryUnbiasedInterruptTime on Windows (excludes sleep and hibernation, Windows 7+, ~16 ms resolution) and time.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.
  • On it: ByteActivity (and so watch_stream silence and _AbortableStream.read deadlines, from one clock), LemonadeClient's retry budget, _call_tool_bounded and 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_stream and _AbortableStream no longer take their own clock (no caller passed one); both read the activity's clock, which is the one injection point.
  • The sleep tests in test_sleep_aware_timers.py swap time.monotonic for one test at a time and reload the watchdog, so they fail on any version that measures a limit on time.monotonic. Nothing in that module starts a thread that outlives a test, and the Agent UI fixtures patch _chat_helpers attributes without create=True.
  • Untested: a non-streamed request (requests.post(timeout=) in chat_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.
  • Checked and already fine: the daemon's Lemonade client leases (LemonadeClients.sweep resets every lease after a gap longer than half the TTL; test_a_sleeping_machine_lapses_no_lease).
  • Not changed, for the daemon owners: the model-slot broker reclaims a lease held for 900 s of time.monotonic (daemon/broker.py). Permission and question prompts still time out across a sleep, which is defensible since the user was away.
  • LLM-affecting only through timing: no prompt, tool or model change.

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.
@github-actions github-actions Bot added documentation Documentation changes llm LLM backend changes tests Test changes performance Performance-critical changes labels Oct 19, 2026
@github-actions

Copy link
Copy Markdown
Contributor

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 evidence

N/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 details

Issues Found

🟢 Socket-read tests patch the global time.monotonic (tests/unit/test_sleep_aware_timers.py, test_a_socket_read_spanning_a_sleep_does_not_time_out / ..._still_times_out_on_a_silent_server)
monkeypatch.setattr(watchdog.time, "monotonic", raw) replaces time.monotonic for the whole process, not just the watchdog module. If an earlier test already started the gaia-awake-clock thread, that thread reads the fake clock for the duration and permanently adds about 8 h to shared().slept. Any other thread (pytest-timeout, httpx pools) also sees fake time. It's harmless today, because differences of the shared clock stay consistent, but it's fragile. Consider giving _AbortableStream an injectable clock, as ByteActivity and watch_stream already have, and passing raw in.

🟢 create=True is unnecessary (tests/unit/chat/ui/test_turn_idle_limit.py, clock and sleeping_pc fixtures)
helpers._sleep_clock now exists. create=True would let the patch silently succeed if the import were renamed, so the "never sleeps" guard would stop applying without any test failing. Drop it so a rename fails loudly.

        patch.object(helpers, "_sleep_clock", lambda: never_sleeps),

🟢 Follow-up noted in the PR, worth an issue (daemon/broker.py)
The 900 s monotonic slot-reclaim can take the model slot from a turn that slept through a model load. The PR calls this out correctly as out of scope. Filing it as an issue would keep it from being lost.

Strengths

  • ByteActivity.excuse clamps to clock(), so a false gap (a starved thread or a slow consumer) can never push last into the future. The worst case is a delayed limit, never a missed one.
  • In watch_stream the excuse runs at the top of every iteration, before the remaining check, so the first poll after waking can't fire a stale stall.
  • shared() ticks on its own thread, so the Agent UI turn clock sees a sleep even when the poll loop is held up by a busy executor. Its only callers (_turn_clock and the retrier) use differences, so the process-wide offset stays consistent.
  • The docs (agent-ui.mdx, configuration.mdx) are updated alongside the code, and the guard tests (silent server is still cut off, silent turn after waking is still stopped) cover the direction that matters most.

kovtcharov-amd and others added 2 commits October 18, 2026 23:07
…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.
@kovtcharov-amd kovtcharov-amd added the ready_for_ci Run CI workflows on draft PR without requesting review label Oct 19, 2026
@github-actions

Copy link
Copy Markdown
Contributor

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.

  • I checked every changed timer for a mix of the new clock and the old one, and found none. The idle and progress timestamps in the Agent UI, the stream watchdog and the retrier each stay on a single clock.
  • The tests cover both sides of each limit: an 8-hour sleep is ignored, and awake silence is still stopped. Without real sleep hardware, that is the strongest proof possible here.
  • The one gap is the live check the PR still lists as unchecked: sleep a Windows laptop for 5+ minutes during a long local answer and confirm it finishes. Run it before the release that ships this.

Real-world evidence

N/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 details

Issues found

🟢 The same comment appears twice in _AbortableStream (src/gaia/llm/stream_watchdog.py:114 and :120). The __init__ comment and the one in read() say the same thing. Keep only the one in read(), where the clock is used:

        self._inner = inner

🟢 The sleeping_pc fixture only renames clock (tests/unit/chat/ui/test_turn_idle_limit.py, new section). It returns clock unchanged. Either use clock directly in the three new tests or drop the fixture. As written, it suggests a different setup that doesn't exist.

🟢 The pc fixture swaps the global time.monotonic by hand (tests/unit/test_sleep_aware_timers.py). The finally block restores it. monkeypatch.setattr(time, "monotonic", ...) would match the rest of the suite and would still restore it if the importlib.reload call fails partway. Optional.

Checked and fine

  • _TurnIdleClock and _ActivityConsole.last_progress both get their times from _turn_clock. The remaining _time.monotonic uses in _chat_helpers.py (registry wait, producer-stop grace, queue wait, perf timings) measure their own intervals and aren't compared against awake-clock values.
  • watch_stream and _AbortableStream now read activity.clock, so silence and the read deadline share one clock. Removing the unused clock= parameter breaks no caller; the only importer is lemonade_client.py.
  • ModelCallRetrier measures everything on its injected _clock, so moving its default to awake_clock.monotonic is consistent across the deadline and the load-wait accounting.
  • The reload in the pc fixture doesn't break other tests. They bind stream_watchdog names at import time, and lemonade_client keeps its original references.

Strengths

  • There is a single lookup point (awake_clock.monotonic(), resolved at call time) and no ticker thread or jump heuristic. A GIL stall or VM pause still counts in full, and test_a_server_silent_while_the_process_was_paused_is_still_cut_off pins that down.
  • Each "sleep is ignored" test has a matching "awake silence still trips" test, so the change can't quietly turn a limit off.
  • The docs (agent-ui.mdx, configuration.mdx) were updated next to the code, and the wording is accurate about the hosted-model case.

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
@kovtcharov-amd
kovtcharov-amd added this pull request to the merge queue Oct 19, 2026
@github-merge-queue
github-merge-queue Bot removed this pull request from the merge queue due to a conflict with the base branch Oct 19, 2026
# Conflicts:
#	docs/sdk/configuration.mdx
@kovtcharov-amd
kovtcharov-amd added this pull request to the merge queue Oct 19, 2026
Merged via the queue into amd:main with commit 0cbbac6 Oct 19, 2026
50 checks passed
@kovtcharov-amd
kovtcharov-amd deleted the claude/rel-sleep-aware-timers branch October 19, 2026 19:04
kovtcharov added a commit to kovtcharov/gaia that referenced this pull request Oct 21, 2026
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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents documentation Documentation changes llm LLM backend changes performance Performance-critical changes ready_for_ci Run CI workflows on draft PR without requesting review tests Test changes

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants