Skip to content

fix(file-lock): fair cross-process queue, ACL-aware unwritable dirs - #5469

Merged
kovtcharov-amd merged 11 commits into
amd:mainfrom
kovtcharov:kalin/file-lock-reliability
Oct 21, 2026
Merged

kovtcharov-amd merged 11 commits into
amd:mainfrom
kovtcharov:kalin/file-lock-reliability

Conversation

@kovtcharov

@kovtcharov kovtcharov commented Oct 21, 2026 •

Copy link
Copy Markdown
Contributor

The cross-process file lock from #5388 broke for several real users. On Windows, a config in a folder the user may not create files in, by ACL, would not load. Waiters for a busy lock took it in random order, so an earlier one could time out with "close any stuck gaia command" while later ones got through. Now waiters are served first come, first served, at about main's cost when nobody waits, and a timeout says how many GAIA operations were ahead. An ACL-denied or read-only folder is detected correctly, and every lock failure names its real cause.

  • Fair queue. Waiters line up in arrival order, across processes, and the one at the front takes the lock within about a millisecond of its release. A crashed waiter or holder doesn't block the line. With nobody waiting the lock costs about what it did on main, however many files share its folder.
  • Unwritable folders. GAIA now tests whether it can write a folder by trying to create a file there. Windows ACLs and read-only mounts count. A folder that refuses new files but already has the lock file still locks, and a save into such a folder names it.
  • Document indexing. A busy cache, a cache folder this user can't write, and a broken lock file are now three separate errors. Each one gives the agent the cache path and the right next step, instead of "check the file".
  • Agent install and uninstall, in the Agent UI and the daemon, take the install slot before stopping the email agent. A second install is refused up front, naming the other GAIA process, instead of having the agent stopped for nothing. The slot is released however the request ends.
  • Skill install undo. A new test checks that undoing a skill install moves the new copy aside whole. Swapping that for a delete now fails the suite.

Reproduced by test_config_loads_from_an_acl_denied_directory and test_processes_get_the_lock_in_the_order_they_asked; fails on main, passes here. The other fixes are reproduced by test_an_unwritable_cache_folder_is_reported_as_such, test_the_slot_is_held_from_before_the_sidecar_stops and test_undo_moves_the_new_copy_aside_whole_while_a_file_in_it_is_open. Each also fails on main or against its reverted fix.

Watch rag_quality in the next RC eval: the agent sees new index-failure hints.

Test plan

  • python -m pytest tests/unit/test_file_lock.py tests/unit/test_concurrent_state_writes.py tests/unit/rag/test_cache_lock_errors.py tests/test_rag.py tests/unit/test_hub_router.py tests/unit/test_hub_installer.py tests/unit/test_daemon_hub_routes.py tests/unit/test_skills_install_concurrency.py on Windows. Everything passes except two test_hub_installer.py pip tests, which also fail on main here because this venv has no pip.
  • On Windows, the ACL tests (test_an_acl_denied_folder_is_reported_unwritable, test_config_loads_from_an_acl_denied_directory) pass. They fail on main.
  • test_processes_get_the_lock_in_the_order_they_asked starts five real gaia processes and passes, 5 of 5 runs. On main they got the lock as ['3', '1', '2', '0'].
  • Speed bounds: uncontended acquire in a 5,000-file folder, hand-off to the next waiter, and a 4-thread busy lock. Each fails when its fix is reverted. The busy-lock bound was flaky on macOS CI (24.3 ms against 8 ms) and under load. test(file-lock): time the lock hand-off against a flat poll, not a fixed bound #5488 replaces it with a timing against a flat 20 ms poll in the same run.
  • python util/lint.py --all
  • Linux CI lane: the POSIX-only tests (test_a_read_only_posix_folder_is_reported_unwritable, the umask test, the delete-while-locked ordering in test_probing_a_new_entry_never_strands_its_owner and test_leaving_never_deletes_a_newer_entry_with_the_same_name) pass in Unit Tests (Linux, py3.12) at the merged head e69e258, as do the Windows and macOS lanes.
🔍 Technical details
  • Queue design. A waiter creates q<number>-<uuid> in <name>.lock.d/ and holds an OS lock on it. It takes <name>.lock once no live entry is ordered before it. Entry names are never reused, so a delete can only remove the file created at that path. With an empty queue the lock is taken without an entry. A waiter that takes the lock writes a spent mark into its entry and unlocks it, so the waiter behind sees itself next. The holder then deletes the entry after its turn.
  • Measured on Windows.
    • Uncontended acquire in a 5,000-file folder: 0.3 ms (main 0.23 ms; the previous head 32 ms).
    • Hand-off to the next waiter: median 0.8 ms.
    • 4 processes × 3 threads × 400 cycles: about 12 s, against 60 s at the previous head and 2.6 s on main. Main is faster only because its releaser re-takes the lock ahead of everyone waiting.
  • Dead entries.
    • A dead entry is re-checked and deleted only after the waiter's own turn, because a Windows delete costs as much as a hand-off.
    • An unmarked dead entry (a crashed waiter, or one created but not yet locked) is re-checked every poll, so a waiter never skips a newer arrival's entry ahead of it.
    • On POSIX a dead entry is deleted while its lock is held.
  • Other users and case.
    • On POSIX the folder is made 0755 and each entry 0644 explicitly, past the umask, so another user's entry can still be tested. Entries that can't be tested (NFS emulates flock) are counted and named in the timeout.
    • Case needs no special handling: the queue folder's name resolves the way the lock file's does.
  • Mixed versions. The main lock is unchanged, so an older GAIA still excludes. It just isn't ordered.
  • Unwritable detection. lock_dir_unwritable reads FileLockError.dir_unwritable. That is set from the real EROFS/PermissionError plus one O_EXCL create probe. tempfile.mkstemp is gone from this module, because on Windows it retries a refused create 10,000 times whenever os.access calls the folder writable.
  • Install slot hand-off.
    • claim_install_slot() returns an InstallSlot backed by a thread-independent HeldFileLock, and install() and uninstall() accept slot=.
    • The UI endpoint runs its worker on a plain thread rather than BackgroundTasks, because Starlette skips those when sending the response fails.
    • install_in_progress() had no callers and is removed.
    • Dot-named folders in the agents root (.backup, the lock queues) are skipped by list_installed and registry discovery.
  • Full unit suite on Windows. Every failure also fails on the base commit here: the venv has no pip, and some tests depend on the profile under a redirected home. A few others failed only under -n 6 load, and they pass when run serially.

The cross-process file lock from amd#5388 failed several real users. A config
in a folder Windows denies by ACL would not load, because os.access ignores
ACLs. Waiters polled with no order, so a later one could take the lock while
an earlier one timed out with a misleading "close any stuck gaia command".

- Waiters now queue in arrival order through <name>.lock.q<number> entry
  files held under an OS lock; a crashed waiter's entry is detected and
  removed. A timeout says how many GAIA operations were ahead.
- An unwritable folder is detected from the real create error plus one
  real create probe, so Windows ACLs and read-only mounts are recognised.
  A folder that refuses new files but has the lock file still locks.
- The RAG SDK tells a busy cache, an unwritable cache folder and a bad lock
  file apart, and the agent tool gives a hint and the cache path for each.
- Install and uninstall, in the Agent UI and the daemon, claim the install
  slot before stopping the email sidecar, hand it to the worker, and
  release it on every path, so a concurrent install is refused instead of
  having the agent stopped under it.
- A test pins that undoing a skill install renames the new copy aside
  intact rather than half-deleting it when a file in it is held open.
@github-actions github-actions Bot added rag RAG system changes tests Test changes performance Performance-critical changes agents daemon Daemon supervisor / sidecar control plane sidecar Agent sidecar contract / harness labels Oct 21, 2026
@github-actions

Copy link
Copy Markdown
Contributor

Verdict: Approve with suggestions

This fixes three real problems with the file lock added in #5388. Processes waiting for a busy lock now get it first come, first served instead of in random order. A Windows folder the user can't create files in is now recognised as unwritable. The Agent UI and the daemon now claim the install slot before they stop the email agent, so a second install is refused without stopping the agent for nothing. The queue design holds up: a crashed waiter can't block the line, a waiter whose queue entry is deleted before it locks it rejoins the queue, and the main lock is unchanged, so older GAIA versions are still kept out. I found nothing blocking.

  • One small fairness gap. A waiter that is leaving releases its queue entry before deleting it. In a narrow window, a new waiter can create an entry with the same name, and the leaving waiter then deletes it. Only queue order suffers: two processes still can't hold the lock at once. On Linux/macOS, deleting before releasing closes the window.
  • No real-world evidence. The install/uninstall endpoints now behave differently, but the description has only pytest runs. One POST /api/agents/install sent twice, with the 409 response and the email agent still running, would show the user-facing change.

Real-world evidence

N/A: no evidence bundle was produced for this run, and I couldn't run the test suite here (no pytest in this runner). The verdict rests on reading the code. The install/uninstall HTTP routes, the ordering test with four real processes and the Windows ACL tests were not run in this review.

🔍 Technical details

🟡 Missing surface evidence (once, per rubric). src/gaia/ui/routers/hub.py and src/gaia/daemon/sidecars/{install,routes}.py change HTTP behaviour: the slot is claimed before the sidecar stops, a new 500 is returned for InstallFailedError and FileLockError, and the install endpoint is now a sync def that starts its own worker thread. A real request/response pair (a duplicate install → 409, a completed install → 202 followed by a terminal install-status) would cover it. The rag_quality watch for the new index hints is already named for the next RC.

🟢 Leave/discard can unlink a newer entry with the same name (src/gaia/utils/file_lock.py:270). leave() unlocks and closes the entry, then unlinks it by path. Suppose a waiter that is checking for dead entries deletes q3 in that window, and a new waiter with q2 as the highest live entry creates a fresh q3. The owner's _discard_entry then removes the new waiter's file. That waiter keeps its lock on a deleted inode, so later waiters don't count it and can go ahead of it. _entry_alive (lines 250–251) has the same release-then-unlink pattern. Exclusion is unaffected and the race is rare. On POSIX you can unlink an open file, so delete while still holding the lock; a waiter checking for dead entries then sees FileNotFoundError, which counts as dead, and that is correct:

    def leave(self) -> None:
        if os.name != "nt":
            # Unlink while locked, so a new waiter can't reuse the name first.
            _discard_entry(self.path)
        try:
            _release_fd(self.fd)
        finally:
            if os.name == "nt":
                _discard_entry(self.path)

Strengths

  • The ValueError checks in _install_slot stop a caller from passing a slot that belongs to another agent or root, or one already released. These mistakes would otherwise be silent.
  • Starting the install worker on a plain thread instead of BackgroundTasks, with the handed_off guard, means the slot is released however the request ends. The tests cover a release from another thread and a second release.
  • test_processes_get_the_lock_in_the_order_they_asked waits until each waiter has queued before it starts the next, so it tests the order and not process startup time. denied_folder.py uses a real ACL deny on Windows, not a mock.

…older a denied save could not write

A leaving or probing waiter released its queue entry before deleting it, so on
Linux and macOS a new waiter could take the same name in between and have its
entry deleted, letting later waiters jump ahead. POSIX now deletes while still
holding the lock. A config save into a folder the user can't create files in now
names that folder instead of a bare permission error.

Adds tests for a holder killed mid-hold, a writer killed mid-rewrite, both
name-reuse races, and denied-folder saves.
@kovtcharov-amd

Copy link
Copy Markdown
Collaborator

Both suggestions are addressed.

  • Fairness gap: fixed. On Linux and macOS a waiter now deletes its queue entry before releasing it, both when it leaves and when it clears a dead entry. A newcomer can no longer reuse the name and lose its place. Windows already blocks this, because a waiter keeps its entry open.
  • Real-world evidence: added below. A real Agent UI server with an isolated GAIA_HOME returned 202 for the first install and 409 for a duplicate. With the slot held by another process, install and uninstall both returned 409. After a failed install, a new install got 202, so the slot was released.

New tests cover a process killed while holding the lock, a writer killed mid-rewrite, both name-reuse races, and saving into a folder the user can't write. That save now fails with an error that names the folder, and the old file stays whole.

🔍 Technical details
  • _release_and_discard() in file_lock.py: on POSIX it unlinks the entry and then releases the lock; on Windows it releases and then unlinks. leave() and _entry_alive() both use it. In _join_queue, the entry is deleted on timeout only if _same_file still matches.
  • test_leaving_never_deletes_a_newer_entry_with_the_same_name and test_probing_a_new_entry_never_strands_its_owner were run on Linux (WSL) against the old and new code. The old code failed both and the new code passes both. On Windows they pass either way, for the reason above.
  • write_bytes_atomic now turns a PermissionError from mkstemp into one that names the folder (test_config_save_with_an_existing_lock_in_a_denied_directory_fails_loudly, real ACL deny).
  • Evidence run: python -m gaia.ui.server --port 4317, GAIA_HOME set to a temp dir.
    • POST /api/agents/install {"id":"email"} returned 202. An immediate duplicate returned 409. The install then ended failed (the hub download timed out), and a new install returned 202.
    • While a separate process held claim_install_slot("hello-world"), POST /api/agents/install and DELETE /api/agents/hello-world both returned 409. After that process exited, the DELETE returned 404 (not installed).
    • No .q* queue entries were left behind.
  • Separate, pre-existing problem (also on main, outside this PR): installing an id the hub doesn't know returns a bare 500, because fetch_manifest lets the hub's 404 HTTPError through instead of raising CatalogError.
  • Affected suites: 305 passed, 3 skipped. Config and lock suites: 197 passed. util/lint.py --all passes.

kovtcharov and others added 3 commits October 21, 2026 01:34
The fair queue from the previous commit listed the lock's whole folder on
every acquire and poll, so an uncontended lock in the RAG cache folder
(thousands of files) went from 0.23 ms to 32 ms. Waiters noticed a release
on a 20 ms poll, so a busy lock handed off about 23x slower than before.

- Queue entries live in their own <name>.lock.d/ folder, so the cost no
  longer grows with the folder. With nobody waiting, the lock is taken
  without an entry at all (0.3 ms in a 5,000-file folder).
- Each waiter polls 1 ms per waiter ahead of it, up to 20 ms, and a new
  holder only unlocks its entry; deletes run after the turn. The next
  waiter takes the lock in under a millisecond.
- Entry names are never reused, and on POSIX a dead entry is deleted while
  its lock is held, so no waiter can delete another's live entry.
- A holder marks its entry spent, so a waiter never mistakes a brand-new,
  not-yet-locked entry ahead of it for a finished one and jumps the line.
- The cross-process 409 names the other GAIA process instead of a status
  URL that 404s there. install_in_progress() had no callers and is gone.
- The multi-process fairness test waits for each child to import and
  queue, so a slow `import gaia` can no longer fail it.
On Windows with Python 3.12, tempfile.mkstemp retries a refused create up to
10,000 times, so saving a config into a folder the user can't create files in
hung instead of failing. One create with a random name fails at once and names
the folder.
@kovtcharov-amd

Copy link
Copy Markdown
Collaborator

The new denied-folder test caught a hang on Windows CI, and it's fixed now. With Python 3.12, saving a config into a folder the user can't create files in retried about 10,000 times and crashed the test worker. Before, the save hung. Now it fails at once with an error that names the folder.

🔍 Technical details

write_bytes_atomic no longer calls tempfile.mkstemp. On Windows, mkstemp retries a create that PermissionError refused, up to TMP_MAX times. The function now does a single O_EXCL | O_BINARY open with a random name. That is the same reason _can_create_in already avoided mkstemp. test_config_save_with_an_existing_lock_in_a_denied_directory_fails_loudly now requires the save to fail within 5 s.

kovtcharov and others added 4 commits October 21, 2026 01:56
Keeps the other session's delete-while-locked helper (_release_and_discard) and its crash, rewrite and name-reuse tests, adapted to the <name>.lock.d/ queue where a holder keeps no live entry. Its denied-folder save message stays, but the temp file is now made with one O_EXCL create: tempfile.mkstemp retries a refused create 10,000 times on Windows when os.access calls the folder writable, which hung its own 10 s test for minutes.
Both sides replaced tempfile.mkstemp in write_bytes_atomic with one O_EXCL create; this keeps the fork's version.
The busy-lock throughput test measured 24-28 ms per turn on two macOS runs
against ~3 ms on Linux; the 8 ms bound stays for Linux and Windows.
# Conflicts:
#	src/gaia/rag/sdk.py
@kovtcharov-amd
kovtcharov-amd added this pull request to the merge queue Oct 21, 2026
Merged via the queue into amd:main with commit b4018e0 Oct 21, 2026
66 checks passed
@kovtcharov-amd
kovtcharov-amd deleted the kalin/file-lock-reliability branch October 21, 2026 10:49
kovtcharov-amd added a commit to kovtcharov/gaia that referenced this pull request Oct 24, 2026
…xed bound (amd#5488)

The busy-lock throughput test from amd#5469 fails on slow or loaded
runners. It failed macOS CI (24.3 ms against an 8 ms bound) and 2 of 22
loaded Windows runs, so it can block unrelated PRs. It now times a lock
hand-off against a flat 20 ms poll in the same run, and asserts the
margin rather than a fixed limit. It passed 30 of 30 runs on Windows
under heavy CPU load and still fails when the fast hand-off is reverted.
The same change fixes the lock's handling of queue entries this user
can't check, such as another user's on NFS:
- A dead one no longer blocks everyone forever.
- A client clock an hour behind the server no longer blocks waiters for
an hour.
- An aged-out one is named in a warning and no longer slows every later
lock.

It also documents the three ways queue order can slip, and drops an
unused "spent" marker.

Reproduced by `test_a_busy_lock_keeps_its_throughput` on macOS CI (run
39573703043); its replacement
`test_a_busy_lock_hands_off_far_faster_than_a_flat_poll` passes here and
fails when the 1 ms poll is reverted to 20 ms. The skew bug is
reproduced by `test_an_unchecked_entrys_age_ignores_this_machines_clock`
(client ±1 h); it fails against the previous head and passes here.

## Test plan

- [x] `test_a_busy_lock_hands_off_far_faster_than_a_flat_poll` 30 of 30
under 6 CPU burners and 30 of 30 under 12 on Windows. Measured: real
hand-off ~0.7–0.9 ms against ~10–14 ms with a flat poll.
- [x] Each new test fails when its fix is reverted:
  - the 1 ms poll set to 20 ms
  - the 20 ms cap removed
  - unchecked entries never ageing out
  - the registry's dot-name skip removed
  - age taken on this machine's clock
  - no warning for an aged-out entry
  - the fast path not looking past it
  - it missing from the timeout message
- [x] Reviewer probes on the new head: a client 5 s, 60 s or 1 h behind
the server now gets the lock (`skew.py`). One stale foreign entry costs
0.34 ms per uncontended lock against 0.31 ms clean (`stalecost.py`).
- [x] `python -m pytest tests/unit/test_file_lock.py
tests/unit/test_concurrent_state_writes.py tests/unit/rag/
tests/test_rag.py tests/unit/test_hub_router.py
tests/unit/test_hub_installer.py tests/unit/test_daemon_hub_routes.py
tests/unit/test_skills_install_concurrency.py
tests/unit/agents/test_registry_load_errors.py -n 4` on Windows, with an
isolated `GAIA_HOME`. Everything passes except three tests that also
fail on main in this environment (no `pip` in the venv; a registry test
that ignores `GAIA_HOME`).
- [x] `python util/lint.py`: black, isort, flake8, pylint and the other
checks pass. The tool-description check fails locally only, because it
imports this machine's editable install from another checkout; CI's lint
passed.
- [x] CI unit lanes pass on Linux, Windows and macOS at e2c595e (run
39609097494).

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

- **Why a margin, not a ratio.** Sleep overshoot (macOS CI) adds about
the same delay to both runs, so a 3× ratio fails there while a 4 ms
margin holds.
- Each run takes 40 rounds, released at a random point of the waiter's
poll.
- The flat run's median landed between 7.9 and 15.2 ms across the
reviewer's 72 runs. The real run stays near 1 ms, so the margin held
every time.
- A 4-thread throughput design was dropped: under the GIL one thread can
run all its cycles alone, so a flat poll looked just as fast.
  - The absolute-bound latency test is folded into this one.
- **Unchecked entries.** An entry this user cannot test (another user's,
or NFS flock emulation) stops counting as ahead once older than
`LOCK_TIMEOUT_SECONDS`.
- **Clock:** the age is measured in the file server's time, as the
waiter's own entry mtime plus the monotonic time since it joined,
against the stuck entry's mtime. Only a waiter with no entry of its own,
in a read-only folder, falls back to this machine's clock.
- **Never deleted:** nobody can confirm its owner is gone. It is logged
once per process, stays in the timeout message's "delete" list, and the
fast path looks past it.
- **Worst case:** a live one with a long timeout loses its place, never
exclusion, because only the main lock decides the holder.
- **Spent marker removed.** It showed no measurable gain and no test
needed it. An unlocked entry is re-checked every poll and reaped after
the waiter's turn, so a not-yet-locked earlier arrival is never skipped
for good.
`test_an_earlier_entry_seen_before_its_owner_locked_it_still_counts`
still guards that.
- **Where order can slip.** The module docstring now lists all three.
Mutual exclusion never depends on any of them.
- A request whose fast path failed, and that has not yet written its
entry, can be beaten by one that arrives as the lock comes free.
- An entry created but not yet locked reads as finished to a waiter
polling at that instant.
  - An aged-out unchecked entry loses its place.
- **New tests.** The `_poll_interval` 20 ms cap, and registry discovery
skipping dot-named folders. `list_installed` already had one.
</details>

---------

Co-authored-by: Kalin Ovtcharov <[email protected]>
kovtcharov-amd added a commit to kovtcharov/gaia that referenced this pull request Oct 24, 2026
…5625)

The v0.25.1 notes stopped at the release PR (amd#5474). That left fixes
that users will notice out of the notes, and the changelog stopped short
of the release commit. This PR adds those three fixes: the GAIA agent
starts on Ubuntu 22.04, Debian 12 and RHEL 9 (amd#5545); Intel Macs can
install again (amd#5546, amd#5481); and Windows settings folders you can read
but can't create files in now load (amd#5469). It also adds six fixes from
rc6 and rc7 and regenerates the changelog from git against rc7.

## Test plan
- [x] `python util/validate_release_notes.py docs/releases/v0.25.1.mdx
--tag v0.25.1`
- [x] `pytest tests/unit/test_docs_json_release.py`
- [x] `mintlify validate` from `docs/`
- [x] The changelog lists 213 commits, the same count as `git rev-list
--count v0.25.0..v0.25.1-rc7`. The narrative stays within the 350-word
patch cap.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents daemon Daemon supervisor / sidecar control plane performance Performance-critical changes rag RAG system changes sidecar Agent sidecar contract / harness tests Test changes

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants