Skip to content

fix(filesystem): stop deleting the file index when it is only locked - #5377

Merged
kovtcharov-amd merged 6 commits into
amd:mainfrom
kovtcharov:rel/file-index-lock-not-corrupt
Oct 19, 2026
Merged

kovtcharov-amd merged 6 commits into
amd:mainfrom
kovtcharov:rel/file-index-lock-not-corrupt

Conversation

@kovtcharov

@kovtcharov kovtcharov commented Oct 19, 2026 •

Copy link
Copy Markdown
Contributor

GAIA deleted ~/.gaia/file_index.db, bookmarks included, whenever it couldn't open the file. That happened even when another GAIA process only had it locked, or an antivirus scan or backup briefly held it. Now only real corruption ("not a database", "malformed") rebuilds the index, including a file whose table pages are damaged behind an intact header. Even then the damaged file is kept, moved aside to file_index.db.corrupt-<timestamp>, and the next bookmark result says the index was rebuilt and where the old file is. A lock, I/O or permission error is raised and the file is left alone.

While the index can't be opened, the bookmark tool returns an error that says why and changes nothing, then re-opens the index on its next call. Before, bookmarks were silently kept in memory for the rest of the session, and lost when it ended.

Reproduced by tests/unit/test_filesystem_index_locked.py and tests/unit/test_filesystem_bookmarks_index_unavailable.py; they fail on main and pass here.

🔍 Technical details
  • Corruption is recognised by SQLite's primary result code (the low byte): SQLITE_CORRUPT (11, including 267) or SQLITE_NOTADB (26), via sqlite_errorcode on Python 3.11+. On older Python it is recognised as a bare DatabaseError. Anything else re-raises after closing the connection: BUSY, LOCKED, IOERR, CANTOPEN, READONLY, ProgrammingError, InternalError. A test drives one of each by result code.
  • The integrity check now runs before _ensure_schema. A page-damaged file used to fail in the schema step, before any rebuild could happen. One test corrupts a real file's table pages and keeps page 1.
  • The check is PRAGMA quick_check, not integrity_check. It still finds page damage, and it runs on every agent start at a fraction of the cost.
  • A rebuild moves the damaged file and its -wal/-shm aside instead of deleting them. If the move fails, the open raises instead of rebuilding over the file.
  • The bookmark tool's advice depends on the cause:
    • BUSY / LOCKED: says another GAIA process is using the index; try again in a moment. This is the only case that says to retry.
    • Corrupt: names the file and says to delete it (and its -wal/-shm) to rebuild. Saved bookmarks in it are lost.
    • CANTOPEN / READONLY / PERM, or an OS error: names the file and says to check the permissions on it and its folder.
    • Anything else: names the file and points at the log.
  • The lazy open is guarded by a per-agent lock, created on first use for any object the tools bind to, so concurrent calls open the index once. Only an agent with no index configured keeps bookmarks in memory. At startup, ChatAgent still just logs "File system index not available" and leaves the index unset.
  • test_service_edge_cases.py encoded the old rule that a disk I/O error means rebuild. It is split into "malformed rebuilds" and "I/O error raises and keeps the file".

Test plan

  • python -m pytest tests/unit/test_filesystem_bookmarks_index_unavailable.py tests/unit/test_filesystem_index_locked.py tests/unit/test_service_edge_cases.py tests/unit/test_filesystem_index.py tests/unit/test_filesystem_tools_mixin.py tests/unit/test_scratchpad_service.py tests/unit/test_starter_skills.py -q (518 passed)
  • python util/lint.py --black --isort --flake8 --pylint --bandit --test-lanes

GAIA deleted ~/.gaia/file_index.db, bookmarks included, on any error
opening it. A "database is locked" from another GAIA process, or a
"disk I/O error" while an antivirus scan or backup held the file, was
treated as corruption and the whole index rebuilt empty.

Only sqlite3.DatabaseError (not a database, malformed image) now counts
as corruption. sqlite3.OperationalError propagates and leaves the file
alone, matching the scratchpad DB; the chat agent already reports it as
"File system index not available" and carries on.
Close the connection before re-raising so a contended file is not held open
until garbage collection, drop a comment that no longer matched the code, and
prove a real exclusive lock reaches the raise path.
@github-actions github-actions Bot added the tests Test changes label Oct 19, 2026
@github-actions

Copy link
Copy Markdown
Contributor

Verdict: Approve with suggestions

Before this PR, GAIA deleted the file index (bookmarks included) whenever it couldn't open it, even when the file was only locked by another GAIA process or held for a moment by an antivirus scan or backup. Now only real corruption triggers a rebuild. A lock or I/O error is raised, and the chat agent's existing handler turns it into a warning. The exception ordering is correct, and the new tests cover both directions, including one with a real SQLite lock.

Nothing blocks merge. One small loose end: a lock that hits during the schema check, between the two guarded steps, still raises without closing the connection, so the contended file stays open until garbage collection.

Real-world evidence

N/A: internal storage fix with no CLI, API, or UI surface change, and no evidence bundle was produced. This verdict rests on static review. I couldn't run the new tests here because pytest isn't installed on this runner; the PR's test plan reports them passing.

🔍 Technical details

Issues

🟢 Lock during _ensure_schema leaks the connection (src/gaia/filesystem/index.py:184): table_exists / migrate can hit database is locked after the WAL pragma succeeds. That error already propagates and doesn't delete anything, so it's correct, but it skips the close_db() the other two paths now do. Wrapping the three steps in one guard keeps the "don't hold the contended file" behaviour consistent:

        try:
            self._ensure_schema()
            self._check_integrity()
        except sqlite3.OperationalError:
            self.close_db()
            raise

(The close_db() calls inside the two existing handlers could then be dropped, but leaving them in is harmless.)

🟢 PR body wording: "reports 'File system index not available' for that turn." The handler at hub/agents/chat/python/gaia_agent_chat/agent.py:508 runs once in __init__, so _fs_index stays None for the whole agent session, not one turn. The behaviour is fine; the description just overstates how quickly it recovers.

Checked and fine

  • OperationalError is a subclass of DatabaseError, and the narrower handler comes first in both places, so corruption (NOTADB, CORRUPT) still rebuilds.
  • FileSystemIndexService has only one caller, and it already catches sqlite3.Error, so the new raise can't crash agent startup.

Strengths

  • test_a_real_exclusive_lock_raises_and_keeps_the_index holds a real SQLite lock instead of only mocking one, so it shows the raise path is the one a real contended file actually takes.
  • It removes two broad except Exception handlers rather than adding to them, which fits the fail-loudly rule.
  • Regression tests cover both directions: locked → kept, and garbage/malformed → still rebuilt.

…ocked

If the file index was locked when an agent started, the bookmark tool used
an in-memory dict for the whole cached session: "list" reported no
bookmarks while they sat on disk, and "add" said "Bookmarked" but lost the
bookmark when the session ended. The tool now re-opens the configured index
on each call and returns an actionable error while it can't. Only an agent
with no index configured keeps bookmarks in memory.

- Corruption is now recognised by SQLite's error code (CORRUPT, NOTADB)
  where Python exposes it, so a ProgrammingError or InternalError no
  longer wipes the index either.
- The edge-case test that still expected a disk I/O error to rebuild is
  split into its two real cases.
kovtcharov and others added 3 commits October 18, 2026 22:28
…when busy

An index whose header was intact but whose table pages were damaged
passed the WAL pragma, then failed in the schema setup before the
integrity check could rebuild it. Every bookmark call after that said
"try again in a moment", in this session and the next. The integrity check
now runs before the schema, so such a file is rebuilt.

- The bookmark tool's error now follows the cause. Only a busy or locked
  index says to retry. A damaged one names the file and how to rebuild
  it. One that can't be opened or is read-only says to check the file's
  and its folder's permissions.
- Concurrent bookmark calls open the index once instead of leaking
  connections.
- Tests cover SQLite's real result codes, extended ones included.
… registrars

A lock hit while checking or migrating the schema now closes the connection
before raising, like the two earlier open steps, so GAIA stops holding a file
another process is contending for.

The filesystem tool registrar also no longer assumes its host declares the
open lock, which broke the starter-skill tests that register tools on a stub.
A rebuild deleted the damaged file_index.db and with it every bookmark,
without telling anyone. The damaged file, with its -wal and -shm, is now
moved aside to file_index.db.corrupt-<timestamp>. The next bookmark result
says the index was rebuilt, that bookmarks may be gone, and where the old
file is. If the file can't be moved, the open fails instead of rebuilding
over it.

- Startup runs PRAGMA quick_check instead of integrity_check. It still
  finds page damage, at a fraction of the cost on every agent start.
- The lock that serializes opening the index is created on first use for
  any object the tools bind to, so the starter-skill stubs work again.
@kovtcharov-amd
kovtcharov-amd added this pull request to the merge queue Oct 19, 2026
Merged via the queue into amd:main with commit 11da36a Oct 19, 2026
40 of 43 checks passed
@kovtcharov-amd
kovtcharov-amd deleted the rel/file-index-lock-not-corrupt branch October 19, 2026 08:27
kovtcharov pushed a commit to kovtcharov/gaia that referenced this pull request Oct 30, 2026
…er (amd#5404)

The proactive Claude reviews were failing about half the time, and each
failure was lost. The code and security audits failed 5 of the last 10
nights, and the doc walkthrough failed 4 of its last 5 runs. Running
three audits every night used up both Claude accounts' weekly limit by
mid-week, so most of those runs stopped before reviewing anything and
blamed a missing file. The next run never went back for the missed work.
Now one audit runs each night between 2 and 4am Pacific, so each audit
runs every third night. Each run checks Claude is available before
starting, and says plainly when it isn't. It picks up everything since
its last successful run, starts from what merged since then, and checks
against the bug types past audits missed. The dedup pass no longer
re-files duplicates that were already closed: 34 of them were closed
alongside this change.

## Test plan

- [ ] `python -m pytest tests/unit/test_audit_synthesis_prep.py
tests/unit/test_audit_history.py tests/unit/test_audit_rotation.py
tests/unit/test_require_claude.py tests/unit/test_recent_changes.py
tests/unit/test_miss_analysis.py
tests/unit/test_claude_audit_workflow_contract.py
tests/unit/test_closed_duplicates.py -q` passes (277 tests)
- [ ] After merge: `gh workflow run claude-audit-rotation.yml -R
amd/gaia -f dry_run=true`. The summary names tonight's audit and the
next five nights, and nothing is dispatched.
- [ ] After merge: `gh workflow run claude-nightly-audit.yml -R amd/gaia
-f dry_run=true`. Check the preflight summary: the mode, a window
reading "since this audit's last successful run", the Claude probe
passing, and "Recent changes read first". At the end, "Dry run
confirmed: no issue created".
- [ ] After merge: `gh workflow run claude-weekly-doc-walkthrough.yml -R
amd/gaia -f doc_filter=docs/quickstart.mdx -f dry_run=true`. The guide
is walked, "Using bash.exe from …" appears, and the dry-run watermark
step passes (it crashed before this change).
- [ ] After merge: `gh workflow run claude-security-audit.yml -R
amd/gaia`. Semgrep scans `tui`, `installer` and `.github/workflows`, and
the SARIF uploads.
- [ ] First scheduled night (10:13 UTC): the dispatched run is titled "…
rotation night N", files at most what's new, and an issue it files
carries `audit-cluster` / `audit-key` markers.

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

**Root causes (last ~2 weeks)**
- Code and security audits, Oct 7/10/12/13/14/17: every lens returned
`is_error` in under a second with "You've hit your weekly limit". The
primary account ran out on Oct 10, the secondary on Oct 12–14, both on
Oct 17. The account switch fired correctly; both accounts were spent.
- Walkthrough Oct 12: same weekly limit on every guide, queued over 57
hours on the Strix Point pool. Oct 5 and Oct 19: the `xsj-aimlab-stxp`
images have no Git for Windows (only WSL's `bash.exe`). Also on Oct 5,
the executor step's `GITHUB_OUTPUT` got UTF-16 appended by
`start-lemonade.ps1` under PowerShell 5.1 `>>`. Sep 21–28: Application
Control blocked `LemonadeServer.exe` and the job landed on Strix Halo
machines; both were fixed by the move to the `xsj-dispatch` pool on Oct
1.
- The walkthrough's two dry-run steps had a literal `\n` mid-command, so
`dry_run=true` always failed.

**Schedule.** One cron, `13 10 * * *` = 03:13 PDT / 02:13 PST. Only
10:00–11:00 UTC is inside 2–4am Pacific in both seasons. Slot = days
since epoch mod 3 → code audit, security audit, doc walkthrough. The
audits lost their own crons; `workflow_dispatch` still runs any of them
on demand. Deep code sweep: whenever the last successful one is over 8
days old (every third turn, retried on the next turn if it fails).

**Dedup bug.** The 2026-09-07 burst (78 issues) predates the dedup pass:
the run checked out main 7 hours before amd#3310 merged. Three duplicate
pairs still got through after amd#3310 (amd#3832/amd#3471, amd#3825/amd#3414,
amd#5199/amd#4875). Backlog matching compared findings against issue titles
only, so a same-section duplicate worded differently scored 0.05–0.15,
below the 0.18 threshold. Now matching includes each audit issue's own
markers (all 13 known pairs rank 1st–2nd). Closed duplicates hand their
keys to the open canonical, so consolidating into amd#1077/amd#4331 does not
trigger re-filing. Both syntheses share the `claude-audit-issue-filing`
concurrency group. The security audit files to private code scanning,
not issues, so it cannot duplicate the other two.

**Closed as duplicates (34):** into amd#4331: amd#3204 amd#3413 amd#3422 amd#3439 amd#3466
amd#3476. Into amd#1077: amd#3173 amd#3412 amd#3418 amd#3426 amd#3429 amd#3430 amd#3433 amd#3437 amd#3442
amd#3449 amd#3454 amd#3455 amd#3464 amd#3468 amd#3475 amd#3477 amd#3482. Into amd#3198: amd#3436
amd#3462. Others: amd#3425→amd#3169, amd#3457→amd#3195, amd#3440→amd#3180, amd#3486→amd#3064,
amd#3471→amd#3832, amd#3414→amd#3825, amd#3434 amd#3485→amd#3219, amd#5199→amd#4875.

**Miss-analysis (merged `fix` PRs, Jun 21–Oct 19).** 29 of 1005 (3%)
closed an issue an audit filed first. Missed, by title: no deadline 90
(amd#5346 amd#5384 amd#5380), release/CI ordering 71 (amd#5127 amd#5147), Windows
behaviour 38 (amd#5018 amd#5377), dishonest status 36 (amd#5112 amd#5317), shared
state across processes 34 (amd#5337 amd#5282 amd#5378), model output handling 27
(amd#4973 amd#5103), doc drift 27, cold start / non-default setup 26 (amd#4951
amd#5130). About 380 more were Agent UI/TUI or agent-behaviour fixes, which
a static read rarely catches. Noise: of the audit issues closed as
duplicate or not planned, 31 were duplicates of amd#1077, 12 of the
test-coverage umbrella amd#2988, and 6 each of amd#4331, amd#3149, amd#3308 and
amd#2922. What changed: `scripts/audit/missed_bug_classes.md` has a
checklist per class and a "Don't report" list, and all three prompts
read it at run time. The code audit gets a deterministic list of calls
with no deadline. The security audit's semgrep run and worklist now
cover TypeScript, Go, the installer and the workflows.
`scripts/audit/miss_analysis.py` refreshes the evidence monthly.

**Recent changes.** Each audit's first job writes `recent-changes.md`:
first-parent commits since the commit its last successful run checked
out, read from the run history, with PR title, a short body excerpt and
the paths each touched, capped at 30 KB. If that commit is unknown it
covers 3 days and says so.
</details>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents tests Test changes

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants