Store API¶
LangGraph long-term memory stores for CockroachDB.
CockroachDBStore¶
Synchronous store.
langchain_cockroachdb.store.store.CockroachDBStore
¶
Bases: BaseStore, BaseCockroachDBStore, PsycopgOps
LangGraph store that keeps long-term memory in CockroachDB.
Items live in one table keyed by namespace and key. Namespaces are stored
as their labels joined with ".". For production, pass a
psycopg_pool.ConnectionPool or use from_conn_string with
pool_config: a pool replaces broken connections and runs batches
concurrently, while a single connection runs one batch at a time.
A batch runs its reads first, then all its puts and deletes in one transaction. Its gets, its searches and its listings take one round trip each. On a store with a vector index, semantic searches under a namespace add one before the searches, to find their namespaces, and one after them when a search must run again exactly. A flat store adds neither. The long-term memory guide explains why.
With history, a batch that overwrites or deletes a memory first
copies the version it ends into a history table, in its transaction.
delete then keeps the memory in history; purge removes a memory
with its history, and history lists the old versions.
Example
__init__(conn, *, pipe=None, index=None, ttl=None, history=None, reconcile_scan_limit=DEFAULT_RECONCILE_SCAN_LIMIT, retry_policy=None, table_name='store', schema='public')
¶
Create a store on a connection or a pool.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
conn
|
Conn
|
A psycopg connection, or a ConnectionPool (recommended). It must be in autocommit mode and use dict_row. |
required |
pipe
|
Pipeline | None
|
A pipeline on |
None
|
index
|
CockroachDBIndexConfig | None
|
Semantic search settings. When given, setup() also creates the vectors table and its C-SPANN index, and puts embed the configured fields of each item. |
None
|
ttl
|
TTLConfig | CockroachDBTTLConfig | None
|
TTL settings. When given, setup() also turns on CockroachDB row-level TTL for expired rows. |
None
|
history
|
bool | HistoryConfig | None
|
Version history: True, or a HistoryConfig to give old versions a TTL. setup() then creates the history table, and every batch keeps the versions it overwrites or deletes there. Default None, no history. |
None
|
reconcile_scan_limit
|
int
|
The most vectors a namespace may hold for find_conflicts to rank every one of them, by primary key (default 2000). A namespace with more finds its similar candidates through the C-SPANN index, and ranks every vector only when the index's window may have left matches out. |
DEFAULT_RECONCILE_SCAN_LIMIT
|
retry_policy
|
RetryPolicy | None
|
How operations retry (default: RetryPolicy()) |
None
|
table_name
|
str
|
Name of the items table (default "store") |
'store'
|
schema
|
str
|
Schema of the store's tables (default "public") |
'public'
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If a pipeline is given with a pool, or a name or the TTL, index, history or reconcile_scan_limit settings are invalid |
abatch(ops)
async
¶
Run batch in a worker thread, as PostgresStore does.
batch(ops)
¶
Run a batch of operations.
Every op is validated, and every put value serialized, before any statement runs. Gets, searches and listings run first, then all puts and deletes commit together in one transaction.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ops
|
Iterable[Op]
|
GetOp, SearchOp, ListNamespacesOp and PutOp operations. |
required |
Returns:
| Type | Description |
|---|---|
list[Result]
|
One result per op, in the order of |
confirm(namespace, key, *, ttl=NOT_PROVIDED)
¶
Mark a live memory as confirmed, renewing its expiry and counting confirmations.
This counts the confirmation and renews the expiry. That way expiry can follow how often a fact is confirmed, not how often it is read. Confirming does not change the version or updated_at, so it never invalidates a pending find_conflicts. Confirmations belong to the memory's value: a write that changes it starts them again from none.
Each call picks a confirmation id before its first attempt and stores it on the memory, so a retry after a commit whose result was lost counts nothing again, unless another confirmation of the same memory lands in between, in which case the retry counts again. The memory's write id stays as it is, so a write retried after its own lost commit still finds it.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
namespace
|
tuple[str, ...]
|
The memory's namespace. |
required |
key
|
str
|
The memory's key. |
required |
ttl
|
float | None | NotProvided | Callable[[MemoryRecord], float | None]
|
How long the memory stays after confirmation. NOT_PROVIDED renews from the row's own TTL. None removes the expiry. A number is minutes. A callable takes the MemoryRecord read in the same transaction and returns a number of minutes or None. Keep it fast and deterministic: it runs again on each retry, and must not call the store. It must be a plain function: an async one is refused before any I/O. |
NOT_PROVIDED
|
Returns:
| Type | Description |
|---|---|
bool
|
True if a live memory was confirmed, False if no live memory has |
bool
|
that key: there is none, or it expired. |
Raises:
| Type | Description |
|---|---|
InvalidNamespaceError
|
If the namespace is empty or a label is invalid |
ValueError
|
If ttl is not NOT_PROVIDED, None, a positive finite number of minutes, or a plain callable; if setup() has not added the columns this method needs; or if the callable returns an invalid value (not None or a positive finite number, a coroutine included) |
delete_if(namespace, key, *, expected)
¶
Delete a memory only if it is still the one the caller read, in one transaction.
delete_if deletes only if the live memory under key still has
the version and updated_at of expected, as put_if checks them.
On a match it deletes as delete does: on a store with history the
memory is kept in history as deleted, and its vectors go. With
expected=None it applies only while no live memory has the key,
so it deletes nothing live.
applied=True means the memory matched expected and this call
deleted it, or, after an earlier attempt of the call that may have
committed, that the memory is gone and was this call's to delete: it
matched expected when that attempt checked it. On a mismatch it
deletes nothing and returns applied=False with current, the
live memory as the same transaction read it, or None if there is
none, as when another writer deleted it or it expired since. A
conflict is returned, not raised.
If an attempt sends its COMMIT and the result is lost, as when the
connection drops while the COMMIT's answer travels, that attempt may
have deleted the memory, so a retry that finds it gone reports it
applied. On a store with history the retry also finds its own history
row, which proves the earlier attempt deleted the memory, and the
result has already_applied. A store without history keeps no row
that proves which attempt deleted it, so already_applied stays
False. Serialization failures and deadlocks (40001, 40P01) roll
attempts back, so after only those a memory gone since is a conflict:
another writer removed it. Once an attempt may have committed, the
retries after it stay lenient, whatever error ends them next. If
another writer put the key again before the retry, the retry reports
a conflict with that memory.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
namespace
|
tuple[str, ...]
|
The memory's namespace. It cannot be empty. |
required |
key
|
str
|
The memory's key. |
required |
expected
|
MemoryRecord | None
|
The MemoryRecord that record() returned for this namespace and key, or None. |
required |
Returns:
| Type | Description |
|---|---|
ConditionalWrite
|
Whether the delete applied, and on a conflict the current memory. |
Raises:
| Type | Description |
|---|---|
InvalidNamespaceError
|
If the namespace is empty or a label is invalid |
ValueError
|
Before any I/O: if |
delete_namespace(namespace_prefix)
¶
Delete every item in a namespace and its descendants.
("user", "a") deletes ("user", "a") and ("user", "a", "b"),
not ("user", "ab"). One statement deletes the items, their
vectors and their history. A store without history deletes history
too when the history table exists, as when the store kept history
before, so nothing of the namespace is left. Its role then needs
SELECT and DELETE on that table: without them the whole call fails
with a permission error and deletes nothing, rather than forget only
part of the namespace.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
namespace_prefix
|
tuple[str, ...]
|
The namespace to delete. It cannot be empty. |
required |
Returns:
| Type | Description |
|---|---|
int
|
The number of items deleted. If a retry follows a commit whose |
int
|
result was lost, the count is that of the retry, usually 0. |
Raises:
| Type | Description |
|---|---|
InvalidNamespaceError
|
If the prefix is empty or a label is invalid |
ValueError
|
If the store keeps history and setup() has not created the history table |
disable_ttl()
¶
Turn off CockroachDB row-level TTL on the store's tables.
Expired items are still left out of reads while omit_expired is on.
Safe to run from several processes at once. On CockroachDB v25.4 a
TTL change fails while another schema change runs on the same table;
that error is retried with the budget that schema_change_policy
gives it, up to ten minutes by default, even if the policy's
retry_on would refuse it. max_attempts=1 turns this off.
drop_vector_index()
¶
Drop the store's vector index, if it exists.
Run setup() afterwards to build it again with the store's current configuration, for example to change the distance. Searches scan the vectors until the new index is built.
find_conflicts(namespace, key, value, *, slot=None, threshold=None, limit=10, filter=None, index=None, ttl=NOT_PROVIDED, provenance=None, valid_at=None)
¶
Find the memories a new one may conflict with, without writing anything.
Candidates are live memories in namespace itself, not in its
descendants, for one of three reasons, strongest first:
"key": the memory underkey, whateverfiltersays."slot": withslot, the memories whose value holds the same value in that field, compared as JSON."similar": on a store with an index, the memories whose vectors score at or abovethresholdagainst the new memory's, with the store's score function: 1 minus the distance on a cosine store, the negated distance on an l2 or inner_product store. The new memory is embedded as a document (embed_documents), while search embeds its query (embed_query), so with a model that embeds the two differently the scores differ from search's.
Key and slot matches carry their best score when they have vectors, and similar ones always do. Candidates come strongest reason first, then best score, then key. Expired memories are never candidates, and no read pushes back an expiry.
The index fields of value are embedded once, and the embedding is
kept for the write. Then two round trips read the candidates: first
the database's clock, the key and slot matches and the namespace's
vector count, then the similar memories and the scores. A namespace
with at most reconcile_scan_limit vectors has all of them ranked.
A larger one takes its similar candidates from a window of the
C-SPANN index. When that window holds nothing below threshold
and gave fewer than limit candidates, matches may lie beyond it,
and one more round trip ranks every vector of the namespace.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
namespace
|
tuple[str, ...]
|
The new memory's namespace. It cannot be empty. |
required |
key
|
str | None
|
The new memory's key, or None for a new uuid4. |
required |
value
|
dict[str, Any]
|
The new memory's value. |
required |
slot
|
str | None
|
A top-level field of |
None
|
threshold
|
float | None
|
The lowest score of a similar candidate. On a cosine
store it defaults to 0.8 and must lie between -1 and 1. On an
l2 or inner_product store, where scores are negated distances,
it must be given. Ignored without an index or with
|
None
|
limit
|
int
|
Most similar candidates (default 10). The key and slot matches come on top of them; 0 keeps only those. |
10
|
filter
|
dict[str, Any] | None
|
Narrows the slot and similar candidates by value, as in
search. The memory under |
None
|
index
|
Literal[False] | list[str] | None
|
Which fields of |
None
|
ttl
|
float | None | NotProvided
|
Minutes the new memory lives once written, or None for no expiry. Defaults to the store's default TTL. |
NOT_PROVIDED
|
provenance
|
dict[str, Any] | None
|
Where the new memory comes from, as a JSON object. |
None
|
valid_at
|
datetime | None
|
When the fact became true, as a timezone-aware datetime. By default the database's current time, raised to the latest candidate's updated_at if that is later, so a correction never looks older than the memory it corrects. A memory written without one is valid from its updated_at. |
None
|
Returns:
| Type | Description |
|---|---|
Conflicts
|
The new memory as a Proposal, its candidates, and the version |
Conflicts
|
and updated_at of the live memory under |
Raises:
| Type | Description |
|---|---|
InvalidNamespaceError
|
If the namespace is empty or a label is invalid |
ValueError
|
If another argument is invalid (above), or setup() has not added the columns this method needs |
from_conn_string(conn_string, *, pipeline=False, pool_config=None, index=None, ttl=None, history=None, reconcile_scan_limit=DEFAULT_RECONCILE_SCAN_LIMIT, retry_policy=None, connect_timeout=10.0, prepare_threshold=5, connect_kwargs=None, table_name='store', schema='public')
classmethod
¶
Create a store on a new connection, or on a new pool with pool_config.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
conn_string
|
str
|
CockroachDB connection string (cockroachdb://, postgresql:// and similar) |
required |
pipeline
|
bool
|
Whether to use pipeline mode on the single connection. Ignored with pool_config. |
False
|
pool_config
|
PoolConfig | None
|
Open a ConnectionPool with these settings instead of one connection |
None
|
index
|
CockroachDBIndexConfig | None
|
Semantic search settings |
None
|
ttl
|
TTLConfig | CockroachDBTTLConfig | None
|
TTL settings |
None
|
history
|
bool | HistoryConfig | None
|
Version history settings (default None, no history) |
None
|
reconcile_scan_limit
|
int
|
The most vectors a namespace may hold for find_conflicts to rank every one of them (default 2000) |
DEFAULT_RECONCILE_SCAN_LIMIT
|
retry_policy
|
RetryPolicy | None
|
How operations retry (default: RetryPolicy()) |
None
|
connect_timeout
|
float | None
|
Seconds to wait when connecting, or None (default: 10) |
10.0
|
prepare_threshold
|
int | None
|
psycopg prepared statement threshold, None to disable (default: 5). Statements sent in a pipeline are never prepared |
5
|
connect_kwargs
|
Mapping[str, Any] | None
|
Extra psycopg connection options, e.g. application_name |
None
|
table_name
|
str
|
Name of the items table (default "store") |
'store'
|
schema
|
str
|
Schema of the store's tables (default "public") |
'public'
|
Yields:
| Type | Description |
|---|---|
CockroachDBStore
|
CockroachDBStore instance. The connection or pool closes on exit. |
With pool_config, pipeline is ignored, as in PostgresStore: a
pipeline needs a single connection.
Raises:
| Type | Description |
|---|---|
ValueError
|
If the index, history or reconcile_scan_limit settings are invalid, before any connection is opened |
history(namespace, key=None, *, limit=20, offset=0)
¶
The old versions of a memory, or of every memory in a namespace, newest first.
A store with history keeps every version that a write ends: one a
put overwrites (reason "overwritten"), one a delete ends
("deleted"), and one that reconcile or resolve supersedes
("superseded", with superseded_by naming the memory that
replaced it). A new memory that reconcile or resolve records as
already superseded by a newer fact is kept there too, as
"superseded". The live value is not one of them; get() returns it.
Without a key, it lists the old versions of every memory in exactly
namespace, not its descendants, as get() reads a namespace. That
is how to find the old versions of memories that reconcile saved
under keys the store generated. Each version carries its own key
and superseded_by, so versions can be grouped by a field of
their value, or followed to the memory that replaced them. Each call
reads the namespace's whole history to sort it, which suits
per-user namespaces. For a very large history, page with limit
and offset.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
namespace
|
tuple[str, ...]
|
The memory's namespace. |
required |
key
|
str | None
|
The memory's key, or None for every memory in the namespace. |
None
|
limit
|
int
|
Most versions to return (default 20). |
20
|
offset
|
int
|
Versions to skip, for paging (default 0). |
0
|
Returns:
| Type | Description |
|---|---|
list[MemoryVersion]
|
Up to |
list[MemoryVersion]
|
when it ended. With a key, highest version first. Without one, |
list[MemoryVersion]
|
newest first by |
list[MemoryVersion]
|
first, so pages are stable. Versions past the history's |
list[MemoryVersion]
|
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If the store keeps no history (create it with
history=True and run setup()), setup() has not created the
history table, or |
InvalidNamespaceError
|
If the namespace is empty or a label is invalid |
purge(namespace, key)
¶
Forget a memory: delete the item, its vectors and its history.
On a store with history, delete() keeps the version it ends, so purge is how to remove a memory for good. One statement deletes all of it.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
namespace
|
tuple[str, ...]
|
The memory's namespace. |
required |
key
|
str
|
The memory's key. |
required |
Returns:
| Type | Description |
|---|---|
bool
|
Whether anything was deleted: the memory, or only its history |
bool
|
after a delete. If a retry follows a commit whose result was |
bool
|
lost, the retry finds nothing and returns False. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the store keeps no history (create it with history=True and run setup(); without history, delete() already removes a memory and its vectors), or setup() has not created the history table |
InvalidNamespaceError
|
If the namespace is empty or a label is invalid |
put_if(namespace, key, value, *, expected, index=None, ttl=NOT_PROVIDED, provenance=None, valid_at=None)
¶
Write a memory only if it is still the one the caller read, in one transaction.
Two threads that read the same memory with record() and both write
it back with put would lose one update without a word. put_if
writes only if the live memory under key still has the version
and updated_at of expected, the check resolve makes: a put
moves the version, and a 0.5.x store, which does not, still moves
updated_at. With expected=None it writes only if no live memory
has the key, so a memory is created once. An expired memory counts
as absent.
On a match it writes as put does, in the transaction that checked:
the write id goes on the row, the version it replaces is kept in
history on a store with history, ending at valid_at when given
or else at the write, and the memory's vectors are replaced. The
result has applied set and the version written.
On a mismatch it writes nothing and returns applied=False with
current, the live memory as the same transaction read it, or
None if there is none. A conflict is an expected outcome here, so it
is returned, not raised: merge and call put_if again with
current, keep the stored memory, or ask the user.
The index fields of value are embedded once, before the first
attempt. If an attempt commits and its result is lost, as when the
connection drops while the COMMIT's answer travels, the retry finds
the write id on the row and returns applied=True with
already_applied. If another writer replaced the memory before the
retry, a 0.5.x store included, the retry reports a conflict with that
writer's memory, which is the current state.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
namespace
|
tuple[str, ...]
|
The memory's namespace. It cannot be empty. |
required |
key
|
str
|
The memory's key. |
required |
value
|
dict[str, Any]
|
The new value. |
required |
expected
|
MemoryRecord | None
|
The MemoryRecord that record() returned for this namespace and key, or None to write only if no live memory has the key. |
required |
index
|
Literal[False] | list[str] | None
|
Which fields of |
None
|
ttl
|
float | None | NotProvided
|
Minutes the memory lives once written, or None for no expiry. Defaults to the store's default TTL. |
NOT_PROVIDED
|
provenance
|
dict[str, Any] | None
|
Where the memory comes from, as a JSON object. It is stored in its own column and kept in history. |
None
|
valid_at
|
datetime | None
|
When the fact became true, as a timezone-aware datetime. Without one the memory stores no valid time and is valid from its updated_at. |
None
|
Returns:
| Type | Description |
|---|---|
ConditionalWrite
|
Whether the write applied, the version written, and on a |
ConditionalWrite
|
conflict the current memory. |
Raises:
| Type | Description |
|---|---|
InvalidNamespaceError
|
If the namespace is empty or a label is invalid |
ValueError
|
Before any I/O: if |
reconcile(namespace, key, value, *, policy, slot=None, threshold=None, limit=10, filter=None, index=None, ttl=NOT_PROVIDED, provenance=None, valid_at=None)
¶
Write a memory and settle the memories it may conflict with, in one transaction.
The candidates are the ones find_conflicts finds: the live memory
under key, the memories in the same slot and, on a store with an
index, those that score at or above threshold. They are read in
the transaction, policy decides what to do with the new memory
and with each candidate, and the decision is applied before the
transaction commits. Serializable isolation covers all of it: if
another writer changes what the policy saw, one of the two
transactions retries, and its policy sees the other's write. Two
agents that reconcile contradicting memories for one user cannot
both win.
policy runs inside the transaction, and runs again on every
retry, so it must be a plain function, fast and deterministic: an
async function is refused before any I/O. A slow policy holds the
transaction open and can run past the attempt timeout. An LLM judge,
or a person, belongs in find_conflicts and resolve, which hold no
transaction while the decision is made. A policy must not call the
store either: the store holds its connection while the policy runs,
so such a call raises RuntimeError at once. A policy that raises
rolls the transaction back, and its exception propagates unchanged,
without a retry. So does the ValueError for an invalid decision.
The decision writes the new memory, as put does, with its provenance
and valid time; skips it, as when it repeats a memory the decision
confirms; or records it as superseded by a candidate whose fact is
newer. A store with history records such a late fact straight into
history; a store without history skips it. Each candidate is kept,
superseded, deleted or confirmed. On a store with history, every
version the decision ends is kept in history: the memory the new one
overwrites and each candidate it supersedes end at the valid_at
given, or at the write without one, and deleted ones end at the
write. Without history, superseding and deleting remove the memory.
Confirming sets confirmed_at, counts the confirmation and renews the
memory's expiry from its own TTL. It changes neither the version nor
updated_at.
The index fields of value are embedded once, before the first
attempt. Each attempt reads the candidates in two round trips, as
find_conflicts does, or three when the index's window may have left
matches out. Then the policy runs, and the writes and the COMMIT go
out together.
If an attempt commits and its result is lost, as when the connection
drops while the COMMIT's answer travels, the retry finds the rows
that carry its write id and writes nothing. It returns the result
rebuilt from those rows, with already_applied set. That result
lists only what the rows prove: kept is empty, and on a store
without history so are superseded and deleted. A
confirmation of the new memory in between leaves the write id on it.
If another writer replaced the new memory before the retry, the
history row of the version it overwrote, or of a memory it
superseded, still proves the write: the result says it was written,
with no version.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
namespace
|
tuple[str, ...]
|
The new memory's namespace. It cannot be empty. |
required |
key
|
str | None
|
The new memory's key, or None for a new uuid4. |
required |
value
|
dict[str, Any]
|
The new memory's value. |
required |
policy
|
Policy
|
Decides, from the new memory as a Proposal and its candidates, what to do with each: a function that returns a Decision. langchain_cockroachdb.store has built-in ones. |
required |
slot
|
str | None
|
A top-level field of |
None
|
threshold
|
float | None
|
The lowest score of a similar candidate, as in find_conflicts: 0.8 by default on a cosine store, required on an l2 or inner_product store, ignored without an index. |
None
|
limit
|
int
|
Most similar candidates (default 10), on top of the key and slot matches. |
10
|
filter
|
dict[str, Any] | None
|
Narrows the slot and similar candidates by value, as in search. |
None
|
index
|
Literal[False] | list[str] | None
|
Which fields of |
None
|
ttl
|
float | None | NotProvided
|
Minutes the new memory lives once written, or None for no expiry. Defaults to the store's default TTL. |
NOT_PROVIDED
|
provenance
|
dict[str, Any] | None
|
Where the new memory comes from, as a JSON object. It is stored in its own column and kept in history. |
None
|
valid_at
|
datetime | None
|
When the fact became true, as a timezone-aware datetime. By default the database's current time, raised to the latest candidate's updated_at if that is later. The memory then stores no valid time and is valid from its updated_at. |
None
|
Returns:
| Type | Description |
|---|---|
ReconcileResult
|
What happened: the new memory's key, whether it was written, |
ReconcileResult
|
skipped or superseded, the version written, and the keys of the |
ReconcileResult
|
candidates superseded, deleted, confirmed and kept. |
Raises:
| Type | Description |
|---|---|
InvalidNamespaceError
|
If the namespace is empty or a label is invalid |
ValueError
|
If another argument is invalid, as in find_conflicts; if the policy is async or returns an invalid decision; or if setup() has not added the columns this method needs or, on a store with history, created the history table |
record(namespace, key)
¶
Read a live memory with its version, provenance, valid time and confirmations.
Reading a memory does not confirm it, so its expiry is never pushed back.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
namespace
|
tuple[str, ...]
|
The memory's namespace. |
required |
key
|
str
|
The memory's key. |
required |
Returns:
| Type | Description |
|---|---|
MemoryRecord | None
|
The memory, or None if no live memory has that key: there is |
MemoryRecord | None
|
none, or it expired. |
Raises:
| Type | Description |
|---|---|
InvalidNamespaceError
|
If the namespace is empty or a label is invalid |
ValueError
|
If setup() has not added the columns this method needs |
resolve(conflicts, decision)
¶
Apply a decision about what find_conflicts found, in one transaction.
This is the second step of the two-step flow: find_conflicts reads the candidates, an LLM or a person decides while no transaction is open, and resolve applies the decision as reconcile applies a policy's. It writes the new memory that find_conflicts planned, with its provenance, valid time and write id, and the vectors it embedded then, so nothing is embedded again. For the same reason it refuses a proposal edited after find_conflicts, rather than drop the edit: to change the memory, call find_conflicts again with the edited one.
In the same transaction, before it writes, resolve checks that nothing the decision depends on has changed. The memory under the new memory's key, and every candidate the decision supersedes, deletes or confirms, or names as superseding the new memory, must still have the version and updated_at that find_conflicts read. A memory written since counts as changed, also when a 0.5.x store wrote it, which sets updated_at without bumping the version. So does one deleted or expired since, and a live memory under the new key where find_conflicts found none. resolve then raises ConflictsChanged with those keys, writes nothing and does not retry: run find_conflicts again and decide again. Candidates the decision keeps are not checked, and confirming a memory changes neither its version nor updated_at, so a confirmation in between never counts.
The write id comes from find_conflicts. If a resolve of the same
Conflicts already committed, as when an error left its outcome
unknown and the caller calls again, resolve writes nothing and
returns that write's result rebuilt from its rows, with
already_applied set, whatever decision this call passes. As with
reconcile, a rebuilt result lists only what the rows prove: kept
is empty, and on a store without history so are superseded and
deleted. Such a store keeps no row of a decision that only
supersedes or deletes. When the commit of such a resolve is lost, its
retry finds those memories gone, as the decision asked. So once an
attempt of the call may have committed (it sent its COMMIT and failed
with an error other than a serialization failure or a deadlock, which
roll the attempt back), a memory the decision supersedes or deletes,
the one under the new key included, counts as unchanged when it is
gone. The retry applies the decision again, which changes nothing
there, and returns its result without already_applied, since no
row proves the earlier commit. After only serialization failures or
deadlocks (40001, 40P01), which roll attempts back, the retry checks
as strictly as the first attempt: a memory gone since was removed by
another writer, and is a change. Once an attempt may have committed,
the retries after it stay lenient, whatever error ends them next. A
new call checks strictly again too: if an error escaped an earlier
call, as when its retries ran out or the hang guard stopped it, and
the caller calls resolve again, such a decision raises
ConflictsChanged naming the keys that the earlier call removed.
find_conflicts then shows the current state.
Without a valid_at given to find_conflicts, the new memory
stores no valid time, so it is valid from its write, and the
versions the decision ends end at that write. A Conflicts and a
Decision can wait in a LangGraph checkpoint while a person decides:
resolve takes them as the checkpoint gives them back.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
conflicts
|
Conflicts
|
What find_conflicts returned, on a store with the same table and index. |
required |
decision
|
Decision
|
What to do with the new memory and each candidate. |
required |
Returns:
| Type | Description |
|---|---|
ReconcileResult
|
What happened, as reconcile reports it. |
Raises:
| Type | Description |
|---|---|
ConflictsChanged
|
If a memory the decision depends on changed since find_conflicts. The attempt that found it wrote nothing. |
ValueError
|
Before any I/O: if |
setup()
¶
Create the store's tables and run its migrations.
MUST be called the first time the store is used. Safe to run from
several processes at once: every migration is idempotent and versions
are recorded with ON CONFLICT DO NOTHING. A setup() that finds another
process still applying migration 2 waits for it, for up to
SCHEMA_CHANGE_SETTLE_SECONDS, before it records the migration, so no
store writes the new columns before they exist. When no job applies
the migration, as after a peer's migration failed, it applies the
migration itself. With an index, it creates
the vectors table and its C-SPANN index (unless flat) on every
call, then checks an existing index against the configuration. With
history, it creates the history table, and with ttl_days turns on
CockroachDB row-level TTL there. With a TTL configuration, it then
turns on CockroachDB row-level TTL on expires_at.
It reads a table's TTL settings first and changes them only when
they differ from the configuration. On CockroachDB v25.4 a TTL
change fails while another schema change runs on the same table,
such as a vector index that another setup() builds. That error is
retried with the budget that schema_change_policy gives it, up to
ten minutes by default for each table, even if the policy's
retry_on would refuse it; max_attempts=1 turns this off.
An application role that did not run setup() needs SELECT, INSERT, UPDATE and DELETE on the store's items and vectors tables, and on the history table when history is on. With history off, it still needs SELECT and DELETE on a history table that exists, left from when history was on, for delete_namespace. Without SELECT on the migrations table, or without a migrations table, as when the tables were created without setup(), the store finds migration 2 through the items table's columns instead. On a multi-node cluster, one write can then fail in the seconds after setup() applies migration 2. Running setup() before rolling out 0.6.0, or granting SELECT on the migrations table, avoids that. The first store call inside a transaction the caller opened gets the permission error once. Only the SELECT grant avoids it.
Raises:
| Type | Description |
|---|---|
ValueError
|
If the vectors table exists with other dims, or its
index uses another distance. A different partition size, or
an index while |
TimeoutError
|
If another process is still applying migration 2 after SCHEMA_CHANGE_SETTLE_SECONDS. Run setup() again. |
start_ttl_sweeper(sweep_interval_minutes=None)
¶
Sweep expired items periodically in a background thread.
CockroachDB's row-level TTL job, turned on by setup() with a TTL configuration, already deletes expired rows. The sweeper deletes them sooner. Expired items are never returned either way.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
sweep_interval_minutes
|
int | None
|
Minutes between sweeps. Defaults to the TTL configuration's sweep_interval_minutes, else 5. |
None
|
Returns:
| Type | Description |
|---|---|
Future[None]
|
A future that completes when the sweeper stops. Cancelling it |
Future[None]
|
stops the sweeper. |
stop_ttl_sweeper(timeout=None)
¶
Stop the TTL sweeper thread if it is running.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
timeout
|
float | None
|
Seconds to wait for the thread to stop, or None to wait. |
None
|
Returns:
| Type | Description |
|---|---|
bool
|
True if the thread stopped or was not running, False on timeout. |
sweep_ttl()
¶
Delete expired items now, without waiting for CockroachDB's TTL job.
Returns:
| Type | Description |
|---|---|
int
|
The number of items deleted. |
AsyncCockroachDBStore¶
Asynchronous store.
langchain_cockroachdb.store.aio.AsyncCockroachDBStore
¶
Bases: AsyncBatchedBaseStore, BaseCockroachDBStore, AsyncPsycopgOps
Async LangGraph store that keeps long-term memory in CockroachDB.
The async twin of CockroachDBStore: same tables, same SQL, same
behavior. For production, pass a psycopg_pool.AsyncConnectionPool
or use from_conn_string with pool_config: a pool replaces broken
connections, while a single connection cannot recover from a dropped one.
aget, aput, asearch and the other awaited calls, and the sync
wrappers, go through AsyncBatchedBaseStore's queue, which runs one
abatch at a time. So a pool does not run those calls in parallel, and
a large pool does not speed them up. What the queue gives instead is
coalescing: ops queued in the same tick run as one batch, with one round
trip per read group and one transaction for the writes. Only direct
abatch calls, or sync batch calls from other threads, run
concurrently on a pool.
The constructor must run inside a running event loop, because
AsyncBatchedBaseStore starts a task on it there. Awaited calls made in
the same tick (aget, aput, asearch and the others) are
coalesced into one abatch. The sync methods (get, put and the
others) are meant for other threads while that loop runs. They run the
async methods on it, so get, put, search, delete and
list_namespaces join the same queue, while batch runs abatch
directly. From the loop itself they raise asyncio.InvalidStateError. When the loop is closed or not
running, or the call comes from a forked child of the process that
created the store, they raise RuntimeError instead of waiting
forever, as AsyncCockroachDBSaver's sync methods do.
A batch runs its reads first, then all its puts and deletes in one transaction. Its gets, its searches and its listings take one round trip each. On a store with a vector index, semantic searches under a namespace add one before the searches, to find their namespaces, and one after them when a search must run again exactly. A flat store adds neither. The long-term memory guide explains why.
With history, a batch that overwrites or deletes a memory first
copies the version it ends into a history table, in its transaction.
adelete then keeps the memory in history; apurge removes a memory
with its history, and ahistory lists the old versions.
afind_conflicts, aresolve, areconcile, aconfirm,
arecord, aput_if and adelete_if are CockroachDBStore's
methods of the same names without the prefix, as coroutines. They run on
the caller's event loop, not through the queue, so on a pool they run
concurrently. A reconcile policy and a confirm TTL function are plain
functions that run on the event loop inside the transaction.
Example
from langchain_cockroachdb import AsyncCockroachDBStore
async with AsyncCockroachDBStore.from_conn_string(
"cockroachdb://root@localhost:26257/defaultdb?sslmode=disable"
) as store:
await store.setup()
await store.aput(("users", "123"), "prefs", {"theme": "dark"})
item = await store.aget(("users", "123"), "prefs")
__init__(conn, *, pipe=None, index=None, ttl=None, history=None, reconcile_scan_limit=DEFAULT_RECONCILE_SCAN_LIMIT, retry_policy=None, table_name='store', schema='public')
¶
Create a store on a connection or a pool, inside a running event loop.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
conn
|
AsyncConn
|
A psycopg AsyncConnection, or an AsyncConnectionPool (recommended). It must be in autocommit mode and use dict_row. |
required |
pipe
|
AsyncPipeline | None
|
A pipeline on |
None
|
index
|
CockroachDBIndexConfig | None
|
Semantic search settings. When given, setup() also creates the vectors table and its C-SPANN index, and puts embed the configured fields of each item. |
None
|
ttl
|
TTLConfig | CockroachDBTTLConfig | None
|
TTL settings. When given, setup() also turns on CockroachDB row-level TTL for expired rows. |
None
|
history
|
bool | HistoryConfig | None
|
Version history: True, or a HistoryConfig to give old versions a TTL. setup() then creates the history table, and every batch keeps the versions it overwrites or deletes there. Default None, no history. |
None
|
reconcile_scan_limit
|
int
|
The most vectors a namespace may hold for find_conflicts to rank every one of them, by primary key (default 2000). A namespace with more finds its similar candidates through the C-SPANN index, and ranks every vector only when the index's window may have left matches out. |
DEFAULT_RECONCILE_SCAN_LIMIT
|
retry_policy
|
RetryPolicy | None
|
How operations retry (default: RetryPolicy()) |
None
|
table_name
|
str
|
Name of the items table (default "store") |
'store'
|
schema
|
str
|
Schema of the store's tables (default "public") |
'public'
|
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If no event loop is running |
ValueError
|
If a pipeline is given with a pool, or a name or the TTL, index, history or reconcile_scan_limit settings are invalid |
abatch(ops)
async
¶
Run a batch of operations.
Every op is validated, and every put value serialized, before any statement runs. Gets, searches and listings run first, then all puts and deletes commit together in one transaction.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ops
|
Iterable[Op]
|
GetOp, SearchOp, ListNamespacesOp and PutOp operations. |
required |
Returns:
| Type | Description |
|---|---|
list[Result]
|
One result per op, in the order of |
aconfirm(namespace, key, *, ttl=NOT_PROVIDED)
async
¶
Mark a live memory as confirmed, renewing its expiry and counting confirmations.
The async form of CockroachDBStore.confirm. This counts the confirmation and renews the expiry. That way expiry can follow how often a fact is confirmed, not how often it is read. Confirming does not change the version or updated_at, so it never invalidates a pending afind_conflicts. Confirmations belong to the memory's value: a write that changes it starts them again from none. Each call picks a confirmation id of its own, so a retry after a lost commit counts nothing again, unless another confirmation of the same memory lands in between, in which case the retry counts again. The memory's write id stays as it is.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
namespace
|
tuple[str, ...]
|
The memory's namespace. |
required |
key
|
str
|
The memory's key. |
required |
ttl
|
float | None | NotProvided | Callable[[MemoryRecord], float | None]
|
How long the memory stays after confirmation. NOT_PROVIDED renews from the row's own TTL. None removes the expiry. A number is minutes. A callable takes the MemoryRecord read in the same transaction and returns a number of minutes or None. It is a plain function that runs on the event loop: keep it fast and deterministic, since it runs again on each retry, and it must not call the store. An async function is refused before any I/O. |
NOT_PROVIDED
|
Returns:
| Type | Description |
|---|---|
bool
|
True if a live memory was confirmed, False if no live memory has |
bool
|
that key: there is none, or it expired. |
Raises:
| Type | Description |
|---|---|
InvalidNamespaceError
|
If the namespace is empty or a label is invalid |
ValueError
|
If ttl is not NOT_PROVIDED, None, a positive finite number of minutes, or a plain callable; if setup() has not added the columns this method needs; or if the callable returns an invalid value (not None or a positive finite number, a coroutine included) |
adelete_if(namespace, key, *, expected)
async
¶
Delete a memory only if it is still the one the caller read, in one transaction.
The async form of CockroachDBStore.delete_if, which describes the
retries in full. adelete_if deletes only if the live memory under
key still has the version and updated_at of expected, as
aput_if checks them. On a match it deletes as adelete does: on a
store with history the memory is kept in history as deleted, and its
vectors go. With expected=None it applies only while no live
memory has the key, so it deletes nothing live.
applied=True means the memory matched expected and this call
deleted it, or, after an earlier attempt of the call that may have
committed, that the memory is gone and was this call's to delete. On
a mismatch it deletes nothing and returns applied=False with
current, the live memory as the same transaction read it, or
None if there is none. A conflict is returned, not raised.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
namespace
|
tuple[str, ...]
|
The memory's namespace. It cannot be empty. |
required |
key
|
str
|
The memory's key. |
required |
expected
|
MemoryRecord | None
|
The MemoryRecord that arecord() returned for this namespace and key, or None. |
required |
Returns:
| Type | Description |
|---|---|
ConditionalWrite
|
Whether the delete applied, and on a conflict the current memory. |
Raises:
| Type | Description |
|---|---|
InvalidNamespaceError
|
If the namespace is empty or a label is invalid |
ValueError
|
Before any I/O: if |
adelete_namespace(namespace_prefix)
async
¶
Delete every item in a namespace and its descendants.
("user", "a") deletes ("user", "a") and ("user", "a", "b"),
not ("user", "ab"). One statement deletes the items, their
vectors and their history. A store without history deletes history
too when the history table exists, as when the store kept history
before, so nothing of the namespace is left. Its role then needs
SELECT and DELETE on that table: without them the whole call fails
with a permission error and deletes nothing, rather than forget only
part of the namespace.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
namespace_prefix
|
tuple[str, ...]
|
The namespace to delete. It cannot be empty. |
required |
Returns:
| Type | Description |
|---|---|
int
|
The number of items deleted. If a retry follows a commit whose |
int
|
result was lost, the count is that of the retry, usually 0. |
Raises:
| Type | Description |
|---|---|
InvalidNamespaceError
|
If the prefix is empty or a label is invalid |
ValueError
|
If the store keeps history and setup() has not created the history table |
adisable_ttl()
async
¶
Turn off CockroachDB row-level TTL on the store's tables.
Expired items are still left out of reads while omit_expired is on.
Safe to run from several processes at once. On CockroachDB v25.4 a
TTL change fails while another schema change runs on the same table;
that error is retried with the budget that schema_change_policy
gives it, up to ten minutes by default, even if the policy's
retry_on would refuse it. max_attempts=1 turns this off.
adrop_vector_index()
async
¶
Drop the store's vector index, if it exists.
Run setup() afterwards to build it again with the store's current configuration, for example to change the distance. Searches scan the vectors until the new index is built.
afind_conflicts(namespace, key, value, *, slot=None, threshold=None, limit=10, filter=None, index=None, ttl=NOT_PROVIDED, provenance=None, valid_at=None)
async
¶
Find the memories a new one may conflict with, without writing anything.
The async form of CockroachDBStore.find_conflicts, which describes
the candidates in full. They are live memories in namespace
itself, for one of three reasons, strongest first: the memory under
key; with slot, the memories whose value holds the same value
in that field; and on a store with an index, the memories whose
vectors score at or above threshold against the new memory's,
with the store's score function. Candidates come strongest reason
first, then best score, then key. Expired memories are never
candidates, and no read pushes back an expiry.
The index fields of value are embedded once, with
aembed_documents, and the embedding is kept for aresolve. Then two
round trips read the candidates, or three when the C-SPANN index's
window may have left matches out.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
namespace
|
tuple[str, ...]
|
The new memory's namespace. It cannot be empty. |
required |
key
|
str | None
|
The new memory's key, or None for a new uuid4. |
required |
value
|
dict[str, Any]
|
The new memory's value. |
required |
slot
|
str | None
|
A top-level field of |
None
|
threshold
|
float | None
|
The lowest score of a similar candidate. On a cosine
store it defaults to 0.8 and must lie between -1 and 1. On an
l2 or inner_product store, where scores are negated distances,
it must be given. Ignored without an index or with
|
None
|
limit
|
int
|
Most similar candidates (default 10). The key and slot matches come on top of them; 0 keeps only those. |
10
|
filter
|
dict[str, Any] | None
|
Narrows the slot and similar candidates by value, as in
search. The memory under |
None
|
index
|
Literal[False] | list[str] | None
|
Which fields of |
None
|
ttl
|
float | None | NotProvided
|
Minutes the new memory lives once written, or None for no expiry. Defaults to the store's default TTL. |
NOT_PROVIDED
|
provenance
|
dict[str, Any] | None
|
Where the new memory comes from, as a JSON object. |
None
|
valid_at
|
datetime | None
|
When the fact became true, as a timezone-aware datetime. By default the database's current time, raised to the latest candidate's updated_at if that is later. |
None
|
Returns:
| Type | Description |
|---|---|
Conflicts
|
The new memory as a Proposal, its candidates, and the version |
Conflicts
|
and updated_at of the live memory under |
Raises:
| Type | Description |
|---|---|
InvalidNamespaceError
|
If the namespace is empty or a label is invalid |
ValueError
|
If another argument is invalid (above), or setup() has not added the columns this method needs |
ahistory(namespace, key=None, *, limit=20, offset=0)
async
¶
The old versions of a memory, or of every memory in a namespace, newest first.
A store with history keeps every version that a write ends: one a
put overwrites (reason "overwritten"), one a delete ends
("deleted"), and one that reconcile or resolve supersedes
("superseded", with superseded_by naming the memory that
replaced it). A new memory that reconcile or resolve records as
already superseded by a newer fact is kept there too, as
"superseded". The live value is not one of them; aget() returns it.
Without a key, it lists the old versions of every memory in exactly
namespace, not its descendants, as aget() reads a namespace. That
is how to find the old versions of memories that areconcile saved
under keys the store generated. Each version carries its own key
and superseded_by, so versions can be grouped by a field of
their value, or followed to the memory that replaced them. Each call
reads the namespace's whole history to sort it, which suits
per-user namespaces. For a very large history, page with limit
and offset.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
namespace
|
tuple[str, ...]
|
The memory's namespace. |
required |
key
|
str | None
|
The memory's key, or None for every memory in the namespace. |
None
|
limit
|
int
|
Most versions to return (default 20). |
20
|
offset
|
int
|
Versions to skip, for paging (default 0). |
0
|
Returns:
| Type | Description |
|---|---|
list[MemoryVersion]
|
Up to |
list[MemoryVersion]
|
when it ended. With a key, highest version first. Without one, |
list[MemoryVersion]
|
newest first by |
list[MemoryVersion]
|
first, so pages are stable. Versions past the history's |
list[MemoryVersion]
|
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If the store keeps no history (create it with
history=True and run setup()), setup() has not created the
history table, or |
InvalidNamespaceError
|
If the namespace is empty or a label is invalid |
apurge(namespace, key)
async
¶
Forget a memory: delete the item, its vectors and its history.
On a store with history, adelete() keeps the version it ends, so apurge is how to remove a memory for good. One statement deletes all of it.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
namespace
|
tuple[str, ...]
|
The memory's namespace. |
required |
key
|
str
|
The memory's key. |
required |
Returns:
| Type | Description |
|---|---|
bool
|
Whether anything was deleted: the memory, or only its history |
bool
|
after a delete. If a retry follows a commit whose result was |
bool
|
lost, the retry finds nothing and returns False. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the store keeps no history (create it with history=True and run setup(); without history, adelete() already removes a memory and its vectors), or setup() has not created the history table |
InvalidNamespaceError
|
If the namespace is empty or a label is invalid |
aput_if(namespace, key, value, *, expected, index=None, ttl=NOT_PROVIDED, provenance=None, valid_at=None)
async
¶
Write a memory only if it is still the one the caller read, in one transaction.
The async form of CockroachDBStore.put_if. Two tasks that read the
same memory with arecord() and both write it back with aput would
lose one update without a word. aput_if writes only if the live
memory under key still has the version and updated_at of
expected: a put moves the version, and a 0.5.x store, which does
not, still moves updated_at. With expected=None it writes only if
no live memory has the key, so a memory is created once. An expired
memory counts as absent.
On a match it writes as aput does, in the transaction that checked,
keeping the version it replaces in history on a store with history.
On a mismatch it writes nothing and returns applied=False with
current, the live memory as the same transaction read it, or
None. A conflict is an expected outcome here, so it is returned, not
raised. If an attempt commits and its result is lost, the retry finds
the write id on the row and returns applied=True with
already_applied. If another writer replaced the memory before the
retry, the retry reports a conflict with that writer's memory.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
namespace
|
tuple[str, ...]
|
The memory's namespace. It cannot be empty. |
required |
key
|
str
|
The memory's key. |
required |
value
|
dict[str, Any]
|
The new value. |
required |
expected
|
MemoryRecord | None
|
The MemoryRecord that arecord() returned for this namespace and key, or None to write only if no live memory has the key. |
required |
index
|
Literal[False] | list[str] | None
|
Which fields of |
None
|
ttl
|
float | None | NotProvided
|
Minutes the memory lives once written, or None for no expiry. Defaults to the store's default TTL. |
NOT_PROVIDED
|
provenance
|
dict[str, Any] | None
|
Where the memory comes from, as a JSON object. It is stored in its own column and kept in history. |
None
|
valid_at
|
datetime | None
|
When the fact became true, as a timezone-aware datetime. Without one the memory stores no valid time and is valid from its updated_at. |
None
|
Returns:
| Type | Description |
|---|---|
ConditionalWrite
|
Whether the write applied, the version written, and on a |
ConditionalWrite
|
conflict the current memory. |
Raises:
| Type | Description |
|---|---|
InvalidNamespaceError
|
If the namespace is empty or a label is invalid |
ValueError
|
Before any I/O: if |
areconcile(namespace, key, value, *, policy, slot=None, threshold=None, limit=10, filter=None, index=None, ttl=NOT_PROVIDED, provenance=None, valid_at=None)
async
¶
Write a memory and settle the memories it may conflict with, in one transaction.
The async form of CockroachDBStore.reconcile, which describes the
decisions and the result in full. The candidates are the ones
afind_conflicts finds. They are read in the transaction, policy
decides what to do with the new memory and with each candidate, and
the decision is applied before the transaction commits. Serializable
isolation covers all of it: if another writer changes what the policy
saw, one of the two transactions retries, and its policy sees the
other's write. Two agents that reconcile contradicting memories for
one user cannot both win.
policy is a plain function, not an async one, which is refused
before any I/O. It runs on the event loop, inside the transaction,
and runs again on every retry, so it must be fast and deterministic:
the loop runs nothing else while it runs. An LLM judge, or a person,
belongs in afind_conflicts and aresolve, which hold no transaction
while the decision is made. A policy must not call the store either:
the store holds its connection while the policy runs, so such a call
raises RuntimeError at once. A policy that raises rolls the
transaction back, and its exception propagates unchanged, without a
retry. So does the ValueError for an invalid decision.
The index fields of value are embedded once, with
aembed_documents, before the first attempt. If an attempt commits
and its result is lost, as when the connection drops while the
COMMIT's answer travels, the retry finds the rows that carry its
write id and writes nothing. It returns the result rebuilt from
those rows, with already_applied set, listing only what the rows
prove: kept is empty, and on a store without history so are
superseded and deleted.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
namespace
|
tuple[str, ...]
|
The new memory's namespace. It cannot be empty. |
required |
key
|
str | None
|
The new memory's key, or None for a new uuid4. |
required |
value
|
dict[str, Any]
|
The new memory's value. |
required |
policy
|
Policy
|
Decides, from the new memory as a Proposal and its candidates, what to do with each: a function that returns a Decision. langchain_cockroachdb.store has built-in ones. |
required |
slot
|
str | None
|
A top-level field of |
None
|
threshold
|
float | None
|
The lowest score of a similar candidate, as in afind_conflicts: 0.8 by default on a cosine store, required on an l2 or inner_product store, ignored without an index. |
None
|
limit
|
int
|
Most similar candidates (default 10), on top of the key and slot matches. |
10
|
filter
|
dict[str, Any] | None
|
Narrows the slot and similar candidates by value, as in search. |
None
|
index
|
Literal[False] | list[str] | None
|
Which fields of |
None
|
ttl
|
float | None | NotProvided
|
Minutes the new memory lives once written, or None for no expiry. Defaults to the store's default TTL. |
NOT_PROVIDED
|
provenance
|
dict[str, Any] | None
|
Where the new memory comes from, as a JSON object. It is stored in its own column and kept in history. |
None
|
valid_at
|
datetime | None
|
When the fact became true, as a timezone-aware datetime. By default the database's current time, raised to the latest candidate's updated_at if that is later. The memory then stores no valid time and is valid from its updated_at. |
None
|
Returns:
| Type | Description |
|---|---|
ReconcileResult
|
What happened: the new memory's key, whether it was written, |
ReconcileResult
|
skipped or superseded, the version written, and the keys of the |
ReconcileResult
|
candidates superseded, deleted, confirmed and kept. |
Raises:
| Type | Description |
|---|---|
InvalidNamespaceError
|
If the namespace is empty or a label is invalid |
ValueError
|
If another argument is invalid, as in afind_conflicts; if the policy is async or returns an invalid decision; or if setup() has not added the columns this method needs or, on a store with history, created the history table |
arecord(namespace, key)
async
¶
Read a live memory with its version, provenance, valid time and confirmations.
Reading a memory does not confirm it, so its expiry is never pushed back.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
namespace
|
tuple[str, ...]
|
The memory's namespace. |
required |
key
|
str
|
The memory's key. |
required |
Returns:
| Type | Description |
|---|---|
MemoryRecord | None
|
The memory, or None if no live memory has that key: there is |
MemoryRecord | None
|
none, or it expired. |
Raises:
| Type | Description |
|---|---|
InvalidNamespaceError
|
If the namespace is empty or a label is invalid |
ValueError
|
If setup() has not added the columns this method needs |
aresolve(conflicts, decision)
async
¶
Apply a decision about what afind_conflicts found, in one transaction.
The async form of CockroachDBStore.resolve, which describes the checks and the retries in full. This is the second step of the two-step flow: afind_conflicts reads the candidates, an LLM or a person decides while no transaction is open, and aresolve applies the decision as areconcile applies a policy's. It writes the new memory that afind_conflicts planned, with its provenance, valid time and write id, and the vectors it embedded then, so nothing is embedded again. For the same reason it refuses a proposal edited after afind_conflicts.
In the same transaction, before it writes, aresolve checks that the memory under the new memory's key, and every candidate the decision supersedes, deletes or confirms, or names as superseding the new memory, still has the version and updated_at that afind_conflicts read. If one changed, it raises ConflictsChanged with those keys, writes nothing and does not retry: find the conflicts again and decide again. Candidates the decision keeps are not checked, and a confirmation in between never counts.
If a resolve of the same Conflicts already committed, aresolve
writes nothing and returns that write's result, rebuilt from its
rows, with already_applied set. Once an attempt of the call may
have committed (it sent its COMMIT and failed with an error other
than a serialization failure or a deadlock), a memory the decision
supersedes or deletes counts as unchanged when it is gone, for the
rest of the call. A Conflicts and a Decision can wait in a LangGraph
checkpoint while a person decides: aresolve takes them as the
checkpoint gives them back.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
conflicts
|
Conflicts
|
What afind_conflicts returned, on a store with the same table and index, sync or async. |
required |
decision
|
Decision
|
What to do with the new memory and each candidate. |
required |
Returns:
| Type | Description |
|---|---|
ReconcileResult
|
What happened, as areconcile reports it. |
Raises:
| Type | Description |
|---|---|
ConflictsChanged
|
If a memory the decision depends on changed since afind_conflicts. The attempt that found it wrote nothing. |
ValueError
|
Before any I/O: if |
batch(ops)
¶
Run abatch on the store's event loop, from another thread.
Raises:
| Type | Description |
|---|---|
InvalidStateError
|
If called from the store's loop |
RuntimeError
|
If that loop is closed, is not running or stops before the work finishes, or in a forked child; or, before any of these checks, if called from inside a reconcile policy or a confirm TTL function of the store |
delete(namespace, key)
¶
Run adelete on the store's event loop, from another thread.
Raises:
| Type | Description |
|---|---|
InvalidStateError
|
If called from the store's loop |
RuntimeError
|
If that loop is closed, is not running or stops before the work finishes, or in a forked child; or, before any of these checks, if called from inside a reconcile policy or a confirm TTL function of the store |
from_conn_string(conn_string, *, pipeline=False, pool_config=None, index=None, ttl=None, history=None, reconcile_scan_limit=DEFAULT_RECONCILE_SCAN_LIMIT, retry_policy=None, connect_timeout=10.0, prepare_threshold=5, connect_kwargs=None, table_name='store', schema='public')
async
classmethod
¶
Create a store on a new connection, or on a new pool with pool_config.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
conn_string
|
str
|
CockroachDB connection string (cockroachdb://, postgresql:// and similar) |
required |
pipeline
|
bool
|
Whether to use pipeline mode on the single connection. Ignored with pool_config. |
False
|
pool_config
|
PoolConfig | None
|
Open an AsyncConnectionPool with these settings instead of one connection |
None
|
index
|
CockroachDBIndexConfig | None
|
Semantic search settings |
None
|
ttl
|
TTLConfig | CockroachDBTTLConfig | None
|
TTL settings |
None
|
history
|
bool | HistoryConfig | None
|
Version history settings (default None, no history) |
None
|
reconcile_scan_limit
|
int
|
The most vectors a namespace may hold for find_conflicts to rank every one of them (default 2000) |
DEFAULT_RECONCILE_SCAN_LIMIT
|
retry_policy
|
RetryPolicy | None
|
How operations retry (default: RetryPolicy()) |
None
|
connect_timeout
|
float | None
|
Seconds to wait when connecting, or None (default: 10) |
10.0
|
prepare_threshold
|
int | None
|
psycopg prepared statement threshold, None to disable (default: 5). Statements sent in a pipeline are never prepared |
5
|
connect_kwargs
|
Mapping[str, Any] | None
|
Extra psycopg connection options, e.g. application_name |
None
|
table_name
|
str
|
Name of the items table (default "store") |
'store'
|
schema
|
str
|
Schema of the store's tables (default "public") |
'public'
|
Yields:
| Type | Description |
|---|---|
AsyncIterator[AsyncCockroachDBStore]
|
AsyncCockroachDBStore instance. The connection or pool closes on exit. |
With pool_config, pipeline is ignored, as in AsyncPostgresStore:
a pipeline needs a single connection.
Raises:
| Type | Description |
|---|---|
ValueError
|
If the index, history or reconcile_scan_limit settings are invalid, before any connection is opened |
get(namespace, key, *, refresh_ttl=None)
¶
Run aget on the store's event loop, from another thread.
Raises:
| Type | Description |
|---|---|
InvalidStateError
|
If called from the store's loop |
RuntimeError
|
If that loop is closed, is not running or stops before the work finishes, or in a forked child; or, before any of these checks, if called from inside a reconcile policy or a confirm TTL function of the store |
list_namespaces(*, prefix=None, suffix=None, max_depth=None, limit=100, offset=0)
¶
Run alist_namespaces on the store's event loop, from another thread.
Raises:
| Type | Description |
|---|---|
InvalidStateError
|
If called from the store's loop |
RuntimeError
|
If that loop is closed, is not running or stops before the work finishes, or in a forked child; or, before any of these checks, if called from inside a reconcile policy or a confirm TTL function of the store |
put(namespace, key, value, index=None, *, ttl=NOT_PROVIDED)
¶
Run aput on the store's event loop, from another thread.
Raises:
| Type | Description |
|---|---|
InvalidStateError
|
If called from the store's loop |
RuntimeError
|
If that loop is closed, is not running or stops before the work finishes, or in a forked child; or, before any of these checks, if called from inside a reconcile policy or a confirm TTL function of the store |
search(namespace_prefix, /, *, query=None, filter=None, limit=10, offset=0, refresh_ttl=None)
¶
Run asearch on the store's event loop, from another thread.
Raises:
| Type | Description |
|---|---|
InvalidStateError
|
If called from the store's loop |
RuntimeError
|
If that loop is closed, is not running or stops before the work finishes, or in a forked child; or, before any of these checks, if called from inside a reconcile policy or a confirm TTL function of the store |
setup()
async
¶
Create the store's tables and run its migrations.
MUST be called the first time the store is used. Safe to run from
several processes at once: every migration is idempotent and versions
are recorded with ON CONFLICT DO NOTHING. A setup() that finds another
process still applying migration 2 waits for it, for up to
SCHEMA_CHANGE_SETTLE_SECONDS, before it records the migration, so no
store writes the new columns before they exist. When no job applies
the migration, as after a peer's migration failed, it applies the
migration itself. With an index, it creates
the vectors table and its C-SPANN index (unless flat) on every
call, then checks an existing index against the configuration. With
history, it creates the history table, and with ttl_days turns on
CockroachDB row-level TTL there. With a TTL configuration, it then
turns on CockroachDB row-level TTL on expires_at.
It reads a table's TTL settings first and changes them only when
they differ from the configuration. On CockroachDB v25.4 a TTL
change fails while another schema change runs on the same table,
such as a vector index that another setup() builds. That error is
retried with the budget that schema_change_policy gives it, up to
ten minutes by default for each table, even if the policy's
retry_on would refuse it; max_attempts=1 turns this off.
An application role that did not run setup() needs SELECT, INSERT, UPDATE and DELETE on the store's items and vectors tables, and on the history table when history is on. With history off, it still needs SELECT and DELETE on a history table that exists, left from when history was on, for delete_namespace. Without SELECT on the migrations table, or without a migrations table, as when the tables were created without setup(), the store finds migration 2 through the items table's columns instead. On a multi-node cluster, one write can then fail in the seconds after setup() applies migration 2. Running setup() before rolling out 0.6.0, or granting SELECT on the migrations table, avoids that. The first store call inside a transaction the caller opened gets the permission error once. Only the SELECT grant avoids it.
Raises:
| Type | Description |
|---|---|
ValueError
|
If the vectors table exists with other dims, or its
index uses another distance. A different partition size, or
an index while |
TimeoutError
|
If another process is still applying migration 2 after SCHEMA_CHANGE_SETTLE_SECONDS. Run setup() again. |
start_ttl_sweeper(sweep_interval_minutes=None)
async
¶
Sweep expired items periodically in a background task.
CockroachDB's row-level TTL job, turned on by setup() with a TTL configuration, already deletes expired rows. The sweeper deletes them sooner. Expired items are never returned either way.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
sweep_interval_minutes
|
int | None
|
Minutes between sweeps. Defaults to the TTL configuration's sweep_interval_minutes, else 5. |
None
|
Returns:
| Type | Description |
|---|---|
Task[None]
|
The sweeper task. It finishes when the sweeper stops. Without a |
Task[None]
|
TTL configuration, a task that finishes at once. |
stop_ttl_sweeper(timeout=None)
async
¶
Stop the TTL sweeper task if it is running.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
timeout
|
float | None
|
Seconds to wait for the task to stop, or None to wait. |
None
|
Returns:
| Type | Description |
|---|---|
bool
|
True if the task stopped or was not running, False on timeout. |
sweep_ttl()
async
¶
Delete expired items now, without waiting for CockroachDB's TTL job.
Returns:
| Type | Description |
|---|---|
int
|
The number of items deleted. |
CockroachDBIndexConfig¶
Semantic search settings, passed as index.
langchain_cockroachdb.store.config.CockroachDBIndexConfig
¶
Bases: IndexConfig
CockroachDB-specific index configuration.
Extends LangGraph IndexConfig with CockroachDB vector index options.
Attributes:
| Name | Type | Description |
|---|---|---|
distance_type |
Literal['cosine', 'l2', 'inner_product']
|
Distance metric (cosine, l2, or inner_product). Default cosine. |
cspann |
CSPANNConfig | None
|
C-SPANN index parameters (both or neither). |
flat |
bool
|
Whether to use a flat (brute-force) index. Default False. |
beam_size |
int
|
Beam width for C-SPANN search. Searches with a query set it with SET LOCAL in their own transaction. Inside a transaction the caller opened on a single connection shared with the store, it lasts until that transaction ends. |
CSPANNConfig¶
C-SPANN partition sizes, passed as index["cspann"].
langchain_cockroachdb.store.config.CSPANNConfig
¶
Bases: TypedDict
C-SPANN index configuration.
Attributes:
| Name | Type | Description |
|---|---|---|
min_partition_size |
int
|
Minimum vectors per partition. |
max_partition_size |
int
|
Maximum vectors per partition. |
CockroachDBTTLConfig¶
Expiry settings, passed as ttl.
langchain_cockroachdb.store.config.CockroachDBTTLConfig
¶
Bases: TTLConfig
CockroachDB-specific TTL configuration.
Extends LangGraph TTLConfig with CockroachDB TTL options.
Attributes:
| Name | Type | Description |
|---|---|---|
omit_expired |
bool
|
Whether to exclude expired items from reads. Default True. |
ttl_job_cron |
str
|
Cron expression for the TTL cleanup job. |
HistoryConfig¶
Version history settings, passed as history.
langchain_cockroachdb.store.config.HistoryConfig
¶
Bases: TypedDict
Version history settings, for the store's history argument.
Attributes:
| Name | Type | Description |
|---|---|---|
ttl_days |
float
|
Days an old version stays in history. setup() turns on CockroachDB row-level TTL on the history table, which deletes it after that. Without it, history is kept until purge() or delete_namespace() removes it. |
PoolConfig¶
Connection pool settings, passed as pool_config to from_conn_string.
langchain_cockroachdb.store.config.PoolConfig
¶
Bases: TypedDict
Connection pool settings for CockroachDBStore.from_conn_string.
The same meaning as PostgresStore's PoolConfig.
Attributes:
| Name | Type | Description |
|---|---|---|
min_size |
int
|
Connections the pool keeps open. Default 1. |
max_size |
int | None
|
Most connections the pool opens, or None for min_size. |
kwargs |
dict[str, Any]
|
Extra psycopg connection options for every pooled connection. autocommit, row_factory and prepare_threshold are set by the store. |
Reconciliation Types¶
The types that reconcile, find_conflicts, resolve, record, confirm, put_if, delete_if and history take and return. Import them from langchain_cockroachdb.store. See Keeping Memories True for how they fit together.
Proposal¶
The new memory that a policy, or a judge in the two-step flow, decides about.
langchain_cockroachdb.store.reconcile.Proposal
dataclass
¶
A new memory being reconciled against existing candidates.
Attributes:
| Name | Type | Description |
|---|---|---|
namespace |
tuple[str, ...]
|
Namespace tuple. |
key |
str
|
Memory key. |
value |
dict[str, Any]
|
Memory value as JSON-serializable dict. |
slot |
str | None
|
Slot field name, or None. |
slot_value |
Any
|
Value of the slot field. |
provenance |
dict[str, Any] | None
|
Provenance metadata, or None. |
valid_at |
datetime
|
When the fact became true (timezone aware). |
Candidate¶
A live memory that the new memory may conflict with.
langchain_cockroachdb.store.reconcile.Candidate
dataclass
¶
A live memory that may conflict with a proposal.
Attributes:
| Name | Type | Description |
|---|---|---|
item |
SearchItem
|
SearchItem with the candidate's data and optional score. |
reason |
Literal['key', 'slot', 'similar']
|
Why this is a candidate (key, slot, or similar). |
version |
int
|
Version number of this memory. |
valid_at |
datetime
|
When the fact became true. |
provenance |
dict[str, Any] | None
|
Provenance metadata, or None. |
confirmed_at |
datetime | None
|
When its current value was last confirmed, or None. |
confirmations |
int
|
Number of confirmations of its current value. |
Decision¶
What a policy or a judge decides: what to do with the new memory and with each candidate.
langchain_cockroachdb.store.reconcile.Decision
dataclass
¶
Policy decision on what to do with the proposal and candidates.
Attributes:
| Name | Type | Description |
|---|---|---|
new |
Literal['write', 'skip', 'superseded']
|
What to do with the new memory (write, skip, or superseded). |
superseded_by |
str | None
|
Key that superseded the proposal, or None. |
actions |
Mapping[str, Action]
|
Mapping from candidate key to an Action, or its value such as "delete" (missing means KEEP). None means no actions. |
Action¶
What a decision does with one candidate.
langchain_cockroachdb.store.reconcile.Action
¶
Bases: str, Enum
Action to take on a candidate memory.
Conflicts¶
What find_conflicts returns, for resolve.
langchain_cockroachdb.store.reconcile.Conflicts
dataclass
¶
What find_conflicts found: a new memory and the memories it may conflict with.
Nothing is written yet. resolve() applies a decision about them in one transaction, once it has checked that the target and every candidate the decision names still have the version and updated_at they had here.
Attributes:
| Name | Type | Description |
|---|---|---|
proposal |
Proposal
|
The new memory, with its key and valid time. |
candidates |
tuple[Candidate, ...]
|
The live memories it may conflict with, strongest reason first, then best score, then key. |
target_version |
int | None
|
The version of the live memory under the new memory's key, or None if there is none. |
target_updated_at |
datetime | None
|
When that memory was last written, or None. |
ConflictsChanged¶
Raised by resolve when a memory the decision depends on changed after find_conflicts.
langchain_cockroachdb.store.reconcile.ConflictsChanged
¶
Bases: Exception
Raised by resolve() when what a decision depends on changed after find_conflicts.
The transaction that found the change wrote nothing. Run find_conflicts again and decide again.
Attributes:
| Name | Type | Description |
|---|---|---|
keys |
The keys whose memory was written, deleted or expired since, or that have a live memory where find_conflicts found none: the new memory's key first, then the candidates in their order. |
ReconcileResult¶
What reconcile or resolve did.
langchain_cockroachdb.store.reconcile.ReconcileResult
dataclass
¶
What a reconcile or resolve did.
An attempt can commit and still lose its result on the way back, as
when the connection drops while the COMMIT's answer travels. The retry
then finds the rows that carry its write id, writes nothing, and
returns a result rebuilt from those rows, with already_applied set.
A rebuilt result lists only what the rows prove: kept is empty, and
superseded and deleted come from the history rows the write
created, so a store without history, which keeps no trace of what it
removed, reports them empty too. A confirmation of the new memory
before the retry leaves the write's proof on it. If another writer
replaced the new memory before the retry, the history row of the
version the write overwrote, or of a memory it superseded, still proves
the write: the result says "written", but its version is None. A
rebuilt result lists keys in key order; a normal one in the order of the
candidates.
Attributes:
| Name | Type | Description |
|---|---|---|
key |
str
|
The new memory's key, whether it was written or not. |
new |
Literal['written', 'skipped', 'superseded']
|
What happened to the new memory: "written", "skipped", or "superseded" when it went straight into history because a newer fact supersedes it. A store without history skips such a memory, and the result says "skipped". |
version |
int | None
|
The version written, or None when nothing was written. A rebuilt result also has None for a written memory that another writer replaced before the retry. |
superseded |
tuple[str, ...]
|
Keys of the candidates the new memory superseded. |
deleted |
tuple[str, ...]
|
Keys of the candidates deleted. |
confirmed |
tuple[str, ...]
|
Keys of the candidates confirmed. |
kept |
tuple[str, ...]
|
Keys of the candidates kept. The memory under the new key is not kept when the new memory overwrote it. |
already_applied |
bool
|
Whether an earlier attempt had already committed, so the result was rebuilt from the stored rows. |
MemoryRecord¶
A live memory with its version, provenance, valid time and confirmations, as record returns it.
langchain_cockroachdb.store.reconcile.MemoryRecord
dataclass
¶
A live memory with its reconciliation metadata.
Attributes:
| Name | Type | Description |
|---|---|---|
item |
Item
|
The memory's Item. |
version |
int
|
Version number. |
provenance |
dict[str, Any] | None
|
Provenance metadata, or None. |
valid_at |
datetime
|
When the fact became true. |
confirmed_at |
datetime | None
|
When its current value was last confirmed, or None. |
confirmations |
int
|
Number of confirmations of its current value. A write that changes the value starts them again from none. |
MemoryVersion¶
An old version of a memory, as history returns it.
langchain_cockroachdb.store.reconcile.MemoryVersion
dataclass
¶
A historical version of a memory.
Attributes:
| Name | Type | Description |
|---|---|---|
namespace |
tuple[str, ...]
|
Namespace tuple. |
key |
str
|
Memory key. |
version |
int
|
Version number. |
value |
dict[str, Any]
|
Memory value. |
provenance |
dict[str, Any] | None
|
Provenance metadata, or None. |
valid_at |
datetime
|
When the fact became true. |
invalid_at |
datetime | None
|
When the fact became invalid, or None. |
written_at |
datetime
|
When the store wrote this version. |
ended_at |
datetime
|
When the store replaced this version. |
reason |
Literal['overwritten', 'superseded', 'deleted']
|
Why this version ended (overwritten, superseded, deleted). |
superseded_by |
str | None
|
Key that superseded this version, or None. |
confirmed_at |
datetime | None
|
When this version was last confirmed, or None. |
confirmations |
int
|
How many times this version was confirmed. They belong to the version's fact: a write that changes the value starts the next version from none. |
ConditionalWrite¶
What put_if or delete_if did.
langchain_cockroachdb.store.reconcile.ConditionalWrite
dataclass
¶
What put_if or delete_if did.
A conflict is an expected outcome of a conditional write, so it is
returned, not raised: applied is False and current holds the
live memory, for the application to merge, write again with, reject,
or show to the user.
Attributes:
| Name | Type | Description |
|---|---|---|
applied |
bool
|
Whether the write applied: the live memory was the one expected, or there was none when None was expected. A retried delete_if that finds the memory gone also counts as applied. |
key |
str
|
The memory's key. |
version |
int | None
|
The version put_if wrote, or None after a delete or a conflict. |
current |
MemoryRecord | None
|
On a conflict, the live memory as the write's transaction read it, or None if no live memory has the key. None when the write applied. |
already_applied |
bool
|
Whether an earlier attempt of the same call had already committed the write, whose result was lost, as the row or history row that carries its write id proves. |
RECONCILE_SERDE_TYPES¶
The classes a checkpoint serializer must allow, so reconcile values can wait in graph state.
langchain_cockroachdb.store.reconcile.RECONCILE_SERDE_TYPES = (('langchain_cockroachdb.store.reconcile', 'Action'), ('langchain_cockroachdb.store.reconcile', 'Candidate'), ('langchain_cockroachdb.store.reconcile', 'ConditionalWrite'), ('langchain_cockroachdb.store.reconcile', 'Conflicts'), ('langchain_cockroachdb.store.reconcile', 'Decision'), ('langchain_cockroachdb.store.reconcile', 'MemoryRecord'), ('langchain_cockroachdb.store.reconcile', 'MemoryVersion'), ('langchain_cockroachdb.store.reconcile', 'Proposal'), ('langchain_cockroachdb.store.reconcile', 'ReconcileResult'), ('langchain_cockroachdb.store.base', 'ConflictsState'), ('langchain_cockroachdb.store.base', 'ProposalPlan'), ('langchain_cockroachdb.store.base', 'PutPlan'), ('langchain_cockroachdb.store.base', 'StoreIdentity'), ('langgraph.store.base', 'Item'), ('langgraph.store.base', 'SearchItem'))
module-attribute
¶
Every class a reconcile value can hold, as (module, class name) pairs.
A strict checkpoint serializer rebuilds only the classes it is given and
gives any other back raw, as LangGraph's does with
LANGGRAPH_STRICT_MSGPACK=true. To keep a Conflicts, a Decision, a
ReconcileResult, a ConditionalWrite, a MemoryRecord or a MemoryVersion in
graph state, give the checkpointer a serializer that allows these:
JsonPlusSerializer(allowed_msgpack_modules=RECONCILE_SERDE_TYPES), with
your own state's types added if they are not built in. The pairs are the form
that allowed_msgpack_modules takes, from langgraph-checkpoint 4.0.1.
Before 4.0.1, JsonPlusSerializer has no allowed_msgpack_modules argument,
and passing it raises TypeError; those releases rebuild every class.
Policies¶
A policy is a function of the Proposal and the sequence of candidates that returns a Decision, typed as Policy (Callable[[Proposal, Sequence[Candidate]], Decision]). It runs inside the reconcile's transaction, and again on every retry, so it must be a plain function, fast and deterministic, and must not call the store. These are the built-in ones, and validate_decision, which checks a decision as reconcile and resolve do.
langchain_cockroachdb.store.reconcile.supersede_same_slot()
¶
Return a policy that supersedes older facts in the same slot.
- If the memory under the proposal's key (the target) has a later valid_at, skip the proposal, whatever reason the target has.
- Otherwise, if no candidate is in the same slot (reason "slot"), write the proposal and keep every candidate.
- If a slot candidate has a later valid_at, record the proposal as superseded by the latest such candidate.
- Otherwise, supersede all slot candidates.
Returns:
| Type | Description |
|---|---|
Policy
|
Policy that supersedes same-slot candidates. |
langchain_cockroachdb.store.reconcile.skip_duplicates(threshold=0.97)
¶
Return a policy that skips a memory that repeats one already stored.
A new memory, one with no live memory under its key, is skipped when a candidate has an equal value or scores at or above threshold, and the highest-scoring such candidate is confirmed (an equal value counts as score 1.0). When the proposal has a slot, only candidates in the same slot count: a repeat outside the slot states another fact, and skipping the new memory for it would leave an older memory in the slot live, which may contradict the new one. A memory whose key holds a live memory is skipped only when it saves that memory's value again, which confirms it. Any other value there is an update, which this policy never skips, whatever repeats it under another key: skipping it would leave the key with its old value, which may contradict the new one. Then it returns the decision that writes the new memory and keeps every candidate, so first_of moves on to the next policy.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
threshold
|
float
|
Similarity threshold (default 0.97). |
0.97
|
Returns:
| Type | Description |
|---|---|
Policy
|
Policy that skips duplicates. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If threshold is not a finite number. |
langchain_cockroachdb.store.reconcile.supersede_similar(threshold=0.9)
¶
Return a policy that supersedes similar memories.
Works like supersede_same_slot, but matches the slot candidates and the candidates scoring at or above threshold. As there, a target with a later valid_at skips the proposal whatever it scores, and so does a target without a score, as on a store without an index.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
threshold
|
float
|
Similarity threshold (default 0.9). |
0.9
|
Returns:
| Type | Description |
|---|---|
Policy
|
Policy that supersedes similar candidates. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If threshold is not a finite number. |
langchain_cockroachdb.store.reconcile.keep_all()
¶
Return a policy that writes the new memory and keeps all candidates.
Returns:
| Type | Description |
|---|---|
Policy
|
Policy that keeps all candidates. |
langchain_cockroachdb.store.reconcile.first_of(*policies)
¶
Return a policy that uses the first decision that acts.
Tries each policy in order and returns the first decision that does more than just write and keep all candidates (Decision.acts). A decision whose actions only KEEP candidates keeps them all, so it does not act. If no policy acts, returns a plain write decision.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
*policies
|
Policy
|
Policies to try in order. |
()
|
Returns:
| Type | Description |
|---|---|
Policy
|
Combined policy. |
langchain_cockroachdb.store.reconcile.validate_decision(proposal, candidates, decision)
¶
Validate a decision against the proposal and candidates.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
proposal
|
Proposal
|
The proposal being reconciled. |
required |
candidates
|
Sequence[Candidate]
|
Candidate memories. |
required |
decision
|
Decision
|
The decision to validate. |
required |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the decision is invalid (with a message naming the key). |
Imports¶
| Name | langchain_cockroachdb.store |
langchain_cockroachdb |
|---|---|---|
CockroachDBStore |
Yes | Yes |
AsyncCockroachDBStore |
Yes | Yes |
CockroachDBIndexConfig |
Yes | Yes |
CockroachDBTTLConfig |
Yes | Yes |
PoolConfig |
Yes | No |
HistoryConfig |
Yes | No |
Proposal |
Yes | No |
Candidate |
Yes | No |
Decision |
Yes | No |
Action |
Yes | No |
Conflicts |
Yes | No |
ConflictsChanged |
Yes | No |
ReconcileResult |
Yes | No |
MemoryRecord |
Yes | No |
MemoryVersion |
Yes | No |
ConditionalWrite |
Yes | No |
RECONCILE_SERDE_TYPES |
Yes | No |
Policy |
Yes | No |
supersede_same_slot |
Yes | No |
skip_duplicates |
Yes | No |
supersede_similar |
Yes | No |
keep_all |
Yes | No |
first_of |
Yes | No |
validate_decision |
Yes | No |
CSPANNConfig |
No, import it from langchain_cockroachdb.store.config |
No |
Key Methods¶
| Method | Async Method | Description |
|---|---|---|
setup() |
setup() |
Create the tables and run migrations, build the vector index with index, turn on TTL with ttl |
put() |
aput() |
Store an item, or replace it |
get() |
aget() |
Read an item |
search() |
asearch() |
Search a namespace prefix, with a filter and an optional semantic query |
delete() |
adelete() |
Delete an item |
list_namespaces() |
alist_namespaces() |
List namespaces by prefix, suffix and depth |
batch() |
abatch() |
Run several operations, with the writes in one transaction |
delete_namespace() |
adelete_namespace() |
Delete a namespace and its descendants with their vectors and history, return the item count |
reconcile() |
areconcile() |
Write a memory and settle the memories it may conflict with, under a policy, in one transaction |
find_conflicts() |
afind_conflicts() |
Find the memories a new one may conflict with, without writing anything |
resolve() |
aresolve() |
Apply a decision about what find_conflicts found, if nothing it depends on changed |
record() |
arecord() |
Read a memory with its version, provenance, valid time and confirmations |
confirm() |
aconfirm() |
Confirm a memory: renew its expiry and count the confirmation |
put_if() |
aput_if() |
Write a memory only if it is still the one record returned |
delete_if() |
adelete_if() |
Delete a memory only if it is still the one record returned |
history() |
ahistory() |
List the old versions of a memory, or of every memory in a namespace, newest first, on a store with history |
purge() |
apurge() |
Remove a memory with its vectors and its history |
sweep_ttl() |
sweep_ttl() |
Delete expired items now, return the count |
start_ttl_sweeper() |
start_ttl_sweeper() |
Sweep periodically in a background thread or task |
stop_ttl_sweeper() |
stop_ttl_sweeper() |
Stop the sweeper |
disable_ttl() |
adisable_ttl() |
Turn off row-level TTL on the store's tables |
drop_vector_index() |
adrop_vector_index() |
Drop the vector index, to rebuild it with setup() |
On AsyncCockroachDBStore, setup(), sweep_ttl(), start_ttl_sweeper() and stop_ttl_sweeper() are coroutines without the a prefix, as in AsyncPostgresStore.
Factory Methods¶
| Method | Description |
|---|---|
from_conn_string(conn_string, ...) |
Create a store on a new connection, or on a new pool with pool_config (context manager) |
Connection Types¶
Both stores accept these connection types, in autocommit mode with dict_row:
| Type | Description |
|---|---|
psycopg.Connection / AsyncConnection |
Single connection (simple scripts) |
psycopg_pool.ConnectionPool / AsyncConnectionPool |
Connection pool (production) |
Examples¶
See the Long-Term Memory Guide for usage, and Keeping Memories True and the Memory Reconciliation Example for the reconciliation methods.