Repository navigation
Report why a SQLite index failed to open, not a guess - #582
Conversation
The "index unavailable" diagnostics in memory_search, kb_search, session_search, their three gateway equivalents, and the two CLI paths all hardcoded "libsqlite3 missing or unreadable". That is true of the FPC build (sqldb + sqlite3conn resolve the shared library at runtime) and of Delphi's Linux64 target, and wrong everywhere else: PasClaw.dpr links FireDAC.Phys.SQLiteWrapper.Stat, so the Delphi Windows / macOS / mobile exe has SQLite compiled in and no sqlite3.dll exists for the user to go find. The message sent them after a file that was never involved and hid the real cause, which on that target is always an unwritable path or a corrupt db. Two changes: - The four index implementations (memory FTS, memory vector, KB, session search) now record the exception that killed Open and expose it as LastError on their interfaces. The vector index also records its three provisioning gaps, so a missing ONNX model is no longer reported as a SQLite problem. - PasClaw.Utils gains SqliteBackendHint, which names the binding THIS build actually uses, and SqliteOpenFailureReason, which prefers the driver's own text and falls back to the hint only for the paths that return False without raising. It also blanks the quote, backslash and newline bytes that would otherwise break out of the gateway's hand-built JSON error bodies -- driver text is not under our control. `pasclaw kb search` against a blocked db path now prints "unable to open database file" where it used to print "libsqlite3 missing or path unwritable". sqlite_hint_tests covers both functions and is wired into the test aggregate. It does not cover the Delphi arms (this suite is compiled by FPC) or the LastError wiring itself; the test header says so.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: e1fdaefedc
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| Idx := nil; | ||
| ErrMsg := 'knowledgebase unavailable (libsqlite3 missing or unreadable)'; | ||
| ErrMsg := 'knowledgebase unavailable (' + SqliteBackendHint + ')'; |
There was a problem hiding this comment.
Preserve the KB open error before releasing the index
When kb_search encounters an unwritable or corrupt database, TKBIndexImpl.Open has populated LastError, but this branch destroys Idx and reports only the generic backend hint. Consequently these tool calls still guess that the shared library is missing instead of reporting the actual driver failure; Tool_KBGet repeats the same sequence. Capture Idx.LastError before assigning nil and pass it to SqliteOpenFailureReason, as the CLI and gateway call sites do.
Useful? React with 👍 / 👎.
Adding LastError to IMemoryIndex changed an interface with two implementors and rewrote Tool_MemorySearch's failure branch. The existing coverage checked the two pure helpers and, via a manual repro, the failure path -- nothing asserted that a SUCCESSFUL search still returns hits. That regression would have been invisible: memory_search would report "no matches" and the agent would carry on without its notes. memory_search_roundtrip_tests drives the real tool registry: markdown notes on disk -> FTS5 index -> ranked hits with paths, bm25 scores and highlighted snippets. It also asserts a clean miss on an absent term (not dressed up as an unavailable index) and that LastError stays empty after a good open, so no spurious reason leaks into a healthy result. The suite refuses to run without $PASCLAW_HOME rather than assuming it -- running the binary by hand would otherwise write notes into the caller's real memory directory. The Makefile target supplies a mktemp -d home and removes it afterwards, preserving the exit code. Not covered, and said so in the header: the vector backend (needs a provisioned ONNX runtime and model, absent here -- Open() declines and we exercise the FTS fallback), the gateway's /v1/memory/search wrapper, and distilled facts.
Codex P2 on PR #582. The two reporting sites in PasClaw.Tools.KB (kb_search and kb_get) released Idx before reading LastError, so they fell back to the generic backend hint and still guessed at a missing shared library instead of quoting the driver. My first pass converted the string at those sites with a bulk replace and the follow-up pass that switched call sites to SqliteOpenFailureReason worked from a hand-built file list that omitted this unit. Both now read Idx.LastError before assigning nil, matching the eight CLI and gateway sites. The third Open in this unit is a silent registration probe that sets no ErrMsg and is deliberately untouched. Two guards, because the string was already "fixed" once without the behaviour being fixed: - A Makefile lint fails the build if any call site outside PasClaw.Utils names SqliteBackendHint directly. Verified by reintroducing the bug: the lint fails and names the file. - An end-to-end assertion through the real registry. Reaching this branch needs a specific sequence, since kb_search only registers when a valid kb.db with at least one source exists at boot: build a real KB, register while healthy, then corrupt the file underneath the registered tool. kb_search now reports "file is not a database" where it used to report "libsqlite3 not installed". Verified by reverting the fix: the assertion fails. The first draft of that assertion passed on "unknown tool: kb_search" rather than on the behaviour -- worth recording, since a check that green-lights an unregistered tool would have shipped this bug twice.
Conflicts were both list lines in the Makefile -- .PHONY and the test
aggregate -- where main had gained targets while this branch added one.
Resolved as a union with main's ordering authoritative:
from main test-sqlite-hint, test-memory-search-roundtrip (this
session's #582, since merged), test-agents
from here test-stats-attribution
All four verified present in .PHONY, in the test aggregate, and as real
targets, plus `make -n test`. bench-stats confirmed still OUT of the
aggregate -- it is a measuring tool, not a pass/fail suite.
PasClaw.Gateway.Server.pas auto-merged; GatewayBucketId and all six of
its call sites survived, and the tree builds clean.
The previous commit shipped a test-sqlite-hint failure. That guard exists to catch a tool call site reaching for the bare platform hint instead of SqliteOpenFailureReason(...LastError) -- it was added after exactly this mistake shipped twice on PR #582 -- and it caught this one. The comment justifying the shortcut said IFactStore had no LastError accessor and so no driver detail to report. That was a rationalisation of a gap rather than a reason: IMemoryIndex has had one for as long as it has had a failure path. IFactStore now has the same thing, captured in Open's exception handler and cleared on entry, and memory_write reports through SqliteOpenFailureReason like every other call site. Verified against a corrupt database rather than an unwritable one -- these tests run as root, so chmod proves nothing and the write succeeds anyway. With 4 KB of random bytes at the store path the tool now answers: cannot open the fact store at .../facts.db (TSQLite3Connection : file is not a database) which is the driver's own message, not a guess. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01LGQKz579j1ZnDRwmr6h1V6
The problem
Every "index unavailable" diagnostic hardcoded
libsqlite3 missing or unreadable— ten sites acrossmemory_search,kb_search,session_search, three gateway handlers, and two CLI paths.That text is true of the FPC build (
sqldb+sqlite3connresolve the shared library at runtime) and of Delphi's Linux64 target. It is wrong everywhere else:PasClaw.dpr:27linksFireDAC.Phys.SQLiteWrapper.Stat, so the Delphi Windows / macOS / mobile exe has SQLite compiled in and nosqlite3.dllexists for the user to go find. The message sent them after a file that was never involved, and hid the real cause — which on that target is always an unwritable path or a corrupt db.This surfaced from a memory note whose suggested remedy ("drop a 64-bit
sqlite3.dllnext topasclaw.exe; long-term, route the memory module through the static FireDAC wrapper too") was wrong on both counts for a Delphi build. The memory module already goes through FireDAC, and therefore already through the static link. The misleading error text is what produced the bad advice.The fix
Rather than swap in a better-targeted guess, report what actually happened.
Indexes now carry the failure reason. The four implementations —
TMemoryIndexImpl,TVectorMemoryIndex,TKBIndexImpl,TSessionSearchImpl— record the exception that killedOpenand expose it asLastErroron their interfaces.TVectorMemoryIndexalso records its three provisioning gaps, so a missing ONNX model is no longer reported as a SQLite problem.Two new helpers in
PasClaw.Utils.SqliteBackendHintnames the binding this build actually uses.SqliteOpenFailureReasonprefers the driver's own text and falls back to the hint only for the paths that can returnFalsewithout raising.Call sites read
LastErrorbefore releasing the interface — the release destroys the object holding it.Effect
Forcing a KB open failure:
The old text was wrong in both halves on that run. A platform-conditional hint alone would still have said "libsqlite3 not installed" there — less wrong, but not right.
JSON safety
SqliteOpenFailureReasonblanks",\, CR and LF. Three gateway handlers splice this into hand-built JSON error bodies rather than going through the JSON writer, and driver text is not under our control — an unescaped quote would emit a malformed 503. Covered by direct assertions.Tests
src/tests/sqlite_hint_tests.pas— 17 assertions over both functions, wired into.PHONYand thetest:aggregate (verified against the aggregate line itself and viamake -n test).What the suite does not cover, stated in its header rather than left implied:
{$IFNDEF FPC}branches never execute here — only their syntax is checked, and only when a Delphi build runs.sqlite3.dll). That rests onPasClaw.dpr's uses clause, not on any assertion here.LastErrorwiring. That it is populated and reaches the ten call sites was verified manually via the repro above, not by this suite — it tests the two pure functions only.Note on the conflict resolution
The cherry-pick onto current
mainconflicted on thetest:aggregate line, which had gainedtest-relay-servertools. Both entries were kept and both confirmed present.Not changed, deliberately
PasClaw.Memory.Indexconnects withDriverName := 'SQLite'whileLocalVector.VectorStore.FireDACusesParams.DriverID := 'SQLite'. These are the same FireDAC call spelled two ways (DriverNamewrites through toParams.DriverID), and neither selects static vs dynamic — that is decided solely by theStatunit being in the link. The one substantive difference isExtensions=True, which exists only soload_extension('vec0')can run. FTS5 is compiled in, so the memory/KB/session indexes need no extension, and enablingload_extensionon a db file widens what a crafted file could do for zero benefit. Left as-is.Separately worth a look someday:
VectorStore.FireDAC.OpenStorehas notry/except, so it raises through the caller instead of returning a reason like the other four. It is vendored from upstream localvector, which is why it differs.🤖 Generated with Claude Code
https://claude.ai/code/session_01LGQKz579j1ZnDRwmr6h1V6
Generated by Claude Code