Repository navigation
fix(memory): scope every trace query to its brain - #530
Conversation
…ort only their own traces Opens two Memory instances with different brain ids on one SQLite file and, when AGENTOS_TEST_POSTGRES_URL is set, on one Postgres database: the same text stored in both brains, recall by text with and without the full-text index, recall by meaning with the HNSW index active, the index rebuild and its 1,000-trace threshold, a brain opened after another brain wrote its index, health() and a Markdown export.
|
Warning Review limit reached
This review includes 11 billable files and costs up to $2.75.
Reviews can continue after your included limit without a manual trigger. An admin must approve usage-based billing. Or wait 41 minutes for your next included review. View limit details
Comment |
Reviewer's GuideThis fix enforces brain-level tenancy across Memory's read paths and exports, and isolates HNSW sidecar files and rebuild inputs per brain and database. Comprehensive SQLite and Postgres regression tests verify that deduplication, lexical/vector recall, health reporting, indexing, and Markdown export never cross brain boundaries. File-Level Changes
Tips and commandsInteracting with Sourcery
Customizing Your ExperienceAccess your dashboard to:
Getting Help
|
Several brains can share one database, and every row carries its brain's id, but these reads of the Memory facade did not filter brain_id: - the content-hash dedup in remember(), so a store in one brain could return another brain's trace and never write its own; - recall(): both full-text queries, the LIKE fallback and the fetch of the hybrid path's top candidates by id; - the HNSW sidecar: the 1,000-trace threshold count, both rebuilds and the index file, brain.hnsw, shared by every brain and database in a directory; - health(), and the Markdown and Obsidian exports. Each now reads the brain's rows only. The sidecar keeps one index file per database file and brain. The full-text queries put the match first, since Postgres's rank reads the query text as $1, and the LIKE fallback binds its parameters in the order of its placeholders. health() returns numbers on Postgres, where COUNT(*) comes back as a string. The memory_add tool names its traces with v4 UUIDs, as the facade and the importers do: its full-text sync finds the new row by id, and an id unique only within one process could name another brain's row.
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
PR Summary by QodoScope memory reads and vector indexes to each brain
AI Description
Diagram
High-Level Assessment
Files changed (11)
|
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: f8bf7905f4
ℹ️ 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".
| .update(`${databaseFile}\u0000${config.brainId}`, 'utf8') | ||
| .digest('hex') | ||
| .slice(0, 32); | ||
| return join(directory, `${databaseFile.replace(/[^A-Za-z0-9._-]/g, '_')}.${digest}.hnsw`); |
There was a problem hiding this comment.
Keep sidecar filenames within filesystem limits
When the SQLite database has an ASCII basename longer than roughly 208 bytes, the added digest and .hnsw.map.json suffix push the sidecar map beyond the common 255-byte component limit. The database itself can still open, but saving the HNSW index fails; after restart the incomplete sidecar cannot load, so semantic-only recall silently falls back to FTS until another rebuild. Truncate or hash the database-name portion so both generated filenames always fit.
Useful? React with 👍 / 👎.
Code Review by Qodo🐞 Bugs (0) 📘 Rule violations (0) 📎 Requirement gaps (0)
Great, no issues found!Qodo reviewed your code and found no material issues that require reviewTip of the day💡 Did you know, you can pick a display mode instead of tweaking every Display option by hand |
Summary
Several brains can share one database: every row carries its brain's id, and
Memory.createPostgres()documentsbrainIdas the multi-tenant scope of every query. TheMemoryfacade wrote and deleted by brain, but these reads did not filterbrain_id:_findExistingTraceByHash, the dedup onremember(), matchedcontent_hashorimport_hashacross every brain.recall(): the conditions of both full-text paths and of theLIKEfallback (no FTS5), and the fetch of the hybrid path's top candidates by id.remember()and after an import), and the index file itself,brain.hnswin the database's directory: one file for every brain in the file and every database in the directory, loaded by any brain that opened after another brain wrote it.health(): every count (traces, active traces, strength, per type, per scope, documents, graph nodes and edges, last consolidation).MarkdownExporter(themarkdownandobsidianformats ofexport()): the trace query.MemoryAddTool: its full-text sync finds the row it just wrote by id alone, and its ids,mt_<ms>_<counter>, are unique only within one process.Effect: with a shared database, a brain's
remember()could return another brain's trace (its content and id) and never write its own; itsrecall()could return another brain's memories; its vector index could hold and serve other brains' vectors;health()counted every brain; a Markdown or Obsidian export wrote every brain's traces; and two processes serving two brains could give twomemory_addtraces one id, indexing one brain's text under the other brain's row.What changed, per query:
_findExistingTraceByHash:brain_id = ?first.recall():t.brain_id = ?leads the conditions of both full-text queries and of theLIKEfallback, and the top-candidate fetch readst.brain_id = ? AND t.deleted = 0 AND t.id IN (...). The match clause now comes first in the full-text queries: Postgres's rank expression reads the query text as$1, the statement's first parameter, so a condition before the match would have ranked against the brain id (with atypeorscopefilter it already ranked against the filter's value). TheLIKEfallback binds its parameters in the order their placeholders appear (its select-list score comes before the conditions); before, any filter value was bound to aLIKE.brain_idand id.HnswSidecartakes an optionalbrainId; with it the index file is<database file name>.<digest>.hnswbeside the database, the digest a SHA-256 of the file name and the brain id, so brains and databases in one directory never share an index. Without it the file staysbrain.hnsw.health(): every count is of the brain's rows, read throughNumber()(Postgres returnsCOUNT(*)as a bigint string, andran_attoo).MarkdownExporter:brain_id = ? AND deleted = 0;ObsidianExporterinherits it.MemoryAddTool: ids aremt_and a v4 UUID, as the facade,CognitiveMemoryManagerand every importer already name traces, so the sync's lookup by id reaches only the row the same transaction wrote.Stays as it was, with the reason:
syncInsertwith(SELECT rowid FROM memory_traces WHERE id = ?)), inremember(),ingest()andmemory_add: the id is a v4 UUID made in the same call and written by the brain-scoped insert just before, and on Postgres the adapter'ssyncInsertbinds$1as the id, so a brain-scoped row expression cannot pass through it (MemoryStoreskips Postgres for the same reason).Brain._repairFullTextIndexcounts every row of the file: it checks the file-wide FTS5 index against its content table.Seen, not changed here:
sqliteexport runsVACUUM INTO, a copy of the whole file with every brain in it, asdocs/memory/MEMORY_STORAGE.mddocuments;Brain.exportToSqlite()is the per-brain copy.ObsidianExporter._prefetchRelatedNodesjoinsknowledge_edgesandknowledge_nodeswithoutbrain_id(knowledge tables, used for wikilinks).memory_update,memory_merge, consolidation) runs the adapter's rebuild, anUPDATEof every brain's_tsv; each row's vector comes from its own content, so nothing crosses brains, but the cost is the whole table's.type,scope,scopeId,minStrength,afterandbeforefilters to the full-text candidates only; the vector candidates are fetched by brain anddeletedonly.SqliteImportercopies every brain of the source file into the importing brain.Linked issues
None.
Type of change
How this was verified
CI only.
src/cognition/memory/io/facade/__tests__/Memory.brain-scope.test.tsopens twoMemoryinstances with different brain ids on one SQLite file through@framers/sql-storage-adapterand, withAGENTOS_TEST_POSTGRES_URL(set by the Test & Lint job), on one Postgres database:typefilter);health()counts the brain's own rows;hnswlib-node's native build does not run in CI, so the test replaces its index with an exact nearest-neighbour index with the same methods, written to the index file as JSON; Memory,
HnswSidecar,HnswIndexSidecarand the database are the real code.tools.test.tspins thememory_addid tomt_and a v4 UUID.The test went in first as its own commit: run 38904519073, Test & Lint red on its 11 tests (8 SQLite, 3 Postgres), every other test file green. The fix (f8bf790): run 38962692936, every check green, the 11 tests and
tools.test.tsamong 960 passing test files.Migration notes
None required. An index file written before this change (
brain.hnsw) is not read, since it can hold other brains' vectors; each brain's index is built again from its own traces at its next store with an embedding once it holds 1,000 traces, or at its next import. The oldbrain.hnswandbrain.hnsw.map.jsoncan be deleted. Traces stored throughmemory_addfrom now on have ids of the formmt_<uuid>; ids stored earlier keep theirs.Checklist
!before the colon for a change that breaks users (feat!:orfeat(api)!:).🤖 Generated with Claude Code
Summary by Sourcery
Enforce brain isolation across memory queries, vector indexes, exports, metrics, and tool-generated trace identifiers.
Bug Fixes:
Enhancements:
Documentation:
Tests: