Repository navigation
fix(state): lock and atomically replace shared ~/.gaia files across processes - #5388
Conversation
…rocesses
The daemon, Agent UI, CLI and TUI write the same ~/.gaia files at once, and
several writes truncated in place or read-modify-wrote without a lock. A
concurrent `gaia config set` made other processes fail with invalid JSON,
two first-run processes minted different RAG HMAC keys, and concurrent
installs dropped each other's skill-lock and .pth entries.
- gaia.utils.file_lock: advisory lock on <name>.lock (reusing
gaia.daemon.lock.try_lock), re-entrant per thread, plus fsynced
temp-and-rename writes that wait out a brief Windows sharing hold.
- config.json: load/save/save_key/save_keys/update take the lock; save()
writes only changed fields; gaia init and the Agent UI model picker go
through it; a read-only config dir still loads.
- RAG: HMAC key created under the lock; cache JSON + .sig replaced together;
a failed verify is a miss, not a delete; clear_cache takes the lock.
- Skills: every skill-lock read-modify-write uses SkillLock.locked(); hub
installs stage aside and swap in, undoing the swap if the lock save fails.
- Hub agents: the install slot is a cross-process lock (uninstall and
rollback take it); the shared .pth update is locked.
- Context7: locked read-modify-write, atomic writes, combined
check-and-consume; corrupt files raise instead of silently becoming {}.
|
Verdict: Request changes (one small fix) This PR makes the daemon, Agent UI, CLI and TUI stop corrupting each other's files under One gap undercuts the headline claim: on a first run, before Real-world evidenceN/A: no evidence bundle was produced for this run. The change is internal file-state handling with no new CLI, API or UI surface. This verdict rests on static review alone. I could not run the PR's tests here because pytest isn't installed on this runner. The PR says the repro tests fail on main and pass on this branch. 🔍 Technical details🟡 A config loaded from a missing file still overwrites concurrent writes (
and A test that would catch it: load with no file, have a second 🟢 Skill lock reads now fail in a read-only skills root ( Strengths
|
…ead-only A config loaded before config.json existed still wrote every default on save, so a key another process saved in between (gaia init and the Agent UI starting together) was lost. Loading a missing file now records the defaults, so save() writes only what this instance changed. - Skill lock reads no longer fail in a skills root this user cannot write; the read-only carve-out GaiaConfig.load had is now shared from file_lock. - Fix the mypy ratchet error on GaiaConfig._snapshot. - The RAG cache overlap test no longer depends on runner speed: the writer keeps going until the reader has overlapped it enough times.
…visibly A reinstall whose lock save failed undid the swap by deleting the new copy in place; a file held open could stop that halfway and the cleanup then deleted the staging dir holding the only previous copy. The undo now renames the new copy aside, and staging is kept while an undo is incomplete. - An Agent UI install that loses the slot to another process now ends in "failed" with the reason instead of polling "queued" forever, and the install endpoint checks the slot across processes before it stops the email sidecar. - A busy RAG cache lock is reported as an error instead of passing for a corrupt cache and triggering a full re-extraction. - Windows renames retry another program's hold for at most 3 s, so a lock holder's worst case stays under the 10 s waiter timeout; skill directory swaps use the same retry, and a read-only file fails at once. - An unopenable lock file in a writable directory is an error, not a reason to read without the lock.
|
Verdict: Approve with suggestions The daemon, Agent UI, CLI and TUI could corrupt or overwrite each other's Three small follow-ups, none blocking:
Real-world evidenceN/A: no evidence bundle was produced for this run. The change is internal state handling with no new CLI, API or UI surface, so this verdict rests on static review. The PR's repro tests (fail on main, pass here) are the right proof, but 🔍 Technical details🟢 Minor
Notes, not findings
Strengths
|
…n only on timeout A hub install that started while the Agent UI was probing its slot was told another install was running; the claim now waits half a second. A document cache whose lock file can't be created no longer says another process is indexing.
…pped it On a loaded CI runner the writer could finish all its saves before the reader looped twice, so the race test failed without a torn read.
…an lock A writer relocking with no gap starved the polling reader on a loaded Windows runner until its lock wait timed out.
Saving a per-model context size now goes through the same locked, atomic config write main adopted in amd#5388, so it can no longer clobber a key another GAIA process saved at the same moment, or overwrite a corrupt config.json. GaiaConfig.edit_doc does the locked read-modify-write and validates the result before writing.
…md#5469) The cross-process file lock from amd#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 - [x] `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`. - [x] 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. - [x] `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']`. - [x] 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. - [x] `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`) were not run locally. <details> <summary>🔍 Technical details</summary> - **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. </details> --------- Co-authored-by: Kalin Ovtcharov <[email protected]>
The daemon, the Agent UI, the CLI and the TUI write the same
~/.gaiafiles at once, and those writes could corrupt each other: agaia config setcould make the Agent UI fail with "config is not valid JSON", and two installs could each drop the other's entry. Now every read-modify-write of these files holds a cross-process lock, and every write goes to a temp file renamed into place. A reader sees the old file or the new one, and no change is lost.Reproduced by
tests/unit/test_concurrent_state_writes.py,tests/unit/test_skills_install_concurrency.py,tests/unit/test_hub_router.pyandTestCacheSecurityintests/test_rag.py; they fail on main and pass here.~/.gaia/config.json: a reader never sees a half-written file. Saves from the CLI,gaia initand the Agent UI's model picker keep each other's keys, becausesave()writes only the fields that instance changed since it loaded, including on first run before the file exists. A config in a folder this user can't write still loads..pthkeep every install's entry. The one-install-per-agent guard holds across processes, and an Agent UI install that finds another process installing ends in "failed" with the reason, without stopping the email sidecar. A reinstall builds the new copy aside and swaps it in. If its lock entry can't be saved, the previous copy is put back, or kept in the skills folder's.stagingwith a logged path when a file held open prevents that.On Windows, a rename that antivirus or the search indexer briefly blocks is retried for up to 3 s, which keeps any lock holder well inside the 10 s other processes wait. A read-only file fails at once. The Go TUI still reads and writes
config.jsonwithout this lock; that is left for a follow-up.Test plan
python -m pytest tests/unit/test_concurrent_state_writes.py tests/unit/test_skills_install_concurrency.py tests/unit/test_file_lock.py tests/unit/test_hub_router.py tests/test_rag.py; each repro test fails with its fix revertedpython -m pytest tests/unit tests/test_rag.py -k "skill or hub or install or config or rag or context7 or cache or lock or capture"withGAIA_HOMEand the home directory pointed at a temp folder: no failures beyond those origin/main has on this machinepython util/lint.py --all: Black, isort, Pylint, Flake8, MyPy ratchet and the rest pass.--tool-descriptionsfails only because this machine's editable install points at another checkout, and it passes when run on its own