FastAPI
Brain in a FastAPI service — choosing the sync HTTP tier or the async wire tier, why the sync client blocks the event loop, lifespan and dependency wiring, per-tenant identity with act_as, streaming, and error mapping.
A FastAPI app, a Brain API key, and something to talk to — a local
brain-edge for the HTTP tier, or a Brain server for the wire
tier. If encode and recall are new, read Your first memory
first.
Pick your tier first
pip install brain-db-sdkOne package, two clients, and the choice is not cosmetic — it decides your concurrency model, which verbs you can reach, and how your service is deployed.
The short rule:
- Reaching a hosted Brain, or a self-hosted edge?
BrainHttpClient. You do not get a choice — the wire port is not exposed. - Running Brain yourself, on a network you control, and want pooled-key
multi-tenancy or transactions?
AsyncBrainClient. This is the tier that makes a Python service the right place to put the part of your system that Next.js and other serverless runtimes cannot host.
One tier per program, not per call
Mixing them is the single most expensive mistake available here. Reaching
for the synchronous client inside a coroutine blocks the loop; wrapping the
async one in asyncio.run from synchronous code opens and tears down a loop
per call, and raises outright if a loop is already running — which, inside a
FastAPI handler, it always is.
The event-loop trap
This deserves its own section because it is the thing FastAPI developers get wrong, it does not raise, and the symptom is "our service is slow under load" rather than anything that points at the cause.
BrainHttpClient has no async def anywhere in it. Not one method. It is
built on urllib.request, which blocks the calling thread until the response
arrives.
Two ways that goes wrong, and they look nothing alike:
# WRONG — TypeError at runtime.
@app.post("/remember")
async def remember(note: Note):
result = await brain.encode(note.text) # encode() returns EncodeResult,
return {"id": result.memory_id} # not an awaitable.That one is merciful: object EncodeResult can't be used in 'await' expression fires on the first request and you fix it in a minute.
# WORSE — correct Python, and it stops your entire service.
@app.post("/remember")
async def remember(note: Note):
result = brain.encode(note.text) # blocks the event loop for the
return {"id": result.memory_id} # whole round trip.This one runs. It returns the right answer. And for the duration of that HTTP call — tens of milliseconds normally, up to the 30-second client timeout when Brain is slow — no other request in the process makes progress. Not the health check, not a request that never touches Brain. One worker, one loop, one blocked thread.
It is worse than it first looks, because the retry policy sleeps. A 503 from
Brain triggers time.sleep(0.1), then time.sleep(0.2): the loop is frozen
for the backoff too, on top of three full round trips.
Three shapes that are correct
A sync def routesimplestDeclare the handler def, not async def. FastAPI runs sync handlers in
a worker thread automatically, so the blocking call blocks that thread and
not the loop. Nothing else changes.
run_in_threadpoolmixed handlerFor an async def handler that has other awaits in it. Starlette's
run_in_threadpool puts the one blocking call on the same thread pool.
AsyncBrainClientno threads at allChange tiers. Every verb is a coroutine and nothing blocks.
@app.post("/remember")
def remember(note: Note) -> RememberOut:
"""`def`, not `async def` — FastAPI threadpools this for us."""
result = brain.encode(note.text)
return RememberOut(id=result.memory_id, deduplicated=result.was_deduplicated)from starlette.concurrency import run_in_threadpool
@app.post("/chat")
async def chat(turn: Turn) -> ChatOut:
answer = await run_in_threadpool(brain.recall, turn.message, max_results=6)
reply = await call_model(turn.message, answer) # genuinely async
return ChatOut(reply=reply)asyncio.to_thread works identically and is standard-library; the difference
is that run_in_threadpool uses the same AnyIO limiter FastAPI uses for its
own sync handlers, so your Brain calls and your sync routes contend for one
budget you can reason about rather than two.
BrainHttpClient is safe to share across threads
It holds a base URL, a key, a timeout and a retry policy — immutable configuration and no connection state — so one instance serves every worker thread. The flip side: there is no connection pool either. Every call opens a fresh TCP connection and, against HTTPS, a fresh TLS handshake. On a hot path against a remote edge that handshake can cost more than the query.
Wiring the client
The HTTP tier
Nothing is awaited, so construction can happen at import. Prefer lifespan anyway — it gives you one place to fail loudly on a missing variable:
import os
from contextlib import asynccontextmanager
from brain_db_sdk.http import BrainHttpClient, HttpRetryPolicy
from fastapi import FastAPI
brain: BrainHttpClient | None = None
@asynccontextmanager
async def lifespan(app: FastAPI):
global brain
key = os.environ["BRAIN_API_KEY"] # fail at boot, not at 3am
brain = BrainHttpClient(
key,
base_url=os.environ["BRAIN_BASE_URL"],
timeout=10.0,
retry=HttpRetryPolicy(max_attempts=3, max_delay=2.0),
)
yield
brain = None
app = FastAPI(lifespan=lifespan)Two defaults worth overriding. base_url defaults to
http://127.0.0.1:8080, which is right for a local edge and silently wrong in
production — an unset variable does not fail, it points at localhost. And
timeout defaults to 30 seconds, which is longer than most upstream gateways
will wait; set it below whatever is in front of you so your error path runs
rather than theirs.
The base URL is validated at construction
urlopen honours every scheme urllib supports, so a file:// base URL
would turn an SDK call into a local file read. The client rejects anything
that is not http or https when you build it, where a misconfigured
environment variable enters — not at the call site, where it would be a far
more interesting bug.
The wire tier
Here the lifespan is not a preference. AsyncBrainClient.connect is a
coroutine, so it cannot run at import; and the connection it returns belongs
to the event loop it was opened on.
from contextlib import asynccontextmanager
from brain_db_sdk import Auth
from brain_db_sdk.aio import AsyncBrainClient
from fastapi import FastAPI
brain: AsyncBrainClient | None = None
@asynccontextmanager
async def lifespan(app: FastAPI):
global brain
brain = await AsyncBrainClient.connect(
os.environ["BRAIN_HOST"],
int(os.environ.get("BRAIN_PORT", "9090")),
Auth.token(os.environ["BRAIN_API_KEY"].encode()),
)
yield
await brain.aclose()A connection belongs to one loop and one process
The binding is checked on every call rather than left to chance, because a connection driven from a second loop does not raise — it waits forever on a future nothing will complete. Two consequences for how you deploy:
- Never connect before a fork.
uvicorn --workers 4forks after startup; a connection opened in the parent is shared by four children and all four write into the same socket. Opening it insidelifespanis what makes it per-worker, which is correct — four workers, four connections. - Never connect inside a
TestClientblock and reuse it outside. EachTestClientcontext runs its own loop.
Auth.token takes bytes, not a string. Passing a str is a type error
the moment the frame is built, which is better than the alternative but still
catches people: .encode() it.
Dependencies and identity
Brain takes its scope from the credential. A key resolves server-side to a
(namespace, space) pair, and no HTTP route accepts a scope argument —
there is no user id to pass. That is the security model: a client cannot read
another tenant's memories by changing a parameter, because the parameter does
not exist.
The standard wiring for a single-scope service:
from typing import Annotated
from fastapi import Depends, HTTPException
def get_brain() -> BrainHttpClient:
if brain is None:
raise HTTPException(503, "brain client not initialised")
return brain
Brain = Annotated[BrainHttpClient, Depends(get_brain)]@app.post("/remember")
def remember(note: Note, brain: Brain) -> RememberOut:
...Multi-tenant: the two shapes
One key per tenant. Resolve the caller, look up their key, build a client:
def get_tenant_brain(claims: Annotated[dict, Depends(verify_jwt)]) -> BrainHttpClient:
return BrainHttpClient(key_store.for_tenant(claims["org"]), base_url=BASE_URL)Isolation is enforced by the server rather than by your code, which is the strongest version. The cost is a key to mint, store and rotate per tenant.
One pooled key with act_as. This is the shape most services want, and it
is the reason to run the wire tier:
from brain_db_sdk import RecallBuilder
@app.post("/chat")
async def chat(turn: Turn, claims: Annotated[dict, Depends(verify_jwt)]) -> ChatOut:
request = (
RecallBuilder(turn.message)
.act_as(claims["org"], claims["sub"])
.limit(6)
.build()
)
answer = await brain.recall(request)
...One connection, one credential, and every request stamped with the identity it
runs as. The server honours act_as only if the connection's principal holds
the can_act_as grant and the target namespace is inside its may_act
allowlist; otherwise it is hard-rejected rather than quietly narrowed.
act_as is wire-tier only
There is no HTTP equivalent. The edge takes its space from the credential
and accepts no selector on any route, so this pattern needs
AsyncBrainClient and a reachable wire port. If you are on the HTTP tier,
use one key per tenant.
act_as takes an opaque selector string you choose — a tenant slug, a
user id, whatever is stable in your system. The server derives the storage
id from it. Do not generate a UUID and pass that as if it were the space's
identifier: clients cannot forge a space id, and that is the point.
Identity from a JWT walks the whole flow.
Reading
@app.post("/context")
def context(q: Query, brain: Brain) -> ContextOut:
answer = brain.recall(q.text, max_results=6)
if answer.answer_kind == "none":
return ContextOut(known=False, memories=[])
return ContextOut(
known=True,
memories=[Snippet(text=m.text, id=m.memory_id) for m in answer.memories],
)recall returns a membership verdict — "single", "many" or "none" — and
"none" is a real answer meaning nothing stored answers this cue, not an
empty page of results. Modelling it as a distinct state rather than an empty
list is the difference between an agent that can say "I don't know" and one
that cannot.
The HTTP edge sends lowercase — "single" / "many" / "none". The wire
protocol sends the variant name — "Single" / "Many" / "None". A
comparison written for one tier silently never matches on the other, so
porting a handler from BrainHttpClient to AsyncBrainClient turns every
empty answer into a non-empty one that renders zero items.
On the wire tier, RecallAnswer.is_empty is spelling-independent and worth
preferring to a string comparison.
Tuning the read
max_resultsintoptional1..=1000, server-enforced. What it bounds is prompt budget, not quality:
Brain has already decided which memories answer the cue. Six to ten for a
chat turn.
subjectstroptionalNarrow to a known entity, when the endpoint already knows what it is about rather than hoping the cue carries it.
scope"space" | "namespace"optional"space" by default. "namespace" fans out across every space in the
namespace and merges the hits — a deliberate cross-tenant read, and almost
never what a per-user endpoint wants. Case-insensitive, and any other
value is rejected rather than quietly narrowed.
include_tracebooloptionalBrain's read-pipeline trace. See the debugging section.
There is deliberately no score threshold. Do not filter hits by
similarity_score yourself — the verdict already encodes that judgement, and
re-thresholding on top of it is how a service discards the one memory that
answered the question.
Do not return a MemoryHit directly
It carries salience and confidence, which are internal retrieval signals
rather than things to publish on your API. Map to your own Pydantic model at
the boundary, as the example above does — you want your response schema to
be yours, not Brain's, so a change on either side does not propagate through
your contract.
Writing
@app.post("/remember")
def remember(note: Note, brain: Brain) -> RememberOut:
result = brain.encode(note.text, session=note.conversation_id)
return RememberOut(id=result.memory_id, deduplicated=result.was_deduplicated)encode is retried by the SDK with a stable server-side request id, so an
ambiguous failure — the write landed, the response was lost — replays the
original result rather than storing twice. Brain also deduplicates
byte-identical text per (space, session), which is what was_deduplicated
reports. Between the two, a double-submitted request produces one memory
without you managing idempotency keys.
Sessions are ids you choose. A session id is a 64-bit integer, so your own
conversation id can be the session id directly, with no mapping table. You do
not need to create it first — a space or session is created lazily by the
first write that names one. create_session exists for attaching a title or
provisioning ahead of a write, and is idempotent on the id.
Writing after the response
A memory write is usually not on the caller's critical path. BackgroundTasks
runs it once the response is sent:
from fastapi import BackgroundTasks
@app.post("/chat")
def chat(turn: Turn, bg: BackgroundTasks, brain: Brain) -> ChatOut:
answer = brain.recall(turn.message, max_results=6)
reply = build_reply(turn.message, answer)
if is_durable(turn.message):
bg.add_task(brain.encode, turn.message, session=turn.conversation_id)
return ChatOut(reply=reply)Two things decide whether this is a good idea or a silent data-loss bug.
The order is recall, then write. Encoding the user's message first and recalling with that same message as the cue means the top hit is the sentence you just stored, echoed back. It looks like retrieval working perfectly, which is exactly what makes it hard to spot.
A background task's exception reaches nobody. The response is already sent. Wrap the call so the failure is at least logged, and count attempts against successes somewhere — a write path that silently stopped working is invisible by construction.
What to write is a product decision
The most common mistake here is not a bug: it is calling encode on every
turn with whatever was in the request body, and finding a month later that the
space is full of conversation-shaped fragments with no clean subject.
- Write claims, not dialogue. "Priya's standup is at 9:30" retrieves. "ok sounds good, let's do 9:30 then" does not.
- Never write the model's own output back. A reply is not an observation about the user; store it and the next recall is fed the model's own words, so a wrong answer becomes a "fact" the next turn repeats.
What to write is the long version, and it is worth reading before the write path ships.
Streaming
Brain's change feed arrives as Server-Sent Events. On the HTTP tier the subscription is a synchronous iterator, so it is driven from a thread:
from brain_db_sdk.http.types import SubscriptionEvent
from fastapi.responses import StreamingResponse
@app.get("/feed")
def feed(brain: Brain) -> StreamingResponse:
def events():
with brain.subscribe() as subscription:
for item in subscription:
if not isinstance(item, SubscriptionEvent):
break # the terminal close
yield f"id: {item.lsn}\ndata: {item.text}\n\n"
return StreamingResponse(
events(),
media_type="text/event-stream",
headers={"cache-control": "no-cache, no-transform"},
)StreamingResponse detects that events() is a synchronous generator and
drives it through the thread pool itself, so there is nothing to wrap. On the
wire tier the subscription is an async iterator and no thread is involved at
all.
TypeScript hands you a tagged item — { kind: "event", event } or
{ kind: "closed", closed } — so the idiomatic check there is
item.kind === "event". Python hands you a plain union of
SubscriptionEvent | SubscriptionClosed, so the check is isinstance, and
the fields are on the item directly: item.lsn, not item.event.lsn.
Porting the TypeScript form across is a silent no-op, not an error:
SubscriptionEvent has a kind attribute — it is the memory kind, an
int — so item.kind != "event" is true for every event and the loop
skips all of them. You get an empty stream and no exception.
What to know either way:
subscribeis not retried and carries no timeout. Both deliberate: a subscription is long-lived by definition, so a deadline would kill it, and a retry would reopen the feed at its original position and re-deliver everything already seen.- Resume with
from_lsn. Every event carries anlsn, and the subscription remembers the last one aslast_event_id. Pass it back on reconnect and you resume exactly rather than replaying or skipping. - Closing unsubscribes. The edge tears the Brain-side subscription down
when the response closes, so the
withblock is the whole teardown, including on an exception. no-transformis not optional. A proxy that buffers turns a live feed into a stream that arrives all at once, minutes late.- Check for disconnects. A generator that never yields again holds a
worker thread forever.
await request.is_disconnected()on the async tier, or a bounded read on the sync one.
Errors
The HTTP client raises one exception type:
class BrainHttpError(Exception):
status: int # HTTP status, or 0 for a transport failure
code: str # the edge's stable code, or "transport"
message: str
field_errors: tuple[FieldError, ...]
retry_after: float | None # seconds, when the server sent a hintBranch on code, never on message — the code is the stable handle, the
message is prose. One exception handler turns the whole taxonomy into your own
API's envelope:
from brain_db_sdk.http import BrainHttpError
from fastapi.responses import JSONResponse
RETRYABLE = {0, 429, 503}
@app.exception_handler(BrainHttpError)
async def brain_error(request: Request, err: BrainHttpError) -> JSONResponse:
logger.warning("brain %s %s: %s", err.status, err.code, err.message)
if err.code == "llm_credential.missing":
# A 409, not a 503, precisely because retrying will never fix it:
# a human has to register a provider key for this namespace.
return JSONResponse(status_code=503, content={"error": "memory_unconfigured"})
if err.status in RETRYABLE:
headers = {"retry-after": str(int(err.retry_after))} if err.retry_after else {}
return JSONResponse(503, {"error": "memory_unavailable"}, headers=headers)
return JSONResponse(500, {"error": "memory_error"})The client already retries: three attempts, 0.1 s base backoff doubling to a
2 s cap, on transport failures, 429 and 503, honouring a server
Retry-After when one is sent. Wrapping a call in your own three-attempt
loop gives you nine attempts and a worst case in the tens of seconds — while
holding a worker thread the whole time. Tune the policy instead, and reach
for HttpRetryPolicy.none() where you would rather fail fast.
Which verbs retry is not uniform, and the split is principled: 43 verbs retry, and the 14 that do not are the ones that create state, where a replay could produce a second thing rather than the same thing again.
| Single-shot | Why |
|---|---|
link, create_entity, create_statement, create_relation | A replay can create a duplicate |
resolve_entity | It can create |
upload_schema, replace_schema, drop_schema | Schema changes are not replayable |
merge_entities, unmerge_entity | The second call operates on a different graph |
supersede_statement, supersede_relation | Supersession chains on itself |
put_llm_credential | A credential write |
subscribe | A retry would replay the feed from the start |
Everything else — including encode, recall, forget and every read — is
retried for you.
Degrade, do not fail
Most memory calls are an enhancement, not a precondition. If recall fails,
an agent that answers without context beats a 500. Decide that per call
site: a chat turn should degrade, while an endpoint whose entire job is
"tell me what you know about this customer" should not pretend it knows
nothing.
Putting it together
The whole integration, as one service. Nothing here is new — it is the pieces above in the order they run.
import os
from contextlib import asynccontextmanager
from typing import Annotated
from brain_db_sdk.http import BrainHttpClient, BrainHttpError, HttpRetryPolicy
from fastapi import BackgroundTasks, Depends, FastAPI, HTTPException
from pydantic import BaseModel
brain: BrainHttpClient | None = None
@asynccontextmanager
async def lifespan(app: FastAPI):
global brain
brain = BrainHttpClient(
os.environ["BRAIN_API_KEY"],
base_url=os.environ["BRAIN_BASE_URL"],
timeout=10.0,
retry=HttpRetryPolicy(max_attempts=3, max_delay=2.0),
)
yield
brain = None
app = FastAPI(lifespan=lifespan)
def get_brain() -> BrainHttpClient:
if brain is None:
raise HTTPException(503, "brain client not initialised")
return brain
Brain = Annotated[BrainHttpClient, Depends(get_brain)]
class Turn(BaseModel):
message: str
conversation_id: int
class ChatOut(BaseModel):
reply: str
grounded: bool
@app.post("/chat")
def chat(turn: Turn, bg: BackgroundTasks, brain: Brain) -> ChatOut:
"""`def`, so the blocking client runs on a worker thread.
Recall first, then reply, then write — in that order. Recalling with a
cue you have just encoded returns your own sentence as the top hit.
"""
try:
answer = brain.recall(turn.message, max_results=6)
context = [m.text for m in answer.memories]
grounded = answer.answer_kind != "none"
except BrainHttpError as err:
# A chat turn degrades rather than fails: an answer without memory
# beats a 503. An endpoint whose whole job is memory would re-raise.
logger.warning("recall failed, answering ungrounded: %s", err.code)
context, grounded = [], False
reply = build_reply(turn.message, context)
if is_durable(turn.message):
bg.add_task(remember, brain, turn)
return ChatOut(reply=reply, grounded=grounded)
def remember(brain: BrainHttpClient, turn: Turn) -> None:
"""Background: nothing is listening, so the failure must be logged."""
try:
brain.encode(turn.message, session=turn.conversation_id)
except BrainHttpError as err:
logger.error("encode failed after response: %s %s", err.status, err.code)is_durable is the part no framework gives you and the part that decides
whether this service is useful in six months. It is a product decision, not an
integration detail — see What to write.
Health and readiness
Two calls, and they answer different questions, so do not collapse them into one probe.
@app.get("/healthz")
def healthz() -> dict[str, bool]:
"""Liveness: is this process up? Never touches Brain."""
return {"ok": True}
@app.get("/readyz")
def readyz(brain: Brain) -> dict[str, object]:
"""Readiness: can we actually serve? Touches Brain, cheaply."""
me = brain.whoami()
caps = brain.capabilities()
return {
"namespace": me.namespace,
"space_id": me.space_id,
"can_encode": me.permissions.can_encode,
"can_recall": me.permissions.can_recall,
"llm_extractor": caps.llm_extractor,
}A liveness probe that calls Brain restarts your service every time Brain is briefly unavailable — turning a degraded dependency into an outage of your own, at the exact moment the dependency is under load. Liveness asks "is this process wedged"; readiness asks "should traffic come here". Only the second one has any business making a network call.
capabilities is also where you find out what the server will actually do.
llm_extractor reports whether the namespace has a provider credential the
extraction pipeline can use: a namespace without one still writes, and still
extracts entities with the pattern and classifier tiers, but produces no
statements. A service that depends on the typed graph and never checks this
looks like it has a retrieval bug.
Concurrency and sizing
This is where the tier choice shows up in your capacity numbers.
On the HTTP tier, every Brain call occupies a thread for its whole round
trip. FastAPI runs sync handlers on AnyIO's default thread limiter, which allows
40 concurrent threads (anyio.to_thread.current_default_thread_limiter()
reports total_tokens = 40). Forty in-flight Brain calls is therefore
your ceiling per worker, regardless of how many connections uvicorn is
holding — the forty-first request waits for a thread, not for Brain. Against a
remote edge at 50 ms per call, that is roughly 800 requests/second per worker
if the handler does nothing else, and proportionally less if it does. Raise
the limiter, add workers, or move to the async tier.
On the wire tier, requests multiplex over one connection and suspend a task rather than a thread, so one connection carries thousands of concurrent requests on a single OS thread. The ceiling becomes Brain's, not your process's.
uvicorn --workers 8 against the wire tier opens eight connections, each
with its own multiplexer. That is correct and necessary — but if you sized
Brain's connection limits for one service instance, eight workers across
three replicas is 24 connections, not three. Count workers, not pods.
When an answer looks wrong
Two calls answer most of "why did it say that".
whoami answers "whose memories am I reading?" It returns the namespace
and space id the key resolved to, plus its permission bits. A key pointing at
the wrong space gives you a service that works perfectly and serves the wrong
data — which presents as a retrieval problem and is not one.
include_trace answers "what did the read pipeline do?" Which retrievers
ran, how their ranks were fused, what the filter chain dropped, what the
reranker moved — enough to distinguish "the memory is not there" from "the
memory is there and ranked tenth".
answer = brain.recall(cue, include_trace=True)
# answer.trace is a JSON *string*, not a dict.The trace does not scale with max_results
It reports every candidate each lane considered, so it grows with the size of the space rather than with the number of hits you asked for. A three-hit recall over roughly 700 memories measured 121 KB. It costs nothing when off — the server only builds it when asked — so switch it on for one request, never for an endpoint.
It comes back as a string deliberately: its ids are 128-bit integers that a JSON number would round. Parse it with a big-integer-safe reader.
Testing
The sync client has no injection seam for fetch, so stub at the dependency:
from unittest.mock import MagicMock
from brain_db_sdk.http.types import RecallResult
from app.deps import get_brain
from app.main import app
@pytest.fixture
def no_memories():
fake = MagicMock()
fake.recall.return_value = RecallResult(answer_kind="none", memories=[])
app.dependency_overrides[get_brain] = lambda: fake
yield fake
app.dependency_overrides.clear()Two details. Build the real RecallResult rather than a bare MagicMock for
the return value — a mock answers .answer_kind with another mock, which is
truthy, so a test of the empty path passes without exercising it. And use
answer_kind="none" in lowercase: that is what the HTTP tier returns, and a
test written against the wire tier's "None" tests a string your code will
never see.
For an integration test against a real edge, set
retry=HttpRetryPolicy.none() so a deliberate 503 does not make the suite
sleep through the backoff.
Production checklist
One tier, chosen deliberately. Grep for BrainHttpClient and
AsyncBrainClient and expect to find one.
No blocking call in an async def. Every BrainHttpClient call is in a
def handler, inside run_in_threadpool, or in a background task.
The wire connection is opened in lifespan, never at import and never
before a fork.
BRAIN_BASE_URL set in every environment. Unset does not fail — it points
at localhost.
Client timeout below your gateway's. Otherwise their error page wins over your error handler.
One BrainHttpError handler, mapping codes to your envelope, with
llm_credential.missing surfaced to operators rather than retried.
Writes are gated. Something decides what is worth remembering, and it is not "every request".
Was this page helpful?
Next.js
Brain in a Next.js App Router app — where the client lives, why the Edge runtime cannot load it, identity from the session, recall in a Server Component, writes in Server Actions and after(), and streaming the change feed.
LangChain
Where Brain fits in LangChain's memory model — the checkpointer it does not replace, the long-term store it does, three wiring options with working code, and the write policy no framework will give you.