The memory of record for agents that act.
CockroachDB × AWS — Build with Agentic Memory
Your agent decides to refund a customer. It calls the payment API. It writes "refunded €42" to its vector store.
Those are two writes. They are not atomic. There is a window — small, never zero — where one lands and the other does not:
- API succeeds, memory write fails → the agent has refunded the customer and has no memory of it. It will refund again.
- Memory write succeeds, API fails → the agent believes it refunded someone it didn't. The customer escalates and the agent argues with them.
At a thousand decisions a day, that window is a weekly incident. The industry's answer is a reconciliation job — a second system whose entire purpose is to find the places where the first system lied.
Now run two agents. A webhook fires twice; a queue redelivers; a support agent
and a fraud agent both open the same dispute. Both read state = open. Both
decide, correctly, that a refund is owed. Both act.
Both agents are correct. The customer is paid twice.
You cannot fix this in application code alone. "Check the state first" is not a fix — both agents check before either writes. It narrows the window; it never closes it. What you need is an agreement between two transactions about the order they happened in, and that is a database's job.
So ENGRAM gives it to the database.
$ python scripts/demo_race.py --agents 8
merchant Bäckerei Krantz GmbH (jurisdiction=eu)
dispute ORD-88213 — EUR 42.00 duplicate charge, state=open
agents 8 racing, all correct, all convinced a refund is owed
--------------------------------------------------------------------------
agent-00 declined retried 1x
agent-01 declined retried 1x
agent-02 declined retried 1x
agent-03 declined retried 1x
agent-04 declined retried 1x
agent-05 declined retried 1x
agent-06 REFUNDED
agent-07 declined retried 1x
--------------------------------------------------------------------------
Result 8 agents, 174ms, 7 × SQLSTATE 40001 (serialization conflicts, retried)
dispute state refund_authorized
decisions recorded committed=1, declined=7 <- every agent's reasoning is on the record
refunds queued 1 -> EUR 42.00 leaves the account
Eight agents raced. Seven were told to start over. One refund. Nobody wrote a lock, a lease, or a distributed mutex.
(That's one real run, pasted verbatim. The retry count varies — we've seen 7 and
we've seen 29, because contention is timing. The number that never varies is
refunds queued: 1. tests/test_guarantees.py asserts both: exactly one refund,
and at least one 40001 — because a run with zero conflicts proves nothing
about serializability and shouldn't be allowed to pass.)
Now the control group — the same eight agents, built the normal way (read in one transaction, act in another; a vector store and an API client):
$ python scripts/demo_race.py --agents 8 --unsafe
agent-00 REFUNDED
agent-01 REFUNDED
... all 8 ...
--------------------------------------------------------------------------
Result 8 agents, 32ms, 0 × SQLSTATE 40001
refunds queued 8 -> EUR 336.00 leaves the account
The customer was refunded 8 times. EUR 336.00 instead of EUR 42.00.
Read that retry count again: 0 conflicts.
Zero conflicts. The database didn't miss anything — there was nothing to catch. Each of those eight transactions was individually correct and individually SERIALIZABLE. Serializability is a property of a transaction, and the decision was never in one.
No isolation level fixes that. No retry logic fixes that. You cannot ask a database to order two operations you never told it were related. €294 gone, and every log line is green.
An adversarial review of this repo caught the framing above overselling itself, so here is the correction, in the same place as the claim.
--unsafe changes two independent things, not one:
- it splits the read and the write across two transactions (the architectural point), and
- it changes the idempotency key from intent-derived
refund:<dispute>to caller-derivedrefund:<dispute>:<agent>.
Neither alone double-refunds. Split the transaction but keep an
intent-derived key and the unique index catches all eight. Keep one transaction
but use a caller-derived key and the serializable conflict on dispute.state
catches all eight. You need both sabotages to lose the money.
So "the transaction is what saves you" is not what this demo shows. What it
shows is: two independent guards, either of which suffices. And a plain
UNIQUE constraint on an intent-derived key gets you exactly-one-refund with no
transaction story at all.
Worse for the original framing: in the safe race the unique index never
fires. All seven losers hit 40001 on the dispute row, retry, re-read
state='refund_authorized', and decline before reaching emit() — which is
why the output shows seven declined and zero duplicate-blocked. The
serializable conflict does all the work. Calling idempotency_key "the
load-bearing constraint" while it sits idle, and then sabotaging it to
manufacture the failure, was a shell game. Unintentional, and still a shell
game.
The claim that survives, and it is narrower: the value of one transaction is
not that it's the only way to avoid a double refund. It's that it makes the
memory — the belief, the episode, the recall trace, the audit row — atomic
with the action. A UNIQUE constraint gives you one refund and tells you
nothing about what the agent knew when it decided. That is the part no
constraint buys you, and it is what the rest of this README is about.
Keep the demo for what it honestly is: proof that eight correct agents contend, that CockroachDB serializes them, and that the losers' reasoning is preserved rather than discarded.
Agent memory is a system of record, not a cache.
Everything below follows from taking that literally.
A cache may be lossy, eventually consistent, and rebuilt from source. A system of record may not. The moment an agent's memory justifies moving money, it inherits every obligation a ledger has: atomicity with the action, durability past the incident, an audit trail that outlives the debate, and a defensible answer to where the personal data physically sits.
A bolt-on vector store beside your OLTP database was not built for that: the memory and the money are in two systems with no shared commit. (pgvector is the honest exception -- it inherits Postgres's ACID guarantees. What it does not inherit is 4 and 5 below.)
Four kinds of memory, with different consistency, lifecycle, and physics. Most
systems have one table called memories and a similarity search. That collapse
is where the problems start — you cannot express "this decays but that must
never" or "this is personal data but that isn't" if everything is one row type.
| Kind | Table | What it is | Locality | Lifecycle |
|---|---|---|---|---|
| Episodic | episode |
What happened | REGIONAL BY ROW |
Append-only, decays after consolidation |
| Semantic | belief |
What is true | REGIONAL BY ROW |
Bitemporal, superseded never deleted |
| Procedural | policy |
How to act | GLOBAL |
Versioned, read everywhere |
| Working | task_state |
What I'm doing now | REGIONAL BY ROW |
Mutable, expires in 7 days |
policy is GLOBAL because it's read on every decision in every region and
written roughly never — the textbook case. It is also the only memory table
not domiciled, because a refund policy isn't personal data. You can only make
that distinction if the model has types.
And a fifth table:
recall_trace |
What the agent actually retrieved | The audit trail's load-bearing wall |
Knowing what was in memory is not knowing what the agent saw. An ANN search returns k rows; the other ten thousand were equally present and equally invisible. Store only the corpus and "the agent should have known" is unfalsifiable. Store the retrieved set and you can tell a reasoning bug (good recall, bad call) from a retrieval bug (bad recall) — different teams, different fixes.
Concession first, because the honest version of this list is shorter than the flattering one: pgvector on Postgres gets you 1–3. It is a vector store and it inherits every ACID property Postgres has, so "a vector database can't do transactions" is false about the one that most people actually use. What no bolt-on store — Pinecone, Qdrant, Chroma, a separate vector service beside your OLTP database — can do is any of them, because the memory and the business state are in different systems with no shared commit.
4 and 5 are the ones nothing but CockroachDB gets you.
ctx = eng.recall(principal_id=m, jurisdiction="eu", query="should I refund this?")
def body(d):
d.used(ctx, prompt=prompt) # what it saw
row = d.conn.execute("SELECT state FROM dispute WHERE ...").fetchone()
if row["state"] != "open":
d.conclude("declined", "another agent got there first")
return
d.conn.execute("UPDATE dispute SET state='refund_authorized' ...")
d.believe("merchant", "refund_history", "one_approved", "...") # semantic
d.observe("action", "Authorized EUR 42.00 refund.", salience=0.95) # episodic
d.emit("refund", f"refund:{dispute_id}", {...}) # the money
d.conclude("committed", "Duplicate charge confirmed against defect history.")
eng.decide(principal_id=m, jurisdiction="eu", session_id=s,
agent_name="refund-agent", body=body)Business state, semantic memory, episodic memory, the refund intent, and the audit row — one transaction, one commit, one timestamp. There is no interval in which the agent has refunded and forgotten, or remembered and not refunded.
Why body is a function and not a with block. CockroachDB is SERIALIZABLE
by default, so any transaction can fail at COMMIT with 40001 and must re-run
from the top. A with txn: block physically cannot do that — by the time
__exit__ sees the error, the body has already executed. A with block cannot re-run its own body, so a library exposing one on
CockroachDB must either push the retry contract onto you or drop it. (It can be
done with SAVEPOINT cockroach_restart and a re-entrant body -- but then the
re-entrancy requirement is yours anyway, and the with is hiding it rather than
naming it.) The API shape is dictated by the retry contract, not
by taste.
Not "exactly-once". Exactly-once across a database and a payment provider is not purchasable at any price: the worker can always die between the provider committing the charge and you recording that it did.
What is achievable, assembled from three parts none of which is exactly-once:
| transport (changefeed) | at-least-once, no cross-row ordering |
intent (uq_effect_idempotency) |
unique |
| execution (CAS under SERIALIZABLE) | at most one transition |
| = result | provider called at most once per key |
The idempotency_key is derived from the intent (refund:<dispute_id>),
never from a uuid or the decision id. That single line is why two agents
independently reaching the same conclusion collide instead of both acting.
Claiming uses a compare-and-set, not SELECT ... FOR UPDATE. Under
SERIALIZABLE, CockroachDB's locks are unreplicated and the docs say they
"should be thought of as best-effort, and should not be relied upon for
correctness".
Correctness comes from serializable conflict detection. The lock would add
latency and subtract nothing.
The obvious build is time-travel queries. It demos beautifully. It is wrong, and Cockroach Labs says so in the docs for the very knob you'd have to turn:
"Increasing the GC TTL is not meant to be a solution for long-term retention of history; for that you should handle versioning in the schema design at the application layer."
Default gc.ttlseconds is 14400 — four hours. We read it off the live
cluster rather than trusting the docs, whose own examples still print the
pre-v23.1 value of 90000. An audit trail that evaporates after four hours is a
debug log with good marketing.
So belief carries two independent time axes:
VALID TIME valid_from / valid_to when it was true
DECISION TIME asserted_at_hlc / retracted_at_hlc when we believed it
Run scripts/demo_audit.py:
March 10 — the agent denies a refund. Terminal reports healthy. March 12 — a vendor advisory lands: that firmware has double-charged since March 1. March 15 — compliance asks: "the terminal was already broken. Explain."
Q1. What is true NOW?
Terminal T-4471 double-charges on contactless due to a firmware defect.
valid from Mar 01 — i.e. it was ALREADY broken when the agent denied.
Q3. What did the agent BELIEVE at the moment it decided?
Terminal T-4471 is operating normally; no known defects.
VERDICT: the agent was correct on the evidence it had.
A single-timestamp memory answers Q1 and convicts the agent. This is not a storage detail: a one-timestamp audit trail systematically makes past decisions look worse than they were, because every fact you have since learned is retroactively projected onto a decision that could not have known it. Hindsight, encoded as a schema bug.
AS OF SYSTEM TIME still earns its place — at the job it's actually good at
(below).
The regression test for the part of your system that has no source file.
Re-run a decision's recall AS OF SYSTEM TIME its own commit HLC — pinning the
corpus to exactly what existed then — and diff against recall_trace. Any
difference cannot be "new memories arrived". It can only be your retrieval
stack changing underneath you:
- the embedding model was upgraded and every vector moved
- beam size or
kwas retuned - the index was rebuilt with different partition sizes
- someone edited the merge policy
Every one of those silently changes what your agents see. None touches a line of
agent code. None shows up in a test suite that asserts on outputs. This is the
one job AS OF SYSTEM TIME is genuinely best at, and it's bounded by the GC
window on purpose — it's a canary, not a forensic tool. The forensic tool is
replay_decision(), which reads ordinary columns and has no horizon.
jurisdiction is a business fact. home_region is a STORED computed column
over it:
ALTER TABLE belief ADD COLUMN home_region crdb_internal_region AS (
CASE jurisdiction
WHEN 'eu' THEN 'eu-west-1'
WHEN 'us' THEN 'us-east-1'
WHEN 'sa' THEN 'ap-south-1'
END
) STORED;
ALTER TABLE belief SET LOCALITY REGIONAL BY ROW AS home_region;Not gateway_region(). CockroachDB's default homes a row wherever the
writer was. For a latency-motivated app that's right. For a compliance-motivated
one it's a silent breach: an agent worker in us-east-1 draining a queue for an EU
merchant would home that merchant's personal data in Virginia. The row would be
fast and illegal.
Placement is a pure function of a declared legal fact, visible in SHOW CREATE TABLE, and cannot drift with deployment topology.
And REGIONAL BY ROW alone does not domicile. Non-voting replicas are on by
default in multi-region clusters — a read-latency feature and a compliance hole.
It takes a super region to constrain all replicas:
ALTER DATABASE engram ADD SUPER REGION "eu-domicile" VALUES "eu-west-1";Everything below was found by running it, not by reading about it. Details in
docs/limits.md.
You cannot domicile data in one region and also survive that region's loss.
We wrote SURVIVE REGION FAILURE and CockroachDB refused:
ERROR: super region eu-domicile only has 1 region(s): at least 3 regions are
required for surviving a region failure
That error is correct and it isn't really about CockroachDB — it's arithmetic.
If every replica must be in the EU and you have one EU region, its loss is
unsurvivable. We ship SURVIVE ZONE FAILURE and strict domicile, because a
residency breach is unrecoverable and an outage isn't. Want both? Add
eu-central-1 + eu-north-1 to the super region. That's the whole migration —
which is the point of putting placement in a computed column.
Domiciling is defensible, not absolute. Quoting the docs, not paraphrasing:
"When columns are indexed, a subset of data from the indexed columns may appear in meta ranges or other system tables... This synchronization does not respect any multi-region settings."
"The replication system's top priority is to prevent the loss of data and it may override the zone configurations if necessary."
Also: a node only knows its locality from the --locality string it was handed;
CockroachDB cannot verify a node is where it claims. ENGRAM gets you an
auditable placement story. It does not get you a lawyer.
There is no CockroachDB region inside Saudi Arabia. sa maps to
ap-south-1 (Mumbai). That is a documented compromise, not PDPL compliance. It
lives in a CASE arm so it's legible in the schema instead of buried in
whichever region a worker happened to run in.
Vector index + Row-Level TTL is unverified at scale. Each is GA alone; we
found no docs on their interaction under sustained delete load. The plausible
failure is TTL churning C-SPANN partitions faster than the index maintains them
— degrading recall silently. Run 003 or 005, not both, if you can't verify it.
Flagged in sql/005_decay.sql.
Changefeeds are at-least-once with no transactional ordering. We rely on this being true and design around it rather than claiming otherwise.
The offline embedder is worse, not equivalent. ENGRAM_OFFLINE_EMBEDDINGS=1
uses a signed hashing-trick bag-of-words so the whole system runs with no AWS
account. It has real lexical structure (so the demos mean something) and it is
not Titan.
Claims verified against a real cluster (CockroachDB v25.4.12, 9-node
cockroach demo), not read off a docs page.
The vector index prefix is (home_region, principal_id) — automatically.
After the REGIONAL BY ROW conversion, EXPLAIN on an ANN query:
└── • lookup join
│ table: episode@pk_episode
└── • vector search
table: episode@idx_episode_semantic
target count: 5
prefix spans: [/'eu-west-1'/'1111…' - /'eu-west-1'/'1111…']
An EU merchant's semantic search is scoped to the EU partition structurally. Residency and tenancy are properties of the index, not filters applied after the fact — so recall can't silently degrade to a cross-tenant scan.
Drop the prefix constraint and it collapses to • scan … FULL SCAN. Correct,
and O(corpus). tests/ asserts on the EXPLAIN plan, because this failure is
invisible from the results.
Using the vector index is a cost-based decision, not a guarantee. Our own
test caught this: with only 20 episodes the planner ignored C-SPANN entirely and
scanned idx_episode_recent instead —
• top-k
└── • index join (episode@pk_episode)
└── • scan (episode@idx_episode_recent)
estimated row count: 1 (0.41% of the table)
— and it was right. Entering a C-SPANN tree to find one row is slower than
reading it. C-SPANN earns its keep at thousands of vectors per tenant, not
twenty. Two things follow that matter in production: a small-corpus tenant will
not use the vector index and should not; and stale stats can talk the
optimizer out of it at real volume, so ANALYZE is the difference between an
ANN search and a sort over everything — with nothing in the results to tell you
which one you got.
Every row a decision writes carries the identical HLC. Verified, not assumed — stable across a 250ms sleep and across all four tables:
decision 1784236288071594600.0000000006
belief 1784236288071594600.0000000006
episode 1784236288071594600.0000000006
effect 1784236288071594600.0000000006
Not "approximately the same time" — the same logical instant, because it's one
commit. That decimal HLC is simultaneously a valid AS OF SYSTEM TIME argument,
a valid CREATE CHANGEFEED ... WITH cursor argument, and our own decision-time
axis. One clock, three systems — which is what makes "replay this decision"
one well-defined operation instead of bespoke tooling.
The full stack applies clean to a 9-node, 3-region cluster. sql/all.sql
ends by verifying itself:
--- super regions (the part that actually domiciles) ---
database_name super_region_name regions
engram eu-domicile {eu-west-1}
--- localities ---
belief REGIONAL BY ROW AS home_region
decision REGIONAL BY ROW AS home_region
effect_outbox REGIONAL BY ROW AS home_region
episode REGIONAL BY ROW AS home_region
policy GLOBAL <- procedural memory, read everywhere
principal REGIONAL BY ROW AS home_region
recall_trace REGIONAL BY ROW AS home_region
task_state REGIONAL BY ROW AS home_region
Every table carrying principal data is domiciled. policy — the only memory
table that isn't personal data — is the only one that's GLOBAL. That
distinction is the payoff for having a typed memory model instead of one
memories table.
timestamptz + interval is rejected in a STORED computed column.
ERROR: +: context-dependent operators are not allowed in STORED COMPUTED COLUMN
It's timezone-dependent, so it isn't a pure function of the row. The TTL expression is inline instead — evaluated at scan time, no stored column, no backfill.
localhost cost us 130 seconds per connection. Measured on the dev machine:
localhost connect+query: 130124 ms
127.0.0.1 connect+query: 2 ms
localhost resolves to ::1 first; the IPv6 connect hangs until fallback. It
presents as "the connection pool times out under concurrency" and gets blamed on
the pool, or on CockroachDB — never on DNS. The default DSN is 127.0.0.1 and
docs/troubleshooting.md says why.
| Tool | Where | Why it, specifically |
|---|---|---|
| Distributed Vector Indexing (C-SPANN) | sql/003_vector_index.sql |
Prefixed (home_region, principal_id, embedding) — tenancy + residency are structural, not post-filters |
| Cloud Managed MCP Server | .mcp.json, infra/MCP.md |
Agents inspect their own memory through the 11 managed tools |
| ccloud CLI | infra/ccloud-setup.ps1 |
Cluster, SQL user, service account + API key for MCP, one script |
| Agent Skills | skills/engram-memory-operations/ |
A skill in the cockroachlabs/cockroachdb-skills format teaching agents to operate this memory |
Beyond the named four, the design leans on: SERIALIZABLE (the race),
cluster_logical_timestamp() (the audit spine), REGIONAL BY ROW AS +
super regions (domiciling), GLOBAL tables (policy), partial indexes
(live beliefs, unconsolidated episodes), Row-Level TTL (decay),
changefeeds (effect delivery), AS OF SYSTEM TIME (drift detection), and
SHOW RANGES (proving replicas obey the super region).
| Service | Where | Why |
|---|---|---|
| Bedrock — Titan Text Embeddings V2 | engram/embeddings.py |
1024-dim, normalize: true, matching VECTOR(1024) |
| Bedrock — Claude via Converse | agent/loop.py, engram/consolidate.py |
Reasoning + tool use; consolidation |
| Lambda | infra/lambda/ |
Drains the outbox; module-scope pool per CockroachDB's serverless guidance |
| S3 (optional) | sql/004_changefeed.sql |
Changefeed archive sink |
No AWS account needed. The offline embedder means you can run every demo, including the race, on a laptop.
# 1. a local cluster
cockroach start-single-node --insecure --listen-addr=127.0.0.1:26257 --store=crdb-data
# 2. schema (001 = core, 003 = vector index, 010 = demo policies.
# 002/004/005 are optional layers.)
cockroach sql --insecure --host=127.0.0.1:26257 -f sql/001_core.sql
cockroach sql --insecure --host=127.0.0.1:26257 -f sql/003_vector_index.sql
cockroach sql --insecure --host=127.0.0.1:26257 -f sql/010_seed_policies.sql
# 3. deps
pip install -e ".[api]"
# 4. run it
export ENGRAM_DSN="postgresql://[email protected]:26257/engram?sslmode=disable"
export ENGRAM_OFFLINE_EMBEDDINGS=1 # drop this once AWS creds are set
python scripts/demo_race.py --agents 8 # <- start here
python scripts/demo_race.py --agents 8 --unsafe
python scripts/demo_audit.pyFull multi-region (9 nodes, 3 regions, super regions, RBR):
cockroach demo --nodes 9 --no-example-database --insecure \
--demo-locality="region=us-east-1:region=us-east-1:region=us-east-1:\
region=eu-west-1:region=eu-west-1:region=eu-west-1:\
region=ap-south-1:region=ap-south-1:region=ap-south-1" \
-f sql/all.sqlCockroachDB Cloud, with MCP wired up: infra/ccloud-setup.ps1 (or .sh).
The console: uvicorn api.main:app --reload → http://127.0.0.1:8000
sql/ 001 core · 002 multi-region · 003 vector · 004 changefeed · 005 decay
010 seed policies (demo data — production writes these by hand)
engram/ store (commit-bound writes) · recall (hybrid) · outbox (effectively-once)
timetravel (bitemporal + drift) · consolidate (episodic→semantic)
db (pool + 40001 retry) · embeddings (Titan + offline)
agent/ the Bedrock Converse loop — recall, reason, decide
scripts/ demo_race · demo_audit · demo_drift
api/ web/ the console
infra/ ccloud · lambda · MCP · docker-compose
skills/ Agent Skill for operating ENGRAM
docs/ limits · time · troubleshooting · architecture
tests/ the claims above, as executable assertions
Read next
docs/time.md |
The three clocks, and why conflating any two breaks the audit trail. The sharpest argument here. |
docs/limits.md |
Everything ENGRAM does not do, found by running it. |
docs/architecture.md |
Diagrams, and where each guarantee comes from. |
docs/troubleshooting.md |
Every trap we hit, with the symptom that presented. |
tests/test_guarantees.py |
Don't take the README's word for it. |
Apache 2.0 — LICENSE.
Built for the CockroachDB × AWS Agentic Memory Hackathon. Every SQL statement, EXPLAIN plan, error message, and timing in this README was produced by running the code against CockroachDB v25.4.12.
Then we pointed three adversarial reviewers at it and they found twelve
places where this repo claimed something the code didn't do — including the
consolidation-gates-forgetting story that four documents told and one CASE
expression contradicted, and a docs/limits.md that confessed no bugs at all
because every "limitation" in it was flattering. Those are fixed, and
docs/limits.md § 11 is now the list, with file names. If
you are going to check one thing in this repo, check that.