Skip to content

fix(scheduler): a job left firing by a crash no longer stays stuck forever - #5380

Merged
kovtcharov-amd merged 5 commits into
amd:mainfrom
kovtcharov:claude/rel-j-stale-firing
Oct 19, 2026
Merged

kovtcharov-amd merged 5 commits into
amd:mainfrom
kovtcharov:claude/rel-j-stale-firing

Conversation

@kovtcharov

@kovtcharov kovtcharov commented Oct 19, 2026 •

Copy link
Copy Markdown
Contributor

A scheduled job that was mid-fire when the daemon crashed, or when its database was locked as the result was written, stayed in "firing" forever. A recurring job (a daily brief) never ran again, and a scheduled email send was never reported as failed. Now a firing job is held as a lease that its driver renews every minute. A lease nobody has renewed for about 12 minutes is recovered. A recurring daemon job or an email snooze runs again; a scheduled send is marked failed with the reason, is never sent twice, and now shows up when the user lists their scheduled jobs. A send still going out on another driver, for example after the laptop wakes from sleep, is not taken over. A send marked failed that later does go out changes to sent, so the error tells the user to check the Sent folder before scheduling it again.

Reproduced by tests/unit/test_daemon_scheduler_stale_firing.py and hub/agents/email/python/tests/test_email_schedule_stale_firing.py; they fail on main and pass here.

🔍 Technical details
  • claim_job returns a claim_id token. While the executor runs, a Heartbeat thread renews claimed_at every heartbeat_seconds (60 s) on its own connection. mark_fired / mark_failed succeed only for the token's holder; a bare job_id match no longer counts (test_only_the_claim_holder_can_record_an_outcome).
  • Recovery happens in two steps. find_stale_firing lists leases not renewed in stale_firing_seconds (600 s). StaleLeases then recovers one only after this driver has seen the same (claim_id, claimed_at) across two more heartbeat intervals of its own passes. After a sleep/resume every lease looks hours old, and the holder's first heartbeat clears it (test_a_fire_still_in_flight_is_not_taken_over_after_a_wake_up). A lease is only taken over once it has gone unrenewed for that whole window.
  • recover_claim is a compare-and-set on claim_id and claimed_at, so a heartbeat landing between the stale scan and the recovery write wins (test_a_lease_renewed_after_it_was_read_is_not_recovered, both stores). It records superseded_claim. A holder that was alive after all can still record its outcome over the recovery's guess. A late failure never overrides a re-run that already claimed the job (test_a_late_error_never_overwrites_the_rerun_that_succeeded).
  • The recovery error gives the last heartbeat in local time and how long ago it was ("at 14:05 on 2026-10-18 (3 hours ago)").
  • EmailJobScheduler takes one injectable clock for claims, heartbeats and recovery; the wake-up test moves that single clock the way a sleep does.
  • list_scheduled_jobs returns failed: jobs that failed in the last 7 days, with the error. Its tool description now asks the agent to tell the user. LLM-affecting (tool description and output). No eval category covers the email scheduling tools, so no scorecard will show this.
  • init_schema adds claimed_at, claim_id and superseded_claim and tolerates another connection adding them first. It starts the window of a row stuck by an older build at upgrade, so that row is not stale on sight.
  • The email package carries its own copy of the lease timing (gaia_agent_email/lease.py), because it supports amd-gaia>=0.22, which predates gaia.daemon.scheduler.lease.
  • Email CHANGELOGs (python and npm) describe the change.

Test plan

  • python -m pytest tests/unit/test_daemon_scheduler_stale_firing.py tests/unit/test_daemon_scheduler.py tests/unit/test_daemon_scheduler_migration.py tests/unit/test_daemon_clock_wiring.py tests/unit/test_email_sidecar_daemon_client.py
  • python -m pytest hub/agents/email/python/tests/test_email_schedule_stale_firing.py hub/agents/email/python/tests/test_email_schedule.py hub/agents/email/python/tests/test_daemon_migration.py hub/agents/email/python/tests/test_email_schedule_relative_time_2526.py hub/agents/email/python/tests/test_email_autonomy_scheduler.py (with hub/agents/email/python on PYTHONPATH): 125 passed together with the daemon set
  • Making mark_fired / mark_failed match on job_id alone fails two of the new tests; dropping the claim_id/claimed_at guard from recover_claim fails the renewal-race test in both stores
  • The reviewer's two-driver repro (send and snooze): the second driver leaves the in-flight job alone and the first driver's outcome stands
  • python util/lint.py --black --isort --flake8 --pylint --test-lanes

…rever

A scheduled job claimed for firing stayed in "firing" forever when the
process died mid-fire or the database was locked as the result was written,
so a recurring job never ran again and a one-shot send was never reported.

Claims now record claimed_at (added to existing stores on startup). Each
pass re-queues a recurring daemon job whose claim is older than
stale_firing_seconds (default one hour) and marks a stale one-shot job
failed with the reason. One-shot jobs, including email scheduled sends and
snoozes, are never run a second time because they may already have taken
effect.
…e scheduler

A snooze restore only puts a message back in the inbox, so running it twice
is harmless; failing it left the message hidden. The scheduler now also adds
claimed_at itself on its first pass, so a driver other than the agent can
call fire_due_jobs on an older database.
@github-actions github-actions Bot added tests Test changes agent::email Email agent changes daemon Daemon supervisor / sidecar control plane labels Oct 19, 2026
@github-actions

Copy link
Copy Markdown
Contributor

Verdict: Approve with suggestions

Before this change, a scheduled job that crashed or hit a locked database while it was running stayed in "firing" forever. The daily brief stopped and failed sends were never reported. Now each pass looks for claims that have had no outcome for an hour. Recurring jobs and email snoozes are re-queued; one-shot jobs such as a scheduled send are marked failed with the reason and are never sent twice. The logic is sound and the claim-time guard stops two drivers from both recovering the same row. There are no blocking issues.

One thing to settle before the daemon starts running email jobs: when email jobs move to the daemon, a snooze becomes a generic one-shot job. The daemon's recovery fails every stuck one-shot, so a stuck snooze would stay hidden instead of coming back to the inbox, which is the opposite of what the email CHANGELOG promises. Nothing calls that migration in production yet, so no user hits this today.

Real-world evidence

N/A: no evidence bundle was produced, and the change is to internal scheduler and store logic with no CLI, REST, MCP or UI surface. The verdict rests on static review alone. I couldn't run the PR's tests here because pytest isn't installed on this runner. The PR's test plan says they fail on main and pass on this branch.

🔍 Technical details

🟢 A snooze run by the daemon is failed, not re-queued (src/gaia/daemon/scheduler/store.py:609)
daemon_migration.collect_one_shot_jobs maps both scheduled_send and snooze to KIND_ONE_SHOT, keeping the email kind in payload["kind"]. store.recover_stale_firing only re-queues KIND_RECURRING, so on the daemon path a stuck snooze is marked failed. That contradicts the email CHANGELOG ("a snooze runs again"). migrate_email_clocks has no production caller yet and daemon/server.py builds the clock with executors or {}, so nothing is affected today. Before that path goes live, either let the daemon store treat a payload kind as safe to re-run (keeping core free of email-specific code, e.g. a rerunnable flag on MigratableJob), or narrow the CHANGELOG to the standalone scheduler.

🟢 A NULL claimed_at is treated as stale immediately, even if an older process is still running that job (store.py:595, schedule_store.py:127)
During an upgrade, a pre-change driver that is mid-fire leaves claimed_at NULL. The new driver recovers that row at once. A recurring job then runs twice. A one-shot is marked failed, and then the old driver's mark_fired (which only checks job_id) overwrites it. The window is small (only during an upgrade, and only for a job that is mid-fire), so this is acceptable. Consider adding a one-line note in the docstring, or treating NULL as stale only when fired_at/created_at is older than stale_after.

Strengths

  • The recovery UPDATE re-checks the claimed_at value it just read, so a claim renewed in the meantime is never taken over.
  • Splitting recovery by whether a job is safe to re-run is the right trade-off for email: an interrupted send is reported, never re-sent.
  • Tests cover the cases that matter: the locked-database outcome write, before and after the stale window, rows with no claim time, and the column migration on an old table. mark_fired now clears the re-queue note, so a re-queued recurring job doesn't keep a stale error.

kovtcharov and others added 3 commits October 18, 2026 22:42
… sends

Review follow-ups. A fire still running on another driver could be taken
over: after a sleep/resume every claim looked hours old, the second driver
marked an in-flight send failed and told the user to schedule it again, and
for a snooze the first driver's late error overwrote the second's success.

- claim_job returns a claim_id token. The firing driver renews claimed_at
  every heartbeat_seconds (60) from a background thread, and mark_fired /
  mark_failed succeed only for the token's holder.
- A lease is recovered only after stale_firing_seconds (600) with no renewal
  and two more heartbeat intervals of this driver's passes with the lease
  unchanged, so a live holder's first heartbeat after waking clears it.
- If the holder was alive after all, its outcome replaces the recovery's
  guess; a late failure never overrides a re-run that already claimed it.
- list_scheduled_jobs returns the jobs that failed in the last 7 days with
  their error, so an unattended send that failed reaches the user.
- init_schema starts a legacy row's window at upgrade instead of counting it
  stale on sight, and tolerates another connection adding the columns first.
- The email package carries its own copy of the lease timing, since it
  supports cores older than the module.
A snooze moved onto the daemon clock became a plain one-shot job, so the
daemon's stale-lease recovery marked a stuck one failed instead of bringing
the message back to the inbox. A one-shot whose payload sets
"rerunnable": true is now re-queued like a recurring job, and the email
migration sets it for snoozes only; a scheduled send still fails and is
never sent twice.
…dable recovery errors

Round-2 review follow-ups.

- The recovery's claim guard had no test: a holder's heartbeat landing
  between the stale scan and the recovery write must make the recovery
  lose. Both stores now test it, along with the email holder overwriting a
  recovery's guessed failure with the real send.
- EmailJobScheduler takes one injectable clock for claims, heartbeats and
  recovery, so the wake-up test moves a single clock the way a sleep does
  instead of mixing a fake reader with a real heartbeat.
- The recovery error named the last heartbeat as a raw epoch. It now reads
  "at 14:05 on 2026-10-18 (3 hours ago)" in local time, and tells the user to
  check the Sent folder before scheduling the mail again, since a late
  success can still turn the job to fired.
- The schedule_store docstring points at gaia_agent_email.lease, and the
  npm CHANGELOG no longer promises a send is never marked failed.
@kovtcharov-amd
kovtcharov-amd added this pull request to the merge queue Oct 19, 2026
Merged via the queue into amd:main with commit 884f531 Oct 19, 2026
57 of 58 checks passed
@kovtcharov-amd
kovtcharov-amd deleted the claude/rel-j-stale-firing branch October 19, 2026 14:35
github-merge-queue Bot pushed a commit that referenced this pull request Oct 21, 2026
…imit (#5456)

Three fixes on main could be reverted with every test still passing.
That covers a scheduled email marked failed while it is still sending
(#5380), the Slack/Telegram notice after an agent restart telling users
to "continue" a conversation the agent forgot (#5382), and nothing
proving a hung tool under the messaging bridge ever ends. Each new test
fails on the user-visible symptom when its fix is undone.

- **Scheduler lease, both stores.** Two claims with the same timestamp
are told apart only by `claim_id`. Without that half of the recovery
guard, a stale read fails a live send or re-queues a running job.
- **Restart notice.** The existing check only caught a quoted
`"continue"`. An unquoted "Send continue" that also dropped "no longer
remembers this conversation" passed everything.
- **Hung tool under the bridge.** A running tool keeps the bridge's idle
clock fresh, so only the agent's own tool limit
(`GAIA_AGENT_TOOL_TIMEOUT`, 180 s) ends it. This drives the real
`gaia-agent` turn loop behind a real `AgentChannel` and checks the user
still gets an answer. It needs the flagship wheel, so it runs in the
gaia-agent lane.

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

Reverts run locally, each against the new test:

| Revert | Result |
|---|---|
| Drop `claim_id = :claim` from `recover_claim` (daemon + email store) |
4 fail: status `failed`/`pending` != `firing` |
| Restart notice → `restarted. Send continue to pick up where it left
off.` | new test fails; all existing messaging tests pass |
| Restart notice → `... Send "continue" to pick up where it left off.` |
new test fails (existing test also catches this one) |
| `_call_tool_bounded` timeout → `inf` | fails: "the hung tool was never
ended", user stuck at the `tool_call` |
| Bridge idle refresh ignores `tool_running` | fails: `error` != `final`
|

The email schedule tests skip from the repo root unless
`gaia_agent_email` is installed, because the root conftest only
redirects hub packages that are already installed. CI does run them:
`test_email_agent_unit.yml` installs the wheel and gates wholesale
skips. Main push run 39538913521 shows all 13 stale-firing tests and 16
`test_email_schedule.py` tests PASSED.
</details>

## Test plan

- [x] `python -m pytest tests/unit/test_daemon_scheduler_stale_firing.py
tests/unit/messaging/ -q`: passes locally and in Unit Tests run
39541345649. That run executed the new daemon and restart tests and
skipped `test_bridge_hung_tool.py` as allowlisted.
- [x] `python -m pytest
hub/agents/email/python/tests/test_email_schedule_stale_firing.py -q`
with `gaia_agent_email` installed: passes locally, and both new cases
(`scheduled_send`, `snooze`) passed in Email Agent Unit Tests run
39541345667.
- [x] `python util/check_test_lane_coverage.py` passes (run locally).
- [x] CI: Gaia Agent Tests run 39541345605 executed
`test_bridge_hung_tool.py` and it passed (not skipped).

---------

Co-authored-by: Kalin Ovtcharov <[email protected]>
kovtcharov pushed a commit to kovtcharov/gaia that referenced this pull request Oct 30, 2026
…er (amd#5404)

The proactive Claude reviews were failing about half the time, and each
failure was lost. The code and security audits failed 5 of the last 10
nights, and the doc walkthrough failed 4 of its last 5 runs. Running
three audits every night used up both Claude accounts' weekly limit by
mid-week, so most of those runs stopped before reviewing anything and
blamed a missing file. The next run never went back for the missed work.
Now one audit runs each night between 2 and 4am Pacific, so each audit
runs every third night. Each run checks Claude is available before
starting, and says plainly when it isn't. It picks up everything since
its last successful run, starts from what merged since then, and checks
against the bug types past audits missed. The dedup pass no longer
re-files duplicates that were already closed: 34 of them were closed
alongside this change.

## Test plan

- [ ] `python -m pytest tests/unit/test_audit_synthesis_prep.py
tests/unit/test_audit_history.py tests/unit/test_audit_rotation.py
tests/unit/test_require_claude.py tests/unit/test_recent_changes.py
tests/unit/test_miss_analysis.py
tests/unit/test_claude_audit_workflow_contract.py
tests/unit/test_closed_duplicates.py -q` passes (277 tests)
- [ ] After merge: `gh workflow run claude-audit-rotation.yml -R
amd/gaia -f dry_run=true`. The summary names tonight's audit and the
next five nights, and nothing is dispatched.
- [ ] After merge: `gh workflow run claude-nightly-audit.yml -R amd/gaia
-f dry_run=true`. Check the preflight summary: the mode, a window
reading "since this audit's last successful run", the Claude probe
passing, and "Recent changes read first". At the end, "Dry run
confirmed: no issue created".
- [ ] After merge: `gh workflow run claude-weekly-doc-walkthrough.yml -R
amd/gaia -f doc_filter=docs/quickstart.mdx -f dry_run=true`. The guide
is walked, "Using bash.exe from …" appears, and the dry-run watermark
step passes (it crashed before this change).
- [ ] After merge: `gh workflow run claude-security-audit.yml -R
amd/gaia`. Semgrep scans `tui`, `installer` and `.github/workflows`, and
the SARIF uploads.
- [ ] First scheduled night (10:13 UTC): the dispatched run is titled "…
rotation night N", files at most what's new, and an issue it files
carries `audit-cluster` / `audit-key` markers.

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

**Root causes (last ~2 weeks)**
- Code and security audits, Oct 7/10/12/13/14/17: every lens returned
`is_error` in under a second with "You've hit your weekly limit". The
primary account ran out on Oct 10, the secondary on Oct 12–14, both on
Oct 17. The account switch fired correctly; both accounts were spent.
- Walkthrough Oct 12: same weekly limit on every guide, queued over 57
hours on the Strix Point pool. Oct 5 and Oct 19: the `xsj-aimlab-stxp`
images have no Git for Windows (only WSL's `bash.exe`). Also on Oct 5,
the executor step's `GITHUB_OUTPUT` got UTF-16 appended by
`start-lemonade.ps1` under PowerShell 5.1 `>>`. Sep 21–28: Application
Control blocked `LemonadeServer.exe` and the job landed on Strix Halo
machines; both were fixed by the move to the `xsj-dispatch` pool on Oct
1.
- The walkthrough's two dry-run steps had a literal `\n` mid-command, so
`dry_run=true` always failed.

**Schedule.** One cron, `13 10 * * *` = 03:13 PDT / 02:13 PST. Only
10:00–11:00 UTC is inside 2–4am Pacific in both seasons. Slot = days
since epoch mod 3 → code audit, security audit, doc walkthrough. The
audits lost their own crons; `workflow_dispatch` still runs any of them
on demand. Deep code sweep: whenever the last successful one is over 8
days old (every third turn, retried on the next turn if it fails).

**Dedup bug.** The 2026-09-07 burst (78 issues) predates the dedup pass:
the run checked out main 7 hours before amd#3310 merged. Three duplicate
pairs still got through after amd#3310 (amd#3832/amd#3471, amd#3825/amd#3414,
amd#5199/amd#4875). Backlog matching compared findings against issue titles
only, so a same-section duplicate worded differently scored 0.05–0.15,
below the 0.18 threshold. Now matching includes each audit issue's own
markers (all 13 known pairs rank 1st–2nd). Closed duplicates hand their
keys to the open canonical, so consolidating into amd#1077/amd#4331 does not
trigger re-filing. Both syntheses share the `claude-audit-issue-filing`
concurrency group. The security audit files to private code scanning,
not issues, so it cannot duplicate the other two.

**Closed as duplicates (34):** into amd#4331: amd#3204 amd#3413 amd#3422 amd#3439 amd#3466
amd#3476. Into amd#1077: amd#3173 amd#3412 amd#3418 amd#3426 amd#3429 amd#3430 amd#3433 amd#3437 amd#3442
amd#3449 amd#3454 amd#3455 amd#3464 amd#3468 amd#3475 amd#3477 amd#3482. Into amd#3198: amd#3436
amd#3462. Others: amd#3425→amd#3169, amd#3457→amd#3195, amd#3440→amd#3180, amd#3486→amd#3064,
amd#3471→amd#3832, amd#3414→amd#3825, amd#3434 amd#3485→amd#3219, amd#5199→amd#4875.

**Miss-analysis (merged `fix` PRs, Jun 21–Oct 19).** 29 of 1005 (3%)
closed an issue an audit filed first. Missed, by title: no deadline 90
(amd#5346 amd#5384 amd#5380), release/CI ordering 71 (amd#5127 amd#5147), Windows
behaviour 38 (amd#5018 amd#5377), dishonest status 36 (amd#5112 amd#5317), shared
state across processes 34 (amd#5337 amd#5282 amd#5378), model output handling 27
(amd#4973 amd#5103), doc drift 27, cold start / non-default setup 26 (amd#4951
amd#5130). About 380 more were Agent UI/TUI or agent-behaviour fixes, which
a static read rarely catches. Noise: of the audit issues closed as
duplicate or not planned, 31 were duplicates of amd#1077, 12 of the
test-coverage umbrella amd#2988, and 6 each of amd#4331, amd#3149, amd#3308 and
amd#2922. What changed: `scripts/audit/missed_bug_classes.md` has a
checklist per class and a "Don't report" list, and all three prompts
read it at run time. The code audit gets a deterministic list of calls
with no deadline. The security audit's semgrep run and worklist now
cover TypeScript, Go, the installer and the workflows.
`scripts/audit/miss_analysis.py` refreshes the evidence monthly.

**Recent changes.** Each audit's first job writes `recent-changes.md`:
first-parent commits since the commit its last successful run checked
out, read from the run history, with PR title, a short body excerpt and
the paths each touched, capped at 30 KB. If that commit is unknown it
covers 3 days and says so.
</details>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agent::email Email agent changes daemon Daemon supervisor / sidecar control plane tests Test changes

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants