Brain Docs

Reference

ConceptsArchitectureWrite pipelineEntitiesIdentity by keyNamespaces, spaces and sessionsPolicies
Brain/Docs
✦ ASKBrain on GitHubDashboard
ConceptsWrite pipeline

Write pipeline

How encode works — a synchronous fast path (validate → embed → reserve → persist) split from asynchronous derivation by the WAL-fsync acknowledgement barrier.

PURPOSE
The write pipeline turns text into a durable, searchable memory and then derives a typed graph from it. It is two phases split by the acknowledgement barrier (the WAL fsync): a synchronous fast path the client waits on, and asynchronous derivation that runs after the ack. Read this when you want to understand why an encode returned in single-digit milliseconds but the entity graph showed up a moment later.

encode is Brain's one write verb. It does not run an N-stage LLM pipeline before returning — it acks as soon as the write is durable, then derives everything else in the background. For the request/response shapes and the SDK method see encode.

SYNCHRONOUS (CLIENT WAITS)06 STAGESASYNCHRONOUS (POST-ACK WORKERS)04 STAGESpost-ack hand-off (by LSN)textvalidateembedreservepersist (WAL fsync = ack)returnauto_edgetemporal_edgeextractortyped graph + text index + HyPE
Two phases split by the WAL-fsync ack barrier. The client waits only for validate → embed → reserve → persist; edges, the typed graph, the text index, and HyPE run after the response returns.

The synchronous fast path

Four phases run before the response is sent. The handler blocks on them; nothing downstream can make the client wait.

PhaseWhat it does
validateInput validation + router policy (kind, salience); idempotency peek by RequestId.
embedBGE-small → the 384-dim vector — the memory's semantic key.
reserveAllocates the arena slot and mints the version-stamped MemoryId.
persistWrites the vector to the arena, fsyncs the WAL (the ack barrier), commits the redb metadata row, and inserts the memory's HNSW point.

The WAL fsync in persist is the acknowledgement barrier: encode never returns success until that record is durable (core invariant — WAL before ack). The response carries the MemoryId, was_deduplicated, the server-stamped salience, auto_edges_added, persisted_at, and the embedding model fingerprint. Typical latency is p50 ~5–10 ms, p99 ~25 ms — dominated by the embedder, dropping to ~2–3 ms on an embedding-cache hit.

The ordering inside persist is load-bearing rather than incidental: the HNSW point goes in before the metadata commit and before the ack, which is what makes a fresh memory semantically searchable the instant the call returns. The WAL fsync is the barrier everything else is defined relative to — before it, nothing is promised; after it, the memory survives a crash whether or not the response ever reached you.

No LLM on the ack path

There is no extraction, no dedupe LLM judge, and no reference-resolution call between the request and the ack. The only model on the fast path is the local BGE-small embedder. Everything that needs the LLM runs after the response returns.

What you actually send

The request surface is small, and three of the fields change behaviour in ways worth knowing before you wire it up:

FieldDefaultNotes
textrequiredUTF-8, 1 byte to ~1 MB. Stored in full; only the embedding truncates past the model's window
sessionthe space's defaultA name or an explicit id. An unknown name creates the session
kindEpisodicOr Semantic. Consolidated is worker-only
metadatanoneA few KB of opaque key-values. Stored verbatim, not indexed
edgesnoneUp to 64 (target, kind, weight) triples
request_idrequiredIdempotency key — a retry returns the original response
occurred_atNoneEvent time, distinct from the server's write time

Long text embeds short. Past roughly 2,000 characters the embedder truncates, and the vector reflects only the prefix. The full text is still stored and still returned — but the part past the cutoff contributes nothing to where the memory sits in similarity space, so it will not be found by a cue that matches only the tail.

This is the argument for one claim per memory restated as a mechanism: a long document encoded whole is semantically indexed by its opening paragraph.

metadata is a blob, not an index

The metadata map is stored and returned verbatim and nothing queries it — there is no metadata filter on recall. Structured attributes you want to filter or traverse by belong on entities and statements, which the typed graph queries directly. If you are putting a field in metadata hoping to search it later, that is the signal you want a predicate instead.

Content deduplication

Text encode deduplicates by content as an always-on DB policy, not a client flag. Before reserving a slot, Brain consults a per-(shard, space, session) fingerprint index keyed on BLAKE3(text). On a hit it returns the existing MemoryId — no new slot, no WAL record, no HNSW node — and sets was_deduplicated = true. Re-saving byte-identical text under the same identity and session yields one memory, never a pile of identical rows.

This is distinct from RequestId idempotency, which dedupes exact replays by request identity. Fingerprint dedup dedupes by content identity. Genuine near-duplicates (paraphrases, the same fact re-stated) are not collapsed here — they're reconciled later by the consolidation worker. Only the direct-vector op keeps an explicit opt-in deduplicate flag, because a caller supplying raw vectors owns that decision.

The asynchronous derivation

After the ack, per-shard workers derive everything else. Each stage is observable live over SUBSCRIBE, keyed by the write's LSN. Three of them are first-class stages that emit completion events:

StageWhat it doesOutput
auto_edgeHNSW k-NN of the new vector → SimilarTo edges.edges
temporal_edgeSession adjacency → FollowedBy edges.edges
extractorThe three-tier pipeline (pattern → classifier → LLM): entities, statements, relations → the typed graph, plus statement-text indexing.the knowledge graph

Two more derivations run asynchronously but aren't first-class stages: the memory_text tantivy upsert (so the lexical retriever can find the memory), and write-time HyPE — hypothetical-question generation whose embeddings widen the recall surface. HyPE and the LLM extractor tier are why a valid LLM provider key is a hard boot requirement.

What is searchable, and when

The ack barrier splits durability from derivation — but it does not split durability from searchability, and that distinction catches people out in both directions.

A fresh memory is semantically searchable immediately. There is no publication lag and nothing to opt into: the HNSW insert runs inside the write submission, before the metadata commit and before the ack. Until a later flush folds it into the main graph, the index serves the new vector out of a pending buffer at exact cosine. So this does what it looks like it does:

encode("first thing",  request_id = 1)
encode("second thing", request_id = 2)
recall("things")                        # sees both

There is no consistency argument to pass and no window in which a just-written memory is invisible to semantic search.

What is not immediate is everything the write derives. The lexical index entry is group-committed; the auto-edge, temporal-edge, extractor and HyPE stages all run post-ack. A recall in the microseconds after an encode will find the memory by vector similarity and may not yet find it by exact term, and the entities extracted from it may not exist yet.

The rule of thumb: if your next read depends on the text, go ahead. If it depends on what the text became, wait for it. Either wait: "derived" on the encode, or a memory_ids-scoped subscription — both described below. Sleeping and hoping is the pattern to avoid, because the drain window varies with the LLM tier's latency.

What can go wrong

Five failure modes, and they do not all fail the same way — which matters, because two of them leave you with a memory you might not expect:

FailureWhat happenedMemory created?
EmbeddingFailedInvalid UTF-8, text too long, or the embedder is unavailableNo
QuotaExceededThe space is over its memory or session allowanceNo
ContextLimitReachedThe session hit its configured memory limitNo
TooManyEdgesMore than 64 edges on one encodeNo — split the call
InvalidEdgeAn edge names a missing target or an invalid kindYes — the memory lands, the bad edge is logged and skipped

That last row is the one to handle deliberately. A partially-edged encode reports success, and the response's per-edge results tell you which edges were actually created. Treating the call as all-or-nothing will silently lose edges you believed you wrote.

Two kinds you can write, one you cannot

A client may encode Episodic or Semantic memories. Consolidated is worker-only — it is the output of the consolidation worker, and asking for it returns InvalidRequest. If you want to write a distilled, durable claim yourself, that is Semantic.

Ownership: one space, one session

A memory belongs to exactly one space and exactly one session, and both are decided at write time.

The space is a hard wall. Cross-space relationships are not merely discouraged — they are inexpressible. There is no edge, relation or statement that spans two spaces, so a memory cannot be shared between them. If one piece of text matters to two agents, each encodes its own copy.

That is deliberate rather than a gap. Shared mutable memory across agents has genuinely hard semantics — who may update it, who may forget it, what the other sees when one does — and the answer here is to not have the question.

Sessions are softer. Edges may span sessions freely within one space, so a session is a grouping for dedup, novelty and consolidation rather than another wall. And a session is created on first use: encoding into a session name that doesn't exist creates it, so there is no separate setup step before the first write.

Observing a write

Because derivation is asynchronous, Brain gives you three ways to watch it — the write itself is unchanged whether or not anyone is looking.

  • wait: "ack" (the default) — return the instant the WAL is durable. The response carries the LSN and the set of pending stages; the graph fills in behind it.
  • wait: "derived" — block until the async stages settle (bounded by the shard's drain window), then return a full EncodeTrace: the per-stage timeline and the concrete artifact each stage produced (the embedding vector, the stored record, analyzed text-index terms, HyPE questions, and the entities / statements / relations graph). A stalled worker can't hang the call — stragglers are recorded as Timeout and still land in MEMORY_INSPECT.
  • SUBSCRIBE — stream StageCompleted events for the LSN as they happen, without blocking the encode.

The same per-stage artifact bundle is persisted per memory in redb, so any memory — not just a fresh write — can be inspected later with MEMORY_INSPECT. Sync fields (vector, record, keyword terms) are present the instant the write acks; the graph and HyPE fields fill in as the workers settle.

wait for writes, trace for reads

A write's completion timing and its observability payload are one decision — the only reason to wait for derivation is to observe it — so writes carry a single wait enum. A read is fully synchronous with nothing to wait for, so recall / plan / reason carry a pure trace: bool toggle instead. No op carries both.

Durability and crash safety

encode is a single-write commit. After it succeeds the memory exists, every valid edge exists, and the metadata is current. If it fails, none of those exist — partial state is never visible to another client, so there is no "half-encoded memory" state to defend against in your code.

If Brain crashes between the WAL fsync and the network ack, the memory is already durable — on recovery the WAL is replayed and the memory becomes fully visible. The client may see a network error; retrying with the same RequestId returns the cached response. The caller never sees a half-written memory: encode is a single atomic commit, and partial state is never visible to other clients.

Latency budget

Rough p50 numbers, single-shard:

Phasep50
validate< 1 ms
embed2–8 ms (BGE-small, local; cache hit ~0)
reserve< 1 ms
persist (incl. WAL fsync)2–15 ms
synchronous total (the ack)~5–25 ms
async derivation (post-ack)100 ms – seconds (LLM-bound), off the response path

Batched encodes push throughput to ~10K/sec/shard; per-encode latency rises slightly due to batching delay.

Two things fall out of that table. The embedder dominates, so an embedding cache hit — roughly one cue in ten in steady state — collapses the whole synchronous path to 2–3 ms. And the async column has no ceiling you control: it is LLM-bound, which is exactly why it sits off the response path rather than in front of the ack.

Throughput and latency pull in opposite directions here. Batching pushes a shard toward ~10K encodes/sec, but a batch has to fill or time out before it runs — so per-encode latency rises by the batching delay. A chat-turn-shaped workload wants the unbatched path; a bulk import wants the batched one. Picking one setting for both gives you the worse half of each.

The ack path is bounded and LLM-free by design. If you need the typed graph before you proceed, use wait: "derived" — but understand you are then paying for the LLM round trip on that call. For steady-state throughput, default to wait: "ack" and consume the graph on the next read.

See also
Read pipeline

The three retrievers, RRF fusion, and the membership band.

Supersession and provenance

How new writes supersede or contradict existing statements.

Entities

What the extractor stage produces — the entity graph.

encode

The encode request and response shapes.

Was this page helpful?

Architecture

Brain is one Rust binary with a strict one-way crate graph — an mmap arena, a WAL, redb, HNSW, tantivy, and bundled models, sharded thread-per-core. No external database.

Entities

The entity graph backing Brain — canonical nouns with a stable EntityId, resolved per tenant, that statements are about and relations connect.

On this page

The synchronous fast pathWhat you actually sendContent deduplicationThe asynchronous derivationWhat is searchable, and whenWhat can go wrongOwnership: one space, one sessionObserving a writeDurability and crash safetyLatency budget
Suggest an editOpen in Playground