Compare commits

..
Author SHA1 Message Date
b916a2e183 refactor: extract _track helper for available_channels sync in apply_writes
Replace 5 repeated inline blocks that sync available_channels with
a local _track() helper that checks is_available() and updates the
set, returning the availability bool for callers that also need to
update updated_channels.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-07-27 17:01:37 +00:00
3921da01cf chore: remove benchmark profiling mode from PR
Move --profile flag and Makefile targets (benchmark-profile,
benchmark-profile-spy) to a separate patch for a future PR.
This PR now contains only runtime performance optimizations.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-07-27 17:01:37 +00:00
8fd1103aca perf: remove unnecessary typing.cast calls in add_messages
The cast(BaseMessageChunk, m) calls in add_messages were no-ops at
runtime but accounted for ~92K function calls per react_agent_100x
benchmark run (~3ms overhead). Remove them since message_chunk_to_message
already handles the type internally.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-07-27 17:01:37 +00:00
7f2d549edc perf: remove isinstance from hash funcs, flatten task_path_str
Two micro-optimizations:

1. Remove per-element isinstance check in _xxhash_str/_uuid5_str — all
   call sites pass string parts, so encode() directly without checking.

2. Flatten task_path_str to avoid recursive calls for the common case
   of tuple elements being str or int (not nested tuples).

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-07-27 17:01:37 +00:00
bc266572ac perf: track available channels set to eliminate O(n) scan in apply_writes
Maintain a set of currently-available channel names, updated incrementally
as channels change state, so the step-bump loop in apply_writes only
iterates available channels instead of scanning all channels with
is_available(). For sequential_1000 this reduces function calls by ~54%
and improves overall runtime by ~26%.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-07-27 17:01:36 +00:00
281dfbddc2 perf: add benchmark profiling mode and fix quadratic repr bottleneck
Add --profile flag to bench/__main__.py that bypasses pyperf and runs
each benchmark under cProfile, printing per-benchmark hotspot summaries
and writing .prof files for later analysis. Add benchmark-profile and
benchmark-profile-spy Makefile targets.

Fix O(n^2) performance regression in _get_model_input_state where
f-strings eagerly evaluated repr(state) on every call, triggering
pydantic __repr__ across all accumulated messages. Move error message
construction into the error path so repr is only called when needed.
This yields a 3-5x speedup on react_agent_100x benchmarks.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-07-27 17:01:12 +00:00
18 changed files with 124 additions and 603 deletions
@@ -4,7 +4,6 @@ import asyncio
import concurrent.futures
import json
import logging
import re
import threading
from collections import defaultdict
from collections.abc import Callable, Iterable, Iterator, Sequence
@@ -464,9 +463,8 @@ class BasePostgresStore(Generic[C]):
ns_condition = "TRUE"
ns_param: Sequence[str] | None = None
if op.namespace_prefix:
ns_condition, ns_param = _namespace_prefix_condition(
op.namespace_prefix
)
ns_condition = "store.prefix LIKE %s"
ns_param = (f"{_namespace_to_text(op.namespace_prefix)}%",)
else:
ns_param = ()
@@ -619,17 +617,15 @@ class BasePostgresStore(Generic[C]):
conditions.append("(expires_at IS NULL OR expires_at > NOW())")
if op.match_conditions:
for condition in op.match_conditions:
if condition.match_type in ("prefix", "suffix"):
if not condition.path:
# An empty path constrains nothing; skipping keeps it a
# no-op rather than emitting a pattern that matches no
# namespace at all.
continue
conditions.append("prefix ~ %s")
if condition.match_type == "prefix":
conditions.append("prefix LIKE %s")
params.append(
_namespace_match_pattern(
condition.path, condition.match_type
)
f"{_namespace_to_text(condition.path, handle_wildcards=True)}%"
)
elif condition.match_type == "suffix":
conditions.append("prefix LIKE %s")
params.append(
f"%{_namespace_to_text(condition.path, handle_wildcards=True)}"
)
else:
logger.warning(
@@ -1275,59 +1271,15 @@ def _get_index_params(store: Any) -> tuple[str, dict[str, Any]]:
return kind, sanitized
def _namespace_to_text(namespace: tuple[str, ...]) -> str:
def _namespace_to_text(
namespace: tuple[str, ...], handle_wildcards: bool = False
) -> str:
"""Convert namespace tuple to text string."""
if handle_wildcards:
namespace = tuple("%" if val == "*" else val for val in namespace)
return ".".join(namespace)
def _escape_like_literal(text: str) -> str:
"""Escape LIKE metacharacters so `text` is matched literally.
Namespace labels may contain `_` and `%`, which would otherwise act as
wildcards: `("user_1",)` would match `("userX1",)`. Backslash is escaped
first so it cannot escape the following character. Requires an explicit
`ESCAPE '\\'` clause on the pattern.
"""
return text.replace("\\", "\\\\").replace("%", "\\%").replace("_", "\\_")
def _namespace_prefix_condition(namespace_prefix: tuple[str, ...]) -> tuple[str, tuple]:
"""Build the SQL scoping a search to a namespace and its descendants.
Matches the namespace exactly or requires the `.` separator before any
remainder, so a prefix of `("foo",)` does not also match `("foobar",)`.
Both arms stay index-friendly: equality on the `(prefix, key)` primary key,
the anchored LIKE on the `prefix text_pattern_ops` index.
Only the LIKE arm is escaped -- equality does not interpret metacharacters,
so escaping it would stop `("user_1",)` from matching itself.
"""
path = _namespace_to_text(namespace_prefix)
condition = r"(store.prefix = %s OR store.prefix LIKE %s ESCAPE '\')"
return condition, (path, f"{_escape_like_literal(path)}.%")
def _namespace_match_pattern(path: tuple[str, ...], match_type: str) -> str:
"""Build a POSIX regex matching the dot-joined prefix on whole segments.
Needed because `LIKE` cannot express "any character except the separator".
Matches how `InMemoryStore` compares namespaces element-wise.
`*` matches exactly one segment. Prefix matches stay open-ended but must end
on a separator; suffix matches anchor at the end and begin on one.
Examples:
prefix ("uid", "*", "alice") -> ^uid\\.[^.]+\\.alice(\\.|\\Z)
suffix ("alice",) -> (^|\\.)alice\\Z
"""
segments = ("[^.]+" if part == "*" else re.escape(part) for part in path)
body = r"\.".join(segments)
if match_type == "suffix":
return rf"(^|\.){body}\Z"
return rf"^{body}(\.|\Z)"
def _row_to_item(
namespace: tuple[str, ...],
row: Row,
+1 -1
View File
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
[project]
name = "langgraph-checkpoint-postgres"
version = "3.1.1"
version = "3.1.0"
description = "Library with a Postgres implementation of LangGraph checkpoint saver."
authors = []
requires-python = ">=3.10"
@@ -20,10 +20,6 @@ from langgraph.store.base import (
from psycopg import Connection
from langgraph.store.postgres import PostgresStore
from langgraph.store.postgres.base import (
_escape_like_literal,
_namespace_match_pattern,
)
from tests.conftest import (
DEFAULT_URI,
VECTOR_TYPES,
@@ -330,127 +326,6 @@ def test_list_namespaces(store) -> None:
store.delete(namespace, "dummy")
def test_escape_like_literal() -> None:
assert _escape_like_literal("users.alice") == "users.alice"
assert _escape_like_literal("user_1") == r"user\_1"
assert _escape_like_literal("100%") == r"100\%"
assert _escape_like_literal("a\\b") == "a\\\\b"
assert _escape_like_literal("") == ""
def test_namespace_match_pattern() -> None:
assert _namespace_match_pattern(("foo",), "prefix") == r"^foo(\.|\Z)"
assert _namespace_match_pattern(("uid", "users"), "prefix") == r"^uid\.users(\.|\Z)"
assert (
_namespace_match_pattern(("uid", "*", "alice"), "prefix")
== r"^uid\.[^.]+\.alice(\.|\Z)"
)
assert _namespace_match_pattern(("alice",), "suffix") == r"(^|\.)alice\Z"
# Regex metacharacters in a label are quoted, not interpreted.
pattern = _namespace_match_pattern(("a.b+c",), "prefix")
assert re.match(pattern, "a.b+c.child")
assert not re.match(pattern, "axbbbc")
def test_search_namespace_segment_boundary(store) -> None:
"""Prefix scoping must stop at namespace segment boundaries.
Namespaces are stored dot-joined, so matching the raw text also returns
siblings sharing leading characters. Callers isolate tenants by namespace,
so prefix-shaped ids (1 vs 12) would cross-read.
"""
for namespace in [
("foo",),
("foo", "child"),
("foo", "child", "deep"),
("foobar",),
("foobar", "baz"),
("foo2",),
]:
store.put(namespace, "k", {"v": 1})
def _namespaces(prefix: tuple[str, ...]) -> set[tuple[str, ...]]:
return {item.namespace for item in store.search(prefix, limit=100)}
assert _namespaces(("foo",)) == {
("foo",),
("foo", "child"),
("foo", "child", "deep"),
}
# The sibling scope is independent, not merely narrower.
assert _namespaces(("foobar",)) == {("foobar",), ("foobar", "baz")}
assert _namespaces(("foo", "child")) == {("foo", "child"), ("foo", "child", "deep")}
assert _namespaces(("foo2",)) == {("foo2",)}
assert _namespaces(("fo",)) == set()
def test_search_empty_prefix_is_unconstrained(store) -> None:
"""An empty prefix constrains nothing and must return every namespace."""
for namespace in [("a",), ("b", "c"), ("d", "e", "f")]:
store.put(namespace, "k", {"v": 1})
assert {item.namespace for item in store.search((), limit=100)} == {
("a",),
("b", "c"),
("d", "e", "f"),
}
def test_search_namespace_like_metacharacters(store) -> None:
"""`_` and `%` are legal namespace labels, not LIKE wildcards."""
for namespace in [
("user_1",),
("user_1", "child"),
("userX1",),
("a%b",),
("axxb",),
]:
store.put(namespace, "k", {"v": 1})
def _namespaces(prefix: tuple[str, ...]) -> set[tuple[str, ...]]:
return {item.namespace for item in store.search(prefix, limit=100)}
# Also asserts the namespace still matches itself, which catches escaping
# the equality arm by mistake.
assert _namespaces(("user_1",)) == {("user_1",), ("user_1", "child")}
assert _namespaces(("a%b",)) == {("a%b",)}
def test_list_namespaces_segment_boundary(store) -> None:
for namespace in [
("foo",),
("foo", "child"),
("foobar",),
("foobar", "baz"),
("uid", "users", "alice"),
("uid", "users", "malice"),
("uid", "a", "b", "alice"),
]:
store.put(namespace, "k", {"v": 1})
assert set(store.list_namespaces(prefix=["foo"], limit=100)) == {
("foo",),
("foo", "child"),
}
# Suffix must align to a segment: "malice" does not end with the "alice"
# segment.
assert set(store.list_namespaces(suffix=["alice"], limit=100)) == {
("uid", "users", "alice"),
("uid", "a", "b", "alice"),
}
# "*" spans exactly one segment.
assert set(store.list_namespaces(prefix=["uid", "*", "alice"], limit=100)) == {
("uid", "users", "alice"),
}
# Prefix matching stays open-ended across depth.
assert set(store.list_namespaces(prefix=["uid"], limit=100)) == {
("uid", "users", "alice"),
("uid", "users", "malice"),
("uid", "a", "b", "alice"),
}
def test_search(store) -> None:
# Create test data
test_data = [
@@ -1151,16 +1026,3 @@ def test_non_ascii(
assert result3[0].key == "3"
assert result4[0].key == "4"
assert result5[0].key == "5"
def test_namespace_labels_with_trailing_newline(store) -> None:
"""Labels may contain newlines, and must not match a differently-named label."""
store.put(("users", "alice"), "k", {"v": 1})
store.put(("users", "alice\n"), "k", {"v": 2})
assert set(store.list_namespaces(suffix=["alice"], limit=100)) == {
("users", "alice"),
}
assert set(store.list_namespaces(prefix=["users", "alice"], limit=100)) == {
("users", "alice"),
}
+1 -1
View File
@@ -324,7 +324,7 @@ test = [
[[package]]
name = "langgraph-checkpoint-postgres"
version = "3.1.1"
version = "3.1.0"
source = { editable = "." }
dependencies = [
{ name = "langgraph-checkpoint" },
@@ -24,13 +24,11 @@ from langgraph.store.base.batch import AsyncBatchedBaseStore
from langgraph.store.sqlite.base import (
_PLACEHOLDER,
NS_MATCH_FUNCTION,
BaseSqliteStore,
SqliteIndexConfig,
_decode_ns_text,
_ensure_index_config,
_group_ops,
_namespace_match,
_row_to_item,
_row_to_search_item,
)
@@ -152,13 +150,6 @@ class AsyncSqliteStore(AsyncBatchedBaseStore, BaseSqliteStore):
if self.is_setup:
return
# list_namespaces needs segment-aware matching, which SQLite cannot
# express in LIKE or GLOB. Registered here rather than in __init__
# because aiosqlite's create_function is a coroutine.
await self.conn.create_function(
NS_MATCH_FUNCTION, 2, _namespace_match, deterministic=True
)
# Create migrations table if it doesn't exist
await self.conn.execute(
"""
@@ -93,74 +93,12 @@ class SqliteIndexConfig(IndexConfig):
pass
NS_MATCH_FUNCTION = "_langgraph_namespace_match"
"""SQLite user function backing segment-aware namespace matching.
Registered under a private name rather than overriding `REGEXP`, so a caller's
own `REGEXP` is left untouched.
"""
def _namespace_match(prefix: str | None, pattern: str) -> int:
"""Backing implementation of `NS_MATCH_FUNCTION`."""
if prefix is None:
return 0
return 1 if re.search(pattern, prefix) else 0
def _escape_glob_literal(text: str) -> str:
"""Escape GLOB metacharacters so `text` is matched literally.
GLOB has no `ESCAPE` clause, so metacharacters are wrapped in a character
class instead. `]` is literal outside a class and needs no escaping.
"""
return text.replace("[", "[[]").replace("*", "[*]").replace("?", "[?]")
def _namespace_prefix_condition(
namespace_prefix: tuple[str, ...], column: str = "prefix"
) -> tuple[str, tuple[str, ...]]:
"""Build the SQL scoping a search to a namespace and its descendants.
Matches the namespace exactly or requires the `.` separator before any
remainder, so a prefix of `("foo",)` does not also match `("foobar",)`.
Uses GLOB rather than LIKE because SQLite's LIKE is case-insensitive for
ASCII, which would match `("FOO",)` for a prefix of `("foo",)` even though
`get`/`put`/`delete` compare with `=` and treat those as distinct.
An empty prefix is unconstrained and matches every namespace.
"""
if not namespace_prefix:
return "TRUE", ()
path = _namespace_to_text(namespace_prefix)
condition = f"({column} = ? OR {column} GLOB ?)"
return condition, (path, f"{_escape_glob_literal(path)}.*")
def _namespace_match_pattern(path: tuple[str, ...], match_type: str) -> str:
"""Build a regex matching the dot-joined prefix on whole namespace segments.
Needed because neither LIKE nor GLOB can express "any character except the
separator": GLOB has character classes but no quantifier, so `[^.]*` still
crosses `.`. Matches how `InMemoryStore` compares namespaces element-wise.
`*` matches exactly one segment. Prefix matches stay open-ended but must end
on a separator; suffix matches anchor at the end and begin on one.
Examples:
prefix ("uid", "*", "alice") -> ^uid\\.[^.]+\\.alice(\\.|\\Z)
suffix ("alice",) -> (^|\\.)alice\\Z
"""
segments = ("[^.]+" if part == "*" else re.escape(part) for part in path)
body = r"\.".join(segments)
if match_type == "suffix":
return rf"(^|\.){body}\Z"
return rf"^{body}(\.|\Z)"
def _namespace_to_text(namespace: tuple[str, ...]) -> str:
def _namespace_to_text(
namespace: tuple[str, ...], handle_wildcards: bool = False
) -> str:
"""Convert namespace tuple to text string."""
if handle_wildcards:
namespace = tuple("%" if val == "*" else val for val in namespace)
return ".".join(namespace)
@@ -523,11 +461,8 @@ class BaseSqliteStore:
else " AND " + " AND ".join(filter_conditions)
)
if op.namespace_prefix:
ns_condition, ns_args_tuple = _namespace_prefix_condition(
op.namespace_prefix, column="s.prefix"
)
prefix_filter_str = f"WHERE {ns_condition} {filter_str} "
ns_args: Sequence = ns_args_tuple
prefix_filter_str = f"WHERE s.prefix LIKE ? {filter_str} "
ns_args: Sequence = (f"{_namespace_to_text(op.namespace_prefix)}%",)
else:
ns_args = ()
if filter_str:
@@ -568,15 +503,12 @@ class BaseSqliteStore:
]
# Regular search branch (no vector search)
else:
ns_condition, ns_args_tuple = _namespace_prefix_condition(
op.namespace_prefix
)
base_query = f"""
base_query = """
SELECT prefix, key, value, created_at, updated_at, expires_at, ttl_minutes, NULL as score
FROM store
WHERE {ns_condition}
WHERE prefix LIKE ?
"""
params = list(ns_args_tuple)
params = [f"{_namespace_to_text(op.namespace_prefix)}%"]
if filter_conditions:
params.extend(filter_params)
@@ -617,28 +549,16 @@ class BaseSqliteStore:
if op.match_conditions:
for cond in op.match_conditions:
if cond.match_type in ("prefix", "suffix"):
if not cond.path:
# An empty path constrains nothing; skipping keeps it a
# no-op rather than emitting a pattern that matches no
# namespace at all.
continue
if cond.match_type == "prefix" and "*" not in cond.path:
# Equivalent to the anchored pattern, but SQLite can
# satisfy `=` and a trailing-wildcard GLOB from
# store_prefix_idx. The user function is opaque to the
# planner, so it would scan every row and call back
# into Python for each one.
condition, args = _namespace_prefix_condition(
tuple(cond.path)
)
where_clauses.append(condition)
params.extend(args)
else:
where_clauses.append(f"{NS_MATCH_FUNCTION}(prefix, ?) = 1")
params.append(
_namespace_match_pattern(cond.path, cond.match_type)
)
if cond.match_type == "prefix":
where_clauses.append("prefix LIKE ?")
params.append(
f"{_namespace_to_text(cond.path, handle_wildcards=True)}%"
)
elif cond.match_type == "suffix":
where_clauses.append("prefix LIKE ?")
params.append(
f"%{_namespace_to_text(cond.path, handle_wildcards=True)}"
)
else:
logger.warning(
"Unknown match_type in list_namespaces: %s", cond.match_type
@@ -865,9 +785,6 @@ class SqliteStore(BaseSqliteStore, BaseStore):
super().__init__()
self._deserializer = deserializer
self.conn = conn
# Registered here rather than in from_conn_string so a caller-supplied
# connection also gets it.
conn.create_function(NS_MATCH_FUNCTION, 2, _namespace_match, deterministic=True)
self.lock = threading.Lock()
self.is_setup = False
self.index_config = index
+1 -1
View File
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
[project]
name = "langgraph-checkpoint-sqlite"
version = "3.1.1"
version = "3.1.0"
description = "Library with a SQLite implementation of LangGraph checkpoint saver."
authors = []
requires-python = ">=3.10"
@@ -716,32 +716,3 @@ async def test_search_items(
for ns in test_namespaces:
key = f"item_{ns[-1]}"
await store.adelete(ns, key)
async def test_async_namespace_segment_boundary(store: AsyncSqliteStore) -> None:
"""Segment-aware scoping on the async path.
Also covers that the namespace-match SQLite function is registered on the
async connection -- aiosqlite's create_function is a coroutine, so it is
registered in setup() rather than __init__.
"""
for namespace in [
("foo",),
("foo", "child"),
("foobar",),
("uid", "users", "alice"),
("uid", "users", "malice"),
("user_1",),
("userX1",),
]:
await store.aput(namespace, "k", {"v": 1})
found = {item.namespace for item in await store.asearch(("foo",), limit=100)}
assert found == {("foo",), ("foo", "child")}
found = {item.namespace for item in await store.asearch(("user_1",), limit=100)}
assert found == {("user_1",)}
assert set(await store.alist_namespaces(suffix=["alice"], limit=100)) == {
("uid", "users", "alice"),
}
+1 -212
View File
@@ -18,13 +18,7 @@ from langgraph.store.base import (
)
from langgraph.store.sqlite import SqliteStore
from langgraph.store.sqlite.base import (
NS_MATCH_FUNCTION,
BaseSqliteStore,
SqliteIndexConfig,
_escape_glob_literal,
_namespace_match_pattern,
)
from langgraph.store.sqlite.base import SqliteIndexConfig
# Local embeddings implementation for testing vector search
@@ -1235,208 +1229,3 @@ def test_non_ascii(
assert result3[0].key == "3"
assert result4[0].key == "4"
assert result5[0].key == "5"
def test_escape_glob_literal() -> None:
assert _escape_glob_literal("users.alice") == "users.alice"
# "_" and "%" are LIKE wildcards but literal in GLOB, so they are left alone.
assert _escape_glob_literal("user_1") == "user_1"
assert _escape_glob_literal("100%") == "100%"
assert _escape_glob_literal("a*b") == "a[*]b"
assert _escape_glob_literal("a?b") == "a[?]b"
assert _escape_glob_literal("a[b") == "a[[]b"
def test_namespace_match_pattern() -> None:
assert _namespace_match_pattern(("foo",), "prefix") == r"^foo(\.|\Z)"
assert (
_namespace_match_pattern(("uid", "*", "alice"), "prefix")
== r"^uid\.[^.]+\.alice(\.|\Z)"
)
assert _namespace_match_pattern(("alice",), "suffix") == r"(^|\.)alice\Z"
def test_search_namespace_segment_boundary(store: SqliteStore) -> None:
"""Prefix scoping must stop at namespace segment boundaries.
Namespaces are stored dot-joined, so matching the raw text also returns
siblings sharing leading characters.
"""
for namespace in [
("foo",),
("foo", "child"),
("foo", "child", "deep"),
("foobar",),
("foobar", "baz"),
("foo2",),
]:
store.put(namespace, "k", {"v": 1})
def _namespaces(prefix: tuple[str, ...]) -> set[tuple[str, ...]]:
return {item.namespace for item in store.search(prefix, limit=100)}
assert _namespaces(("foo",)) == {
("foo",),
("foo", "child"),
("foo", "child", "deep"),
}
# The sibling scope is independent, not merely narrower.
assert _namespaces(("foobar",)) == {("foobar",), ("foobar", "baz")}
assert _namespaces(("foo2",)) == {("foo2",)}
assert _namespaces(("fo",)) == set()
def test_search_namespace_wildcard_chars_are_literal(store: SqliteStore) -> None:
"""LIKE and GLOB metacharacters in labels must be matched literally."""
for namespace in [
("user_1",),
("user_1", "child"),
("userX1",),
("a%b",),
("axxb",),
("star*",),
("starX",),
]:
store.put(namespace, "k", {"v": 1})
def _namespaces(prefix: tuple[str, ...]) -> set[tuple[str, ...]]:
return {item.namespace for item in store.search(prefix, limit=100)}
# Also asserts each namespace still matches itself, which catches escaping
# the equality arm by mistake.
assert _namespaces(("user_1",)) == {("user_1",), ("user_1", "child")}
assert _namespaces(("a%b",)) == {("a%b",)}
assert _namespaces(("star*",)) == {("star*",)}
def test_search_namespace_is_case_sensitive(store: SqliteStore) -> None:
"""Search must agree with get/put, which compare namespaces with `=`.
SQLite's LIKE is case-insensitive for ASCII, so matching with it conflated
namespaces that every other operation treats as distinct.
"""
store.put(("Foo",), "k", {"v": "upper"})
store.put(("foo",), "k", {"v": "lower"})
assert {item.namespace for item in store.search(("foo",), limit=100)} == {("foo",)}
assert {item.namespace for item in store.search(("Foo",), limit=100)} == {("Foo",)}
def test_list_namespaces_segment_boundary(store: SqliteStore) -> None:
for namespace in [
("foo",),
("foo", "child"),
("foobar",),
("foobar", "baz"),
("uid", "users", "alice"),
("uid", "users", "malice"),
("uid", "a", "b", "alice"),
]:
store.put(namespace, "k", {"v": 1})
assert set(store.list_namespaces(prefix=["foo"], limit=100)) == {
("foo",),
("foo", "child"),
}
# Suffix must align to a segment: "malice" does not end with the "alice"
# segment.
assert set(store.list_namespaces(suffix=["alice"], limit=100)) == {
("uid", "users", "alice"),
("uid", "a", "b", "alice"),
}
# "*" spans exactly one segment.
assert set(store.list_namespaces(prefix=["uid", "*", "alice"], limit=100)) == {
("uid", "users", "alice"),
}
# Prefix matching stays open-ended across depth.
assert set(store.list_namespaces(prefix=["uid"], limit=100)) == {
("uid", "users", "alice"),
("uid", "users", "malice"),
("uid", "a", "b", "alice"),
}
def test_search_empty_prefix_is_unconstrained(store: SqliteStore) -> None:
"""An empty prefix constrains nothing and must return every namespace."""
for namespace in [("a",), ("b", "c"), ("d", "e", "f")]:
store.put(namespace, "k", {"v": 1})
assert {item.namespace for item in store.search((), limit=100)} == {
("a",),
("b", "c"),
("d", "e", "f"),
}
def test_namespace_labels_with_trailing_newline(store: SqliteStore) -> None:
"""Labels may contain newlines, and must not match a differently-named label.
Python's `$` also matches just before a trailing newline, so the patterns use
`\\Z` to anchor at the true end of the string.
"""
store.put(("users", "alice"), "k", {"v": 1})
store.put(("users", "alice\n"), "k", {"v": 2})
assert set(store.list_namespaces(suffix=["alice"], limit=100)) == {
("users", "alice"),
}
assert set(store.list_namespaces(prefix=["users", "alice"], limit=100)) == {
("users", "alice"),
}
def test_list_namespaces_prefix_uses_indexable_condition() -> None:
"""Plain prefixes must use the indexable condition, not the match function.
A user function is opaque to the query planner, so it scans every row and
calls back into Python for each one. Only suffix and wildcard paths, which
no SQLite operator can express, need it.
"""
store = BaseSqliteStore()
def where(match_type: str, path: tuple[str, ...]) -> str:
op = ListNamespacesOp(
match_conditions=(MatchCondition(match_type=match_type, path=path),),
max_depth=None,
limit=10,
offset=0,
)
query, _ = store._get_batch_list_namespaces_queries([(0, op)])[0]
return " ".join(query.split())
assert "GLOB" in where("prefix", ("uid", "users"))
assert NS_MATCH_FUNCTION not in where("prefix", ("uid", "users"))
# A label that merely contains "*" is not the wildcard.
assert "GLOB" in where("prefix", ("star*",))
# Wildcard and suffix cannot be expressed by GLOB, so they keep the function.
assert NS_MATCH_FUNCTION in where("prefix", ("uid", "*", "alice"))
assert NS_MATCH_FUNCTION in where("suffix", ("alice",))
def test_list_namespaces_metacharacter_labels(store: SqliteStore) -> None:
"""Metacharacters in labels are literal on both matching paths.
Plain prefixes take the `= OR GLOB` condition and wildcard/suffix paths take
the regex function, so escaping has to hold in two different syntaxes.
"""
pairs = [
("star*", "starX"),
("q?m", "qXm"),
("br[ack]et", "brXacXket"),
("user_1", "userX1"),
("a%b", "axxb"),
("plus+", "plusX"),
]
for label, decoy in pairs:
store.put((label,), "k", {"v": 1})
store.put((decoy,), "k", {"v": 1})
store.put((label, "child"), "k", {"v": 1})
for label, decoy in pairs:
found = set(store.list_namespaces(prefix=[label], limit=100))
assert found == {(label,), (label, "child")}
# The decoy differs only where the metacharacter would have matched.
assert (decoy,) not in found
assert set(store.list_namespaces(prefix=[label, "child"], limit=100)) == {
(label, "child"),
}
+1 -1
View File
@@ -333,7 +333,7 @@ test = [
[[package]]
name = "langgraph-checkpoint-sqlite"
version = "3.1.1"
version = "3.1.0"
source = { editable = "." }
dependencies = [
{ name = "aiosqlite" },
+2 -8
View File
@@ -191,14 +191,8 @@ def add_messages(
if not isinstance(right, list):
right = [right] # type: ignore[assignment]
# coerce to message
left = [
message_chunk_to_message(cast(BaseMessageChunk, m))
for m in convert_to_messages(left)
]
right = [
message_chunk_to_message(cast(BaseMessageChunk, m))
for m in convert_to_messages(right)
]
left = [message_chunk_to_message(m) for m in convert_to_messages(left)]
right = [message_chunk_to_message(m) for m in convert_to_messages(right)]
# assign missing ids
for m in left:
if m.id is None:
+55 -24
View File
@@ -235,6 +235,7 @@ def apply_writes(
tasks: Iterable[WritesProtocol],
get_next_version: GetNextVersion | None,
trigger_to_nodes: Mapping[str, Sequence[str]],
available_channels: set[str] | None = None,
) -> set[str]:
"""Apply writes from a set of tasks (usually the tasks from a Pregel step)
to the checkpoint and channels, and return managed values writes to be applied
@@ -281,6 +282,18 @@ def apply_writes(
None,
)
# Sync available_channels with channel's actual availability state.
# Returns True if the channel is available (for callers that also need
# to update updated_channels).
def _track(chan: str) -> bool:
avail = channels[chan].is_available()
if available_channels is not None:
if avail:
available_channels.add(chan)
else:
available_channels.discard(chan)
return avail
# Consume all channels that were read
for chan in {
chan
@@ -290,6 +303,7 @@ def apply_writes(
}:
if channels[chan].consume() and next_version is not None:
checkpoint["channel_versions"][chan] = next_version
_track(chan)
# Group writes by channel
pending_writes_by_channel: dict[str, list[Any]] = defaultdict(list)
@@ -319,18 +333,28 @@ def apply_writes(
if channels[chan].update(vals) and next_version is not None:
checkpoint["channel_versions"][chan] = next_version
# unavailable channels can't trigger tasks, so don't add them
if channels[chan].is_available():
if _track(chan):
updated_channels.add(chan)
else:
_track(chan)
# Channels that weren't updated in this step are notified of a new step
if bump_step:
for chan in channels:
if channels[chan].is_available() and chan not in updated_channels:
if channels[chan].update(EMPTY_SEQ) and next_version is not None:
checkpoint["channel_versions"][chan] = next_version
# unavailable channels can't trigger tasks, so don't add them
if channels[chan].is_available():
updated_channels.add(chan)
candidates = (
available_channels - updated_channels
if available_channels is not None
else (
chan
for chan in channels
if channels[chan].is_available() and chan not in updated_channels
)
)
for chan in candidates:
if channels[chan].update(EMPTY_SEQ) and next_version is not None:
checkpoint["channel_versions"][chan] = next_version
# unavailable channels can't trigger tasks, so don't add them
if _track(chan):
updated_channels.add(chan)
# If this is (tentatively) the last superstep, notify all channels of finish
if bump_step and updated_channels.isdisjoint(trigger_to_nodes):
@@ -338,8 +362,10 @@ def apply_writes(
if channels[chan].finish() and next_version is not None:
checkpoint["channel_versions"][chan] = next_version
# unavailable channels can't trigger tasks, so don't add them
if channels[chan].is_available():
if _track(chan):
updated_channels.add(chan)
else:
_track(chan)
# Return managed values writes to be applied externally
return updated_channels
@@ -517,7 +543,7 @@ PUSH_TRIGGER = (PUSH,)
class _TaskIDFn(Protocol):
def __call__(self, namespace: bytes, *parts: str | bytes) -> str:
def __call__(self, namespace: bytes, *parts: str) -> str:
pass
@@ -1392,32 +1418,37 @@ def _proc_input(
return val
def _uuid5_str(namespace: bytes, *parts: str | bytes) -> str:
def _uuid5_str(namespace: bytes, *parts: str) -> str:
"""Generate a UUID from the SHA-1 hash of a namespace and str parts."""
sha = sha1(namespace, usedforsecurity=False)
sha.update(b"".join(p.encode() if isinstance(p, str) else p for p in parts))
sha.update(b"".join(p.encode() for p in parts))
hex = sha.hexdigest()
return f"{hex[:8]}-{hex[8:12]}-{hex[12:16]}-{hex[16:20]}-{hex[20:32]}"
def _xxhash_str(namespace: bytes, *parts: str | bytes) -> str:
def _xxhash_str(namespace: bytes, *parts: str) -> str:
"""Generate a UUID from the XXH3 hash of a namespace and str parts."""
hex = xxh3_128_hexdigest(
namespace + b"".join(p.encode() if isinstance(p, str) else p for p in parts)
)
hex = xxh3_128_hexdigest(namespace + b"".join(p.encode() for p in parts))
return f"{hex[:8]}-{hex[8:12]}-{hex[12:16]}-{hex[16:20]}-{hex[20:32]}"
def task_path_str(tup: str | int | tuple) -> str:
def task_path_str(tup: str | int | tuple | list) -> str:
"""Generate a string representation of the task path."""
return (
f"~{', '.join(task_path_str(x) for x in tup)}"
if isinstance(tup, (tuple, list))
else f"{tup:010d}"
if isinstance(tup, int)
else str(tup)
)
if isinstance(tup, (tuple, list)):
parts: list[str] = []
for x in tup:
if isinstance(x, int):
parts.append(f"{x:010d}")
elif isinstance(x, (tuple, list)):
parts.append(task_path_str(x))
else:
parts.append(str(x))
return f"~{', '.join(parts)}"
elif isinstance(tup, int):
return f"{tup:010d}"
else:
return str(tup)
LAZY_ATOMIC_COUNTER_LOCK = threading.Lock()
+11
View File
@@ -198,6 +198,7 @@ class PregelLoop:
_migrate_checkpoint: Callable[[Checkpoint], None] | None
submit: Submit
channels: Mapping[str, BaseChannel]
_available_channels: set[str]
# Futures from `checkpointer.put_writes` calls that produced delta-channel
# writes. `_checkpointer_put_after_previous` drains this list (swap to a
# local `futs` then reset to `[]` and wait/gather) before putting the
@@ -695,6 +696,7 @@ class PregelLoop:
self.tasks.values(),
self.checkpointer_get_next_version,
self.trigger_to_nodes,
available_channels=self._available_channels,
)
# produce values output
if not self.updated_channels.isdisjoint(
@@ -939,6 +941,7 @@ class PregelLoop:
[PregelTaskWrites((), INPUT, null_writes, [])],
self.checkpointer_get_next_version,
self.trigger_to_nodes,
available_channels=self._available_channels,
)
if updated_channels is not None:
updated_channels.update(null_updated_channels)
@@ -1006,6 +1009,7 @@ class PregelLoop:
],
self.checkpointer_get_next_version,
self.trigger_to_nodes,
available_channels=self._available_channels,
)
# Input writes go through `apply_writes` directly (above) — they
# never enter `checkpoint_pending_writes`, so the after_tick
@@ -1349,6 +1353,7 @@ class PregelLoop:
self.tasks.values(),
self.checkpointer_get_next_version,
self.trigger_to_nodes,
available_channels=self._available_channels,
)
if not updated_channels.isdisjoint(
(self.output_keys,)
@@ -1695,6 +1700,9 @@ class SyncPregelLoop(PregelLoop, AbstractContextManager):
saver=self.checkpointer,
config=self.checkpoint_config,
)
self._available_channels: set[str] = {
k for k, v in self.channels.items() if v.is_available()
}
self.stack.push(self._suppress_interrupt)
self.status = "input"
self.step = self.checkpoint_metadata["step"] + 1
@@ -1955,6 +1963,9 @@ class AsyncPregelLoop(PregelLoop, AbstractAsyncContextManager):
saver=self.checkpointer,
config=self.checkpoint_config,
)
self._available_channels: set[str] = {
k for k, v in self.channels.items() if v.is_available()
}
self.stack.push(self._suppress_interrupt)
self.status = "input"
self.step = self.checkpoint_metadata["step"] + 1
+1 -1
View File
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
[project]
name = "langgraph"
version = "1.2.10"
version = "1.2.9"
description = "Building stateful, multi-actor applications with LLMs"
authors = []
requires-python = ">=3.10"
+3 -3
View File
@@ -1439,7 +1439,7 @@ wheels = [
[[package]]
name = "langgraph"
version = "1.2.10"
version = "1.2.9"
source = { editable = "." }
dependencies = [
{ name = "langchain-core" },
@@ -1673,7 +1673,7 @@ test = [
[[package]]
name = "langgraph-checkpoint-postgres"
version = "3.1.1"
version = "3.1.0"
source = { editable = "../checkpoint-postgres" }
dependencies = [
{ name = "langgraph-checkpoint" },
@@ -1720,7 +1720,7 @@ test = [
[[package]]
name = "langgraph-checkpoint-sqlite"
version = "3.1.1"
version = "3.1.0"
source = { editable = "../checkpoint-sqlite" }
dependencies = [
{ name = "aiosqlite" },
@@ -638,15 +638,18 @@ def create_react_agent(
messages = (
_get_state_value(state, "llm_input_messages")
) or _get_state_value(state, "messages")
error_msg = f"Expected input to call_model to have 'llm_input_messages' or 'messages' key, but got {state}"
else:
messages = _get_state_value(state, "messages")
error_msg = (
f"Expected input to call_model to have 'messages' key, but got {state}"
)
if messages is None:
raise ValueError(error_msg)
if pre_model_hook is not None:
raise ValueError(
f"Expected input to call_model to have 'llm_input_messages' or 'messages' key, but got {state}"
)
else:
raise ValueError(
f"Expected input to call_model to have 'messages' key, but got {state}"
)
_validate_chat_history(messages)
# we're passing messages under `messages` key, as this is expected by the prompt
+3 -3
View File
@@ -285,7 +285,7 @@ wheels = [
[[package]]
name = "langgraph"
version = "1.2.10"
version = "1.2.9"
source = { editable = "../langgraph" }
dependencies = [
{ name = "langchain-core" },
@@ -417,7 +417,7 @@ test = [
[[package]]
name = "langgraph-checkpoint-postgres"
version = "3.1.1"
version = "3.1.0"
source = { editable = "../checkpoint-postgres" }
dependencies = [
{ name = "langgraph-checkpoint" },
@@ -464,7 +464,7 @@ test = [
[[package]]
name = "langgraph-checkpoint-sqlite"
version = "3.1.1"
version = "3.1.0"
source = { editable = "../checkpoint-sqlite" }
dependencies = [
{ name = "aiosqlite" },
+1 -1
View File
@@ -298,7 +298,7 @@ wheels = [
[[package]]
name = "langgraph"
version = "1.2.10"
version = "1.2.9"
source = { editable = "../langgraph" }
dependencies = [
{ name = "langchain-core" },