Skip to content

fix(schedule): allow one schedule daemon per store and lock store writes - #4272

Merged
kovtcharov-amd merged 6 commits into
amd:mainfrom
kovtcharov:claude/schedule-single-daemon
Sep 26, 2026
Merged

kovtcharov-amd merged 6 commits into
amd:mainfrom
kovtcharov:claude/schedule-single-daemon

Conversation

@kovtcharov

Copy link
Copy Markdown
Contributor

Stacked on #4271. Merge that first.

With two gaia schedule daemon processes running (for example a login item plus a manual start), every schedule ran twice: two LLM runs and two Telegram messages. Separately, a gaia schedule add that raced the daemon's run bookkeeping could silently drop the new schedule. Now the daemon holds ~/.gaia/schedules.lock (next to whichever store it uses) for its whole lifetime, so a second daemon exits at once with an error that names the running pid. Each store read-modify-write also takes a short lock, so concurrent changes are all kept. The flock/msvcrt calls in gaia.daemon.lock became shared try_lock/unlock helpers rather than a second copy.

Test plan

  • ~/.cache/gaia-dev/venv/bin/python -m pytest tests/unit/test_schedule_lock.py -q: without the wiring, the second-daemon and concurrent add + mark_run tests fail (2 failed, and the race test loses schedule b). With the fix, 6 pass.
  • gaia schedule daemon twice against one HOME: the second exits 1 with another gaia schedule daemon (pid N) is already running … Stop the other daemon first, and the first keeps running
  • ~/.cache/gaia-dev/venv/bin/python -m pytest tests/unit/test_schedule_lock.py tests/unit/test_schedule_daemon.py tests/unit/test_schedule_store.py tests/unit/test_schedule_sinks.py tests/unit/cli/test_cli_schedule.py tests/unit/test_scheduler.py tests/unit/test_daemon_client.py tests/unit/test_daemon_scheduler.py tests/unit/test_daemon_cli_dev_anchor.py -q: all pass
  • black, isort, and pylint (errors-only, CI flags) are clean on the changed files
  • Windows: a second daemon is refused (the pid is omitted there, because Windows blocks reads of the locked byte)

Fixes #4208

Kalin Ovtcharov added 3 commits September 24, 2026 17:34
A schedule due while the laptop slept or the daemon was busy for more than one second was dropped, because the daemon inherited APScheduler's 1-second misfire grace. Late runs now fire if they are within an hour of the due time, several missed runs collapse into one, and every skipped run (too late, or overlapping the previous run) is logged with its schedule name.

Fixes amd#4207
Two `gaia schedule daemon` processes on one machine fired every schedule twice, and a `gaia schedule add` racing the daemon's run bookkeeping could drop the added schedule. The daemon now holds `schedules.lock` for its lifetime, so a second one exits at once with an error naming the running pid, and each store read-modify-write takes a short lock so concurrent changes are all kept.

The flock/msvcrt calls in `gaia.daemon.lock` are lifted into `try_lock`/`unlock` so both daemons share one implementation.

Fixes amd#4208
@github-actions github-actions Bot added documentation Documentation changes cli CLI changes tests Test changes daemon Daemon supervisor / sidecar control plane labels Sep 25, 2026
@github-actions

Copy link
Copy Markdown
Contributor

Verdict: Approve with suggestions

This stops two gaia schedule daemon processes from double-firing every schedule, and makes concurrent edits to the schedule file safe so a gaia schedule add can no longer be silently swallowed by the daemon's own bookkeeping write. The design is the right one — OS advisory locks, so a crashed daemon can't strand a stale lock — and the failure message names the running pid and tells the user what to do. Nothing here blocks merge on Linux/macOS.

The one thing worth a maintainer's attention before merge: the Windows behaviour is unverified. Windows file locking works differently enough from Linux that the new lock has a separate code path there, and the repo's unit tests only run on Linux — so the platform most GAIA users are on is the one nobody has run this against. The author's own test plan leaves that box unchecked. Given the bug being fixed (a schedule firing twice) is most likely to hit someone with a login-item daemon on Windows, it's worth ten minutes on a real machine rather than trusting the reasoning.

Smaller things, all optional: a lock-file naming edge case that would make the daemon lock and the store lock collide for an unusual store location, a stray-bytes case in reading the holder's pid that would replace the friendly error with a crash, and the fact that only the daemon subcommand turns a lock failure into a clean message — add/remove/pause/resume would show a raw traceback instead.

Real-world evidence

No evidence-bundle.md was produced for this PR, so no automated stage exercised it here. The PR description does carry hand-run CLI evidence for the surface that changed — two gaia schedule daemon starts against one HOME, with the second exiting 1 and naming the running pid while the first keeps going — which is the right evidence for a CLI-only change and matches what the code does. Unit-test evidence is also named per-file, including the fail-without-the-fix check.

The gap is platform, not surface: that run was on Linux/macOS, the Windows box in the test plan is unchecked, and test_unit.yml runs tests/unit/ on ubuntu-latest only — so the Windows lock branch has neither manual nor CI coverage. My verdict rests on static review for that platform.

🔍 Technical details

🟡 Important

Windows lock path is unexercised by CI and unverified by hand (src/gaia/schedule/lock.py, via src/gaia/daemon/lock.py:31-54)

test_unit.yml:67 pins pytest tests/unit/ to ubuntu-latest, so tests/unit/test_schedule_lock.py never runs the msvcrt branch, and the PR's Windows checkbox is open. Three behaviours differ there and all three are load-bearing:

  • msvcrt.locking locks one byte at the current offset, not the whole file. daemon_lock handles this (lock.py:75-76 writes the pid, _release at lock.py:52 seeks back to 0 before unlocking) — correct as written, but it's exactly the kind of thing worth confirming rather than reasoning about.
  • os.ftruncate(fd, 0) at lock.py:75 runs while byte 0 is locked through the same handle. Permitted for the lock owner as far as I can tell, but untested.
  • _read_pid's OSError catch (lock.py:86) assumes Windows refuses the read. If it instead succeeds, fine; if it raises something else, the contender crashes instead of printing the actionable error.

Suggest running the existing tests/unit/test_schedule_lock.py once on Windows, or adding it to whatever Windows lane is cheapest (test_gaia_cli_windows.yml already has a Windows runner). The reasoning in the code is sound — it just hasn't been executed.

🟢 Minor

1. daemon_lock_path and store_lock_path collide for a suffix-less store path (src/gaia/schedule/lock.py:35-41)

with_suffix(".lock") on schedules.toml gives schedules.lock, distinct from schedules.toml.lock — correct for the default store. But for a store path with no suffix (Path("schedules")), both helpers return schedules.lock. The daemon would then hold the store lock for its whole lifetime, and every write — including its own mark_run — would block for STORE_LOCK_TIMEOUT_SECONDS and then raise. Not reachable today (run_daemon's store_path is only ever DEFAULT_STORE_PATH), but it's a quiet trap for the next caller who parameterizes it.

def daemon_lock_path(store_path: Path) -> Path:
    store_path = Path(store_path)
    return store_path.with_name(store_path.stem + ".lock")

That keeps ~/.gaia/schedules.lock (matching docs/reference/cli.mdx) while never colliding with the <name>.lock store lock. A one-line test asserting daemon_lock_path(p) != store_lock_path(p) would pin it.

2. _read_pid can raise UnicodeDecodeError past the OSError guard (src/gaia/schedule/lock.py:83-88)

If the lock file ever holds non-UTF-8 bytes — a pre-existing file at that path, a partial write — .decode() raises and the contender gets a traceback instead of "another daemon is already running". The isdigit() check downstream already handles garbage; just don't let the decode throw:

    try:
        os.lseek(fd, 0, os.SEEK_SET)
        pid = os.read(fd, 32).decode(errors="replace").strip()
    except OSError:
        # Windows refuses reads of the holder's locked byte; name no pid then.
        return ""

3. Only daemon converts ScheduleLockError into a clean message (src/gaia/cli.py:3437-3443)

store.add/remove/set_enabled can now raise ScheduleLockError on a 10s timeout, but _handle_schedule only catches it for the daemon action — add at cli.py:3387 and remove at cli.py:3417 would print a traceback. The same is already true of the ValueError/KeyError those calls raise, so this is a pre-existing shape rather than a regression; wrapping the whole dispatch once would fix all of them together.

4. gaia.schedule.store now imports the custody-daemon package (src/gaia/schedule/lock.py:25)

from gaia.daemon.lock import try_lock, unlock pulls gaia/daemon/__init__.py (and paths, errors, instance) into the import graph of every gaia schedule command. Deduping the flock/msvcrt calls instead of copying them is the right call — but these are generic OS primitives with no daemon semantics, and a shared home (e.g. gaia/utils/filelock.py, imported by both) would avoid making the scheduler depend on the custody daemon. Cheap to do now, awkward later.

Strengths

  • The tests prove the bug, not just the code. test_concurrent_add_and_mark_run_keep_both_changes drives a real two-thread interleaving by stalling load() inside the read-modify-write window, and the PR notes it loses schedule b without the fix. test_second_daemon_fails_fast_without_arming asserts build_scheduler is never called, which is the property that actually matters — no timers armed before the refusal.
  • Error messages follow the fail-loudly contract properly. Both ScheduleLockError messages name what failed, the consequence ("running two would fire every schedule twice"), and the next step — and the daemon-lock path deliberately doesn't wait, which is correct for a single-instance guard.
  • Docs were updated with the behaviour, not just the flag. docs/reference/cli.mdx explains the misfire window, the coalescing, the skip-and-log, and that the OS releases the lock after a crash — all of which match the code.
  • Refactoring StartLock's platform branches into try_lock/unlock rather than copying them into the schedule package was the right instinct (see minor Documentation update from v0.7.2 tag. #4 for where to land them).

Note on scope

This diff includes the misfire/grace-time work from the stacked PR (MISFIRE_GRACE_SECONDS, JOB_DEFAULTS, _log_skipped_run and their tests), since the branch sits on top of it. I reviewed it as context rather than as this PR's content; it reads correctly — the JobExecutionEvent vs JobSubmissionEvent split in _log_skipped_run matches how APScheduler dispatches EVENT_JOB_MISSED and EVENT_JOB_MAX_INSTANCES respectively.

The single-daemon guard takes msvcrt.locking on Windows and fcntl.flock
everywhere else, but tests/unit/ runs on ubuntu-latest only — so the
branch that matters to the users most likely to hit the bug (a login-item
daemon plus a manual one, firing every schedule twice) had never been
executed. Running the existing suite on Windows fails: msvcrt refuses
another handle's read of the locked byte, so no pid is available and
test_error_names_the_running_daemon_pid cannot pass there.

The pid assertion is now POSIX-only, with a Windows counterpart asserting
the documented degradation — no pid claimed, message still actionable.
TestWindowsLockingPrimitive pins the three msvcrt differences the code
depends on: the owner may truncate and write the byte it locked, unlocking
needs the seek back to 0 that _release does (otherwise only the close
releases it, because unlock() swallows the error), and a second handle's
read raises. test_gaia_cli_windows.yml runs the file so this stays true.

Two real bugs the new coverage caught:

- daemon_lock_path and store_lock_path both returned `<name>.lock` for a
  suffix-less store, so the daemon would have held the STORE lock for its
  whole life and every write, including its own mark_run, would have
  timed out. with_suffix alone does not fix it — `schedules` has no
  suffix to replace — so the collision is detected and sidestepped.
- _read_pid decoded strictly inside an OSError-only guard, so a lock file
  holding non-UTF-8 bytes replaced the actionable refusal with a
  UnicodeDecodeError traceback on POSIX.
# Conflicts:
#	docs/reference/cli.mdx
#	tests/unit/test_schedule_daemon.py
@github-actions github-actions Bot added the devops DevOps/infrastructure changes label Sep 25, 2026
@kovtcharov-amd

Copy link
Copy Markdown
Collaborator

Ran the suite on a real Windows box, which is what the open checkbox was for — and it does not pass there. The Windows path also had two bugs that only running it would surface.

msvcrt refuses another handle's read of the locked byte, so no pid is available and test_error_names_the_running_daemon_pid fails on Windows. That assertion is now POSIX-only, with a Windows counterpart asserting the degradation the PR description predicted: no pid claimed, message still actionable. A new TestWindowsLockingPrimitive pins the three msvcrt differences the code leans on, and the Windows CI lane now runs the file so it stays pinned rather than reasoned about.

Two real bugs it caught:

  • The daemon lock and the store lock resolved to the same path for a store filename with no extension. The daemon would then have held the store lock for its whole life, and every write — including its own mark_run — would have hung for ten seconds and then failed.
  • A lock file holding non-UTF-8 bytes replaced the actionable "another daemon is already running" with a decode traceback.
🔍 Technical details

Windows behaviour, measured on this host rather than inferred — all three of the review's load-bearing assumptions hold:

Behaviour Result
os.ftruncate(fd, 0) under the owner's own byte-0 lock permitted
msvcrt.locking(LK_UNLCK, 1) at the post-pid-write offset (4) PermissionError 13
…after lseek(fd, 0) succeeds — the seek in _release is load-bearing
Second handle reading the locked byte PermissionError 13 → _read_pid returns ""

The seek matters more than it looks: unlock() swallows OSError, so without it the only thing releasing the lock is the os.close that follows.

Fix 1 — lock-path collision (src/gaia/schedule/lock.py). The suggested with_suffix → stem swap does not fix it: Path("schedules").stem is "schedules", so both helpers still return schedules.lock. The collision is now detected and sidestepped with a .daemon.lock name; ~/.gaia/schedules.lock is unchanged for the default store, so cli.mdx stays accurate. test_the_two_locks_never_share_a_path covers schedules.toml, schedules, sched.d and schedules.lock, and test_the_daemon_can_still_write_the_store_while_holding_its_own_lock drives the failure mode end to end.

Fix 2 — _read_pid decode. decode(errors="replace") inside the guard; isdigit() downstream already rejects the garbage. Two tests: a garbled lock file still yields the refusal, and _read_pid on non-UTF-8 bytes returns "".

CI. test_gaia_cli_windows.yml gains a Run Windows Schedule-Lock Tests step beside the DACL one, with -rs so a misfiring platform guard shows as a visible SKIP rather than silent absence.

test_schedule_lock.py test_schedule_daemon.py test_schedule_store.py
test_schedule_sinks.py cli/test_cli_schedule.py test_scheduler.py
test_daemon_client.py test_daemon_scheduler.py
→ 192 passed, 1 skipped   (the skip is the POSIX-only pid test, on Windows)
black + isort clean

tests/unit/test_daemon_cli_dev_anchor.py has 3 path-separator failures on this Windows host; identical set with origin/main's own copies of the test and src/gaia/daemon, so environmental.

Merged origin/main to clear the conflict. Two: cli.mdx, where main refined the misfire wording — kept main's sentence and this PR's single-daemon paragraph, plus a line on the Windows pid omission; and test_schedule_daemon.py, where main's daemon.MISFIRE_GRACE_SECONDS replaces the literal 3600. AST-parsed both, no stray markers.

Not changed: only the daemon action turns ScheduleLockError into a clean message — add/remove would still traceback, as they already do for the ValueError/KeyError beside it. Left as the pre-existing shape rather than widened here.

@kovtcharov-amd

Copy link
Copy Markdown
Collaborator

CI note: the one red unit-test job is not from this branch. test_lemonade_server_process_lifecycle.py::test_launch_server_leaves_a_non_gaia_listener_running fails identically on main itself (run for 3e82b2b4a, all three OS lanes), and this branch inherited it by merging main. Nothing to fix here — it needs fixing on main.

kovtcharov-amd added a commit to kovtcharov/gaia that referenced this pull request Sep 26, 2026
@kovtcharov-amd
kovtcharov-amd added this pull request to the merge queue Sep 26, 2026
Merged via the queue into amd:main with commit 2551f99 Sep 26, 2026
56 of 58 checks passed
@kovtcharov-amd
kovtcharov-amd deleted the claude/schedule-single-daemon branch September 26, 2026 03:44
kovtcharov-amd added a commit to kovtcharov/gaia that referenced this pull request Sep 26, 2026
…md#4273)

Stacked on amd#4272 (itself stacked on amd#4271). Merge those first.

`gaia schedule add` used to accept sinks that could never deliver: a
misspelled sink name, `telegram` without `--to`, a bare `file` with no
path, or `notification` on Windows. Each of those schedules then failed
on every run, only after spending a full LLM call. Now `add` rejects
them with an actionable message and stores nothing. Each run also checks
its sink before calling the agent, so schedules stored before this
change fail fast too. The Telegram token is still checked only at
delivery, because the daemon reads it from its own environment, not the
shell that ran `add`.

## Test plan
- [x] `~/.cache/gaia-dev/venv/bin/python -m pytest
tests/unit/test_schedule_sinks.py tests/unit/cli/test_cli_schedule.py
tests/unit/test_schedule_daemon.py -q`: 18 failed before the fix, 86
pass after
- [x] `gaia schedule add --name t --cron "0 7 * * *" --prompt hi --sink
telegram` exits 1 with `telegram sink needs a recipient: pass --to`.
`--sink telegarm` and `--sink file` are rejected the same way, `--sink
telegram --to 123` is added, and `gaia schedule list` shows only that
schedule.
- [x] `~/.cache/gaia-dev/venv/bin/python -m pytest tests/unit/cli/ -q`:
all pass except the 4 `test_gaia_binary_on_path` cases, which fail
locally because the dev venv's binaries aren't on PATH (unrelated)
- [x] black, isort, and pylint (errors-only, CI flags) are clean on the
changed files

Fixes amd#4228

---------

Co-authored-by: Kalin Ovtcharov <[email protected]>
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

cli CLI changes daemon Daemon supervisor / sidecar control plane devops DevOps/infrastructure changes documentation Documentation changes tests Test changes

Projects

None yet

Development

Successfully merging this pull request may close these issues.

fix(schedule): two schedule daemons fire every job twice

2 participants