Agent memory (phase 1, step 1): what is built¶
Crate open/crates/oliviadb-memory (AGPL-3.0-only or commercial). Single node, on the OliviaDB
engine (oliviadb-core). Tests: cargo test -p oliviadb-memory; latency:
cargo bench -p oliviadb-memory --bench memory.
Data model¶
Every key starts with the tenant; keys hold only surrogate ids, HMAC pseudonyms and
fixed labels, never personal data (src/key.rs, layout in src/memory.rs).
| record | key | tree | body |
|---|---|---|---|
| entity | tenant/E/eid |
durable | display name sealed under the subject key; operational attributes for row predicates; legal hold |
| alias | tenant/A/HMAC(tenant key, normalized name)/eid |
durable | — |
| claim | tenant/C/eid/attribute/id |
durable | value sealed under the subject key; valid time [valid_from, valid_to); transaction time recorded_ts / superseded_ts; status, source, trust, confidence, support count, evidence, author, visibility, inferred flag |
| attribute version | tenant/H/eid/attribute |
durable | number of decisions on it (compare-and-set) |
| episode | tenant/T/principal/thread/time/id |
durable or session | text sealed under every subject key and the thread key |
| core, policy | tenant/K/principal, tenant/P/name |
durable | core sealed under the principal key; policy text |
| step, pack, utility | tenant/I/step, tenant/X/pack, tenant/U/id |
session | idempotency result; what a pack contained; learned utility |
| weights | tenant/W |
durable | recall weights and their version |
The recall index (BM25 postings, vectors, mention, thread and day lists, per-record
metadata) is stored in the trees next to the records it describes and written in the same
commit (spec memory-index.md; section "Recall index" below). Only the entity tables
(names, aliases, row attributes, restrictions) and per-tenant BM25 statistics are built in
memory at open.
Operations¶
- REMEMBER: idempotent per agent step id (a repeat returns the first result and writes nothing). Entities are found by alias pseudonym or created. Each extracted claim is verified against the episode text (value and entity must appear; inferred claims are allowed with lower trust), then decided: new, reinforce (same value: support
- 1, evidence added), supersede (other value: the old claim is closed at the new
valid_from), dispute (an active claim of higher trust, e.g. a system-of-record value,
stays; the new one is stored as disputed and recalled next to it). The decision and
the write are one compare-and-set on the attribute's version, under the tree's single
writer: 8 threads × 10 conflicting writes on one attribute leave version 80 and exactly
one active claim (test
no_races_on_one_attribute). A durable episode and its claims are one synced commit whose records carry the commit timestamp as transaction time (Db::commit_with). Each call returnswts; RECALL withmin_tsnewer than anything applied fails instead of silently missing writes.assert_factwrites a fact without extraction, withexpected_version. - RECALL: policies first (never truncated; a budget below them is an error), core
memory if it fits a quarter of the budget, then five channels filtered by visibility,
restriction, row predicate and time before ranking (structural: entities named in the
query; BM25; vectors; the thread's recent episodes; one hop through entities named in
facts), reciprocal rank fusion with learned channel weights, score
w1·ln rrf + w2·ln trust + w3·ln conf − w4·ln(1 + age/h) + w5·utility(h: 365 days for facts, 30 for episodes). Level of detail: an entity with three or more candidate facts enters as one digest line (its current facts) when that fits; episodes enter as a summary sentence and are expanded to full text by gain per token while budget remains. Near-duplicates are dropped, refs the agent already has are left out (delta mode). Output: canonical text with stable refs[mN],prefix_hashof the pinned part (stable across calls → prompt cache hits), token count within budget. The pack's composition is stored for feedback and audit. - Time:
valid_atasks what held at a moment (claims by valid time, episodes up to it);known_atasks what memory knew at a transaction time (claims recorded by then and not yet superseded). Claims keep every version, so both work for all history; tree history for other records is kept forhistory_ms(30 days by default). - FEEDBACK: refs the agent used (given, or cited in its answer; a ref counts only if the answer contains it) gain utility (bounded); on failure unused items lose a little; the channels that ranked used items gain weight (bounded, normalized), weights are versioned per tenant.
- CONSOLIDATE: utility decays; old, unused episodes are cooled (body replaced by its summary sentence, ids and evidence links unchanged); contradictions are counted; tree history older than the window is released.
- FORGET: decay (above), retraction (status retracted with reason: kept, never recalled), subject erasure: the subject's key is destroyed first (every sealed copy in logs, tables and backups becomes unreadable, including episodes shared with others), then its claims, aliases, entity record and episodes are deleted and the derived indexes cleaned; claims about others whose only evidence was an erased episode are reported for review. Under legal hold erasure becomes restriction (hidden from agents, kept). Export of everything about a subject (GDPR art. 15/20) and rectification by the subject (art. 16, a superseding claim with source "subject") are calls.
- Durability classes: durable (synced per commit), session (separate tree, no sync per commit: a machine crash may lose the last moments, a process crash nothing), scratch (process memory with a time to live, never written).
Recall index¶
Spec spec/memory-index.md, code src/rindex.rs (formats) and src/diskix.rs (writes,
reads, caches).
- On disk, one commit. Each claim and episode writes its document entry, postings (term
tokens: HMAC under the tenant key, never the term), vector entry (sealed like the record's
text, so destroying a subject key makes it unreadable everywhere), mention, thread and day
entries and a statistics delta in the commit that writes the record. Nothing is rebuilt at
open. Index keys keep a short history (
oliviadb_core::Options::short_history: the tree's history window does not apply to them) and are not in the change journal. - Memory budget.
Config::index_budget_bytes, server settingrecall_index_mb(default 256 MiB): document entries (10 %), posting lists (20 %), mention lists (5 %), utilities (5 %), texts (5 %) and a tenant's vectors when they all fit (55 %; else a search scans them, with the same result). Caches evict by CLOCK (a hit sets a bit, no reordering). The built-in embedder's vectors are not stored: they are computed again from the text when a tenant's vectors are loaded; a model embedder's are stored sealed.GET /v1/admin/statsreportsmemory.index.budget_bytesandresident_bytes. Answers do not depend on the budget. - Writes. A claim decision reads the attribute's active-claim entries, not its history.
Measured in process (
examples/remember_cpu.rs, 20 000 episodes with one claim each, this laptop, 2026-12-03): bytes logged per REMEMBER 6.0 KB against 4.4 KB with the in-memory index; REMEMBER p50 equal (4.1 ms, one log sync each), p99 7.3-8.2 ms against 5.8-7.1 ms (the log syncs share the disk with more flushing); a warm RECALL p50 2.5-2.8 ms against 2.9-3.4 ms, p99 3.7-4.1 ms against 3.7-4.7 ms. - Reads and locks. A call that reads the index holds the index's read lock for its run
and locks each tree for each read; writers take the index's, the durable tree's and the
session tree's write locks in that order: index, durable tree, session tree.
src/lockorder.rschecks the order at every lock as an invariant check, on in every build: a breach panics (it is a bug that could deadlock);tests/lock_stress.rsruns every kind of call at once under a deadlock watchdog, and the HA simulator drives memory across failovers. A commit that changes the index holds the index's write lock, so a call reads one state, the latest. A row predicate given to RECALL may call memory again. - Open (HA): in the HA simulator's asynchronous-mode mix with the deliberate exposure bug, a fact another reader saw was later missing on the serving node in 15 of 400 seeds with the in-memory index and in none with this one; the simulator now checks the exposure itself (a record another principal sees must be held by the standby), which catches the bug in 116 of 160 seeds on this index. Why the after-failover loss became rarer is not explained yet (exposure is as frequent on both; replication timing is the suspect).
- Erasure. The subject's key is destroyed first, then its records and every index entry
of them are deleted in the same commits. Deleted index entries leave the live files at the
next compaction of each level that holds them;
oliviadb-server memory-index purge --dir DIR,POST /v1/admin/memory/index/purgeor"purge": trueon subject erasure flushes and fully compacts both trees at once. Backups keep what they hold until their retention ends. - Upgrade. A store written before the format is refused at open with an error naming
oliviadb-server memory-index build --dir DIR(resumable: 1024 records per commit, the cursor in the marker). Another embedder, masker or analyzer is refused too:memory-index drop, thenbuild. - Tests.
tests/index_model.rs(random histories against the crate as of c111746,model/, a test fixture: same packs, decisions, navigation; reopens; a 64 KiB budget; the build tool on a store that crate wrote),src/diskix.rs(BM25 scores worked by hand, cooling),tests/index_erasure.rs(erasure and purge leave no stored version and no log entry; recalls during writes and erasure),tests/index_budget.rs(five times the budget of episodes: index within the budget, heap in use within budget + cache + memtables + 16 MiB, transients included).
Change stream¶
The durable tree keeps a change journal (oliviadb_core::journal: the keys each commit
changed, written in the same atomic batch, keys only). Memory::changes_as(viewer,
policy, user, from, limit) reads it after a position and gives the claims and episodes
each commit touched, in commit order, as the viewer may see them now (row predicates,
attribute visibility, masks, private records of others, restriction, replication); an
erasure is a delete record with only the id. Whole commits per call. CONSOLIDATE trims the
journal together with the tree history it releases. Network API: GET
/v1/changes?path=MEMORY (docs/network-api.md). Open: the agent-state documents and
session-class records are not streamed; a record shows the present state, not the state
at its commit.
Native aggregates (typed-node trees, oliviadb_core::typednodes) have the same journal:
TypedTree::changes gives each node inserted, replaced or deleted (typed path, data
before and after) after a version. No server hosts native aggregates yet, so there is no
network route for them; decoding their data by a layout is the consumer's step for now.
Keys (crypto-shredding)¶
Master key (key file; the interface takes 32 bytes, an external KMS can supply them) →
KEK per tenant (alias HMAC key), subject, thread and principal, each a file in the key
directory wrapped by the master key, outside the trees and backups → DEK per record,
wrapped by its KEKs as XOR shares (all are needed to open). XChaCha20-Poly1305 with the
record id as associated data; HMAC-SHA-256 for pseudonyms (RustCrypto crates, MIT or
Apache-2.0). Destroying a KEK overwrites and unlinks its file, leaves a tombstone without
key material and syncs the directory; a destroyed key is never recreated. Test
forget_retract_erase_export_and_hold checks that no plaintext reaches any file of the
trees and that an erased subject stays erased after a restart.
Measured¶
Apple M3 Max, internal SSD, macOS 27.2, release build, 5000 episodes per class, each
with one claim (cargo bench -p oliviadb-memory --bench memory), 2026-11-30:
| call | p50 | p99 |
|---|---|---|
| REMEMBER, session episode + 1 durable claim | 4.0 ms | 11.9 ms |
| REMEMBER, durable episode + 1 claim | 4.9 ms | 9.2 ms |
| RECALL, 1000-token budget, 20 000 records | 5.1 ms | 6.6 ms |
REMEMBER is bound by the synced commit of this disk (~4 ms per log sync here; the
design's 0.5–1 ms assumes server NVMe). Group commit: decisions and commits happen under
the tree's writer lock, the log is synced outside it (Db::log_syncer), and a call is
acknowledged once a sync covers its commit; concurrent writers share syncs:
| durable REMEMBER, 2000 calls | throughput | log syncs | calls per sync |
|---|---|---|---|
| 1 writer | 213/s | 2000 | 1.0 |
| 8 concurrent writers | 383/s | 751 | 2.7 |
| 32 concurrent writers | 314/s | 297 | 6.7 |
Above 8 writers the serialized part of a call (decision, sealing, index update) is the limit, not the disk. Readers may see a write up to one sync before its writer is acknowledged (a crash in between loses it, and its writer never got an answer). RECALL is dominated by the exact vector scan and BM25 over all records of the tenant.
Not built yet (honest list)¶
- No language model anywhere: claims must come from the caller (extraction is the agent's job or a later step); "verification against the source" is textual containment; contested decisions are rules (trust), not model judgement; consolidation does not promote episodes into facts or procedures and stores no model-written digests (the digest is assembled from current facts at recall time).
- Without models the embedder is lexical feature hashing (
oliviadb-hash-v1); with the CPU models (oliviadb-mcp --models) it is bge-small-en-v1.5, with an ms-marco-MiniLM-L6 cross-encoder reranking the best 80 candidates (about 1.1 s of CPU per recall;--no-rerankswitches it off; docs/models.md). Time in questions (Config::temporal): the days a question points at ("about two weeks ago", "in March") and the events it compares ("which happened first, A or B") are searched for (docs/benchmarks.md). Vector search is an exact scan, not HNSW (over the cached vectors, or over the sealed vector entries when a tenant's vectors exceed the budget's share: correct but slow). - Entities in episodes are the ones the caller declares; no PII/NER detection yet (step 2), so the mention index (erasure search) covers declared entities only. An episode about several subjects is erased whole when any of them is erased (no skeleton/sub-segment split yet).
- No plans, steps, leases, branches, BLOBs, CTXPACK Merkle audit, memory_eval gate, positional-bias correction in feedback; no KMS/HSM integration or HMAC key rotation.
- Single node: durability classes are trees with and without per-commit sync, not zone and cross-zone quorums.
Agent state (namespaced documents)¶
oliviadb_memory::state (Memory::state), tools state_put, state_append, state_get,
state_delete, state_list, state_namespaces, state_search: what agent frameworks
keep besides facts and episodes (conversation items, graph checkpoints, key-value stores,
documents with vectors). An item is (namespace path, key) → JSON value with a version
(a counter of its writes; compare-and-set, 0 = only if absent), creation and update times and an
optional TTL; private to its principal unless written with tenant visibility. Listing in
key order either way and after a key; append writes under a fresh increasing key;
namespaces under a prefix with suffix and depth; search under a namespace prefix with
filters ($eq, $ne, $gt, $gte, $lt, $lte, $in on fields) and ranking by a
query (BM25 and the embedder, fused) or by a vector given with the items. Values are
sealed under a key per tenant; the search structures are rebuilt in memory at open.
Tests: oliviadb-memory/tests/state.rs. Not built: TTL refresh on read, "as of" reads of
state, subject erasure reaching into state (items are not linked to entities).
Transactions over agent state¶
StateStore::transact(tenant, principal, policy, body) runs body as an optimistic
transaction (oliviadb_core::otx, below) over the principal's and the tenant's items:
StateTx::get, put (with the same options as state_put, compare-and-set included)
and delete. The body may run more than once, so it must be repeatable and do nothing
outside the transaction; its writes commit together once nothing it read has changed;
the search index and the group commit follow the commit. The tool state_update
(REST POST /v1/state/update) is such a transaction with a fixed body: operations on one
document (inc at a JSON pointer, exact for integers; set; remove; merge of
top-level fields), for hot counters and shared tallies that several agents change at
once; it answers the new value, its version, the attempts and whether it went
pessimistic. Plain writes (state_put, state_delete) wait for items a pessimistic
transaction holds (up to 5 s, then a retryable refusal). Tests:
oliviadb-memory/tests/state_tx.rs (eight threads counting one tenant tally, transfers
between documents conserving the total, a failing body writing nothing, the operations),
oliviadb-server/tests/mcp_http.rs (concurrent state_update over REST),
oliviadb-mcp/tests/conformance.rs (its messages against the protocol schema).
The engine (oliviadb_core::otx::TxDb, native API, open source): an attempt reads at a
snapshot (the newest commit when it starts) and records its reads (keys with their
values, scanned ranges with what they held); its writes are buffered. At commit, under
the tree's write lock, the reads are checked against the newest state (a changed value,
a key that appeared or vanished in a scanned range, or a key another transaction has
locked is a conflict) and the writes go in as one batch: serializable (write skew and
phantoms are tested). After TxPolicy::optimistic failed attempts (3) the next attempt
first locks everything the previous one read or wrote (all at once, so pessimistic
transactions do not deadlock each other) and so completes unless it reads something new.
A lock not granted within TxPolicy::lock_timeout (5 s), or no completion within
max_attempts (10), is Error::Busy, retryable. Not for DL/I: programs keep program
isolation and the lock manager (docs/status.md). Tests: oliviadb-core/tests/otx.rs.
Open: what a DL/I program gets when a lock wait times out (status code or abnormal end)
is to be taken from the IMS messages and codes documentation and is not decided; DL/I
waits have no timeout in the engine (the DL/I server oliviadb serve refuses a call after
--lock-wait, retryably). The defaults and their setting per profile are open too.