Changelog¶
All notable changes to langchain-cockroachdb will be documented in this file.
The format is based on Keep a Changelog, and this project adheres to Semantic Versioning.
Unreleased¶
Changed¶
- Tested on CockroachDB v26.4. CI's main jobs now run on v26.4.1, next to the v25.4 minimum. On v26.4 a vector index that sets
min_partition_sizemust setmax_partition_sizetoo, at least four times it: v26.4 enforces that ratio and rejects a minimum given alone (cockroachlabs/cockroach#13982). Earlier versions accept a minimum on its own. The vector index guide and theCSPANNIndexdocstring now say so. The memory store'scspannsetting already required both sizes.
[0.6.0] - 2026-11-10¶
Added¶
- Memory reconciliation on
CockroachDBStoreandAsyncCockroachDBStore, to keep long-term memory true.reconcile(namespace, key, value, policy=...)writes a memory and, in one serializable transaction, finds the memories it may conflict with, runs the application's policy on them, and supersedes, deletes, confirms or keeps each one. The candidates are the live memory under the same key, the memories whose value holds the sameslotvalue, and on a store with an index those whose vectors score at or abovethreshold. That is 0.8 by default on a cosine store, and must be given on anl2orinner_productstore. The candidates are read in the transaction that writes, so two agents that reconcile contradictory memories for one user cannot both win.find_conflictsandresolvedo the same in two steps, so an LLM or a person can decide while no transaction is open.resolvechecks that the memories the decision depends on still have the version andupdated_atthatfind_conflictsread. If one changed, it raisesConflictsChangedand writes nothing. The built-in policies aresupersede_same_slot(),skip_duplicates(),supersede_similar(),keep_all()andfirst_of(), andreconcilehas no default policy.skip_duplicates()skips a new memory that repeats one already stored, and confirms that memory. With aslot, only a memory in the same slot counts as a repeat, so a repeat outside the slot never keeps an older memory in the slot live. For a key that holds a live memory, it skips only a save of the same value, and never an update to another value, whichfirst_ofpasses to the next policy. The store settingreconcile_scan_limit(default 2000) is the most vectors a namespace may hold for its similar candidates to be ranked exactly. A larger namespace takes them from the C-SPANN index. - Version history, turned on with
history=Trueorhistory={"ttl_days": ...}on the store and onfrom_conn_string.setup()then creates<table>_history. Every write that overwrites, supersedes or deletes a memory keeps the version it ends, in the same transaction, with when its fact was true, why it ended, what replaced it and its provenance. That includes plainputanddelete, so LangMem-style tools, which write through them, get history too. With history on,deleteis a soft delete.purge(namespace, key)removes a memory with its vectors and its history,delete_namespaceremoves the history under the prefix too, even on a store created without history when the history table exists, andhistory(namespace, key)lists a memory's old versions. Without a key,history(namespace)lists the old versions of every memory in the namespace, newest first, each with its key andsuperseded_by, so the old versions of memories saved under generated keys can be found too.limitandoffsetpage through both forms. - Provenance and valid time.
reconcile,find_conflictsandput_iftakeprovenance, any JSON object, kept in its own column, andvalid_at, when the fact became true. Withoutvalid_atthe valid time comes from the database's clock. Of the built-in policies, onlysupersede_same_slot()andsupersede_similar()compare valid times: a fact that arrives late is recorded as superseded instead of replacing a newer one, and a late fact under its own live key is skipped, not recorded.record(namespace, key)returns a live memory with its version, provenance, valid time and confirmations. confirm(namespace, key, ttl=...)marks a memory as confirmed. It renews the expiry, from the memory's own TTL or from minutes, None or a function of the memory, and counts the confirmation. Confirmations belong to the fact: a write that changes the value starts them again from none, an exact re-save keeps them, and history keeps each version's count.recordandfind_conflictsnever push back an expiry, and withrefresh_on_read=Falseexpiry follows confirmations rather than reads.- Conditional writes.
put_if(namespace, key, value, expected=record)anddelete_if(namespace, key, expected=record)apply only if the memory is still the onerecordreturned, andexpected=Nonecreates a memory only if none is live under the key. A conflict is returned, not raised: theConditionalWriteresult hasapplied=Falseandcurrent, the live memory, to merge with. - The async store has each of these methods as a coroutine with an
aprefix. The new types and policies are exported fromlangchain_cockroachdb.store:Proposal,Candidate,Decision,Action,Conflicts,ConflictsChanged,ReconcileResult,MemoryRecord,MemoryVersion,ConditionalWrite,HistoryConfig,Policyandvalidate_decision.RECONCILE_SERDE_TYPES, exported there too, lists the classes these values hold, in the form that a checkpoint serializer'sallowed_msgpack_modulestakes from langgraph-checkpoint 4.0.1. With it, aConflictsor aDecisioncan wait in graph state while a person decides. - What this does not do: the store makes no LLM calls, though a judge in the two-step flow may. It does not record TTL expiry in history either, since CockroachDB's TTL job deletes rows directly. A changefeed on the items table captures those deletes.
examples/memory_reconciliation.py, and a "Keeping memories true" section in the long-term memory guide, with an example page and API entries in the documentation.- A guide to virtual-cluster connections for the engine, chat history, the checkpointers and the store: a Cockroach Continuum virtual cluster's own connection string, or a self-hosted virtualized cluster selected with the percent-encoded
options=-ccluster%3D<name>. Unit tests cover connection-string handling, and an opt-in suite checks that two virtual clusters keep their data apart. - Recovery tests for LangGraph graphs on pooled checkpointers: an application process that is killed and restarted in a fresh process, and a pooled connection lost while a graph runs. Graphs resume from their last saved checkpoint, a node that finished and saved its writes does not run again, and no checkpoint write is lost or duplicated.
- A checkpointer guide section on LangGraph's durability modes. It explains that LangGraph's default,
"async", can lose the last checkpoint and the tool call recorded in it when the process dies, why an idempotency key built from the tool-call ID does not catch the repeat that follows, and when to passdurability="sync".
Changed¶
- Upgrading from 0.5: run
setup()once. It applies migration 2, which addsversion,provenance,confirmed_at,confirmations,write_id,valid_atandconfirm_idto the items table in one statement. On a large table, run it once from a single process before the rollout: the backfill takes longer the more items the table holds. When several processes runsetup()at once, the statement from all but one returns at once, before the columns exist, so each of those waits until the columns are public and SHOW JOBS shows no schema change job on the table, for up toSCHEMA_CHANGE_SETTLE_SECONDS(10 minutes, exported), before it records migration 2. A store that finds migration 2 recorded then never writes columns that are not there yet. Two cases leave the columns alone to decide: SHOW JOBS shows a role without admin only its own jobs, and it can cut a long qualified table name from a job's description. If no job applies the migration, as after a peer's migration failed, the waitingsetup()applies it itself and logs that at INFO. The wait logs an INFO line when it starts, a WARNING once it has waitedSCHEMA_CHANGE_QUIET_SECONDS(30) and one a minute after that, and an INFO line when it ends. If it runs out,setup()raisesTimeoutErrorsaying what remained. The wait is not a retry, somax_attempts=1does not shorten it. Until then the store works as 0.5 did, and the new methods raiseValueErrorasking forsetup(). With history off and the new methods unused, the store behaves as in 0.5 apart from the new columns. During a rolling upgrade, 0.5 writers do not bump the version but do setupdated_at, andresolve,put_ifanddelete_ifcheck both. 0.5 writers never archive, and one that re-creates a deleted key starts it again at version 1, which history then cannot keep, since it already holds a version 1 of that key. So turn history on only once every writer runs 0.6.0. On the checkpointers, if you turned on row-level TTL, runenable_ttl()once more with the same interval and cron (see Fixed). That adds the grace for blob rows, stores months and years as days, and brings forward the blob rows of threads idle since the upgrade, pausing TTL while it does. It blocks for about 15 seconds plus the pass, so if startup probes are tight, run it once from a single process or a one-off job before the rollout. Until then, puts refresh blob rows, but a thread that has written since the upgrade can lose blob rows up to a tenth of the interval before its last checkpoint expires, a thread idle since the upgrade up to the whole interval before, and a setting in months or years is refreshed only approximately. - Least-privilege roles. An application role that did not run
setup()needs SELECT, INSERT, UPDATE and DELETE on the 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 left from when history was on, sincedelete_namespacedeletes the namespace's rows there, and fails as a whole without them. The store now reads the migrations table before its first write, to learn whether migration 2 is in place. A role without SELECT on it, or a store whose tables were created withoutsetup()and have no migrations table, reads the items table's columns instead. On a multi-node cluster such a role can fail one write in the seconds aftersetup()applies migration 2, so runsetup()before rolling out 0.6.0, or grant SELECT on the migrations table. Without that grant, the first store call inside a transaction the caller opened gets the permission error, once per store. Only the grant avoids it. - A memory store semantic search takes at least 41 vectors from the C-SPANN index for its window, where it took twice the page. Finding 41 costs the index about the same as finding fewer: on a 20,000-row table it read about 10% more rows than a window of 9, in the same time. A larger window lets more filtered searches skip the exact second query.
- The README and the docs site use the new Cockroach Labs logo, and the docs site has a favicon that follows the system theme.
Fixed¶
- A vector store search with a metadata
filternow uses the C-SPANN index. CockroachDB uses a vector index only when every filter matches its prefix columns, so a filter made every filteredsimilarity_searchand its variants, every filtered MMR search and the vector leg of every filtered hybrid search scan the table. With a usable index, the store now takes the nearest rows from the index (twicekplus one, and at least 41), applies the filter to them, and runs the exact search as before when fewer thankrows pass: always when none does, and when some do unless the window held every row of the table or namespace. The exact search returns only the store's namespace, but its plan can scan the whole table. A result that comes from the window is approximate, as every index search is, and the beam size sets how close it comes; filtered searches used to scan and were exact. In MMR searchfetch_ktakes the place ofk, and in hybrid search so does its pool,fetch_kormax(4 * k, 20). A usable index is on the embedding column, has the operator class of the store's distance strategy, and has no prefix column for a store without a namespace, or the namespace column as its only prefix column for a namespaced store. A namespaced store also needs the primary key or an index to lead with the namespace column, asainit_vectorstore_tablecreates, or it keeps the exact search. The store reads the table's indexes withSHOW CREATE TABLEon its first filtered search. The engine keeps the answer for every store on it with the same table, embedding column, distance strategy and namespace column, so a store built per request does not read again. It reads again onceVECTOR_INDEX_REFRESH_SECONDS(60, exported) have passed, and right after an index is applied or dropped through any store on the engine. If that read fails with a database error that the retry policy does not retry, such as a missing privilege, the store logs it once at INFO and runs the exact search. Without a filter or a usable index, a search runs the same single statement as before. The vector indexes guide has a new section on filtered search. It now gives the default beam size as 32, says that prefix columns come only fromprefix_columnsand that a key infilteris never one, and warns that building an index on a table that holds data blocks writes to it until the backfill ends. setup()run by several processes at once now converges, as when pods restart into 0.6.0 together. On CockroachDB v25.4 a TTL change fails while another schema change runs on the same table. While one process's migration 2 backfills the items table, which takes longer the more items it holds, the others go on to change its TTL settings. That error was retried under the store's retry policy, for about a second by default, so theirsetup()could fail.setup()now reads each table's TTL settings first and changes them only when they differ, so the processes after the first change nothing. And the error now has a retry budget sized for schema changes: each TTL change retries it for up to ten minutes of wall time by default, as long as asetup()waits for another process's migration, so it also waits out a long backfill or vector index build. Asetup()can wait one such budget per table whose TTL it changes. It logs a WARNING on the first retry and at most one a minute after that. The same budget applies to the store'sdisable_ttl()andadisable_ttl(), and toenable_ttl()anddisable_ttl()on the checkpointers and their async forms. Its defaults are exported asSCHEMA_CHANGE_BUSY_SECONDS(600) andSCHEMA_CHANGE_BUSY_MAX_BACKOFF(3 seconds), andschema_change_policy()takessecondsandmax_backoffand keeps aRetryPolicysubclass'sis_retryableanddelayoverrides for every other error. Other errors keep the policy's own attempts and backoff, andmax_attempts=1still turns every retry off.- Loading the state of a graph that uses LangGraph's
DeltaChannelread the checkpoint history one checkpoint at a time. Deep Agents stores its messages and files in delta channels, which keep only each step's change and a full snapshot every 50 updates, so LangGraph asks the checkpointer for the history back to the last snapshot on everyget_stateand every resumed run. The checkpointers inherited LangGraph's default for that request, which callsget_tupleonce per ancestor, three queries each. Loading a Deep Agent's state after four turns took 63 queries, and the count grew with every turn until the next snapshot.CockroachDBSaverandAsyncCockroachDBSavernow overrideget_delta_channel_historyandaget_delta_channel_history. They follow the parent chain with a recursive query and load each page of ancestors in one batch, in pages that start at 16 ancestors and grow up to 256 (DELTA_HISTORY_FIRST_PAGE,DELTA_HISTORY_PAGE_SIZE). The result is the same as LangGraph's default, which the new tests check on every checkpoint of real graphs, including a forked thread. - A checkpoint's pending writes came back ordered by
task_id, a hash, instead of LangGraph'swrites_sort_keyorder (task_path,task_id,idx). LangGraph replays stored writes in the order the checkpointer returns them, so when parallel tasks in one step wrote the same channel, state rebuilt after a reload could differ from the state the run produced. With aDeltaChannel, such as Deep Agents' messages and files, a reloaded list could come back in a different order.get_tuple,listand their async versions now return pending writes inwrites_sort_keyorder. - Row-level TTL on the checkpointers could delete values that an active thread still used.
enable_ttl()expires each row by its owncreated_at. A blob row holds one channel version and is written once, so a channel that had not changed since an early step, such as a profile set on the first turn, kept its first blob row, which every newer checkpoint used. Once that row was older than the interval, the TTL job deleted it, and the value dropped out of the thread's state without an error. On an idle thread, blob rows could also expire before the checkpoint that used them. With TTL on,putandaputnow bringcreated_atforward on the blob rows the new checkpoint uses but does not write, once they are older than a tenth of the interval (TTL_REFRESH_FRACTION, 10), in the same transaction as the checkpoint.enable_ttl()gives blob rows that tenth as a grace,(created_at + interval + interval / 10), keeps checkpoints and writes at(created_at + interval), stores months and years as days, 30 to a month and 365 to a year, since calendar months differ in length and no grace could cover them, and refuses an interval longer than 106,751 days, the longest duration CockroachDB keeps. When it turns TTL on or changes it, it first writes the new settings with TTL paused (ttl_pause), so nothing is deleted, and waitsTTL_STATE_CACHE_SECONDS(10) plusTTL_PAUSE_MARGIN_SECONDS(5), or plus the retry policy'sattempt_timeoutwhen that is longer, so that every saver reads the new setting and the puts already under way finish; savers refresh while TTL is paused. Then it makes one pass, so threads idle at that moment are covered too: each blob row that checkpoints inside the interval use, and that is older than the newest of them by more than the window, is brought forward to now. Only rows left unchanged that long are rewritten, not the table. The pass reads every checkpoint once,TTL_REFRESH_BATCH_SIZE(500) at a time, changes at mostTTL_REFRESH_UPDATE_SIZE(100) rows perUPDATE, each its own short statement under the retry policy'sddl_attempt_timeout, and logs at INFO when it starts and ends. Then it reads the setting again and resumes TTL,checkpoint_blobslast, unless another run has written a different setting meanwhile: it leaves the resume to that run and logs at INFO. CockroachDB may skip its next scheduled TTL job once after the resume, with "found a recent schema change", which delays deletion by one cron period. So whenever the setting changes,enable_ttl()blocks for about 15 seconds on a table of any size, plus the pass, the first call after upgrading included, and it returns at once when the same setting is in place and running; any other change makes the whole run, a longer interval too. A run that stops before it resumes TTL leaves it paused, which deletes nothing. One that stops during the resume leaves onlycheckpoint_blobspaused, so checkpoints and writes expire again while blob rows stay, which only leaves behind blob rows that no checkpoint uses. The nextenable_ttl()finishes either, and a saver that finds TTL paused logs a WARNING once per process each time, saying to runenable_ttl()again if no run is under way.disable_ttl()and thenenable_ttl()force a pass. If startup probes are tight, runenable_ttl()once from a single process or a one-off job before a rollout. Use one interval in every process, and change it from one process. So onceenable_ttl()has run, a blob row expires no earlier than the newest checkpoint that uses it, and a thread expires once it has been idle for the interval. The savers read the TTL setting ofcheckpoint_blobsfrom the catalog on the first put that needs it, and again afterTTL_STATE_CACHE_SECONDS(10) or right after their ownenable_ttl()ordisable_ttl(). Each attempt of a put decides again whether to refresh, so a retry made after the saver learns that TTL is on refreshes too. A TTL setting thatenable_ttl()did not write turns the refresh off and is logged at INFO once per process. If that read fails with a database error that the retry policy does not retry, such as a missing privilege, puts go on without the refresh, and the saver logs a WARNING once. While TTL is on, a put that uses blob rows it does not write sends one moreUPDATEin its transaction, and a blob row is rewritten at most once per tenth of the interval. Graphs that useDeltaChannelrebuild state from older checkpoints, which TTL still expires by age, soget_delta_channel_historynow logs a WARNING, once per missing checkpoint and saver, when that history stops at a missing checkpoint before a snapshot. The checkpointer guide's TTL section says what TTL expires and covers both cases.
[0.5.1] - 2026-10-28¶
Fixed¶
- A checkpointer or store could fail with
prepared statement "_pg3_N" does not exist(SQLSTATE 26000) after a batch failed before its statements ran, even when the error that failed the batch was retryable. psycopg prepares a statement on its sixth run on a connection (prepare_threshold=5, the default), and in pipeline mode it records the statement as prepared before the server confirms it. When an earlier statement in the batch failed, such as BEGIN refused by CockroachDB's license limit, the server never prepared it, but psycopg kept using it. A checkpoint write then failed on its retry. A store read failed on that connection every time until the connection closed, so a pool could hand out the broken connection until it was replaced, by default within an hour. Statements sent in a pipeline are no longer prepared. Statements outside a pipeline, such as the checkpointers' reads on a pool or on a connection withoutpipeline=True, still are, and every connection keeps its ownprepare_threshold. examples/long_term_memory.pyand the store guide no longer print pydantic serializer warnings. Their tools now annotate the runtime asToolRuntime[Context, dict]. A plainToolRuntimeexpects no context, andToolRuntime[Context]fails on Python 3.10, which cannot fill in the default of the second type argument.- The checkpointer guide said PostgresSaver's
prepare_threshold=0turns prepared statements off. It prepares every query from its first run.
[0.5.0] - 2026-10-26¶
Added¶
CockroachDBStoreandAsyncCockroachDBStore, LangGraph long-term memory stores on CockroachDB. They implement LangGraph'sBaseStorewith the API of langgraph-checkpoint-postgres'sPostgresStore(from_conn_stringwithpipelineandpool_config,setup(),indexandttl), so they work withcreate_agent(store=...),StateGraph.compile(store=...)and Deep Agents'StoreBackend.from_conn_stringalso takesretry_policy,connect_timeout,prepare_thresholdandconnect_kwargs, as the checkpointers do. The two stores,CockroachDBIndexConfig,CockroachDBTTLConfigandPoolConfigare exported fromlangchain_cockroachdb.store, and all of them butPoolConfigfromlangchain_cockroachdbtoo.- Semantic search on CockroachDB's
VECTORtype, with a C-SPANN index that has the namespace as a prefix column.indextakes LangGraph'sdims,embedandfields, plusdistance_type(cosine,l2orinner_product),cspannpartition sizes,flatto skip the index, andbeam_size, which is set for each search. A search under a namespace first lists the namespaces at or under it, then ranks with the index within them, and runs a second, exact query when a filter or expired items leave its page short, unless a count shows that the index returned every vector of those namespaces. A search of the whole store, every search of aflatstore, and a search over more than 1000 namespaces (MAX_SEARCH_NAMESPACES) rank every match exactly instead. So a filter or expired items never leave a page short while more matches exist. - Expiry through CockroachDB row-level TTL. With a
ttlconfiguration,setup()turns on the TTL job for the items and vectors tables, on a schedule fromsweep_interval_minutesorttl_job_cron(@hourlyby default), so no sweeper thread is needed. Vectors carry their item's expiry. Expired items are left out of reads, searches and listings by default, even by a store built withoutttl;ttl={"omit_expired": False}turns that off. Withrefresh_on_read, a read pushes back the expiry of the items it returns, in the same statement.sweep_ttl(),start_ttl_sweeper()andstop_ttl_sweeper()work as in PostgresStore. A store built withoutttlapplies no default expiry, never refreshes one, and itssetup()leaves an existing TTL setting alone. On CockroachDB v25.4,disable_ttl(),adisable_ttl()and the TTL step ofsetup()retry while another process changes the same table. delete_namespace(namespace_prefix)andadelete_namespace, which delete every item and vector in a namespace and its descendants in one transaction and return the number of items deleted.- The sync methods of
AsyncCockroachDBStore(batch,get,put,search,deleteandlist_namespaces) raiseRuntimeErrorinstead of hanging when the store's event loop is closed or not running, or when called from a forked child, as those ofAsyncCockroachDBSaverdo. From the loop's own thread they raiseasyncio.InvalidStateError. - Differences from PostgresStore: the puts and deletes of one batch commit in one transaction; every call retries transient errors under the store's
RetryPolicy; aCockroachDBStoreon a pool runs batches concurrently; putting an item again or deleting it removes its old vectors; a filter that compares with a number matches numeric values only (PostgresStore compares text), nested dictionaries match nested keys, and$nematches items without the key; results with the same score orupdated_atare ordered by namespace and key, so paging is stable;table_nameandschemaconfigure the tables (defaultsstore,store_vectorsandstore_migrationsinpublic); aqueryon a store withoutindexlogs a WARNING and runs a plain search; aftersetup(), a changeddimsordistance_typeraises, and other partition sizes, orflatwith an index present, log a WARNING;disable_ttl()andadisable_ttl()remove the table TTL setting, anddrop_vector_index()andadrop_vector_index()drop the vector index so thatsetup()can build it again, for example with another distance; and there is nodeserializer=argument, because psycopg decodes JSONB before the store sees it. examples/long_term_memory.py, a LangGraph agent that saves a memory in one thread and recalls it in another, and a guide, an example page and an API page for the store in the documentation.
Fixed¶
enable_ttlanddisable_ttl(andaenable_ttlandadisable_ttl) on the checkpointers no longer fail when several processes run them at once on CockroachDB v25.4. That version refuses to change a table's TTL settings while another schema change on it runs, with SQLSTATE 0A000, which was not retried. These TTL changes now retry that error under the saver's retry policy, even if itsretry_onwould refuse it;max_attempts=1turns this off. The code and phrase are exported asSCHEMA_CHANGE_BUSY_SQLSTATEandSCHEMA_CHANGE_BUSY_MESSAGES, withis_schema_change_busy()andschema_change_policy().- A checkpointer or store on one connection in pipeline mode (
pipe=, orfrom_conn_string(..., pipeline=True)) could hang when a large write met a slow link, such as TLS to a distant cluster. psycopg's pipeline sync can leave the last bytes of a write unsent, so the server waited for them while the client waited for the server. The library now sends them before it waits.CockroachDBSaverandAsyncCockroachDBSaverhad this since 0.2.0;CockroachDBStoreandAsyncCockroachDBStorehave the fix from the start. Pools, and single connections without a pipeline, were not affected.
[0.4.1] - 2026-10-16¶
Performance¶
- Checkpointers on a psycopg_pool pool now run operations concurrently, each on its own pooled connection, so one saver can serve many agents, threads or tasks. Before, every operation in the process waited on one lock, which on a multi-region cluster capped a saver at a few operations per second. A saver on a single connection (including
pipeline=True) still runs one operation at a time. Concurrency is bounded by the pool'smax_size; when every connection is busy, operations wait for the pool (30 s by default) and aPoolTimeoutis not retried. On a 9-node, 3-region CockroachDB cluster (Docker, with simulated cross-region latency and a stubbed model) with 16 LangGraph agents sharing one pooled saver, throughput went from 0.27 turns per second (median turn 55 s) in 0.4.0 to about 7.5 turns per second (median turn about 1.2 s) in 0.4.1.
Fixed¶
putwith channel blobs,put_writeswith several writes, anddelete_threadnow send BEGIN, their statements and COMMIT as one batch, so each write is saved completely or not at all, even when the caller is cancelled or fails partway. Before, an interrupted write could leave blob rows without their checkpoint, part of a task's pending writes (which LangGraph treats as a finished task), or a half-deleted thread. A write still takes one round trip, and CockroachDB can still retry it on the server. Single-statement writes are unchanged. Connections not in autocommit mode use psycopg'sconn.transaction()(the docs already requireautocommit=True).- On a single connection that the caller also uses, a write made inside a transaction the caller opened joins it as a savepoint, so the caller's commit or rollback decides. The saver never rolls back a transaction it did not open, and an error inside the caller's transaction is raised at once, without retries, so the caller's own retry loop can restart the whole transaction.
- Pooled checkpointers retry when psycopg reports the connection broken, even when the error text is unfamiliar. This fixed checkpointer retries over TLS: on CockroachDB Cloud a dropped connection reads "SSL error: unexpected eof while reading" (OpenSSL 3), which was not recognized, so a pooled saver gave up instead of retrying. That wording is now also in
TRANSIENT_MESSAGES. A definite SQLSTATE still decides first, as on the SQLAlchemy path. AsyncCockroachDBSaver's sync methods raise a clearRuntimeErrorinstead of hanging when the saver's loop is closed, stopped, or the process forked, and they cancel the abandoned work.putandput_writescalled from the saver's own loop thread now raiseInvalidStateErrorinstead of deadlocking (the other sync methods already did).- Engines built with
loop=(CockroachDBEngine(engine, loop=...)orCockroachDBEngine.from_engine(engine, loop=...)) fail fast with a clearRuntimeErrorinstead of hanging when that loop is closed, never started, stops or closes during a call, or the process forked (including an engine rebuilt in a child around the parent's loop). A loop that has not started yet gets a short grace period (LOOP_START_TIMEOUT, 1 s). RetryPolicyrejects NaN and infinity in its numeric fields, anddelay()can no longer overflow for large attempt numbers or multipliers.- The flat
jitter/retry_jitterargument now raisesTypeErrorfor anything other thanTrue,False,0or1. It used to be read by truthiness, so 0.3 became a jitter of 0.5. UseRetryPolicy(jitter=...)for a ratio. - Retry warnings name the underlying driver error when an application wraps it, and never include SQL text or parameter values.
aadd_texts,add_texts,afrom_textsandfrom_textsvalidate input (lengths, ids, duplicates, metadata JSON andbatch_size) before calling the embedding model, so invalid input no longer pays for embedding calls. The namespace conflict check is a database query and still runs after embedding.- Applying a vector index whose name already exists with different prefix columns (order or count) or a different partition size you set now logs a WARNING naming each difference, like the existing opclass warning, instead of doing nothing silently. Applying the same index again logs nothing. A partition size you leave unset accepts whatever the index has.
- Checkpointer setup logs its bootstrap step as "checkpointer setup" instead of a second "checkpointer migration 0".
[0.4.0] - 2026-10-14¶
Added¶
RetryPolicy: one configurable object for which errors are retried and how, set on the engine and inherited by the vector store and chat history; checkpointers take one too. Exported defaults (RETRYABLE_SQLSTATES,TRANSIENT_MESSAGES, ...) andget_sqlstate().- Retries for 40001, 40003, every 08xxx code, 57P01, 58C00, 58C01 and 53300, plus connection loss reported without a code. Failed logins and SSL or configuration errors are never retried.
- Optional hang guard (
attempt_timeout,ddl_attempt_timeout) that abandons and retries an attempt the server never answers. aadd_embeddings/add_embeddings,amax_marginal_relevance_search_by_vector, the full langchain-postgres filter grammar ($between,$exists,$like,$ilike,$not).CockroachDBChatMessageHistoryaccepts a sharedCockroachDBEngineand has a publicacreate_table_if_not_exists().- Checkpointer
from_conn_stringoptions:retry_policy,connect_timeout,prepare_threshold,connect_kwargs. connect_timeoutonCockroachDBEngine.from_connection_string(default 10 seconds).CockroachDBEngine.from_engine(engine, loop=...).postgresql://andcockroachdb://URL spellings are normalized to the psycopg driver.examples/resilience.py, end-to-end tests for every example, LangGraph checkpointer conformance tests, and integration tests that inject real CockroachDB faults.
Fixed¶
- Errors were classified by psycopg2's
pgcode, which psycopg 3 does not set, and by words like "connection" and "timeout" in any exception. Missing tables and statement timeouts were retried. - The vector store never applied its retry settings; chat history and both checkpointers had no retries.
- Sync methods failed under concurrency ("bound to a different event loop") because every call ran its own event loop against a shared pool. They now share one background loop.
- Metadata filters broke on apostrophes, could carry injected SQL, and failed on boolean and null values. All values are bound parameters now.
- Vector indexes ignored the distance strategy and were always
vector_l2_ops, so cosine and inner product searches never used them. vector_search_beam_sizestayed set on pooled connections after a search.- Chat history
add_messagescould leave partial writes and could duplicate messages on retry. - MMR re-embedded every candidate through the embeddings API.
from_textsfailed withidsor vector store arguments.- Concurrent checkpointer
setup()could fail on a duplicate migration version, and calling the saver while iteratinglist()deadlocked. - Running setup a second time failed with SQLSTATE 57000 when
autocommit_before_ddlwas off and the table was schema_locked, which is the default for new tables on v26. This hitinit_vectorstore_tablewithnamespace_columnorcreate_tsvector, and chat historycreate_table_if_not_exists. Schema setup now runs one statement per implicit transaction. - In pipeline mode, checkpointer
setup()andenable_ttl()/disable_ttl()failed withautocommit_before_ddloff. That covered a fresh database and an upgrade that adds migrations. Every schema statement now runs in its own implicit transaction. - After a session is canceled (
CANCEL SESSION, or a connection dropped by a load balancer or drain), CockroachDB can answer the next query with SQLSTATE XXUUU "read tcp ...: i/o timeout". v25.4 always does; v26.3 sometimes does. The checkpointers raised it. It is now retried on a fresh connection. - In a vector store with a namespace, adding a document whose id already belonged to another namespace overwrote that row and moved it into the writing namespace. Such ids now raise
ValueErrorbefore anything is written, and the upsert never updates a row in another namespace. - New connections set
gssencmode=disableunless the URL or connect args choose otherwise. CockroachDB has no GSS encryption, and this avoids a Kerberos lookup that can crash forked workers on macOS. adrop_vector_index()anddrop_vector_index()can be called without an index to drop the default-named index, as the upgrade note says.from_texts(namespace=...)now creates the namespace column.- Two spellings of the same UUID in one call are rejected as duplicates.
Changed¶
- psycopg 3 only:
psycopg2-binaryis no longer a dependency. Requireslangchain-core1.x and caps every dependency at its next major version. Python 3.10 to 3.14. - Supports CockroachDB v25.4 or later; tested on v25.4 LTS and v26.3.
- The vector store's retry settings default to the engine's (5 attempts) instead of 3.
max_retries < 1raisesValueErrorinstead of never calling the function.- Table, schema, column and index names must be plain SQL identifiers.
- Indexes created by 0.3.x for COSINE or INNER_PRODUCT should be dropped and applied again.
add_texts/add_embeddingsreject duplicate ids within one call (ValueError), and metadata that is not JSON serializable, including NaN and infinity (TypeError). Both checks run before anything is written. They used to fail partway, after earlier batches had committed.- Range filters (
$gt,$gte,$lt,$lte,$between) with a string value now compare as text, and only match string fields, like langchain-postgres. In 0.3.0,{"year": {"$gte": "2020"}}matched numeric fields; pass a number to compare numerically. - Top-level keys next to
$and/$orused to be ignored. They are now combined with AND, so results can narrow. - The
retry_*attributes on the engine and vector store are now read-only properties. Set them throughretry_policyor the constructor. - Chat message ids are generated by the client before the first attempt.
batch_sizeis capped at 16,383. Long id lists are split automatically.
[0.3.0] - 2026-07-15¶
Fixed¶
- Hybrid search now actually executes. Setting
hybrid_search_configpreviously had no effect: only vector similarity ran and the FTS half never fired (#7). The regular search methods now run both searches in parallel and fuse the results.
Added¶
fts_languageparameter onainit_vectorstore_tablefor non-English tsvector columnsfetch_kkeyword argument to control the hybrid candidate pool sizefts_rank_normalizationoption exposing the ts_rank bitmask- Score normalization for weighted sum fusion
Changed¶
- Default fusion method is now reciprocal rank fusion. Pass
fusion_type="weighted_sum"for the previous default. HybridSearchConfigvalidatesfts_query_language
0.2.1 - 2026-03-24¶
Changed¶
- Checkpointer query performance optimization: replaced correlated subqueries with separate lightweight queries and raw BYTEA deserialization.
- Batch fetching in
list(): 3 total queries instead of 2N+1. - Prepared statement caching (
prepare_threshold=5) for query plan reuse.
Added¶
- CockroachDB row-level TTL:
enable_ttl()/disable_ttl()(sync and async) - Checkpointer performance benchmark script
0.2.0 - 2026-02-19¶
Added¶
- LangGraph checkpointer:
CockroachDBSaverandAsyncCockroachDBSaverfor persisting LangGraph workflow state (short-term memory, human-in-the-loop, fault tolerance) - Multi-tenancy: opt-in namespace column on vectorstore for tenant isolation
- Vectorstore standard tests compliance (25/25 LangChain standard tests passing)
- Checkpointer guide, multi-tenancy guide, API reference, runnable examples
Changed¶
- Clarified isolation level support: works with both SERIALIZABLE (default, recommended) and READ COMMITTED
- Test suite expanded from 92 to 177 tests
0.1.0 - 2024-01-31¶
Added¶
- Initial release of langchain-cockroachdb
CockroachDBEnginefor connection managementAsyncCockroachDBVectorStorefor async vector operationsCockroachDBVectorStoresync wrapperCSPANNIndexfor C-SPANN vector indexesHybridSearchConfigfor FTS + vector searchCockroachDBChatMessageHistoryfor chat persistence- Automatic retry logic with exponential backoff
- Comprehensive test suite (92 tests)
- Full documentation with mkdocs
- 7 working examples
- Support for Python 3.10-3.12
Features¶
- Native CockroachDB VECTOR type support
- C-SPANN distributed vector indexes
- Advanced metadata filtering
- Connection pooling with health checks
- Configurable retry parameters
- Both async and sync APIs
- Multi-tenant index support