Skip to content

fix(rag): keep the RAG cache in ~/.gaia/cache/rag and clear only its files - #4260

Merged
kovtcharov-amd merged 1 commit into
amd:mainfrom
kovtcharov:claude/rag-cache-dir-safety
Sep 25, 2026
Merged

kovtcharov-amd merged 1 commit into
amd:mainfrom
kovtcharov:claude/rag-cache-dir-safety

Conversation

@kovtcharov

Copy link
Copy Markdown
Contributor

Running /clear-cache in gaia chat from your home directory deleted the whole ~/.gaia folder, which holds memory, connector sign-ins, installed agents and models. It then recreated an empty folder, so nothing looked wrong until the next run asked you to log in again. Started from anywhere else, every run left a stray .gaia/ folder in the working directory. Now the RAG cache lives in ~/.gaia/cache/rag (it honours GAIA_CONFIG_DIR), clearing removes only the files the cache wrote, and it refuses outright if the cache dir is $HOME or ~/.gaia. Old ./.gaia caches aren't migrated: the cache is content-hashed and rebuilds on the next index.

Test plan

  • New tests fail on origin/main (5 failed) and pass with the fix: ~/.cache/gaia-dev/venv/bin/python -m pytest tests/test_rag.py -q → 47 passed
  • Neighbours: pytest tests/unit/rag tests/unit/test_rag*.py hub/agents/chat/python/tests -q pass. tests/test_sdk.py has 17 failures from its own stale interface checks (index_documents, create_app); none involve this change
  • python -m gaia.rag.app clear-cache --force run from a scratch home with GAIA_CONFIG_DIR set: removed the cache file, .gaia/memory.db survived, and status shows the absolute cache path
  • black / isort clean; pylint shows no findings in the changed files
  • /clear-cache inside an interactive gaia chat session (needs Lemonade running)

Fixes #4194

…files

Running /clear-cache in `gaia chat` from your home directory deleted all of
~/.gaia (memory, connector state, installed agents, models), and every other
run left a stray .gaia/ folder in the working directory. The RAG cache now
defaults to <GAIA_CONFIG_DIR>/cache/rag, clearing removes only the files the
cache wrote, and it refuses to clear $HOME or the GAIA home dir.

The chat app's /clear-cache now calls RAGSDK.clear_cache() instead of its
own rmtree, so the guard has one owner.

Fixes amd#4194
@github-actions github-actions Bot added documentation Documentation changes rag RAG system changes tests Test changes performance Performance-critical changes labels Sep 25, 2026
@github-actions

Copy link
Copy Markdown
Contributor

Verdict: Approve with suggestions

This fixes a genuinely destructive bug: clearing the document cache from your home folder wiped the whole ~/.gaia directory — memory, sign-ins, installed agents — and silently recreated it empty. The cache now lives in its own dedicated folder, clearing deletes only the files the cache itself wrote, and it refuses outright if someone points it at a home directory. The logic, the guard rails and the tests all check out; I found no blocking issues.

Two things worth a look before merge, neither blocking:

  • Now that every session shares one cache folder instead of one per working directory, two sessions clearing at the same time can hit a file that's already gone and crash with a raw traceback instead of a clean message. A one-word change makes the delete tolerant of that.
  • The key used to sign cache files still lives at a fixed home path even though the cache itself now follows a custom GAIA home. Anyone using a custom GAIA directory ends up with the signatures and the files they sign in two different trees.

Also worth calling out for users: the "export document text" feature writes its markdown into the cache folder by default, so those exports quietly move from the working directory into the hidden home cache — and a later cache clear removes them. Worth one line in the changelog.

Real-world evidence

No evidence-bundle.md was produced for this PR, so the automated stage captured nothing. The PR description does carry the matching surface evidence itself: a real clear-cache --force run from a scratch home showing the cache file removed, .gaia/memory.db surviving, and status reporting the absolute cache path. That exercises the same SDK call the chat command now delegates to, and the new unit tests cover the refusal and the selective-delete behaviour directly.

The one gap is the author's own unchecked box — /clear-cache inside a live gaia chat session, which needs Lemonade running. That's the surface the original bug was reported against. The change there is a thin delegation to the now-tested SDK call, so I'm not blocking on it, but a single transcript of that command in a real session would close the loop on the reported issue.

🔍 Technical details

🟢 Minor

Concurrent clears can raise an unhandled FileNotFoundError (src/gaia/rag/sdk.py:3476)

The default cache dir moved from a per-cwd ./.gaia to a machine-wide ~/.gaia/cache/rag, so two GAIA processes now share it. If both clear concurrently (or an index write races a clear), entry.unlink() raises FileNotFoundError, which propagates past the except ValueError in app.py:905 to the generic handler as a raw traceback. missing_ok=True closes that half cheaply (a PermissionError on a Windows-locked file would still surface, which is arguably correct per the fail-loudly rule).

                        entry.unlink(missing_ok=True)

HMAC key path doesn't follow GAIA_CONFIG_DIR (src/gaia/rag/sdk.py:351)

default_rag_cache_dir() correctly resolves through gaia_config.GAIA_CONFIG_DIR, but _get_hmac_key() still hardcodes Path.home() / ".gaia" / "cache" / "hmac.key". Pre-existing, but this PR is what creates the split: with a custom GAIA_CONFIG_DIR, caches land in the custom tree while the key that signs them stays under $HOME/.gaia. Not a correctness bug today (the key is still found), but it means a custom-config-dir install can't be relocated or torn down as a unit. Worth a follow-up issue rather than expanding this PR.

Extracted-markdown exports relocate silently (src/gaia/agents/tools/rag_tools.py:1798)

export_document_text defaults output_path to config.cache_dir, so a user-requested export now lands in ~/.gaia/cache/rag/ rather than next to the working directory — and _CACHE_OWNED_FILE's unanchored _extracted\.md$ branch means the next /clear-cache deletes it. Consistent with the old rmtree behaviour, so not a regression, but it's a user-visible move that the CHANGELOG entry doesn't mention.

Verification performed

  • _CACHE_OWNED_FILE matched against the real producers: _get_cache_path ({16hex}_{32hex}.json and {64hex}_notfound.json, sdk.py:464/471), _save_cache's .sig sidecar (sdk.py:386), _save_extracted_markdown (sdk.py:3411) and the rag_tools export. All five match; settings.json, notes.md, memory.db, hmac.key and foo.json.sig correctly do not.
  • hmac.key lives in the parent cache/ dir, so it survives a clear — important, since deleting it would silently invalidate every signed cache.
  • The new continue at app.py:907 is inside the while True at line 181 and is equivalent to the existing fall-through continue at line 944; no per-iteration work is skipped.
  • Directory recreation is no longer needed after clearing since nothing is rmtreed, and __init__ already does os.makedirs(..., exist_ok=True) (sdk.py:209).
  • Doc surfaces are in sync: no other cache_dir default or clear_cache description in docs/ still claims the old behaviour, and the chat package's README doesn't document /clear-cache separately.
  • Could not execute the test suite in this environment (no pytest available), so the test results rest on the author's run and CI.

Strengths

  • The guard is the right shape: refusing $HOME and the GAIA home outright, with an error that names the offending path and the correct default, rather than quietly doing something safer.
  • Allowlisting the files the cache owns instead of denylisting what to keep is the safe direction — an unrecognised file survives by default.
  • field(default_factory=...) rather than a module-import-time constant keeps the default resolvable under test monkeypatching, and the tests exploit exactly that.
  • The tests reproduce the actual reported failure (a sentinel memory.db under an isolated $HOME) instead of asserting on the implementation, and cover the refusal path both ways via parametrize.

kovtcharov-amd pushed a commit to kovtcharov/gaia that referenced this pull request Sep 25, 2026
)

Document and image extraction failed whenever the model wrote a
placeholder such as `{field}` before its JSON answer: the parser only
tried the first `{`, gave up, and the extraction raised "did not parse".
It now moves past an invalid span and finds the real JSON. It still
never looks inside a broken object, so truncated or malformed output
returns nothing instead of a misleading fragment. Also adds table tests
for the JSON parser behind every VLM extraction path, and tests that pin
the Stable Diffusion prompt text to the real per-model defaults so the
size, steps, and CFG the model is told to use can't drift from them.

Covers the parser and SD-prompt parts of amd#4257. Chunking and
cache-clearing are in amd#4262 and amd#4260. `deltas_cli`,
`code_bench_fixtures`, and the TUI flag wiring already had tests.
`talk/app.py` is left out because it needs a design decision (see the
issue).

## Test plan
- [x] `python -m pytest tests/unit/test_parsing.py`: 2 placeholder cases
fail on `main`, 13/13 pass with the fix
- [x] `python -m pytest tests/unit/test_parsing.py
tests/unit/test_sd_prompts.py tests/unit/test_file_watcher.py
tests/unit/test_structured_vlm_extraction.py
tests/unit/test_vlm_extraction_failures.py tests/unit/test_sd_mixin.py
tests/unit/test_sd_error_messages.py
hub/agents/gaia/python/tests/test_sd_tools_do_not_rewrite_the_prompt.py`:
176 passed, 3 skipped
- [x] black, isort, and pylint (errors-only, CI config) are clean on the
changed files
- [x] `python util/check_test_lane_coverage.py` does not flag either new
file (the `pytest tests/unit/` lane runs them)

Part of amd#4257

Co-authored-by: Kalin Ovtcharov <[email protected]>
@kovtcharov-amd
kovtcharov-amd added this pull request to the merge queue Sep 25, 2026
Merged via the queue into amd:main with commit a9865fc Sep 25, 2026
41 of 43 checks passed
kovtcharov-amd pushed a commit to kovtcharov/gaia that referenced this pull request Sep 26, 2026
…imports (amd#4360)

About 6,700 lines of code had no caller. One file couldn't even be
imported, yet CLAUDE.md still listed it as "Shell integration". The dead
code kept stale behaviour looking alive, like `rag/demo.py` printing
`gaia rag` commands that don't exist, and it cost reviewers time. This
PR deletes six of the items from amd#4243. It also adds a test that imports
every module under `src/gaia`, so an unimportable file now fails CI
instead of lingering. The test fails on current `main`: it flags
`shell/prompt.py` and the three uncollected mic scripts.

Left for a maintainer decision:
- `src/gaia/eval/model_comparison.py`: it has no caller, but amd#3741
merged it yesterday as a library building block, with CLI wiring planned
as a follow-up.
- `governance/`, `talk/app.py` (amd#4333) and the webui AgentManager panel
(amd#4330) were excluded.

`docs/plans/cpp-framework-parity.md` still calls the C++ plan resolver
dead code to resolve. I left it alone because amd#3812 deletes that file.

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

- Deleted: `src/gaia/shell/`, `rag/demo.py`, `rag/app.py` + `rag_main`
export, `audio/tests/*.py`, `eval/longthread_quality.py` + its test and
fixture, `hub/agents/email/node/`, `Agent::resolvePlanParameters` (+
decl, + now-unused `<regex>` include).
- Two `rag_app` tests in `test_rag_index_status.py` went with
`rag/app.py`. The chat/talk/file-monitor index-status tests stay.
- `thread_fold` keeps its own coverage in
`hub/agents/email/python/tests/test_thread_fold*.py`.
- The import test's allowlist is keyed on the *missing package* (`mcp`,
`reportlab`), not the module. An allowlisted module still fails if it
breaks another way, and a second test checks each allowlisted package is
an optional extra in `setup.py`, not a base dependency. Loose `.py`
files outside a package are loaded by path, so broken relative imports
fail too.
- A CI-equivalent venv (`.[api]` + the unit job's test deps) flags only
`mcp` and `reportlab` today, and the sweep takes ~7 s cold. No module
does an unguarded platform-only import at top level, so the Windows
smoke lane should match. That lane is not verified locally.
- No open PR modifies a deleted file. amd#4260 edits the chat agent's
`app.py`, not `src/gaia/rag/app.py`.
</details>

## Test plan

- [x] `pytest tests/unit/test_import_all_modules.py`: fails on
`origin/main` (shell/prompt.py + 3 mic scripts). It also fails with
prompt_toolkit installed (broken relative import) and with an
`__init__.py` added (`gaia.shell.commands` missing). Passes on this
branch in both the full dev venv and a `.[api]`-only venv.
- [x] `pytest tests/unit/test_rag_index_status.py
tests/unit/test_packaging.py tests/unit/test_model_comparison.py
tests/unit/email tests/unit/rag tests/test_rag.py`: 296 passed, 9
skipped
- [x] `pytest tests/unit` (`.[api]` venv): 14422 passed. The 23 failures
(`test_cli_smoke`, `test_uninstall_command`, `test_lemonade_asr`) also
fail on `origin/main` in the same env.
- [x] C++: `cmake -S cpp -G Ninja && cmake --build` builds clean, and
`tests_mock` passes 1002/1002
- [x] black, isort, pylint (CI flags) on the changed Python files
- [ ] Windows and macOS unit smoke lanes pass (CI)

Part of amd#4243

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

documentation Documentation changes performance Performance-critical changes rag RAG system changes tests Test changes

Projects

None yet

Development

Successfully merging this pull request may close these issues.

fix(rag): /clear-cache can delete all of ~/.gaia

2 participants