Skip to content

fix(state): lock and atomically replace shared ~/.gaia files across processes - #5388

Merged
kovtcharov-amd merged 8 commits into
amd:mainfrom
kovtcharov:kalin/gaia-home-concurrent-writes
Oct 19, 2026
Merged

kovtcharov-amd merged 8 commits into
amd:mainfrom
kovtcharov:kalin/gaia-home-concurrent-writes

Conversation

@kovtcharov

@kovtcharov kovtcharov commented Oct 19, 2026 •

Copy link
Copy Markdown
Contributor

The daemon, the Agent UI, the CLI and the TUI write the same ~/.gaia files at once, and those writes could corrupt each other: a gaia config set could 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.py and TestCacheSecurity in tests/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 init and the Agent UI's model picker keep each other's keys, because save() 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.
  • Document cache: first-run processes agree on one HMAC key, and a cache and its signature are replaced together. A failed check is a cache miss and never deletes an entry another process just wrote. A cache another process holds locked is reported as an error rather than re-extracted.
  • Skills and hub agents: the skill lock and the shared .pth keep 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 .staging with a logged path when a file held open prevents that.
  • Context7 cache: concurrent writers keep every entry, and the rate limit counts every process. A corrupt file is an error that names the fix, not a silent reset that wipes the rest.

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.json without 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 reverted
  • python -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" with GAIA_HOME and the home directory pointed at a temp folder: no failures beyond those origin/main has on this machine
  • python util/lint.py --all: Black, isort, Pylint, Flake8, MyPy ratchet and the rest pass. --tool-descriptions fails only because this machine's editable install points at another checkout, and it passes when run on its own

…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 {}.
@github-actions github-actions Bot added mcp MCP integration changes rag RAG system changes tests Test changes performance Performance-critical changes daemon Daemon supervisor / sidecar control plane sidecar Agent sidecar contract / harness labels Oct 19, 2026
@github-actions

Copy link
Copy Markdown
Contributor

Verdict: Request changes (one small fix)

This PR makes the daemon, Agent UI, CLI and TUI stop corrupting each other's files under ~/.gaia. Every read-modify-write now holds a cross-process lock and every write is a temp file renamed into place. The design is sound and the coverage is thorough: config, RAG cache, skills, hub installs and Context7.

One gap undercuts the headline claim: on a first run, before config.json exists, a save can still erase a key another process just wrote. Loading a missing file returns a config that doesn't record what it loaded, so its save writes every field, defaults included, over the other process's change. That is the first-run window the PR sets out to close (gaia init and the Agent UI starting together). The fix is one line in two places.

Real-world evidence

N/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 (src/gaia/config.py, load())

_changed() returns every field when _loaded is None. load() leaves it None on both early returns: when the parent directory is missing and when the file is missing (if text is None: return cls()). Here is how a key gets lost:

  1. Process A loads with no file present.
  2. Process B saves default_model=X.
  3. A sets lemonade_mode and calls save().
  4. A's _apply writes all fields, including default_model=None, so X is lost.

update() already re-reads under the lock and rewrites every declared field. Snapshotting the defaults therefore produces the same file in the no-race case and keeps B's key in the race case. The callers that hit this are the cfg = GaiaConfig.load(); …; cfg.save() sites in lemonade_choice.py and gateway.py.

        if not config_file.parent.is_dir():
            return cls()._snapshot()

and

        if text is None:
            return cls()._snapshot()

A test that would catch it: load with no file, have a second save_key("default_model", "X"), then set another field on the first config, save(), and assert default_model == "X".

🟢 Skill lock reads now fail in a read-only skills root (src/gaia/skills/lock.py, load())
load() now takes _hold(path), which has to create skills-lock.json.lock. In a root this user can't write (one with a lock file but no write access), a plain read raises SkillLockBusyError where it used to succeed. GaiaConfig.load handles this exact case with _cannot_create_in. It's worth applying the same carve-out here, or confirming that no read-only root ever carries a lock file.

Strengths

  • file_lock is careful. It is re-entrant per thread and uses flock (per open-file description, so threads in one process still exclude each other). It seeks to offset 0 before the msvcrt unlock, and its Windows _replace retry is bounded and actionable.
  • The skill install now stages a copy and swaps it in, rolling back if the lock entry fails to save. A loader never sees a half-copied skill, and files and lock stay consistent.
  • It removes several silent fallbacks in line with the fail-loudly rule. A corrupt Context7 cache or rate state used to be reset to empty, which wiped entries and lifted the rate limit. Now it raises an error that names the fix, and gaia cache clear --context7 exists. The RAG cache-miss path no longer deletes an entry another process may have just written.

kovtcharov-amd and others added 2 commits October 18, 2026 23:11
…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.
@kovtcharov-amd kovtcharov-amd added the ready_for_ci Run CI workflows on draft PR without requesting review label Oct 19, 2026
@github-actions

Copy link
Copy Markdown
Contributor

Verdict: Approve with suggestions

The daemon, Agent UI, CLI and TUI could corrupt or overwrite each other's ~/.gaia files. This PR fixes that: each read-modify-write of the config, skill lock, hub .pth, RAG cache and Context7 cache now holds a cross-process lock, and every write goes to a temp file that is renamed into place. I found nothing blocking. The lock helper is small, re-entrant within a thread and bounded on Windows. Skill reinstalls keep the previous copy if anything fails.

Three small follow-ups, none blocking:

  • The Agent UI's "is an install already running?" check briefly takes the same lock a real install claims. A gaia hub install started at that exact moment can be wrongly told an install is in progress. Rare, but it's a false failure the user has to retry.
  • The hub .pth lock leaves a gaia-hub-agents.pth.lock file in the Python environment's site-packages, and it stays there after uninstall.
  • When the document cache lock can't be taken, the message always says another process is probably indexing, even when the real cause was a permissions error creating the lock file.

Real-world evidence

N/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 pytest isn't installed on this review runner, so I couldn't re-run them.

🔍 Technical details

🟢 Minor

  1. The probe can spuriously reject a concurrent claim (src/gaia/hub/installer.py:368). install_in_progress() takes .<id>.install.lock with timeout=0, and _install_slot() also claims it with timeout=0. A CLI install whose single attempt lands while the router is probing gets InstallInProgressError. One fix: give _install_slot a short timeout (e.g. timeout=0.5), which is still far below any real install. That way it only rejects when a holder exists, not when someone is probing.

                with file_lock(
                    root / f".{_require_safe_agent_id(agent_id)}.install", timeout=0.5
                ):
    
  2. A stray lock file is left in site-packages (src/gaia/hub/installer.py:919, :954). file_lock(pth_path) creates gaia-hub-agents.pth.lock beside the .pth. It does no harm, since Python ignores non-.pth files there, but it is never cleaned up. Consider putting the lock under the install root (e.g. root / ".active-env-pth"), or unlinking it in _write_pth_lines when the .pth itself is removed.

  3. The cache-busy message assumes contention (src/gaia/rag/sdk.py:3201). _cache_busy gets every FileLockError, including the non-timeout case where rag-cache.lock couldn't be created (an unwritable cache dir). That message already names the directory, so the "Another GAIA process is probably indexing" sentence should only be added for FileLockTimeout.

Notes, not findings

  • Behaviour change worth knowing about: _write_config_keys now goes through save_keys, which validates the whole file. An unrelated invalid key, say one the Go TUI wrote, now blocks saving the model choice with a 500, where before only the JSON syntax was checked. This is consistent with fail-loudly, and the error names the problem.
  • Context7 and the rate state now raise on a corrupt file instead of silently resetting. gaia cache clear --context7 clears the library and doc files the remedy points at, and the rate-state message tells the user to delete the file by hand. Both are fine.

Strengths

  • file_lock is re-entrant per thread, which lets helpers like SkillLock.save() inside SkillLock.locked() and Context7RateLimiter.acquire() → can_make_request() compose without deadlocking.
  • GaiaConfig.save() writes only the fields that changed since load. That fixes the lost-update problem without changing the API for existing callers.
  • The skill reinstall stages the new copy, swaps it in and rolls back if the lock entry fails to save. It never deletes the only copy of the previous install, which is careful work.
  • The hub router now records a terminal "failed" state when another process holds the slot, so the UI no longer polls "queued" forever.

…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.
@kovtcharov-amd
kovtcharov-amd added this pull request to the merge queue Oct 19, 2026
Merged via the queue into amd:main with commit 2086c04 Oct 19, 2026
66 checks passed
@kovtcharov-amd
kovtcharov-amd deleted the kalin/gaia-home-concurrent-writes branch October 19, 2026 18:26
kovtcharov-amd added a commit to kovtcharov/gaia that referenced this pull request Oct 19, 2026
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.
grtninja pushed a commit to grtninja/gaia that referenced this pull request Oct 21, 2026
…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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

daemon Daemon supervisor / sidecar control plane mcp MCP integration changes performance Performance-critical changes rag RAG system changes ready_for_ci Run CI workflows on draft PR without requesting review sidecar Agent sidecar contract / harness tests Test changes

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants