Skip to content

fix(agent): loud clock errors cancel the tool; Modern Standby counts - #5464

Merged
kovtcharov-amd merged 13 commits into
amd:mainfrom
kovtcharov:kalin/awake-clock-s0ix
Oct 23, 2026
Merged

kovtcharov-amd merged 13 commits into
amd:mainfrom
kovtcharov:kalin/awake-clock-s0ix

Conversation

@kovtcharov

@kovtcharov kovtcharov commented Oct 21, 2026 •

Copy link
Copy Markdown
Contributor

On a Windows PC with Modern Standby, standby time is real running time, so time limits rightly keep counting through it; this PR stops the docs from saying otherwise. A real 186-minute Modern Standby on the test PC (Kernel-Power 506 at 09:46 UTC, 507 at 12:51 UTC on 2026-10-21) never paused a GAIA process: it logged a sample every minute throughout. An earlier version of this PR tried to leave standby out of limits using display-off notifications. It left out nothing on that standby, and it could have excused a real hang, so it is removed.

What remains is what's proven. The awake clock is QueryUnbiasedInterruptTime on Windows, which leaves out S3 sleep and hibernation, and time.monotonic elsewhere. If Windows refuses that read, every time limit fails with an error that says to restart GAIA and run gaia diagnostics. In the Agent UI, a chat turn hit by that error shows it instead of "try again". A tool whose clock fails is cancelled instead of left running. A new test also pins that a tool's 180 s limit keeps leaving out the time a user spent answering a file-access prompt after the prompt closes; breaking that passed every existing test.

Eval categories to watch on the next RC, since this touches the LLM timeout paths: error_recovery, gaia_resilience.

Reproduced by test_a_tool_whose_clock_fails_is_cancelled_not_left_running, which fails with main's agent.py (the tool is never told to stop) and passes here.

Test plan

  • pytest tests/unit/test_awake_clock.py tests/unit/test_sleep_aware_timers.py tests/unit/test_path_access_grant.py tests/unit/chat/ui/test_turn_idle_limit.py: all pass
  • 10 mutations of the remaining behaviour, each killed by a test:
    • the clock source and its kernel function
    • a refused read
    • its message
    • the tool cancel
    • the Agent UI message
    • a tool limit read on the wall clock
    • three user-wait mutations: dropping all wait time, dropping answered prompts, and timing the wait on a clock that counts sleep (an S3 sleep mid-prompt would then come off the limit twice)
  • Full tests/unit (-n 6) at 5d0dbe0 (7ef719f after it only adds tests): 70 failed, 26,773 passed. With the changed source files swapped back to the merge base, the same tests fail; none fails only on this branch.
  • python util/lint.py --all; mypy is clean on awake_clock.py
  • Real Modern Standby measured: the process ran through it, so it is documented as running time
🔍 Technical details
  • Clock source. A PC that never used S3 sleep can't tell QueryUnbiasedInterruptTime from a clock that counts sleep, so a test pins the source with a fake that returns known ticks. The sleep-aware timer tests now give the two fake clocks different origins, so a limit that reads the wrong clock fails.
  • What was removed. The display-notification monitor thread, the tick thread, the hidden window and power-setting subscription, the probable-standby exclusion, and the stuck-monitor restart machinery. That leaves 10 files changed against the merge base.
  • Docs. cli.mdx, agent-ui.mdx, sdk/configuration.mdx and the module docstring all say S3 sleep and hibernation are left out and Modern Standby counts as running time.

A reply or tool that spanned Modern Standby still hit the stream,
no-progress and 180 s tool limits on wake. Most current Windows laptops
(and this repro PC, which only offers S0 low-power idle) never enter S3,
and QueryUnbiasedInterruptTime keeps counting through S0ix: 9.85 h of
Kernel-Power 506/507 standby since boot here, 0.0 s excluded.

The awake clock now runs a monitor thread with a hidden window
subscribed to GUID_CONSOLE_DISPLAY_STATE. Windows freezes desktop apps
for the standby, so a stretch the process did not run for more than
10 s that began with the display off is left out past its first 10 s,
and logged with its size. A freeze with the display on is a pause, not
a sleep, and still counts (logged as a warning). Readers that wake
before the monitor are held at the cut-off, so no reading ever includes
the standby or goes backwards. A failed subscription or a dead monitor
raises AwakeClockError from every read; shutdown at exit unregisters
the notification and destroys the window.

Also adds a test for the tool-limit user-wait clock: forgetting the
time of an already-answered prompt passed every test before.
…standby

Review follow-up. Readers and the monitor read the raw clock before
taking the ledger lock, so a stale timestamp could step a reading back
by the length of a stall. The ledger now owns the raw clock and reads it
under its lock.

A process starved of its turn (a thread holding the GIL) with the
display off looked like standby. A gap now also needs the process to
have used under half of it in CPU time, which a frozen process does not
and a busy one does; a busy gap is counted and logged.

The window is message-only, so system broadcasts never wait on its
pump. The end-to-end tests set the display state themselves and bound
their timing by the parent's wall clock, and a monitor thread that exits
without an error is covered.
Review follow-up. shutdown() turned the display "on" before stopping
the monitor, so a display-off notification arriving in between, or
after a stop that timed out, left every later reading held at the
standby cut-off for good. The ledger now detaches under its lock:
it judges the last gap, then ignores display changes and never holds.
Review follow-up. A monitor whose stop timed out could still beat later
and add a standby gap, stepping unheld readings back once. Exclusion now
needs the ledger to still be monitored. Tests cover a standby that ends
at shutdown and a beat after it.
@github-actions github-actions Bot added documentation Documentation changes tests Test changes labels Oct 21, 2026
@github-actions

Copy link
Copy Markdown
Contributor

Verdict: Approve with suggestions

On Windows laptops that use Modern Standby, replies and tools no longer hit their time limits the moment the PC wakes. Time spent in standby is now left out of every limit except its first 10 seconds. I found no correctness bugs. The clock never runs backwards and never shows a reader the standby time, and a dead or unsubscribed monitor raises an error instead of quietly counting standby again. The new tests cover each branch, including a real end-to-end run that freezes a child process the way standby does.

Two things to weigh before merging. Neither blocks:

  • No way around a failed monitor. If Windows won't deliver the display-power notification to a process (unusual sessions such as services or containers), every time limit raises, so every agent turn fails on that machine with no override. That follows the fail-loudly rule, but nothing here shows how often it happens.
  • The end-to-end Windows tests run on tight timing (a 2.5 s gap with 0.5 s of slack) on shared CI runners. They could flake there. Windows unit CI is still pending.

The one real-world check (close the lid mid-reply on a Modern Standby laptop) is still unticked in the test plan. Please run it before merge, since no test here proves Windows actually freezes GAIA's process during standby.

Real-world evidence

N/A: no evidence bundle was produced for this run. The change has no CLI, API, MCP or Agent UI output to capture, and real standby needs a Modern Standby laptop. This verdict rests on static review plus the PR's unit and end-to-end tests. The manual lid-close check is still pending.

🔍 Technical details

Issues

🟢 The failure stays failed for the life of the process, with no override (src/gaia/utils/awake_clock.py, _ensure_monitor)
_start_error is cached for good, and monotonic() sits under _execute_tool, ByteActivity, _UserWaitClock and the retry clock. So one failed RegisterPowerSettingNotification means every tool call and every streamed reply raises AwakeClockError. The error is loud and actionable, which is correct. It's worth confirming the subscription works from session 0 (a scheduled task or service) and over SSH before this ships, or deciding on an explicit, documented opt-out env var. An opt-out the user sets on purpose isn't a silent fallback.

🟢 End-to-end timing margins (tests/unit/test_awake_clock.py, GAP = 2.5 and the + 0.5 slack)
On windows-latest, a scheduler hiccup over about 1.5 s between beats in test_a_process_frozen_through_standby_wakes_with_the_standby_left_out or test_a_process_frozen_with_the_display_on_counts_every_second breaks the bound. If these flake, widening GAP to about 4 s and FREEZE to about 12 s keeps the same proof with more headroom.

🟢 Brief thaws during standby each cost up to 10 s
If Windows briefly resumes the process during a long standby (maintenance or network activity in connected standby), each resume starts a new stretch, and each stretch's first STANDBY_GAP seconds are counted. This is bounded and every stretch is logged, so it's acceptable. It's just worth knowing if a multi-hour standby still trips a limit.

Strengths

  • SleepLedger is pure and injectable, which lets the ordering cases be tested directly: a reader waking before the monitor, the display-on notification arriving before the beat, and a beat after shutdown. test_readings_never_go_backwards_through_standbys_and_pauses is a good property check over all of them.
  • Using process CPU time to tell "frozen" from "starved" keeps a busy hung tool caught, and a display-on pause still counts. Both are logged as warnings, so a wrong call shows up in gaia.log.
  • The new _UserWaitClock test catches the mutation the PR describes: the tool limit forgetting the prompt wait once the prompt closes. That gap was real.
  • The three doc pages that describe sleep handling (agent-ui, cli, sdk/configuration) were all updated together.

…ry limit

Review follow-up. A monitor wedged in a log call held the clock at the
standby cut-off forever with the display off: 25 s passed and 11 s
counted, with no error. A second thread now only ticks, so it shows when
the process was running; running past an overdue beat for 5 s means the
monitor is stuck, and a real standby freezes the tick thread too.

A stuck, dead or failed monitor is replaced on the next read, at most 3
times, each logged as an error, carrying the standby already left out;
its missed time counts. After that every read raises an error that says
to restart GAIA and run `gaia diagnostics`, and the Agent UI shows it
instead of "temporary issue, try again". A failed restart is retried on
the next read instead of leaving the clock unmonitored.

Each exclusion is now a warning, worded "probable standby (display off,
low CPU)", since a paging stall or a debugger pause reads the same. The
monitor logs once whether display notifications arrive, and says when
the process is outside the console session (a service, a remote logon),
where standby still counts. Stopping it joins both threads; tests now
pin the unsubscribe and window destroy.
Review follow-up. Now that the awake clock can raise, an error from it
inside the tool-timeout loop escaped before the tool was told to stop,
so its worker kept running after the turn had failed. The loop now
cancels the tool on any exception before re-raising.

The awake-clock monitor's failures share one counter and one wording,
the count resets after a replacement runs 10 minutes without trouble,
and a monitor given up on is stopped first. The give-up message names a
short cause instead of repeating the subscribe error's report line. The
display-notice test skips outside the console session, where Windows
sends none.
Review nit. The fourth failure logged "starting a new one" although GAIA
gives up there. Its line now says so. The reset test also checks that
the next failure counts from one again.
… unpinned

Re-review follow-up. A monitor whose threads never stop keeps a thread
and a window, and the 10-minute healthy reset let them pile up. The
replaced ones still running are now tracked, and more than 2 gives up
with an error that says how many, whatever the failure count.

A failed session-id lookup in the "no display notifications" warning is
logged instead of killing the monitor. New tests pin what deleting
passed before: the dead-tick-thread check (without it a stuck monitor
froze limits silently again), shutdown's detach, stop() waiting for a
tick in progress, abandon(), and the wedged cap. The docs name a native
call blocking while holding the GIL as a known limit, next to paging and
a debugger.
@kovtcharov
kovtcharov marked this pull request as draft October 21, 2026 09:14
…r to call it wedged

Review follow-up. When the wedged cap fired, the failure line said
"starting a new one" just before a second line said it was giving up.
The cap is now checked before the line is written, and the line says it
gives up and why. A replaced monitor gets 2 s instead of 0.5 s to stop
before it counts as wedged, so a loaded machine doesn't trip the cap.
The module docstring names the cap.
A real 186-minute Modern Standby on the test PC (Kernel-Power 506/507)
did not pause a process using the awake clock: it logged a sample every
minute throughout, so nothing was left out and that time counted. The
docs no longer say standby is left out in general; the Agent UI guide
says it is left out only while Windows has paused GAIA, and counts when
GAIA keeps running. The module docstring no longer states that Windows
freezes desktop processes for the standby.
…and hibernation only

A real 186-minute Modern Standby on the test PC never paused the
process, so standby is running time there and the display-off
heuristic had no shown benefit. It could also excuse a real hang (a
low-CPU stall with the display off). The monitor thread, the tick
thread, the hidden window, the power-setting subscription, the
probable-standby exclusion and the restart machinery are all gone.

The awake clock is QueryUnbiasedInterruptTime on Windows, which leaves
out S3 sleep and hibernation, and time.monotonic elsewhere. If Windows
refuses the read, every time limit fails with an error that says to
restart GAIA and run `gaia diagnostics`. Tests now pin the clock source
(a PC that never used S3 can't tell it from one that counts sleep) and
catch a limit that reads the wrong clock. The docs say S3 sleep and
hibernation are left out and Modern Standby counts as running time.
@kovtcharov kovtcharov changed the title fix(llm): leave Modern Standby out of time limits fix(agent): count a user's answer off the tool limit, and fail loudly on a broken clock Oct 21, 2026
@kovtcharov
kovtcharov marked this pull request as ready for review October 21, 2026 23:08
@github-actions

Copy link
Copy Markdown
Contributor

Verdict: Approve with suggestions

The docs now say plainly that Modern Standby counts as running time and only S3 sleep and hibernation are left out. If Windows refuses the time-limit clock, GAIA now fails with a "restart GAIA" message, and a tool caught by that failure is told to stop instead of running on. The change is small, and it comes with tests that fail without it. Nothing blocks merge.

  • One gap worth closing: when the clock fails inside a tool call, the agent treats it as an ordinary tool error and lets the model retry. Every retry hits the same broken clock. The user still sees the restart message once the chat turn's own clock read fails, but the model can waste steps first. Consider letting this error end the turn.

Real-world evidence

N/A: no evidence bundle was produced for this run. The changed paths only fire when Windows refuses a clock read, which no CI runner can trigger. This verdict rests on static review plus the PR's tests. The Windows-only clock tests are skipped on Linux CI, so they run only on a Windows runner. The author's Modern Standby measurement is described in the PR but isn't attached as a log here.

🔍 Technical details

Issues

🟢 A clock failure inside a tool is downgraded to a retryable tool error (src/gaia/agents/base/agent.py:6762). _call_tool_bounded now re-raises AwakeClockError after setting cancel, which is correct. But _execute_tool's except Exception then turns it into {"status": "error", ...} with recoverable=True, so the agent loop goes into error recovery and calls more tools, and each one fails the same way. The "Restart GAIA" text reaches the model, not the user. The UI turn's own _awake_clock.monotonic() read will raise eventually and show the right message, so this is wasted steps, not a wrong answer. Suggested fix: re-raise it before the generic handler:

        except AwakeClockError:
            # Unrecoverable: every retry reads the same broken clock.
            raise
        except Exception as e:

(This needs from gaia.utils.awake_clock import AwakeClockError. Check that callers above _execute_tool don't swallow it too.)

🟢 The UI test patches only the helper's clock (tests/unit/chat/ui/test_turn_idle_limit.py:580). It shows the message comes through when the turn-idle clock fails. It doesn't cover the error coming up from the agent or tool path, which is the case the item above describes. Worth adding if you take that fix.

Strengths

  • The try/except BaseException around the wait loop sets cancel before re-raising, so a tool body that polls tool_cancelled() actually stops. test_a_tool_whose_clock_fails_is_cancelled_not_left_running pins this, and the PR states it fails on main.
  • The two fake clocks in SleepingPC now start at different values, so a limit that reads the wrong clock fails. That cheaply hardens every existing sleep-aware test.
  • The error follows the fail-loudly rule: it names what failed, says to restart GAIA, points to gaia diagnostics and the issue tracker, and keeps the WinError as __cause__. The doc wording is updated the same way in cli.mdx, agent-ui.mdx, configuration.mdx and the module docstring.

… its kernel call

Review follow-up. Nothing tested that a tool's prompt wait is timed on
the awake clock: timed on one that counts sleep, an S3 sleep while a
question is on screen would come off the limit twice and hide a hung
tool for that long. A test now sleeps the PC mid-prompt, hangs the tool,
and expects it abandoned after about its limit of awake time. Another
pins the Windows clock to QueryUnbiasedInterruptTime by name.
@kovtcharov kovtcharov changed the title fix(agent): count a user's answer off the tool limit, and fail loudly on a broken clock fix(agent): cancel a tool on a clock error; say Modern Standby counts Oct 21, 2026
@kovtcharov kovtcharov changed the title fix(agent): cancel a tool on a clock error; say Modern Standby counts fix(agent): loud clock errors cancel the tool; Modern Standby counts Oct 21, 2026
@kovtcharov-amd

Copy link
Copy Markdown
Collaborator

On re-raising AwakeClockError from _execute_tool: not taken here. Raising it out of the tool runner would let it escape the agent loop, which changes behaviour for the CLI and the MCP agent server, not just the desktop app. As it stands, a clock failure inside a tool comes back as a tool error, and the user still gets the restart message as soon as the turn's own clock read fails. Cutting the extra retry steps cleanly is better done as a follow-up that stops the turn without raising past the loop.

@kovtcharov-amd
kovtcharov-amd added this pull request to the merge queue Oct 23, 2026
Merged via the queue into amd:main with commit ad21a68 Oct 23, 2026
48 checks passed
@kovtcharov-amd
kovtcharov-amd deleted the kalin/awake-clock-s0ix branch October 23, 2026 07:17
kovtcharov added a commit to kovtcharov/gaia that referenced this pull request Oct 23, 2026
…tes it

amd#5464 documented the desktop app's `~/.local/bin/gaia` shim in backticks, and
the doc check's exemption for that shim only matched it followed by a space, so
the TUI build went red on main and on every open PR. The shim wraps the Python
CLI, so naming it is correct; the exemption now accepts any non-name character
after it, the same boundary the check already uses for `bin/gaia`.
kovtcharov-amd added a commit to tylerbea/gaia that referenced this pull request Oct 30, 2026
…reach (amd#5653)

Of the last 150 bug fixes, 147 shipped a regression test, yet CI caught
only about 7 of those bugs before users or RC testing did. Each test
guards the one call site that broke, and the next site with the same
flaw ships untested. Meanwhile every PR ran all ~27k unit tests on three
operating systems, even for a docs edit, and most main-branch runs were
cancelled before they finished. This PR guards the recurring bug shapes
everywhere, fixes a real bug the new tests found, and makes a PR run
only the tests it can affect.

- **Guards for the shapes behind most recent fixes.** A ratchet counts
subprocess and HTTP calls with no timeout, kill-by-image-name, and
`except Exception` bodies that only pass or return a placeholder.
Existing sites are grandfathered, new ones fail CI, and fixing one
lowers the count.
- **Folder grants were lost when several GAIA processes saved at once.**
A four-process test lost 96–98 of 100: the read-modify-write had no
lock, and a torn read "rebuilt" the file from empty. It is now locked
and atomic. Six runtime calls that could hang forever now time out, with
actionable errors.
- **PRs run only the reachable tests.** `util/select_tests.py` combines
a nightly per-test coverage map with static rules for what coverage
can't see. Windows and macOS run the OS-touching subset of that. The
median PR runs about a quarter of the suite. On ~1,150 recent commits,
it selected every bug fix's own regression test from the fix's source
changes alone.
- **Full coverage moves to main and nightly.** Every push to main runs
the full suite on Linux and now finishes instead of being cancelled. The
nightly run covers all three operating systems and rebuilds the map. The
frozen flagship binary also builds on packaging PRs and weekly, not only
at an RC.
- **Duplicates trimmed.** The email unit lane no longer re-runs ~90
files `test_unit.yml` already covers, and the warning-only C++
benchmarks run on main instead of every PR.

Also unbreaks main's TUI build: amd#5464 documented the desktop app's
`gaia` shim in backticks, and the TUI doc check only exempted it before
a space, so every PR's TUI checks went red. The shim is the Python
CLI's, so the exemption now accepts any punctuation after it.

Trade-offs to know: a Windows- or macOS-only bug outside the OS-touching
subset surfaces at the nightly run, not on the PR, and PRs no longer
upload partial coverage to Codecov. To run the full suite on a branch,
dispatch `test_unit.yml` on it.

## Test plan
- [x] `pytest tests/unit/test_select_tests.py
tests/unit/test_process_safety_ratchet.py
tests/unit/test_allowed_paths_concurrency.py`: 26 + 33 + 1 passed; the
concurrency test fails on the old code (96–98 of 100 grants lost)
- [x] Full `tests/unit` locally: 27,501 passed; 26 failures that fail
identically on main in this environment (PATH-installed `gaia`, real
wheel installs)
- [x] `python util/lint.py --all` passes, including the lane-coverage,
path-coverage, trigger and ancestor-skip checks
- [x] Selector replayed over ~1,150 recent commits with a map built from
a real `--cov-context=test` run
- [ ] After merge: the first nightly run saves `unit-test-map-*`, and
the next PR's "Select unit tests" summary reports a map-based selection

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

- Static rules: module-level imports (transitive); every import and
module-naming string in tests and tooling (transitive); filename strings
and directory scans (one hop); nested `conftest.py`; top-level fixtures
by requested name, through fixture chains; autouse isolation fixtures
(one hop); CLIs run with `python -m`, whose lazy imports coverage can't
see. A package `__init__` reaches everything below it when it changes,
but the walk never continues through one.
- Full-run triggers: any `conftest.py`, packaging or pytest config, the
selector or `test_unit.yml`, and any deleted or renamed file (`git diff
--no-renames`). So does a selection over 70% of the suite.
- With no map (a cache miss), function-level imports are followed too
and the job summary says so; a map over 3 days old raises a warning.
- A push diffs against the last commit a successful main run tested, so
merges whose runs were dropped while pending still reach Windows and
macOS. The event name is in the concurrency group, so a push can't drop
the nightly.
- Known blind spot, documented in `docs/reference/dev.mdx`: code behind
a cache or shared fixture is credited in coverage only to the first test
that ran it.
- Open PRs touching the same files (amd#5453, amd#5417, amd#5511, amd#5600, amd#5475,
amd#5542, amd#5558) test-merge cleanly against this branch; none gains a
conflict from it.
</details>

---------

Co-authored-by: Kalin Ovtcharov <[email protected]>
Co-authored-by: v <v@x>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents documentation Documentation changes tests Test changes

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants