diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/_internal/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/_internal/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2dcf9227cd00121813ecbaef7e78ad2a755bec5f Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/_internal/__pycache__/__init__.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/_internal/__pycache__/_cache.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/_internal/__pycache__/_cache.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7a2cd89866c4360a8ac48cddd00e490e40ac88f3 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/_internal/__pycache__/_cache.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/_internal/__pycache__/_config.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/_internal/__pycache__/_config.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..188481a35d6916c0467f53d25b00c0e1126562ed Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/_internal/__pycache__/_config.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/_internal/__pycache__/_constants.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/_internal/__pycache__/_constants.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9905af2b0e3f2a56738913a508f41dd1c1e1900c Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/_internal/__pycache__/_constants.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/_internal/__pycache__/_fields.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/_internal/__pycache__/_fields.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cbdaf85eb82836fb8ce13ffbf0fec20ceeefaa12 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/_internal/__pycache__/_fields.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/_internal/__pycache__/_future.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/_internal/__pycache__/_future.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d02e006dd62325256cc04de81c6fc74d69f55ce3 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/_internal/__pycache__/_future.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/_internal/__pycache__/_pydantic.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/_internal/__pycache__/_pydantic.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c00b1b03eccc0f72ffe5670054d050ef62c79cd3 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/_internal/__pycache__/_pydantic.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/_internal/__pycache__/_queue.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/_internal/__pycache__/_queue.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..98ded27fff11ea3f8aecb798478c1d79725418ba Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/_internal/__pycache__/_queue.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/_internal/__pycache__/_replay.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/_internal/__pycache__/_replay.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b59323a69924adaad16740b808897adee1aa939c Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/_internal/__pycache__/_replay.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/_internal/__pycache__/_retry.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/_internal/__pycache__/_retry.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..db9e8b14f8d31c4cb354409f0727634f2934a09a Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/_internal/__pycache__/_retry.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/_internal/__pycache__/_runnable.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/_internal/__pycache__/_runnable.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..88790bb95f2f6e54d51be73cf92ee87071379ea9 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/_internal/__pycache__/_runnable.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/_internal/__pycache__/_scratchpad.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/_internal/__pycache__/_scratchpad.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5f0c7dd87ccf2232e960e50500e16f9d826c0ee7 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/_internal/__pycache__/_scratchpad.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/_internal/__pycache__/_serde.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/_internal/__pycache__/_serde.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9cf3d0dd3d57c6848380102adba7246749f29ba4 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/_internal/__pycache__/_serde.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/_internal/__pycache__/_timeout.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/_internal/__pycache__/_timeout.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e21cd66b87f87ee615685b46531061cfe1709dcd Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/_internal/__pycache__/_timeout.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/_internal/__pycache__/_typing.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/_internal/__pycache__/_typing.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..824770d9cf75643d60546b398b399c9e23af9c43 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/_internal/__pycache__/_typing.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/cache/base/__init__.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/cache/base/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..092324e721d4717bdc35bc843ee0c317aabaf19c --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/cache/base/__init__.py @@ -0,0 +1,48 @@ +from __future__ import annotations + +from abc import ABC, abstractmethod +from collections.abc import Mapping, Sequence +from typing import Generic, TypeVar + +from langgraph.checkpoint.serde.base import SerializerProtocol +from langgraph.checkpoint.serde.jsonplus import JsonPlusSerializer + +ValueT = TypeVar("ValueT") +Namespace = tuple[str, ...] +FullKey = tuple[Namespace, str] + + +class BaseCache(ABC, Generic[ValueT]): + """Base class for a cache.""" + + serde: SerializerProtocol = JsonPlusSerializer(pickle_fallback=False) + + def __init__(self, *, serde: SerializerProtocol | None = None) -> None: + """Initialize the cache with a serializer.""" + self.serde = serde or self.serde + + @abstractmethod + def get(self, keys: Sequence[FullKey]) -> dict[FullKey, ValueT]: + """Get the cached values for the given keys.""" + + @abstractmethod + async def aget(self, keys: Sequence[FullKey]) -> dict[FullKey, ValueT]: + """Asynchronously get the cached values for the given keys.""" + + @abstractmethod + def set(self, pairs: Mapping[FullKey, tuple[ValueT, int | None]]) -> None: + """Set the cached values for the given keys and TTLs.""" + + @abstractmethod + async def aset(self, pairs: Mapping[FullKey, tuple[ValueT, int | None]]) -> None: + """Asynchronously set the cached values for the given keys and TTLs.""" + + @abstractmethod + def clear(self, namespaces: Sequence[Namespace] | None = None) -> None: + """Delete the cached values for the given namespaces. + If no namespaces are provided, clear all cached values.""" + + @abstractmethod + async def aclear(self, namespaces: Sequence[Namespace] | None = None) -> None: + """Asynchronously delete the cached values for the given namespaces. + If no namespaces are provided, clear all cached values.""" diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/cache/base/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/cache/base/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cd5e9f0ea47805d7649ac918d7a9082152c9b245 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/cache/base/__pycache__/__init__.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/cache/base/py.typed b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/cache/base/py.typed new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/cache/memory/__init__.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/cache/memory/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..7b10db0511c62f2e4c98a19a8bc796599db71124 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/cache/memory/__init__.py @@ -0,0 +1,73 @@ +from __future__ import annotations + +import datetime +import threading +from collections.abc import Mapping, Sequence + +from langgraph.cache.base import BaseCache, FullKey, Namespace, ValueT +from langgraph.checkpoint.serde.base import SerializerProtocol + + +class InMemoryCache(BaseCache[ValueT]): + def __init__(self, *, serde: SerializerProtocol | None = None): + super().__init__(serde=serde) + self._cache: dict[Namespace, dict[str, tuple[str, bytes, float | None]]] = {} + self._lock = threading.RLock() + + def get(self, keys: Sequence[FullKey]) -> dict[FullKey, ValueT]: + """Get the cached values for the given keys.""" + with self._lock: + if not keys: + return {} + now = datetime.datetime.now(datetime.timezone.utc).timestamp() + values: dict[FullKey, ValueT] = {} + for ns_tuple, key in keys: + ns = Namespace(ns_tuple) + if ns in self._cache and key in self._cache[ns]: + enc, val, expiry = self._cache[ns][key] + if expiry is None or now < expiry: + values[(ns, key)] = self.serde.loads_typed((enc, val)) + else: + del self._cache[ns][key] + return values + + async def aget(self, keys: Sequence[FullKey]) -> dict[FullKey, ValueT]: + """Asynchronously get the cached values for the given keys.""" + return self.get(keys) + + def set(self, keys: Mapping[FullKey, tuple[ValueT, int | None]]) -> None: + """Set the cached values for the given keys.""" + with self._lock: + now = datetime.datetime.now(datetime.timezone.utc) + for (ns, key), (value, ttl) in keys.items(): + if ttl is not None: + delta = datetime.timedelta(seconds=ttl) + expiry: float | None = (now + delta).timestamp() + else: + expiry = None + if ns not in self._cache: + self._cache[ns] = {} + self._cache[ns][key] = ( + *self.serde.dumps_typed(value), + expiry, + ) + + async def aset(self, keys: Mapping[FullKey, tuple[ValueT, int | None]]) -> None: + """Asynchronously set the cached values for the given keys.""" + self.set(keys) + + def clear(self, namespaces: Sequence[Namespace] | None = None) -> None: + """Delete the cached values for the given namespaces. + If no namespaces are provided, clear all cached values.""" + with self._lock: + if namespaces is None: + self._cache.clear() + else: + for ns in namespaces: + if ns in self._cache: + del self._cache[ns] + + async def aclear(self, namespaces: Sequence[Namespace] | None = None) -> None: + """Asynchronously delete the cached values for the given namespaces. + If no namespaces are provided, clear all cached values.""" + self.clear(namespaces) diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/cache/memory/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/cache/memory/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7d15c0778eef1dda89330a1878509f7cf6bc5708 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/cache/memory/__pycache__/__init__.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/cache/redis/__init__.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/cache/redis/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..ea4f71480d02a01ec242335d32ac532f61ccfb7d --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/cache/redis/__init__.py @@ -0,0 +1,144 @@ +from __future__ import annotations + +from collections.abc import Mapping, Sequence +from typing import Any + +from langgraph.cache.base import BaseCache, FullKey, Namespace, ValueT +from langgraph.checkpoint.serde.base import SerializerProtocol + + +class RedisCache(BaseCache[ValueT]): + """Redis-based cache implementation with TTL support.""" + + def __init__( + self, + redis: Any, + *, + serde: SerializerProtocol | None = None, + prefix: str = "langgraph:cache:", + ) -> None: + """Initialize the cache with a Redis client. + + Args: + redis: Redis client instance (sync or async) + serde: Serializer to use for values + prefix: Key prefix for all cached values + """ + super().__init__(serde=serde) + self.redis = redis + self.prefix = prefix + + def _make_key(self, ns: Namespace, key: str) -> str: + """Create a Redis key from namespace and key.""" + ns_str = ":".join(ns) if ns else "" + return f"{self.prefix}{ns_str}:{key}" if ns_str else f"{self.prefix}{key}" + + def _parse_key(self, redis_key: str) -> tuple[Namespace, str]: + """Parse a Redis key back to namespace and key.""" + if not redis_key.startswith(self.prefix): + raise ValueError( + f"Key {redis_key} does not start with prefix {self.prefix}" + ) + + remaining = redis_key[len(self.prefix) :] + if ":" in remaining: + parts = remaining.split(":") + key = parts[-1] + ns_parts = parts[:-1] + return (tuple(ns_parts), key) + else: + return (tuple(), remaining) + + def get(self, keys: Sequence[FullKey]) -> dict[FullKey, ValueT]: + """Get the cached values for the given keys.""" + if not keys: + return {} + + # Build Redis keys + redis_keys = [self._make_key(ns, key) for ns, key in keys] + + # Get values from Redis using MGET + try: + raw_values = self.redis.mget(redis_keys) + except Exception: + # If Redis is unavailable, return empty dict + return {} + + values: dict[FullKey, ValueT] = {} + for i, raw_value in enumerate(raw_values): + if raw_value is not None: + try: + # Deserialize the value + encoding, data = raw_value.split(b":", 1) + values[keys[i]] = self.serde.loads_typed((encoding.decode(), data)) + except Exception: + # Skip corrupted entries + continue + + return values + + async def aget(self, keys: Sequence[FullKey]) -> dict[FullKey, ValueT]: + """Asynchronously get the cached values for the given keys.""" + return self.get(keys) + + def set(self, mapping: Mapping[FullKey, tuple[ValueT, int | None]]) -> None: + """Set the cached values for the given keys and TTLs.""" + if not mapping: + return + + # Use pipeline for efficient batch operations + pipe = self.redis.pipeline() + + for (ns, key), (value, ttl) in mapping.items(): + redis_key = self._make_key(ns, key) + encoding, data = self.serde.dumps_typed(value) + + # Store as "encoding:data" format + serialized_value = f"{encoding}:".encode() + data + + if ttl is not None: + pipe.setex(redis_key, ttl, serialized_value) + else: + pipe.set(redis_key, serialized_value) + + try: + pipe.execute() + except Exception: + # Silently fail if Redis is unavailable + pass + + async def aset(self, mapping: Mapping[FullKey, tuple[ValueT, int | None]]) -> None: + """Asynchronously set the cached values for the given keys and TTLs.""" + self.set(mapping) + + def clear(self, namespaces: Sequence[Namespace] | None = None) -> None: + """Delete the cached values for the given namespaces. + If no namespaces are provided, clear all cached values.""" + try: + if namespaces is None: + # Clear all keys with our prefix + pattern = f"{self.prefix}*" + keys = self.redis.keys(pattern) + if keys: + self.redis.delete(*keys) + else: + # Clear specific namespaces + keys_to_delete = [] + for ns in namespaces: + ns_str = ":".join(ns) if ns else "" + pattern = ( + f"{self.prefix}{ns_str}:*" if ns_str else f"{self.prefix}*" + ) + keys = self.redis.keys(pattern) + keys_to_delete.extend(keys) + + if keys_to_delete: + self.redis.delete(*keys_to_delete) + except Exception: + # Silently fail if Redis is unavailable + pass + + async def aclear(self, namespaces: Sequence[Namespace] | None = None) -> None: + """Asynchronously delete the cached values for the given namespaces. + If no namespaces are provided, clear all cached values.""" + self.clear(namespaces) diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/cache/redis/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/cache/redis/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..23892ebdc54c3fe8c53322c3e33b8e319d875654 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/cache/redis/__pycache__/__init__.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/cache/sqlite/__init__.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/cache/sqlite/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..cd327bd4876856bababa3604f23c0574d17f4cae --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/cache/sqlite/__init__.py @@ -0,0 +1,120 @@ +from __future__ import annotations + +import asyncio +import datetime +import sqlite3 +import threading +from collections.abc import Mapping, Sequence + +from langgraph.cache.base import BaseCache, FullKey, Namespace, ValueT +from langgraph.checkpoint.serde.base import SerializerProtocol + + +class SqliteCache(BaseCache[ValueT]): + """File-based cache using SQLite.""" + + def __init__( + self, + *, + path: str, + serde: SerializerProtocol | None = None, + ) -> None: + """Initialize the cache with a file path.""" + super().__init__(serde=serde) + # SQLite backing store + self._conn = sqlite3.connect( + path, + check_same_thread=False, + ) + # Serialize access to the shared connection across threads + self._lock = threading.RLock() + # Better concurrency & atomicity + self._conn.execute("PRAGMA journal_mode=WAL;") + # Schema: key -> (expiry, encoding, value) + self._conn.execute( + """CREATE TABLE IF NOT EXISTS cache ( + ns TEXT, + key TEXT, + expiry REAL, + encoding TEXT NOT NULL, + val BLOB NOT NULL, + PRIMARY KEY (ns, key) + )""" + ) + self._conn.commit() + + def get(self, keys: Sequence[FullKey]) -> dict[FullKey, ValueT]: + """Get the cached values for the given keys.""" + with self._lock, self._conn: + now = datetime.datetime.now(datetime.timezone.utc).timestamp() + if not keys: + return {} + placeholders = ",".join("(?, ?)" for _ in keys) + params: list[str] = [] + for ns_tuple, key in keys: + params.extend((",".join(ns_tuple), key)) + cursor = self._conn.execute( + f"SELECT ns, key, expiry, encoding, val FROM cache WHERE (ns, key) IN ({placeholders})", + tuple(params), + ) + values: dict[FullKey, ValueT] = {} + rows = cursor.fetchall() + for ns, key, expiry, encoding, raw in rows: + if expiry is not None and now > expiry: + # purge expired entry + self._conn.execute( + "DELETE FROM cache WHERE (ns, key) = (?, ?)", (ns, key) + ) + continue + values[(tuple(ns.split(",")), key)] = self.serde.loads_typed( + (encoding, raw) + ) + return values + + async def aget(self, keys: Sequence[FullKey]) -> dict[FullKey, ValueT]: + """Asynchronously get the cached values for the given keys.""" + return await asyncio.to_thread(self.get, keys) + + def set(self, mapping: Mapping[FullKey, tuple[ValueT, int | None]]) -> None: + """Set the cached values for the given keys and TTLs.""" + with self._lock, self._conn: + now = datetime.datetime.now(datetime.timezone.utc) + for key, (value, ttl) in mapping.items(): + if ttl is not None: + delta = datetime.timedelta(seconds=ttl) + expiry: float | None = (now + delta).timestamp() + else: + expiry = None + encoding, raw = self.serde.dumps_typed(value) + self._conn.execute( + "INSERT OR REPLACE INTO cache (ns, key, expiry, encoding, val) VALUES (?, ?, ?, ?, ?)", + (",".join(key[0]), key[1], expiry, encoding, raw), + ) + + async def aset(self, mapping: Mapping[FullKey, tuple[ValueT, int | None]]) -> None: + """Asynchronously set the cached values for the given keys and TTLs.""" + await asyncio.to_thread(self.set, mapping) + + def clear(self, namespaces: Sequence[Namespace] | None = None) -> None: + """Delete the cached values for the given namespaces. + If no namespaces are provided, clear all cached values.""" + with self._lock, self._conn: + if namespaces is None: + self._conn.execute("DELETE FROM cache") + else: + placeholders = ",".join("?" for _ in namespaces) + self._conn.execute( + f"DELETE FROM cache WHERE (ns) IN ({placeholders})", + tuple(",".join(key) for key in namespaces), + ) + + async def aclear(self, namespaces: Sequence[Namespace] | None = None) -> None: + """Asynchronously delete the cached values for the given namespaces. + If no namespaces are provided, clear all cached values.""" + await asyncio.to_thread(self.clear, namespaces) + + def __del__(self) -> None: + try: + self._conn.close() + except Exception: + pass diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/cache/sqlite/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/cache/sqlite/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..926536026d8ab065ee767cc704570d1e2c8fae2c Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/cache/sqlite/__pycache__/__init__.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/channels/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/channels/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..70a5aabbe4d79a7f84d6f8b3a18a55afb6076db8 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/channels/__pycache__/__init__.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/channels/__pycache__/any_value.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/channels/__pycache__/any_value.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0376d2427fbcea604c5b900901716a822975b8ee Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/channels/__pycache__/any_value.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/channels/__pycache__/base.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/channels/__pycache__/base.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8e6ee83d6e1ae8f6b11afd96b38addac289eb5fe Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/channels/__pycache__/base.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/channels/__pycache__/binop.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/channels/__pycache__/binop.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..910e301da2889c93871b1b486e20973fe1f013e9 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/channels/__pycache__/binop.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/channels/__pycache__/delta.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/channels/__pycache__/delta.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f88f2ebb06ddd58f4a11aa9cbc0a6cf432807746 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/channels/__pycache__/delta.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/channels/__pycache__/ephemeral_value.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/channels/__pycache__/ephemeral_value.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b97a6c1af61b4270b5e518bce63e494c5aec9dc5 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/channels/__pycache__/ephemeral_value.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/channels/__pycache__/last_value.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/channels/__pycache__/last_value.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3ebeb30e2dd6d1f1446963043763f0432b34a30e Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/channels/__pycache__/last_value.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/channels/__pycache__/named_barrier_value.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/channels/__pycache__/named_barrier_value.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f0117d5ce398a829c6263393e20e6ea2b9df4d62 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/channels/__pycache__/named_barrier_value.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/channels/__pycache__/topic.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/channels/__pycache__/topic.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..185e5a3384d29e27a35dd956541ed62f58d2e9c3 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/channels/__pycache__/topic.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/channels/__pycache__/untracked_value.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/channels/__pycache__/untracked_value.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..190cf156bf8825f50f8f2eaf8a34a321e960c365 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/channels/__pycache__/untracked_value.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/checkpoint/base/__init__.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/checkpoint/base/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..6e42061190d539c20c4358771824837e8598da6c --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/checkpoint/base/__init__.py @@ -0,0 +1,860 @@ +from __future__ import annotations + +import copy +import logging +from collections.abc import AsyncIterator, Collection, Iterator, Mapping, Sequence +from typing import ( + Any, + Generic, + Literal, + NamedTuple, + TypedDict, + TypeVar, +) + +from langchain_core.runnables import RunnableConfig +from typing_extensions import NotRequired + +from langgraph.checkpoint.base.id import uuid6 +from langgraph.checkpoint.serde.base import SerializerProtocol, maybe_add_typed_methods +from langgraph.checkpoint.serde.encrypted import EncryptedSerializer +from langgraph.checkpoint.serde.jsonplus import JsonPlusSerializer +from langgraph.checkpoint.serde.types import ( + ERROR, + INTERRUPT, + RESUME, + SCHEDULED, + ChannelProtocol, +) + +V = TypeVar("V", int, float, str) +PendingWrite = tuple[str, str, Any] + + +logger = logging.getLogger(__name__) + + +# Marked as total=False to allow for future expansion. +class CheckpointMetadata(TypedDict, total=False): + """Metadata associated with a checkpoint.""" + + source: Literal["input", "loop", "update", "fork"] + """The source of the checkpoint. + + - `"input"`: The checkpoint was created from an input to invoke/stream/batch. + - `"loop"`: The checkpoint was created from inside the pregel loop. + - `"update"`: The checkpoint was created from a manual state update. + - `"fork"`: The checkpoint was created as a copy of another checkpoint. + """ + step: int + """The step number of the checkpoint. + + `-1` for the first `"input"` checkpoint. + `0` for the first `"loop"` checkpoint. + `...` for the `nth` checkpoint afterwards. + """ + parents: dict[str, str] + """The IDs of the parent checkpoints. + + Mapping from checkpoint namespace to checkpoint ID. + """ + run_id: str + """The ID of the run that created this checkpoint.""" + counters_since_delta_snapshot: dict[str, tuple[int, int]] + """Per-channel counters since the last `_DeltaSnapshot` was written. + + !!! warning "Beta" + + This metadata field backs `DeltaChannel` (beta). The key name and + contents may change while the delta-channel design stabilizes. + + Maps channel name -> `(updates, supersteps)`: + + - index 0 (`updates`): number of supersteps that wrote to this channel + since its last snapshot blob. + - index 1 (`supersteps`): total supersteps elapsed since this channel's + last snapshot, regardless of whether the channel was written. + + A snapshot fires when EITHER `updates >= ch.snapshot_frequency` OR + `supersteps >= DELTA_MAX_SUPERSTEPS_SINCE_SNAPSHOT` (system-wide bound, + default 5000, env `LANGGRAPH_DELTA_MAX_SUPERSTEPS_SINCE_SNAPSHOT`). + The supersteps bound prevents unbounded ancestor walks on threads where + a delta channel exists but is no longer being updated. + + Absent on threads that don't use delta channels. Persisted as a + 2-element list in JSON (no native tuple). + """ + + +ChannelVersions = dict[str, str | int | float] + + +class Checkpoint(TypedDict): + """State snapshot at a given point in time.""" + + v: int + """The version of the checkpoint format. Currently `1`.""" + id: str + """The ID of the checkpoint. + + This is both unique and monotonically increasing, so can be used for sorting + checkpoints from first to last.""" + ts: str + """The timestamp of the checkpoint in ISO 8601 format.""" + channel_values: dict[str, Any] + """The values of the channels at the time of the checkpoint. + + Mapping from channel name to deserialized channel snapshot value. + """ + channel_versions: ChannelVersions + """The versions of the channels at the time of the checkpoint. + + The keys are channel names and the values are monotonically increasing + version strings for each channel. + """ + versions_seen: dict[str, ChannelVersions] + """Map from node ID to map from channel name to version seen. + + This keeps track of the versions of the channels that each node has seen. + Used to determine which nodes to execute next. + """ + updated_channels: list[str] | None + """The channels that were updated in this checkpoint. + """ + + +def copy_checkpoint(checkpoint: Checkpoint) -> Checkpoint: + return Checkpoint( + v=checkpoint["v"], + ts=checkpoint["ts"], + id=checkpoint["id"], + channel_values=checkpoint["channel_values"].copy(), + channel_versions=checkpoint["channel_versions"].copy(), + versions_seen={k: v.copy() for k, v in checkpoint["versions_seen"].items()}, + pending_sends=checkpoint.get("pending_sends", []).copy(), + updated_channels=checkpoint.get("updated_channels", None), + ) + + +class CheckpointTuple(NamedTuple): + """A tuple containing a checkpoint and its associated data.""" + + config: RunnableConfig + checkpoint: Checkpoint + metadata: CheckpointMetadata + parent_config: RunnableConfig | None = None + pending_writes: list[PendingWrite] | None = None + + +class DeltaChannelHistory(TypedDict): + """Per-channel result entry from `BaseCheckpointSaver.get_delta_channel_history`. + + !!! warning "Beta" + + Part of the `DeltaChannel` support surface; in beta. Field names and + semantics may change. + + Storage-level view of what one channel contributed across the ancestor + chain of a target checkpoint: + + * `writes` — on-path deltas oldest→newest as `PendingWrite` tuples. + Always present; possibly empty. Already filtered to one channel. + Writes stored at the target checkpoint itself are pending for the + next super-step and are excluded. + * `seed` — the stored value at the nearest ancestor whose + `channel_values[ch]` is populated. Omitted if the walk reached the + root without finding any stored value (consumer treats absence as + "start empty"). Typically a `_DeltaSnapshot` for delta channels with + finite snapshot frequency, or a plain value for threads migrated + from a pre-delta channel type. + """ + + writes: list[PendingWrite] + seed: NotRequired[Any] + + +class BaseCheckpointSaver(Generic[V]): + """Base class for creating a graph checkpointer. + + Checkpointers allow LangGraph agents to persist their state + within and across multiple interactions. + + When a checkpointer is configured, you should pass a `thread_id` in the config when + invoking the graph: + + ```python + config = {"configurable": {"thread_id": "my-thread"}} + graph.invoke(inputs, config) + ``` + + The `thread_id` is the primary key used to store and retrieve checkpoints. Without + it, the checkpointer cannot save state, resume from interrupts, or enable + time-travel debugging. + + How you choose ``thread_id`` depends on your use case: + + - **Single-shot workflows**: Use a unique ID (e.g., uuid4) for each run when + executions are independent. + - **Conversational memory**: Reuse the same `thread_id` across invocations + to accumulate state (e.g., chat history) within a conversation. + + Attributes: + serde (SerializerProtocol): Serializer for encoding/decoding checkpoints. + + Note: + When creating a custom checkpoint saver, consider implementing async + versions to avoid blocking the main thread. + """ + + serde: SerializerProtocol = JsonPlusSerializer() + + def __init__( + self, + *, + serde: SerializerProtocol | None = None, + ) -> None: + self.serde = maybe_add_typed_methods(serde or self.serde) + + @property + def config_specs(self) -> list: + """Define the configuration options for the checkpoint saver. + + Returns: + list: List of configuration field specs. + """ + return [] + + def get(self, config: RunnableConfig) -> Checkpoint | None: + """Fetch a checkpoint using the given configuration. + + Args: + config: Configuration specifying which checkpoint to retrieve. + + Returns: + The requested checkpoint, or `None` if not found. + """ + if value := self.get_tuple(config): + return value.checkpoint + + def get_tuple(self, config: RunnableConfig) -> CheckpointTuple | None: + """Fetch a checkpoint tuple using the given configuration. + + Args: + config: Configuration specifying which checkpoint to retrieve. + + Returns: + The requested checkpoint tuple, or `None` if not found. + + Raises: + NotImplementedError: Implement this method in your custom checkpoint saver. + """ + raise NotImplementedError + + def list( + self, + config: RunnableConfig | None, + *, + filter: dict[str, Any] | None = None, + before: RunnableConfig | None = None, + limit: int | None = None, + ) -> Iterator[CheckpointTuple]: + """List checkpoints that match the given criteria. + + Args: + config: Base configuration for filtering checkpoints. + filter: Additional filtering criteria. + before: List checkpoints created before this configuration. + limit: Maximum number of checkpoints to return. + + Returns: + Iterator of matching checkpoint tuples. + + Raises: + NotImplementedError: Implement this method in your custom checkpoint saver. + """ + raise NotImplementedError + + def put( + self, + config: RunnableConfig, + checkpoint: Checkpoint, + metadata: CheckpointMetadata, + new_versions: ChannelVersions, + ) -> RunnableConfig: + """Store a checkpoint with its configuration and metadata. + + Args: + config: Configuration for the checkpoint. + checkpoint: The checkpoint to store. + metadata: Additional metadata for the checkpoint. + new_versions: New channel versions as of this write. + + Returns: + RunnableConfig: Updated configuration after storing the checkpoint. + + Raises: + NotImplementedError: Implement this method in your custom checkpoint saver. + """ + raise NotImplementedError + + def put_writes( + self, + config: RunnableConfig, + writes: Sequence[tuple[str, Any]], + task_id: str, + task_path: str = "", + ) -> None: + """Store intermediate writes linked to a checkpoint. + + Args: + config: Configuration of the related checkpoint. + writes: List of writes to store. + task_id: Identifier for the task creating the writes. + task_path: Path of the task creating the writes. + + Raises: + NotImplementedError: Implement this method in your custom checkpoint saver. + """ + raise NotImplementedError + + def delete_thread( + self, + thread_id: str, + ) -> None: + """Delete all checkpoints and writes associated with a specific thread ID. + + Args: + thread_id: The thread ID whose checkpoints should be deleted. + """ + raise NotImplementedError + + def delete_for_runs( + self, + run_ids: Sequence[str], + ) -> None: + """Delete all checkpoints and writes associated with the given run IDs. + + Args: + run_ids: The run IDs whose checkpoints should be deleted. + + !!! warning "DeltaChannel" + + Deleting a run that produced ancestor `checkpoint_writes` — or + the only `_DeltaSnapshot` blob — for a still-live thread will + break reconstruction of any `DeltaChannel` whose history + depended on those rows. See the `DeltaChannel` note on `prune` + for safe-recovery strategies. + """ + raise NotImplementedError + + def copy_thread( + self, + source_thread_id: str, + target_thread_id: str, + ) -> None: + """Copy all checkpoints and writes from one thread to another. + + Args: + source_thread_id: The thread ID to copy from. + target_thread_id: The thread ID to copy to. + + !!! warning "DeltaChannel" + + Implementations must copy the **complete** parent chain (all + ancestor checkpoints and their `checkpoint_writes`) — copying + only the head checkpoint will leave the target thread with + `DeltaChannel` state that cannot be reconstructed (no path back + to a `_DeltaSnapshot` ancestor). Equivalently, the copy must + include enough ancestors that every `DeltaChannel`-backed key + has either a `_DeltaSnapshot` in `channel_values` somewhere in + the chain, or a complete write history back to the chain root. + """ + raise NotImplementedError + + def prune( + self, + thread_ids: Sequence[str], + *, + strategy: str = "keep_latest", + ) -> None: + """Prune checkpoints for the given threads. + + Args: + thread_ids: The thread IDs to prune. + strategy: The pruning strategy. `"keep_latest"` retains only the most + recent checkpoint per namespace. `"delete"` removes all checkpoints. + + !!! warning "DeltaChannel" + + Custom implementations must be `DeltaChannel`-aware. `DeltaChannel` + stores only a sentinel in `channel_values` for non-snapshot steps; + reconstruction walks the parent chain via + `get_delta_channel_history`, accumulating rows from + `checkpoint_writes` until it reaches an ancestor whose + `channel_values` contains a `_DeltaSnapshot` blob (written every + `snapshot_frequency` updates). + + A naive `"keep_latest"` that drops intermediate checkpoints and + their writes can sever that chain: the surviving "latest" + checkpoint is rarely a snapshot point itself, so its delta + channels would silently reconstruct as empty (no error raised — + `get_delta_channel_history` simply returns no `seed`). Safe + options when the graph uses `DeltaChannel`: + + * Walk back from each kept checkpoint and preserve every + ancestor (plus its `checkpoint_writes`) up to the nearest one + whose `channel_values` already contains a `_DeltaSnapshot` for + every `DeltaChannel`-backed key. + * Force a fresh snapshot on the kept checkpoint before deleting + ancestors — rewrite `channel_values[k] = _DeltaSnapshot(value)` + for each delta channel `k` (resolving `value` via the existing + ancestor walk first), then prune. + * Skip pruning threads whose graph uses `DeltaChannel` until one + of the above is implemented. + """ + raise NotImplementedError + + async def aget(self, config: RunnableConfig) -> Checkpoint | None: + """Asynchronously fetch a checkpoint using the given configuration. + + Args: + config: Configuration specifying which checkpoint to retrieve. + + Returns: + The requested checkpoint, or `None` if not found. + """ + if value := await self.aget_tuple(config): + return value.checkpoint + + async def aget_tuple(self, config: RunnableConfig) -> CheckpointTuple | None: + """Asynchronously fetch a checkpoint tuple using the given configuration. + + Args: + config: Configuration specifying which checkpoint to retrieve. + + Returns: + The requested checkpoint tuple, or `None` if not found. + + Raises: + NotImplementedError: Implement this method in your custom checkpoint saver. + """ + raise NotImplementedError + + async def alist( + self, + config: RunnableConfig | None, + *, + filter: dict[str, Any] | None = None, + before: RunnableConfig | None = None, + limit: int | None = None, + ) -> AsyncIterator[CheckpointTuple]: + """Asynchronously list checkpoints that match the given criteria. + + Args: + config: Base configuration for filtering checkpoints. + filter: Additional filtering criteria for metadata. + before: List checkpoints created before this configuration. + limit: Maximum number of checkpoints to return. + + Returns: + Async iterator of matching checkpoint tuples. + + Raises: + NotImplementedError: Implement this method in your custom checkpoint saver. + """ + raise NotImplementedError + yield + + async def aput( + self, + config: RunnableConfig, + checkpoint: Checkpoint, + metadata: CheckpointMetadata, + new_versions: ChannelVersions, + ) -> RunnableConfig: + """Asynchronously store a checkpoint with its configuration and metadata. + + Args: + config: Configuration for the checkpoint. + checkpoint: The checkpoint to store. + metadata: Additional metadata for the checkpoint. + new_versions: New channel versions as of this write. + + Returns: + RunnableConfig: Updated configuration after storing the checkpoint. + + Raises: + NotImplementedError: Implement this method in your custom checkpoint saver. + """ + raise NotImplementedError + + async def aput_writes( + self, + config: RunnableConfig, + writes: Sequence[tuple[str, Any]], + task_id: str, + task_path: str = "", + ) -> None: + """Asynchronously store intermediate writes linked to a checkpoint. + + Args: + config: Configuration of the related checkpoint. + writes: List of writes to store. + task_id: Identifier for the task creating the writes. + task_path: Path of the task creating the writes. + + Raises: + NotImplementedError: Implement this method in your custom checkpoint saver. + """ + raise NotImplementedError + + async def adelete_thread( + self, + thread_id: str, + ) -> None: + """Delete all checkpoints and writes associated with a specific thread ID. + + Args: + thread_id: The thread ID whose checkpoints should be deleted. + """ + raise NotImplementedError + + async def adelete_for_runs( + self, + run_ids: Sequence[str], + ) -> None: + """Asynchronously delete all checkpoints and writes for the given run IDs. + + Args: + run_ids: The run IDs whose checkpoints should be deleted. + + !!! warning "DeltaChannel" + + See `delete_for_runs` — deleting rows a still-live thread's + `DeltaChannel` reconstruction depends on (writes between the + head and its nearest `_DeltaSnapshot` ancestor) will silently + corrupt that channel's state. + """ + raise NotImplementedError + + async def acopy_thread( + self, + source_thread_id: str, + target_thread_id: str, + ) -> None: + """Asynchronously copy all checkpoints and writes from one thread to another. + + Args: + source_thread_id: The thread ID to copy from. + target_thread_id: The thread ID to copy to. + + !!! warning "DeltaChannel" + + See `copy_thread` — the copy must carry the complete parent + chain (or at least back to a `_DeltaSnapshot` ancestor for every + `DeltaChannel`) so the target thread can reconstruct delta + state. + """ + raise NotImplementedError + + async def aprune( + self, + thread_ids: Sequence[str], + *, + strategy: str = "keep_latest", + ) -> None: + """Asynchronously prune checkpoints for the given threads. + + Args: + thread_ids: The thread IDs to prune. + strategy: The pruning strategy. `"keep_latest"` retains only the most + recent checkpoint per namespace. `"delete"` removes all checkpoints. + + !!! warning "DeltaChannel" + + See `prune` for the full `DeltaChannel` caveat. In short: + `"keep_latest"` must not drop ancestor checkpoints / writes that + sit between the kept checkpoint and the nearest `_DeltaSnapshot` + ancestor, or delta channels will silently reconstruct as empty. + """ + raise NotImplementedError + + def get_delta_channel_history( + self, *, config: RunnableConfig, channels: Sequence[str] + ) -> Mapping[str, DeltaChannelHistory]: + """Walk the parent chain returning per-channel writes + seed. + + !!! warning "Beta" + + This method is part of the `DeltaChannel` support surface and is + in beta. The signature, return shape (`DeltaChannelHistory`), and + interaction with `_DeltaSnapshot` blobs may change. Override at + your own risk; the default implementation will continue to work + against the public `BaseCheckpointSaver` contract. + + For each requested channel, walks ancestors of the checkpoint + identified by `config` (following `parent_config`) and accumulates + `pending_writes` for that channel. The walk terminates per-channel + at the nearest ancestor whose `channel_values[ch]` is populated; + that value is returned as `seed`. If the walk reaches the root + without finding a stored value, `seed` is omitted from that + channel's entry — the consumer treats the absence as "start + empty." + + Walks the **parent chain** (not `list(before=...)`): for forked + threads, only on-path ancestors contribute. + + The default implementation walks `get_tuple` + `parent_config` + once for all channels — each ancestor visited once, not once per + channel. Savers with direct storage access (`InMemorySaver`, + `PostgresSaver`) override for performance; the return contract is + fixed here. + + Args: + config: Configuration identifying the target checkpoint. + channels: Channel names to walk for. Empty → empty mapping. + + Returns: + Per-channel `DeltaChannelHistory` for every name in `channels`. + """ + if not channels: + return {} + collected_by_ch: dict[str, list[PendingWrite]] = {c: [] for c in channels} + seed_by_ch: dict[str, Any] = {} + remaining: set[str] = set(channels) + target_tuple = self.get_tuple(config) + cursor_config: RunnableConfig | None = ( + target_tuple.parent_config if target_tuple else None + ) + while cursor_config is not None and remaining: + tup = self.get_tuple(cursor_config) + if tup is None: + break + if tup.pending_writes: + for write in reversed(tup.pending_writes): + ch = write[1] + if ch in remaining: + collected_by_ch[ch].append(write) + for ch in list(remaining): + if ch in tup.checkpoint["channel_values"]: + seed_by_ch[ch] = tup.checkpoint["channel_values"][ch] + remaining.discard(ch) + cursor_config = tup.parent_config + result: dict[str, DeltaChannelHistory] = {} + for ch in channels: + entry: DeltaChannelHistory = {"writes": list(reversed(collected_by_ch[ch]))} + if ch in seed_by_ch: + entry["seed"] = seed_by_ch[ch] + result[ch] = entry + return result + + async def aget_delta_channel_history( + self, *, config: RunnableConfig, channels: Sequence[str] + ) -> Mapping[str, DeltaChannelHistory]: + """Async version of `get_delta_channel_history`. + + !!! warning "Beta" + + This method is part of the `DeltaChannel` support surface and is + in beta. See `get_delta_channel_history` for caveats. + """ + if not channels: + return {} + collected_by_ch: dict[str, list[PendingWrite]] = {c: [] for c in channels} + seed_by_ch: dict[str, Any] = {} + remaining: set[str] = set(channels) + target_tuple = await self.aget_tuple(config) + cursor_config: RunnableConfig | None = ( + target_tuple.parent_config if target_tuple else None + ) + while cursor_config is not None and remaining: + tup = await self.aget_tuple(cursor_config) + if tup is None: + break + if tup.pending_writes: + for write in reversed(tup.pending_writes): + ch = write[1] + if ch in remaining: + collected_by_ch[ch].append(write) + for ch in list(remaining): + if ch in tup.checkpoint["channel_values"]: + seed_by_ch[ch] = tup.checkpoint["channel_values"][ch] + remaining.discard(ch) + cursor_config = tup.parent_config + result: dict[str, DeltaChannelHistory] = {} + for ch in channels: + entry: DeltaChannelHistory = {"writes": list(reversed(collected_by_ch[ch]))} + if ch in seed_by_ch: + entry["seed"] = seed_by_ch[ch] + result[ch] = entry + return result + + def get_next_version(self, current: V | None, channel: None) -> V: + """Generate the next version ID for a channel. + + Default is to use integer versions, incrementing by `1`. + + If you override, you can use `str`/`int`/`float` versions, as long as they are monotonically increasing. + + Args: + current: The current version identifier (`int`, `float`, or `str`). + channel: Deprecated argument, kept for backwards compatibility. + + Returns: + V: The next version identifier, which must be increasing. + """ + if isinstance(current, str): + raise NotImplementedError + elif current is None: + return 1 + else: + return current + 1 + + def with_allowlist( + self, extra_allowlist: Collection[tuple[str, ...]] + ) -> BaseCheckpointSaver[V]: + """Return a shallow clone with a derived msgpack allowlist.""" + serde = _with_msgpack_allowlist(self.serde, extra_allowlist) + if serde is self.serde: + return self + clone = copy.copy(self) + clone.serde = maybe_add_typed_methods(serde) + return clone + + +def _with_msgpack_allowlist( + serde: SerializerProtocol, extra_allowlist: Collection[tuple[str, ...]] +) -> SerializerProtocol: + if isinstance(serde, JsonPlusSerializer): + return serde.with_msgpack_allowlist(extra_allowlist) + if isinstance(serde, EncryptedSerializer): + inner = serde.serde + if isinstance(inner, JsonPlusSerializer): + updated_inner = inner.with_msgpack_allowlist(extra_allowlist) + if updated_inner is inner: + return serde + return EncryptedSerializer(serde.cipher, updated_inner) + logger.warning( + "Serializer %s does not support msgpack allowlist. " + "Strict msgpack deserialization will not be enforced.", + type(serde).__name__, + ) + return serde + + +class EmptyChannelError(Exception): + """Raised when attempting to get the value of a channel that hasn't been updated + for the first time yet.""" + + pass + + +def get_checkpoint_id(config: RunnableConfig) -> str | None: + """Get checkpoint ID.""" + return config["configurable"].get("checkpoint_id") + + +def get_checkpoint_metadata( + config: RunnableConfig, metadata: CheckpointMetadata +) -> CheckpointMetadata: + """Get checkpoint metadata in a backwards-compatible manner.""" + metadata = { + k: v.replace("\u0000", "") if isinstance(v, str) else v + for k, v in metadata.items() + } + for obj in (config.get("metadata"), config.get("configurable")): + if not obj: + continue + for key, v in obj.items(): + if key in metadata or key in EXCLUDED_METADATA_KEYS or key.startswith("__"): + continue + elif isinstance(v, str): + metadata[key] = v.replace("\u0000", "") + elif isinstance(v, (int, bool, float)): + metadata[key] = v + return metadata + + +def get_serializable_checkpoint_metadata( + config: RunnableConfig, metadata: CheckpointMetadata +) -> CheckpointMetadata: + """Get checkpoint metadata in a backwards-compatible manner.""" + checkpoint_metadata = get_checkpoint_metadata(config, metadata) + if "writes" in checkpoint_metadata: + checkpoint_metadata.pop("writes") + return checkpoint_metadata + + +""" +Mapping from error type to error index. +Regular writes just map to their index in the list of writes being saved. +Special writes (e.g. errors) map to negative indices, to avoid those writes from +conflicting with regular writes. +Each Checkpointer implementation should use this mapping in put_writes. +""" +WRITES_IDX_MAP = {ERROR: -1, SCHEDULED: -2, INTERRUPT: -3, RESUME: -4} + +EXCLUDED_METADATA_KEYS = { + "thread_id", + "checkpoint_id", + "checkpoint_ns", + "checkpoint_map", + "langgraph_step", + "langgraph_node", + "langgraph_triggers", + "langgraph_path", + "langgraph_checkpoint_ns", +} + +# --- below are deprecated utilities used by past versions of LangGraph --- + +LATEST_VERSION = 2 + + +def empty_checkpoint() -> Checkpoint: + from datetime import datetime, timezone + + return Checkpoint( + v=LATEST_VERSION, + id=str(uuid6(clock_seq=-2)), + ts=datetime.now(timezone.utc).isoformat(), + channel_values={}, + channel_versions={}, + versions_seen={}, + pending_sends=[], + updated_channels=None, + ) + + +def create_checkpoint( + checkpoint: Checkpoint, + channels: Mapping[str, ChannelProtocol] | None, + step: int, + *, + id: str | None = None, +) -> Checkpoint: + """Create a checkpoint for the given channels.""" + from datetime import datetime, timezone + + ts = datetime.now(timezone.utc).isoformat() + if channels is None: + values = checkpoint["channel_values"] + else: + values = {} + for k, v in channels.items(): + if k not in checkpoint["channel_versions"]: + continue + try: + values[k] = v.checkpoint() + except EmptyChannelError: + pass + return Checkpoint( + v=LATEST_VERSION, + ts=ts, + id=id or str(uuid6(clock_seq=step)), + channel_values=values, + channel_versions=checkpoint["channel_versions"], + versions_seen=checkpoint["versions_seen"], + pending_sends=checkpoint.get("pending_sends", []), + updated_channels=None, + ) diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/checkpoint/base/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/checkpoint/base/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5b070c13e408f0a223533a489bbe5d77a639ff41 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/checkpoint/base/__pycache__/__init__.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/checkpoint/base/__pycache__/id.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/checkpoint/base/__pycache__/id.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b5a1d89dbc983505c3c864473c127a014663748c Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/checkpoint/base/__pycache__/id.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/checkpoint/base/id.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/checkpoint/base/id.py new file mode 100644 index 0000000000000000000000000000000000000000..30abc48a509601216fe7ddee3be55ceaa6cd93bd --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/checkpoint/base/id.py @@ -0,0 +1,109 @@ +"""Adapted from +https://github.com/oittaa/uuid6-python/blob/main/src/uuid6/__init__.py#L95 +Bundled in to avoid install issues with uuid6 package +""" + +from __future__ import annotations + +import random +import time +import uuid + +_last_v6_timestamp = None + + +class UUID(uuid.UUID): + r"""UUID draft version objects""" + + __slots__ = () + + def __init__( + self, + hex: str | None = None, + bytes: bytes | None = None, + bytes_le: bytes | None = None, + fields: tuple[int, int, int, int, int, int] | None = None, + int: int | None = None, + version: int | None = None, + *, + is_safe: uuid.SafeUUID = uuid.SafeUUID.unknown, + ) -> None: + r"""Create a UUID.""" + + if int is None or [hex, bytes, bytes_le, fields].count(None) != 4: + return super().__init__( + hex=hex, + bytes=bytes, + bytes_le=bytes_le, + fields=fields, + int=int, + version=version, + is_safe=is_safe, + ) + if not 0 <= int < 1 << 128: + raise ValueError("int is out of range (need a 128-bit value)") + if version is not None: + if not 6 <= version <= 8: + raise ValueError("illegal version number") + # Set the variant to RFC 4122. + int &= ~(0xC000 << 48) + int |= 0x8000 << 48 + # Set the version number. + int &= ~(0xF000 << 64) + int |= version << 76 + super().__init__(int=int, is_safe=is_safe) + + @property + def subsec(self) -> int: + return ((self.int >> 64) & 0x0FFF) << 8 | ((self.int >> 54) & 0xFF) + + @property + def time(self) -> int: + if self.version == 6: + return ( + (self.time_low << 28) + | (self.time_mid << 12) + | (self.time_hi_version & 0x0FFF) + ) + if self.version == 7: + return self.int >> 80 + if self.version == 8: + return (self.int >> 80) * 10**6 + _subsec_decode(self.subsec) + return super().time + + +def _subsec_decode(value: int) -> int: + return -(-value * 10**6 // 2**20) + + +def uuid6(node: int | None = None, clock_seq: int | None = None) -> UUID: + r"""UUID version 6 is a field-compatible version of UUIDv1, reordered for + improved DB locality. It is expected that UUIDv6 will primarily be + used in contexts where there are existing v1 UUIDs. Systems that do + not involve legacy UUIDv1 SHOULD consider using UUIDv7 instead. + + If 'node' is not given, a random 48-bit number is chosen. + + If 'clock_seq' is given, it is used as the sequence number; + otherwise a random 14-bit sequence number is chosen.""" + + global _last_v6_timestamp + + nanoseconds = time.time_ns() + # 0x01b21dd213814000 is the number of 100-ns intervals between the + # UUID epoch 1582-10-15 00:00:00 and the Unix epoch 1970-01-01 00:00:00. + timestamp = nanoseconds // 100 + 0x01B21DD213814000 + if _last_v6_timestamp is not None and timestamp <= _last_v6_timestamp: + timestamp = _last_v6_timestamp + 1 + _last_v6_timestamp = timestamp + if clock_seq is None: + clock_seq = random.getrandbits(14) # instead of stable storage + if node is None: + node = random.getrandbits(48) + time_high_and_time_mid = (timestamp >> 12) & 0xFFFFFFFFFFFF + time_low_and_version = timestamp & 0x0FFF + uuid_int = time_high_and_time_mid << 80 + uuid_int |= time_low_and_version << 64 + uuid_int |= (clock_seq & 0x3FFF) << 48 + uuid_int |= node & 0xFFFFFFFFFFFF + return UUID(int=uuid_int, version=6) diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/checkpoint/base/py.typed b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/checkpoint/base/py.typed new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/checkpoint/memory/__init__.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/checkpoint/memory/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..80043c71060dea0cd56de974e6505049ce0cd2ad --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/checkpoint/memory/__init__.py @@ -0,0 +1,704 @@ +from __future__ import annotations + +import logging +import os +import pickle +import random +import shutil +from collections import defaultdict +from collections.abc import AsyncIterator, Iterator, Mapping, Sequence +from contextlib import AbstractAsyncContextManager, AbstractContextManager, ExitStack +from types import TracebackType +from typing import Any + +from langchain_core.runnables import RunnableConfig + +from langgraph.checkpoint.base import ( + WRITES_IDX_MAP, + BaseCheckpointSaver, + ChannelVersions, + Checkpoint, + CheckpointMetadata, + CheckpointTuple, + DeltaChannelHistory, + PendingWrite, + SerializerProtocol, + get_checkpoint_id, + get_checkpoint_metadata, +) + +logger = logging.getLogger(__name__) + + +class InMemorySaver( + BaseCheckpointSaver[str], AbstractContextManager, AbstractAsyncContextManager +): + """An in-memory checkpoint saver. + + This checkpoint saver stores checkpoints in memory using a `defaultdict`. + + Note: + Only use `InMemorySaver` for debugging or testing purposes. + For production use cases we recommend installing [langgraph-checkpoint-postgres](https://pypi.org/project/langgraph-checkpoint-postgres/) and using `PostgresSaver` / `AsyncPostgresSaver`. + + If you are using LangSmith Deployment, no checkpointer needs to be specified. The correct managed checkpointer will be used automatically. + + Args: + serde: The serializer to use for serializing and deserializing checkpoints. + + Example: + ```python + import asyncio + + from langgraph.checkpoint.memory import InMemorySaver + from langgraph.graph import StateGraph + + builder = StateGraph(int) + builder.add_node("add_one", lambda x: x + 1) + builder.set_entry_point("add_one") + builder.set_finish_point("add_one") + + memory = InMemorySaver() + graph = builder.compile(checkpointer=memory) + coro = graph.ainvoke(1, {"configurable": {"thread_id": "thread-1"}}) + asyncio.run(coro) # Output: 2 + ``` + """ + + # thread ID -> checkpoint NS -> checkpoint ID -> checkpoint mapping + storage: defaultdict[ + str, + dict[str, dict[str, tuple[tuple[str, bytes], tuple[str, bytes], str | None]]], + ] + # (thread ID, checkpoint NS, checkpoint ID) -> (task ID, write idx) + writes: defaultdict[ + tuple[str, str, str], + dict[tuple[str, int], tuple[str, str, tuple[str, bytes], str]], + ] + blobs: dict[ + tuple[ + str, str, str, str | int | float + ], # thread id, checkpoint ns, channel, version + tuple[str, bytes], + ] + + def __init__( + self, + *, + serde: SerializerProtocol | None = None, + factory: type[defaultdict] = defaultdict, + ) -> None: + super().__init__(serde=serde) + self.storage = factory(lambda: defaultdict(dict)) + self.writes = factory(dict) + self.blobs = factory() + self.stack = ExitStack() + if factory is not defaultdict: + self.stack.enter_context(self.storage) # type: ignore[arg-type] + self.stack.enter_context(self.writes) # type: ignore[arg-type] + self.stack.enter_context(self.blobs) # type: ignore[arg-type] + + def __enter__(self) -> InMemorySaver: + self.stack.__enter__() + return self + + def __exit__( + self, + exc_type: type[BaseException] | None, + exc_value: BaseException | None, + traceback: TracebackType | None, + ) -> bool | None: + return self.stack.__exit__(exc_type, exc_value, traceback) + + async def __aenter__(self) -> InMemorySaver: + self.stack.__enter__() + return self + + async def __aexit__( + self, + __exc_type: type[BaseException] | None, + __exc_value: BaseException | None, + __traceback: TracebackType | None, + ) -> bool | None: + return self.stack.__exit__(__exc_type, __exc_value, __traceback) + + def _load_blobs( + self, + thread_id: str, + checkpoint_ns: str, + versions: ChannelVersions, + ) -> dict[str, Any]: + result: dict[str, Any] = {} + for k, ver in versions.items(): + kk = (thread_id, checkpoint_ns, k, ver) + if kk not in self.blobs: + continue + vv = self.blobs[kk] + if vv[0] == "empty": + continue + result[k] = self.serde.loads_typed(vv) + return result + + def get_delta_channel_history( + self, *, config: RunnableConfig, channels: Sequence[str] + ) -> Mapping[str, DeltaChannelHistory]: + """Override: walk the parent chain ONCE for all requested channels. + + Each channel terminates independently at the nearest ancestor + whose stored blob is non-empty. Other channels keep walking until + they find their own terminator or hit the root. + + Pre-delta plain-value blobs subsume their ancestor's pending + writes (the value already includes them); `_DeltaSnapshot` blobs + do not (snapshot is the value AT that ancestor, prior to its own + pending writes that produce the child). + """ + if not channels: + return {} + # Imported lazily to avoid a hard checkpoint→serde-types coupling at + # module import; only this override needs the runtime check. + from langgraph.checkpoint.serde.types import _DeltaSnapshot + + thread_id = config["configurable"]["thread_id"] + checkpoint_ns = config["configurable"].get("checkpoint_ns", "") + checkpoint_id = config["configurable"].get("checkpoint_id", "") + ns_storage = self.storage.get(thread_id, {}).get(checkpoint_ns, {}) + + chain: list[str] = [] + target_entry = ns_storage.get(checkpoint_id) + current: str | None = target_entry[2] if target_entry is not None else None + while current is not None: + entry = ns_storage.get(current) + if entry is None: + break + chain.append(current) + _, _, parent = entry + current = parent + + collected_by_ch: dict[str, list[PendingWrite]] = {c: [] for c in channels} + seed_by_ch: dict[str, Any] = {} + remaining: set[str] = set(channels) + + for cp_id in chain: + if not remaining: + break + entry = ns_storage.get(cp_id) + ckpt = self.serde.loads_typed(entry[0]) if entry is not None else None + + terminated_here: set[str] = set() + blob_value_by_ch: dict[str, Any] = {} + if ckpt is not None: + versions = ckpt.get("channel_versions", {}) + for ch in remaining: + ver = versions.get(ch) + if ver is None: + continue + blob_entry = self.blobs.get((thread_id, checkpoint_ns, ch, ver)) + if blob_entry is None or blob_entry[0] == "empty": + continue + blob_value_by_ch[ch] = self.serde.loads_typed(blob_entry) + terminated_here.add(ch) + + step_writes = self.writes.get((thread_id, checkpoint_ns, cp_id), {}) + for (_task_id, _idx), (tid, ch, serialized, _) in sorted( + step_writes.items(), reverse=True + ): + if ch not in remaining: + continue + blob_value = blob_value_by_ch.get(ch) + if blob_value is not None and not isinstance( + blob_value, _DeltaSnapshot + ): + continue + collected_by_ch[ch].append( + (tid, ch, self.serde.loads_typed(serialized)) + ) + + for ch in terminated_here: + seed_by_ch[ch] = blob_value_by_ch[ch] + remaining.discard(ch) + + result: dict[str, DeltaChannelHistory] = {} + for ch in channels: + entry_h: DeltaChannelHistory = { + "writes": list(reversed(collected_by_ch[ch])) + } + if ch in seed_by_ch: + entry_h["seed"] = seed_by_ch[ch] + result[ch] = entry_h + return result + + async def aget_delta_channel_history( + self, *, config: RunnableConfig, channels: Sequence[str] + ) -> Mapping[str, DeltaChannelHistory]: + return self.get_delta_channel_history(config=config, channels=channels) + + def get_tuple(self, config: RunnableConfig) -> CheckpointTuple | None: + """Get a checkpoint tuple from the in-memory storage. + + This method retrieves a checkpoint tuple from the in-memory storage based on the + provided config. If the config contains a `checkpoint_id` key, the checkpoint with + the matching thread ID and timestamp is retrieved. Otherwise, the latest checkpoint + for the given thread ID is retrieved. + + Args: + config: The config to use for retrieving the checkpoint. + + Returns: + The retrieved checkpoint tuple, or None if no matching checkpoint was found. + """ + thread_id: str = config["configurable"]["thread_id"] + checkpoint_ns: str = config["configurable"].get("checkpoint_ns", "") + if checkpoint_id := get_checkpoint_id(config): + if saved := self.storage[thread_id][checkpoint_ns].get(checkpoint_id): + checkpoint, metadata, parent_checkpoint_id = saved + writes = self.writes[(thread_id, checkpoint_ns, checkpoint_id)].values() + checkpoint_: Checkpoint = self.serde.loads_typed(checkpoint) + return CheckpointTuple( + config=config, + checkpoint={ + **checkpoint_, + "channel_values": self._load_blobs( + thread_id, checkpoint_ns, checkpoint_["channel_versions"] + ), + }, + metadata=self.serde.loads_typed(metadata), + pending_writes=[ + (id, c, self.serde.loads_typed(v)) for id, c, v, _ in writes + ], + parent_config=( + { + "configurable": { + "thread_id": thread_id, + "checkpoint_ns": checkpoint_ns, + "checkpoint_id": parent_checkpoint_id, + } + } + if parent_checkpoint_id + else None + ), + ) + else: + if checkpoints := self.storage[thread_id][checkpoint_ns]: + checkpoint_id = max(checkpoints.keys()) + checkpoint, metadata, parent_checkpoint_id = checkpoints[checkpoint_id] + writes = self.writes[(thread_id, checkpoint_ns, checkpoint_id)].values() + checkpoint_ = self.serde.loads_typed(checkpoint) + return CheckpointTuple( + config={ + "configurable": { + "thread_id": thread_id, + "checkpoint_ns": checkpoint_ns, + "checkpoint_id": checkpoint_id, + } + }, + checkpoint={ + **checkpoint_, + "channel_values": self._load_blobs( + thread_id, checkpoint_ns, checkpoint_["channel_versions"] + ), + }, + metadata=self.serde.loads_typed(metadata), + pending_writes=[ + (id, c, self.serde.loads_typed(v)) for id, c, v, _ in writes + ], + parent_config=( + { + "configurable": { + "thread_id": thread_id, + "checkpoint_ns": checkpoint_ns, + "checkpoint_id": parent_checkpoint_id, + } + } + if parent_checkpoint_id + else None + ), + ) + + def list( + self, + config: RunnableConfig | None, + *, + filter: dict[str, Any] | None = None, + before: RunnableConfig | None = None, + limit: int | None = None, + ) -> Iterator[CheckpointTuple]: + """List checkpoints from the in-memory storage. + + This method retrieves a list of checkpoint tuples from the in-memory storage based + on the provided criteria. + + Args: + config: Base configuration for filtering checkpoints. + filter: Additional filtering criteria for metadata. + before: List checkpoints created before this configuration. + limit: Maximum number of checkpoints to return. + + Yields: + An iterator of matching checkpoint tuples. + """ + thread_ids = (config["configurable"]["thread_id"],) if config else self.storage + config_checkpoint_ns = ( + config["configurable"].get("checkpoint_ns") if config else None + ) + config_checkpoint_id = get_checkpoint_id(config) if config else None + for thread_id in thread_ids: + for checkpoint_ns in self.storage[thread_id].keys(): + if ( + config_checkpoint_ns is not None + and checkpoint_ns != config_checkpoint_ns + ): + continue + + for checkpoint_id, ( + checkpoint, + metadata_b, + parent_checkpoint_id, + ) in sorted( + self.storage[thread_id][checkpoint_ns].items(), + key=lambda x: x[0], + reverse=True, + ): + # filter by checkpoint ID from config + if config_checkpoint_id and checkpoint_id != config_checkpoint_id: + continue + + # filter by checkpoint ID from `before` config + if ( + before + and (before_checkpoint_id := get_checkpoint_id(before)) + and checkpoint_id >= before_checkpoint_id + ): + continue + + # filter by metadata + metadata = self.serde.loads_typed(metadata_b) + if filter and not all( + query_value == metadata.get(query_key) + for query_key, query_value in filter.items() + ): + continue + + # limit search results + if limit is not None and limit <= 0: + break + elif limit is not None: + limit -= 1 + + writes = self.writes[ + (thread_id, checkpoint_ns, checkpoint_id) + ].values() + + checkpoint_: Checkpoint = self.serde.loads_typed(checkpoint) + + yield CheckpointTuple( + config={ + "configurable": { + "thread_id": thread_id, + "checkpoint_ns": checkpoint_ns, + "checkpoint_id": checkpoint_id, + } + }, + checkpoint={ + **checkpoint_, + "channel_values": self._load_blobs( + thread_id, + checkpoint_ns, + checkpoint_["channel_versions"], + ), + }, + metadata=metadata, + parent_config=( + { + "configurable": { + "thread_id": thread_id, + "checkpoint_ns": checkpoint_ns, + "checkpoint_id": parent_checkpoint_id, + } + } + if parent_checkpoint_id + else None + ), + pending_writes=[ + (id, c, self.serde.loads_typed(v)) for id, c, v, _ in writes + ], + ) + + def put( + self, + config: RunnableConfig, + checkpoint: Checkpoint, + metadata: CheckpointMetadata, + new_versions: ChannelVersions, + ) -> RunnableConfig: + """Save a checkpoint to the in-memory storage. + + This method saves a checkpoint to the in-memory storage. The checkpoint is associated + with the provided config. + + Args: + config: The config to associate with the checkpoint. + checkpoint: The checkpoint to save. + metadata: Additional metadata to save with the checkpoint. + new_versions: New versions as of this write + + Returns: + RunnableConfig: The updated config containing the saved checkpoint's timestamp. + """ + c = checkpoint.copy() + thread_id = config["configurable"]["thread_id"] + checkpoint_ns = config["configurable"]["checkpoint_ns"] + values: dict[str, Any] = c.pop("channel_values") # type: ignore[misc] + for k, v in new_versions.items(): + self.blobs[(thread_id, checkpoint_ns, k, v)] = ( + self.serde.dumps_typed(values[k]) if k in values else ("empty", b"") + ) + self.storage[thread_id][checkpoint_ns].update( + { + checkpoint["id"]: ( + self.serde.dumps_typed(c), + self.serde.dumps_typed(get_checkpoint_metadata(config, metadata)), + config["configurable"].get("checkpoint_id"), # parent + ) + } + ) + return { + "configurable": { + "thread_id": thread_id, + "checkpoint_ns": checkpoint_ns, + "checkpoint_id": checkpoint["id"], + } + } + + def put_writes( + self, + config: RunnableConfig, + writes: Sequence[tuple[str, Any]], + task_id: str, + task_path: str = "", + ) -> None: + """Save a list of writes to the in-memory storage. + + This method saves a list of writes to the in-memory storage. The writes are associated + with the provided config. + + Args: + config: The config to associate with the writes. + writes: The writes to save. + task_id: Identifier for the task creating the writes. + task_path: Path of the task creating the writes. + + Returns: + RunnableConfig: The updated config containing the saved writes' timestamp. + """ + thread_id = config["configurable"]["thread_id"] + checkpoint_ns = config["configurable"].get("checkpoint_ns", "") + checkpoint_id = config["configurable"]["checkpoint_id"] + outer_key = (thread_id, checkpoint_ns, checkpoint_id) + outer_writes_ = self.writes.get(outer_key) + for idx, (c, v) in enumerate(writes): + inner_key = (task_id, WRITES_IDX_MAP.get(c, idx)) + if inner_key[1] >= 0 and outer_writes_ and inner_key in outer_writes_: + continue + + self.writes[outer_key][inner_key] = ( + task_id, + c, + self.serde.dumps_typed(v), + task_path, + ) + + def delete_thread(self, thread_id: str) -> None: + """Delete all checkpoints and writes associated with a thread ID. + + Args: + thread_id: The thread ID to delete. + + Returns: + None + """ + if thread_id in self.storage: + del self.storage[thread_id] + for k in list(self.writes.keys()): + if k[0] == thread_id: + del self.writes[k] + for k in list(self.blobs.keys()): + if k[0] == thread_id: + del self.blobs[k] + + async def aget_tuple(self, config: RunnableConfig) -> CheckpointTuple | None: + """Asynchronous version of `get_tuple`. + + This method is an asynchronous wrapper around `get_tuple` that runs the synchronous + method in a separate thread using asyncio. + + Args: + config: The config to use for retrieving the checkpoint. + + Returns: + The retrieved checkpoint tuple, or None if no matching checkpoint was found. + """ + return self.get_tuple(config) + + async def alist( + self, + config: RunnableConfig | None, + *, + filter: dict[str, Any] | None = None, + before: RunnableConfig | None = None, + limit: int | None = None, + ) -> AsyncIterator[CheckpointTuple]: + """Asynchronous version of `list`. + + This method is an asynchronous wrapper around `list` that runs the synchronous + method in a separate thread using asyncio. + + Args: + config: The config to use for listing the checkpoints. + + Yields: + An asynchronous iterator of checkpoint tuples. + """ + for item in self.list(config, filter=filter, before=before, limit=limit): + yield item + + async def aput( + self, + config: RunnableConfig, + checkpoint: Checkpoint, + metadata: CheckpointMetadata, + new_versions: ChannelVersions, + ) -> RunnableConfig: + """Asynchronous version of `put`. + + Args: + config: The config to associate with the checkpoint. + checkpoint: The checkpoint to save. + metadata: Additional metadata to save with the checkpoint. + new_versions: New versions as of this write + + Returns: + RunnableConfig: The updated config containing the saved checkpoint's timestamp. + """ + return self.put(config, checkpoint, metadata, new_versions) + + async def aput_writes( + self, + config: RunnableConfig, + writes: Sequence[tuple[str, Any]], + task_id: str, + task_path: str = "", + ) -> None: + """Asynchronous version of `put_writes`. + + This method is an asynchronous wrapper around `put_writes` that runs the synchronous + method in a separate thread using asyncio. + + Args: + config: The config to associate with the writes. + writes: The writes to save, each as a (channel, value) pair. + task_id: Identifier for the task creating the writes. + task_path: Path of the task creating the writes. + + Returns: + None + """ + return self.put_writes(config, writes, task_id, task_path) + + async def adelete_thread(self, thread_id: str) -> None: + """Delete all checkpoints and writes associated with a thread ID. + + Args: + thread_id: The thread ID to delete. + + Returns: + None + """ + return self.delete_thread(thread_id) + + def get_next_version(self, current: str | None, channel: None) -> str: + if current is None: + current_v = 0 + elif isinstance(current, int): + current_v = current + else: + current_v = int(current.split(".")[0]) + next_v = current_v + 1 + next_h = random.random() + return f"{next_v:032}.{next_h:016}" + + +MemorySaver = InMemorySaver # Kept for backwards compatibility + + +class PersistentDict(defaultdict): + """Persistent dictionary with an API compatible with shelve and anydbm. + + The dict is kept in memory, so the dictionary operations run as fast as + a regular dictionary. + + Write to disk is delayed until close or sync (similar to gdbm's fast mode). + + Input file format is automatically discovered. + Output file format is selectable between pickle, json, and csv. + All three serialization formats are backed by fast C implementations. + + Adapted from https://code.activestate.com/recipes/576642-persistent-dict-with-multiple-standard-file-format/ + + """ + + def __init__(self, *args: Any, filename: str, **kwds: Any) -> None: + self.flag = "c" # r=readonly, c=create, or n=new + self.mode = None # None or an octal triple like 0644 + self.format = "pickle" # 'csv', 'json', or 'pickle' + self.filename = filename + super().__init__(*args, **kwds) + + def sync(self) -> None: + "Write dict to disk" + if self.flag == "r": + return + tempname = self.filename + ".tmp" + fileobj = open(tempname, "wb" if self.format == "pickle" else "w") + try: + self.dump(fileobj) + except Exception: + os.remove(tempname) + raise + finally: + fileobj.close() + shutil.move(tempname, self.filename) # atomic commit + if self.mode is not None: + os.chmod(self.filename, self.mode) + + def close(self) -> None: + self.sync() + self.clear() + + def __enter__(self) -> PersistentDict: + return self + + def __exit__(self, *exc_info: Any) -> None: + self.close() + + def dump(self, fileobj: Any) -> None: + if self.format == "pickle": + pickle.dump(dict(self), fileobj, 2) + else: + raise NotImplementedError("Unknown format: " + repr(self.format)) + + def load(self) -> None: + # try formats from most restrictive to least restrictive + if self.flag == "n": + return + with open(self.filename, "rb" if self.format == "pickle" else "r") as fileobj: + for loader in (pickle.load,): + fileobj.seek(0) + try: + return self.update(loader(fileobj)) + except EOFError: + return + except Exception: + logger.error(f"Failed to load file: {fileobj.name}") + raise + raise ValueError("File not in a supported format") diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/checkpoint/memory/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/checkpoint/memory/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f4ec31e9f20a46f37f95f4a0d201a7bc262d2945 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/checkpoint/memory/__pycache__/__init__.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/checkpoint/memory/py.typed b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/checkpoint/memory/py.typed new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/checkpoint/serde/__init__.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/checkpoint/serde/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/checkpoint/serde/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/checkpoint/serde/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c139e99a3fbababcc2106b3bbed4a2c6f703e12c Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/checkpoint/serde/__pycache__/__init__.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/checkpoint/serde/__pycache__/_msgpack.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/checkpoint/serde/__pycache__/_msgpack.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..167088ae177a4e02377467500a0947e79ac2373a Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/checkpoint/serde/__pycache__/_msgpack.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/checkpoint/serde/__pycache__/base.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/checkpoint/serde/__pycache__/base.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2e91a17196343178df1c77204f494889688d57a7 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/checkpoint/serde/__pycache__/base.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/checkpoint/serde/__pycache__/encrypted.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/checkpoint/serde/__pycache__/encrypted.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f17104eddbd628e1d3c71acc3075d73c141d6c26 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/checkpoint/serde/__pycache__/encrypted.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/checkpoint/serde/__pycache__/event_hooks.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/checkpoint/serde/__pycache__/event_hooks.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d6af7277b125b19852b068c3a1b3303301b2a127 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/checkpoint/serde/__pycache__/event_hooks.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/checkpoint/serde/__pycache__/jsonplus.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/checkpoint/serde/__pycache__/jsonplus.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bbd01fc3139eb74255e14e58515289364e654fa0 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/checkpoint/serde/__pycache__/jsonplus.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/checkpoint/serde/__pycache__/types.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/checkpoint/serde/__pycache__/types.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b506891bc592b206eb6b12cb92ff4209174b9628 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/checkpoint/serde/__pycache__/types.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/checkpoint/serde/_msgpack.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/checkpoint/serde/_msgpack.py new file mode 100644 index 0000000000000000000000000000000000000000..1a5188f1fd9da8e80b8d090454883885ca3aa466 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/checkpoint/serde/_msgpack.py @@ -0,0 +1,97 @@ +"""Msgpack deserialization safety controls. + +Set ``LANGGRAPH_STRICT_MSGPACK=true`` to restrict checkpoint deserialization +to the types listed in ``SAFE_MSGPACK_TYPES``. Without this, any Python +callable stored in checkpoint data will be imported and executed on load. +""" + +import os +from collections.abc import Iterable +from typing import cast + +STRICT_MSGPACK_ENABLED = os.getenv("LANGGRAPH_STRICT_MSGPACK", "false").lower() in ( + "1", + "true", + "yes", +) + + +_SENTINEL = cast(None, object()) + +SAFE_MSGPACK_TYPES: frozenset[tuple[str, ...]] = frozenset( + { + # datetime types + ("datetime", "datetime"), + ("datetime", "date"), + ("datetime", "time"), + ("datetime", "timedelta"), + ("datetime", "timezone"), + # uuid + ("uuid", "UUID"), + # numeric + ("decimal", "Decimal"), + # collections + ("builtins", "set"), + ("builtins", "frozenset"), + ("collections", "deque"), + # ip addresses + ("ipaddress", "IPv4Address"), + ("ipaddress", "IPv4Interface"), + ("ipaddress", "IPv4Network"), + ("ipaddress", "IPv6Address"), + ("ipaddress", "IPv6Interface"), + ("ipaddress", "IPv6Network"), + # pathlib + ("pathlib", "Path"), + ("pathlib", "PosixPath"), + ("pathlib", "WindowsPath"), + # pathlib in Python 3.13+ + ("pathlib._local", "Path"), + ("pathlib._local", "PosixPath"), + ("pathlib._local", "WindowsPath"), + # zoneinfo + ("zoneinfo", "ZoneInfo"), + # regex + ("re", "compile"), + # langchain-core messages (safe container types used by graph state) + ("langchain_core.messages.base", "BaseMessage"), + ("langchain_core.messages.base", "BaseMessageChunk"), + ("langchain_core.messages.human", "HumanMessage"), + ("langchain_core.messages.human", "HumanMessageChunk"), + ("langchain_core.messages.ai", "AIMessage"), + ("langchain_core.messages.ai", "AIMessageChunk"), + ("langchain_core.messages.system", "SystemMessage"), + ("langchain_core.messages.system", "SystemMessageChunk"), + ("langchain_core.messages.chat", "ChatMessage"), + ("langchain_core.messages.chat", "ChatMessageChunk"), + ("langchain_core.messages.tool", "ToolMessage"), + ("langchain_core.messages.tool", "ToolMessageChunk"), + ("langchain_core.messages.function", "FunctionMessage"), + ("langchain_core.messages.function", "FunctionMessageChunk"), + ("langchain_core.messages.modifier", "RemoveMessage"), + # langchain-core document model + ("langchain_core.documents.base", "Document"), + # langgraph + ("langgraph.types", "Send"), + ("langgraph.types", "TimeoutPolicy"), + ("langgraph.types", "Interrupt"), + ("langgraph.types", "Command"), + ("langgraph.types", "StateSnapshot"), + ("langgraph.types", "PregelTask"), + ("langgraph.types", "Overwrite"), + ("langgraph.store.base", "Item"), + ("langgraph.store.base", "GetOp"), + } +) + +# Allowed (module, name, method) triples for EXT_METHOD_SINGLE_ARG. +# Only these specific method invocations are permitted during deserialization. +# This is separate from SAFE_MSGPACK_TYPES which only governs construction. +SAFE_MSGPACK_METHODS: frozenset[tuple[str, str, str]] = frozenset( + { + ("datetime", "datetime", "fromisoformat"), + } +) + + +AllowedMsgpackModules = Iterable[tuple[str, ...] | type] diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/checkpoint/serde/base.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/checkpoint/serde/base.py new file mode 100644 index 0000000000000000000000000000000000000000..186e162fa76eb9cbabca88419673996a07453b28 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/checkpoint/serde/base.py @@ -0,0 +1,64 @@ +from __future__ import annotations + +from typing import Any, Protocol, runtime_checkable + + +class UntypedSerializerProtocol(Protocol): + """Protocol for serialization and deserialization of objects.""" + + def dumps(self, obj: Any) -> bytes: ... + + def loads(self, data: bytes) -> Any: ... + + +@runtime_checkable +class SerializerProtocol(Protocol): + """Protocol for serialization and deserialization of objects. + + - `dumps_typed`: Serialize an object to a tuple `(type, bytes)`. + - `loads_typed`: Deserialize an object from a tuple `(type, bytes)`. + + Valid implementations include the `pickle`, `json` and `orjson` modules. + """ + + def dumps_typed(self, obj: Any) -> tuple[str, bytes]: ... + + def loads_typed(self, data: tuple[str, bytes]) -> Any: ... + + +class SerializerCompat(SerializerProtocol): + def __init__(self, serde: UntypedSerializerProtocol) -> None: + self.serde = serde + + def dumps_typed(self, obj: Any) -> tuple[str, bytes]: + return type(obj).__name__, self.serde.dumps(obj) + + def loads_typed(self, data: tuple[str, bytes]) -> Any: + return self.serde.loads(data[1]) + + +def maybe_add_typed_methods( + serde: SerializerProtocol | UntypedSerializerProtocol, +) -> SerializerProtocol: + """Wrap serde old serde implementations in a class with loads_typed and dumps_typed for backwards compatibility.""" + + if not isinstance(serde, SerializerProtocol): + return SerializerCompat(serde) + + return serde + + +class CipherProtocol(Protocol): + """Protocol for encryption and decryption of data. + + - `encrypt`: Encrypt plaintext. + - `decrypt`: Decrypt ciphertext. + """ + + def encrypt(self, plaintext: bytes) -> tuple[str, bytes]: + """Encrypt plaintext. Returns a tuple `(cipher name, ciphertext)`.""" + ... + + def decrypt(self, ciphername: str, ciphertext: bytes) -> bytes: + """Decrypt ciphertext. Returns the plaintext.""" + ... diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/checkpoint/serde/encrypted.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/checkpoint/serde/encrypted.py new file mode 100644 index 0000000000000000000000000000000000000000..9f517e40551974671830a32151b1ee4f830082aa --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/checkpoint/serde/encrypted.py @@ -0,0 +1,80 @@ +import os +from typing import Any + +from langgraph.checkpoint.serde.base import CipherProtocol, SerializerProtocol +from langgraph.checkpoint.serde.jsonplus import JsonPlusSerializer + + +class EncryptedSerializer(SerializerProtocol): + """Serializer that encrypts and decrypts data using an encryption protocol.""" + + def __init__( + self, cipher: CipherProtocol, serde: SerializerProtocol = JsonPlusSerializer() + ) -> None: + self.cipher = cipher + self.serde = serde + + def dumps_typed(self, obj: Any) -> tuple[str, bytes]: + """Serialize an object to a tuple `(type, bytes)` and encrypt the bytes.""" + # serialize data + typ, data = self.serde.dumps_typed(obj) + # encrypt data + ciphername, ciphertext = self.cipher.encrypt(data) + # add cipher name to type + return f"{typ}+{ciphername}", ciphertext + + def loads_typed(self, data: tuple[str, bytes]) -> Any: + enc_cipher, ciphertext = data + # unencrypted data + if "+" not in enc_cipher: + return self.serde.loads_typed(data) + # extract cipher name + typ, ciphername = enc_cipher.split("+", 1) + # decrypt data + decrypted_data = self.cipher.decrypt(ciphername, ciphertext) + # deserialize data + return self.serde.loads_typed((typ, decrypted_data)) + + @classmethod + def from_pycryptodome_aes( + cls, serde: SerializerProtocol = JsonPlusSerializer(), **kwargs: Any + ) -> "EncryptedSerializer": + """Create an `EncryptedSerializer` using AES encryption.""" + try: + from Crypto.Cipher import AES + except ImportError: + raise ImportError( + "Pycryptodome is not installed. Please install it with `pip install pycryptodome`." + ) from None + + # check if AES key is provided + if "key" in kwargs: + key: bytes = kwargs.pop("key") + else: + key_str = os.getenv("LANGGRAPH_AES_KEY") + if key_str is None: + raise ValueError("LANGGRAPH_AES_KEY environment variable is not set.") + key = key_str.encode() + if len(key) not in (16, 24, 32): + raise ValueError("LANGGRAPH_AES_KEY must be 16, 24, or 32 bytes long.") + + # set default mode to EAX if not provided + if kwargs.get("mode") is None: + kwargs["mode"] = AES.MODE_EAX + + class PycryptodomeAesCipher(CipherProtocol): + def encrypt(self, plaintext: bytes) -> tuple[str, bytes]: + cipher = AES.new(key, **kwargs) + ciphertext, tag = cipher.encrypt_and_digest(plaintext) + return "aes", cipher.nonce + tag + ciphertext + + def decrypt(self, ciphername: str, ciphertext: bytes) -> bytes: + assert ciphername == "aes", f"Unsupported cipher: {ciphername}" + nonce = ciphertext[:16] + tag = ciphertext[16:32] + actual_ciphertext = ciphertext[32:] + + cipher = AES.new(key, **kwargs, nonce=nonce) + return cipher.decrypt_and_verify(actual_ciphertext, tag) + + return cls(PycryptodomeAesCipher(), serde) diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/checkpoint/serde/event_hooks.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/checkpoint/serde/event_hooks.py new file mode 100644 index 0000000000000000000000000000000000000000..9ea0a5b496265f1c2fa4b1b08fd704395078a1ff --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/checkpoint/serde/event_hooks.py @@ -0,0 +1,52 @@ +from __future__ import annotations + +import logging +from collections.abc import Callable +from threading import Lock +from typing import TypedDict + +from typing_extensions import NotRequired + +logger = logging.getLogger(__name__) + + +class SerdeEvent(TypedDict): + kind: str + module: str + name: str + method: NotRequired[str] + + +SerdeEventListener = Callable[[SerdeEvent], None] + +_listeners: list[SerdeEventListener] = [] +_listeners_lock = Lock() + + +def register_serde_event_listener(listener: SerdeEventListener) -> Callable[[], None]: + """Register a listener for serde allowlist events.""" + with _listeners_lock: + _listeners.append(listener) + + def unregister() -> None: + with _listeners_lock: + try: + _listeners.remove(listener) + except ValueError: + pass + + return unregister + + +def emit_serde_event(event: SerdeEvent) -> None: + """Emit a serde event to all listeners. + + Listener failures are isolated and logged. + """ + with _listeners_lock: + listeners = tuple(_listeners) + for listener in listeners: + try: + listener(event) + except Exception: + logger.warning("Serde listener failed", exc_info=True) diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/checkpoint/serde/jsonplus.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/checkpoint/serde/jsonplus.py new file mode 100644 index 0000000000000000000000000000000000000000..abd03f1ca8448dcc80793c5f8cd41539f85fbd32 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/checkpoint/serde/jsonplus.py @@ -0,0 +1,883 @@ +from __future__ import annotations + +import copy +import dataclasses +import decimal +import importlib +import json +import logging +import pathlib +import pickle +import re +import sys +from collections import deque +from collections.abc import Callable, Iterable, Sequence +from datetime import date, datetime, time, timedelta, timezone +from enum import Enum +from inspect import isclass +from ipaddress import ( + IPv4Address, + IPv4Interface, + IPv4Network, + IPv6Address, + IPv6Interface, + IPv6Network, +) +from typing import TYPE_CHECKING, Any, Literal, cast +from uuid import UUID +from zoneinfo import ZoneInfo + +import ormsgpack +from langchain_core.load.load import Reviver + +from langgraph.checkpoint.serde import _msgpack as _lg_msgpack +from langgraph.checkpoint.serde.base import SerializerProtocol +from langgraph.checkpoint.serde.event_hooks import emit_serde_event +from langgraph.checkpoint.serde.types import ( + SendProtocol, + _DeltaSnapshot, +) +from langgraph.store.base import Item + +if TYPE_CHECKING: + from langgraph.checkpoint.serde._msgpack import ( + AllowedMsgpackModules, + ) + +LC_REVIVER = Reviver(allowed_objects="core") +EMPTY_BYTES = b"" +logger = logging.getLogger(__name__) + +# Dedup log warnings across process lifetime; cap bounds state if types are +# dynamically generated (also acts as a circuit breaker on warning volume). +# Dedup is best-effort: racing threads may each emit once for the same key, +# and warnings are silently dropped once _MAX_WARNED_TYPES is reached. +_MAX_WARNED_TYPES = 1000 +_warned_unregistered_types: set[tuple[str, str]] = set() +_warned_blocked_types: set[tuple[str, str]] = set() + + +def _is_safe_json_type(id_list: list[str]) -> bool: + """Return True if an lc=2 id refers to a type in SAFE_MSGPACK_TYPES. + + Safe types bypass the ``allowed_json_modules`` gate so that old "json" format + checkpoints (written before the msgpack migration) can be resumed without + requiring users to configure an explicit allowlist. + """ + if len(id_list) < 2: + return False + module_name = ".".join(id_list[:-1]) + return (module_name, id_list[-1]) in _lg_msgpack.SAFE_MSGPACK_TYPES + + +def _warn_once( + seen: set[tuple[str, str]], key: tuple[str, str], msg: str, *args: object +) -> None: + if key in seen or len(seen) >= _MAX_WARNED_TYPES: + return + seen.add(key) + logger.warning(msg, *args) + + +class JsonPlusSerializer(SerializerProtocol): + """Serializer that uses ormsgpack, with optional fallbacks. + + !!! warning + + Security note: This serializer is intended for use within the `BaseCheckpointSaver` + class and called within the Pregel loop. It should not be used on untrusted + python objects. If an attacker can write directly to your checkpoint database, + they may be able to trigger code execution when data is deserialized. + + Set the environment variable ``LANGGRAPH_STRICT_MSGPACK=true`` to restrict + deserialization to a built-in allowlist of safe types. You can also pass + an explicit ``allowed_msgpack_modules`` to the constructor. + """ + + def __init__( + self, + *, + pickle_fallback: bool = False, + allowed_json_modules: Iterable[tuple[str, ...]] | Literal[True] | None = None, + allowed_msgpack_modules: ( + AllowedMsgpackModules | Literal[True] | None + ) = _lg_msgpack._SENTINEL, + __unpack_ext_hook__: Callable[[int, bytes], Any] | None = None, + ) -> None: + if allowed_msgpack_modules is _lg_msgpack._SENTINEL: + if _lg_msgpack.STRICT_MSGPACK_ENABLED: + # Strict: only SAFE_MSGPACK_TYPES are allowed. + allowed_msgpack_modules = None + else: + # Permissive (default): all types allowed with a warning. + # Set LANGGRAPH_STRICT_MSGPACK=true to lock this down. + allowed_msgpack_modules = True + self.pickle_fallback = pickle_fallback + self._allowed_json_modules: set[tuple[str, ...]] | Literal[True] | None = ( + _normalize_allowlist(allowed_json_modules) + ) + self._allowed_msgpack_modules = _normalize_allowlist(allowed_msgpack_modules) + + self._custom_unpack_ext_hook = __unpack_ext_hook__ is not None + self._unpack_ext_hook = ( + __unpack_ext_hook__ + if __unpack_ext_hook__ is not None + else _create_msgpack_ext_hook(self._allowed_msgpack_modules) + ) + + def with_msgpack_allowlist( + self, extra_allowlist: Iterable[tuple[str, ...] | type] + ) -> JsonPlusSerializer: + """Return a new serializer with a merged msgpack allowlist.""" + base_allowlist = self._allowed_msgpack_modules + if base_allowlist is True or base_allowlist is False: + return self + elif base_allowlist: + base_allowlist = set(base_allowlist) + else: + base_allowlist = set() + extra = _normalize_module_keys(tuple(extra_allowlist)) + merged = base_allowlist | extra + if merged == base_allowlist: + return self + allowed_msgpack_modules: AllowedMsgpackModules | Literal[True] | None + if merged: + allowed_msgpack_modules = tuple(merged) + elif isinstance(self._allowed_msgpack_modules, set): + allowed_msgpack_modules = tuple(self._allowed_msgpack_modules) + else: + allowed_msgpack_modules = self._allowed_msgpack_modules + + clone = copy.copy(self) + clone._allowed_json_modules = _normalize_allowlist(self._allowed_json_modules) + clone._allowed_msgpack_modules = _normalize_allowlist(allowed_msgpack_modules) + if not clone._custom_unpack_ext_hook: + clone._unpack_ext_hook = _create_msgpack_ext_hook( + clone._allowed_msgpack_modules + ) + return clone + + def _reviver(self, value: dict[str, Any]) -> Any: + if ( + value.get("lc", None) == 2 + and value.get("type", None) == "constructor" + and value.get("id", None) is not None + ): + id_list = value["id"] + is_safe = _is_safe_json_type(id_list) + if self._allowed_json_modules or is_safe: + try: + return self._revive_lc2(value) + except InvalidModuleError as e: + if not is_safe: + logger.warning( + "Object %s is not in the deserialization allowlist.\n%s", + value["id"], + e.message, + ) + + return LC_REVIVER(value) + + def _revive_lc2(self, value: dict[str, Any]) -> Any: + self._check_allowed_json_modules(value) + + [*module, name] = value["id"] + # The `method` field on lc:2 envelopes is intentionally ignored. + # Revival is restricted to the default constructor (no `getattr` + # dispatch on attacker-influenced names). The framework's own + # encoder has not emitted `method=` since the msgpack migration, + # and the only legacy emission was `method=(None, "construct")` + # for pydantic models, where the first entry (`None`) already + # meant "default constructor", which is what we do here. + try: + mod = importlib.import_module(".".join(module)) + cls = getattr(mod, name) + if isclass(cls) and issubclass(cls, BaseException): + return None + args = value.get("args") + kwargs = value.get("kwargs") + if args and kwargs: + return cls(*args, **kwargs) + elif args: + return cls(*args) + elif kwargs: + return cls(**kwargs) + else: + return cls() + except Exception as exc: + # Method-field dispatch has been removed (GHSA-fjqc-hq36-qh5p), so + # legacy pydantic payloads emitting `method=[None, "construct"]` + # no longer fall back to `cls.construct(**kwargs)` when the + # default constructor rejects the serialized kwargs. Surface a + # one-line warning so operators can spot payloads that now revive + # to `None` instead of silently degrading to the raw envelope. + logger.warning( + "Failed to revive lc:2 envelope %s " + "(legacy_method_field=%s, error=%s); returning None", + ".".join((*module, name)), + "method" in value, + type(exc).__name__, + ) + return None + + def _check_allowed_json_modules(self, value: dict[str, Any]) -> None: + needed = tuple(value["id"]) + dotted = ".".join(needed) + # Safe types (the same set already allowed for msgpack deserialization) are + # permitted without an explicit allowlist — they are known-safe LangGraph and + # LangChain types. This restores backwards-compat for old "json" checkpoints + # that pre-date the msgpack migration without reopening the broader security gate. + if _is_safe_json_type(list(needed)): + return + + if not self._allowed_json_modules: + raise InvalidModuleError( + f"Refused to deserialize JSON constructor: {dotted}. " + "No allowed_json_modules configured.\n\n" + "Unblock with ONE of:\n" + f" • JsonPlusSerializer(allowed_json_modules=[{needed!r}, ...])\n" + " • (DANGEROUS) JsonPlusSerializer(allowed_json_modules=True)\n\n" + "Note: Prefix allowlists are intentionally unsupported; prefer exact symbols " + "or plain-JSON representations revived without import-time side effects." + ) + + if self._allowed_json_modules is True: + return + if needed in self._allowed_json_modules: + return + + raise InvalidModuleError( + f"Refused to deserialize JSON constructor: {dotted}. " + "Symbol is not in the deserialization allowlist.\n\n" + "Add exactly this symbol to unblock:\n" + f" JsonPlusSerializer(allowed_json_modules=[{needed!r}, ...])\n" + "Or, as a last resort (DANGEROUS):\n" + " JsonPlusSerializer(allowed_json_modules=True)" + ) + + def dumps_typed(self, obj: Any) -> tuple[str, bytes]: + if obj is None: + return "null", EMPTY_BYTES + elif isinstance(obj, bytes): + return "bytes", obj + elif isinstance(obj, bytearray): + return "bytearray", obj + else: + try: + return "msgpack", _msgpack_enc(obj) + except ormsgpack.MsgpackEncodeError as exc: + if self.pickle_fallback: + return "pickle", pickle.dumps(obj) + raise exc + + def loads_typed(self, data: tuple[str, bytes]) -> Any: + type_, data_ = data + if type_ == "null": + return None + elif type_ == "bytes": + return data_ + elif type_ == "bytearray": + return bytearray(data_) + elif type_ == "json": + return json.loads(data_, object_hook=self._reviver) + elif type_ == "msgpack": + return ormsgpack.unpackb( + data_, ext_hook=self._unpack_ext_hook, option=ormsgpack.OPT_NON_STR_KEYS + ) + elif self.pickle_fallback and type_ == "pickle": + return pickle.loads(data_) + else: + raise NotImplementedError(f"Unknown serialization type: {type_}") + + +# --- msgpack --- + +EXT_CONSTRUCTOR_SINGLE_ARG = 0 +EXT_CONSTRUCTOR_POS_ARGS = 1 +EXT_CONSTRUCTOR_KW_ARGS = 2 +EXT_METHOD_SINGLE_ARG = 3 +EXT_PYDANTIC_V1 = 4 +EXT_PYDANTIC_V2 = 5 +EXT_NUMPY_ARRAY = 6 +EXT_DELTA_SNAPSHOT = 7 + + +def _msgpack_default(obj: Any) -> str | ormsgpack.Ext: + if isinstance(obj, _DeltaSnapshot): + return ormsgpack.Ext(EXT_DELTA_SNAPSHOT, _msgpack_enc(obj.value)) + elif hasattr(obj, "model_dump") and callable(obj.model_dump): # pydantic v2 + return ormsgpack.Ext( + EXT_PYDANTIC_V2, + _msgpack_enc( + ( + obj.__class__.__module__, + obj.__class__.__name__, + obj.model_dump(), + "model_validate_json", + ), + ), + ) + elif hasattr(obj, "get_secret_value") and callable(obj.get_secret_value): + return ormsgpack.Ext( + EXT_CONSTRUCTOR_SINGLE_ARG, + _msgpack_enc( + ( + obj.__class__.__module__, + obj.__class__.__name__, + obj.get_secret_value(), + ), + ), + ) + elif hasattr(obj, "dict") and callable(obj.dict): # pydantic v1 + return ormsgpack.Ext( + EXT_PYDANTIC_V1, + _msgpack_enc( + ( + obj.__class__.__module__, + obj.__class__.__name__, + obj.dict(), + ), + ), + ) + elif hasattr(obj, "_asdict") and callable(obj._asdict): # namedtuple + return ormsgpack.Ext( + EXT_CONSTRUCTOR_KW_ARGS, + _msgpack_enc( + ( + obj.__class__.__module__, + obj.__class__.__name__, + obj._asdict(), + ), + ), + ) + elif isinstance(obj, pathlib.Path): + return ormsgpack.Ext( + EXT_CONSTRUCTOR_POS_ARGS, + _msgpack_enc( + (obj.__class__.__module__, obj.__class__.__name__, obj.parts), + ), + ) + elif isinstance(obj, re.Pattern): + return ormsgpack.Ext( + EXT_CONSTRUCTOR_POS_ARGS, + _msgpack_enc( + ("re", "compile", (obj.pattern, obj.flags)), + ), + ) + elif isinstance(obj, UUID): + return ormsgpack.Ext( + EXT_CONSTRUCTOR_SINGLE_ARG, + _msgpack_enc( + (obj.__class__.__module__, obj.__class__.__name__, obj.hex), + ), + ) + elif isinstance(obj, decimal.Decimal): + return ormsgpack.Ext( + EXT_CONSTRUCTOR_SINGLE_ARG, + _msgpack_enc( + (obj.__class__.__module__, obj.__class__.__name__, str(obj)), + ), + ) + elif isinstance(obj, (set, frozenset, deque)): + return ormsgpack.Ext( + EXT_CONSTRUCTOR_SINGLE_ARG, + _msgpack_enc( + (obj.__class__.__module__, obj.__class__.__name__, tuple(obj)), + ), + ) + elif isinstance(obj, (IPv4Address, IPv4Interface, IPv4Network)): + return ormsgpack.Ext( + EXT_CONSTRUCTOR_SINGLE_ARG, + _msgpack_enc( + (obj.__class__.__module__, obj.__class__.__name__, str(obj)), + ), + ) + elif isinstance(obj, (IPv6Address, IPv6Interface, IPv6Network)): + return ormsgpack.Ext( + EXT_CONSTRUCTOR_SINGLE_ARG, + _msgpack_enc( + (obj.__class__.__module__, obj.__class__.__name__, str(obj)), + ), + ) + elif isinstance(obj, datetime): + return ormsgpack.Ext( + EXT_METHOD_SINGLE_ARG, + _msgpack_enc( + ( + obj.__class__.__module__, + obj.__class__.__name__, + obj.isoformat(), + "fromisoformat", + ), + ), + ) + elif isinstance(obj, timedelta): + return ormsgpack.Ext( + EXT_CONSTRUCTOR_POS_ARGS, + _msgpack_enc( + ( + obj.__class__.__module__, + obj.__class__.__name__, + (obj.days, obj.seconds, obj.microseconds), + ), + ), + ) + elif isinstance(obj, date): + return ormsgpack.Ext( + EXT_CONSTRUCTOR_POS_ARGS, + _msgpack_enc( + ( + obj.__class__.__module__, + obj.__class__.__name__, + (obj.year, obj.month, obj.day), + ), + ), + ) + elif isinstance(obj, time): + return ormsgpack.Ext( + EXT_CONSTRUCTOR_KW_ARGS, + _msgpack_enc( + ( + obj.__class__.__module__, + obj.__class__.__name__, + { + "hour": obj.hour, + "minute": obj.minute, + "second": obj.second, + "microsecond": obj.microsecond, + "tzinfo": obj.tzinfo, + "fold": obj.fold, + }, + ), + ), + ) + elif isinstance(obj, timezone): + return ormsgpack.Ext( + EXT_CONSTRUCTOR_POS_ARGS, + _msgpack_enc( + ( + obj.__class__.__module__, + obj.__class__.__name__, + obj.__getinitargs__(), # type: ignore[attr-defined] + ), + ), + ) + elif isinstance(obj, ZoneInfo): + return ormsgpack.Ext( + EXT_CONSTRUCTOR_SINGLE_ARG, + _msgpack_enc( + (obj.__class__.__module__, obj.__class__.__name__, obj.key), + ), + ) + elif isinstance(obj, Enum): + return ormsgpack.Ext( + EXT_CONSTRUCTOR_SINGLE_ARG, + _msgpack_enc( + (obj.__class__.__module__, obj.__class__.__name__, obj.value), + ), + ) + elif isinstance(obj, SendProtocol): + args: tuple[Any, ...] = (obj.node, obj.arg) + if (timeout := getattr(obj, "timeout", None)) is not None: + args = (obj.node, obj.arg, timeout) + return ormsgpack.Ext( + EXT_CONSTRUCTOR_POS_ARGS, + _msgpack_enc( + (obj.__class__.__module__, obj.__class__.__name__, args), + ), + ) + elif dataclasses.is_dataclass(obj): + # doesn't use dataclasses.asdict to avoid deepcopy and recursion + return ormsgpack.Ext( + EXT_CONSTRUCTOR_KW_ARGS, + _msgpack_enc( + ( + obj.__class__.__module__, + obj.__class__.__name__, + { + field.name: getattr(obj, field.name) + for field in dataclasses.fields(obj) + }, + ), + ), + ) + elif isinstance(obj, Item): + return ormsgpack.Ext( + EXT_CONSTRUCTOR_KW_ARGS, + _msgpack_enc( + ( + obj.__class__.__module__, + obj.__class__.__name__, + {k: getattr(obj, k) for k in obj.__slots__}, + ), + ), + ) + elif (np_mod := sys.modules.get("numpy")) is not None and isinstance( + obj, np_mod.ndarray + ): + order = "F" if obj.flags.f_contiguous and not obj.flags.c_contiguous else "C" + if obj.flags.c_contiguous: + mv = memoryview(obj) + try: + meta = (obj.dtype.str, obj.shape, order, mv) + return ormsgpack.Ext(EXT_NUMPY_ARRAY, _msgpack_enc(meta)) + finally: + mv.release() + else: + buf = obj.tobytes(order="A") + meta = (obj.dtype.str, obj.shape, order, buf) + return ormsgpack.Ext(EXT_NUMPY_ARRAY, _msgpack_enc(meta)) + + elif isinstance(obj, BaseException): + return repr(obj) + else: + raise TypeError(f"Object of type {obj.__class__.__name__} is not serializable") + + +def _send_from_args(args: Sequence[Any]) -> Any: + # ya we have a cyclic import here ¯\_(ツ)_/¯ + from langgraph.types import Send # type: ignore + + if len(args) == 2: + return Send(*args) + return Send(args[0], args[1], timeout=args[2]) + + +def _create_msgpack_ext_hook( + allowed_modules: set[tuple[str, ...]] | Literal[True] | None, +) -> Callable[[int, bytes], Any]: + """Create msgpack ext hook with allowlist. + + Args: + allowed_modules: Set of (module, name) tuples that are allowed to be + deserialized, or True to allow all with warnings for unregistered types, or None to only allow safe types. + + Returns: + An ext_hook function for use with ormsgpack.unpackb. + """ + + def _check_allowed(module: str, name: str) -> bool: + """Check if type is allowed. Returns True if allowed, False if blocked.""" + key = (module, name) + + if key in _lg_msgpack.SAFE_MSGPACK_TYPES: + return True + + if allowed_modules is True: + # default is to warn but allow unregistered types + emit_serde_event( + { + "kind": "msgpack_unregistered_allowed", + "module": module, + "name": name, + } + ) + _warn_once( + _warned_unregistered_types, + key, + "Deserializing unregistered type %s.%s from checkpoint. " + "This will be blocked in a future version. " + "Set LANGGRAPH_STRICT_MSGPACK=true to block now, or add " + "to allowed_msgpack_modules to allow explicitly: [(%r, %r)]", + module, + name, + module, + name, + ) + return True + if allowed_modules is not None: + if key in allowed_modules: + return True + # strict mode blocks unregistered types + emit_serde_event( + { + "kind": "msgpack_blocked", + "module": module, + "name": name, + } + ) + _warn_once( + _warned_blocked_types, + key, + "Blocked deserialization of %s.%s - not in allowed_msgpack_modules. " + "Add to allowed_msgpack_modules to allow: [(%r, %r)]", + module, + name, + module, + name, + ) + return False + + def _check_allowed_method(module: str, name: str, method: str) -> bool: + """Check if a method invocation is allowed.""" + key = (module, name, method) + if key in _lg_msgpack.SAFE_MSGPACK_METHODS: + return True + emit_serde_event( + { + "kind": "msgpack_method_blocked", + "module": module, + "name": name, + "method": method, + } + ) + logger.warning( + "Blocked deserialization of method call %s.%s.%s - " + "not in allowed methods set.", + module, + name, + method, + ) + return False + + def ext_hook(code: int, data: bytes) -> Any: + if code == EXT_DELTA_SNAPSHOT: + return _DeltaSnapshot( + ormsgpack.unpackb( + data, ext_hook=ext_hook, option=ormsgpack.OPT_NON_STR_KEYS + ) + ) + elif code == EXT_CONSTRUCTOR_SINGLE_ARG: + try: + tup = ormsgpack.unpackb( + data, ext_hook=ext_hook, option=ormsgpack.OPT_NON_STR_KEYS + ) + if not _check_allowed(tup[0], tup[1]): + # We default to returning the raw data. If the user + # is using this in the context of a pydantic state, etc., then + # it would be validated upon construction. + return tup[2] + # module, name, arg + return getattr(importlib.import_module(tup[0]), tup[1])(tup[2]) + except Exception: + return None + elif code == EXT_CONSTRUCTOR_POS_ARGS: + try: + tup = ormsgpack.unpackb( + data, ext_hook=ext_hook, option=ormsgpack.OPT_NON_STR_KEYS + ) + if not _check_allowed(tup[0], tup[1]): + return tup[2] + if tup[0] == "langgraph.types" and tup[1] == "Send": + return _send_from_args(tup[2]) + # module, name, args + return getattr(importlib.import_module(tup[0]), tup[1])(*tup[2]) + except Exception: + return None + elif code == EXT_CONSTRUCTOR_KW_ARGS: + try: + tup = ormsgpack.unpackb( + data, ext_hook=ext_hook, option=ormsgpack.OPT_NON_STR_KEYS + ) + if not _check_allowed(tup[0], tup[1]): + return tup[2] + # module, name, kwargs + return getattr(importlib.import_module(tup[0]), tup[1])(**tup[2]) + except Exception: + return None + elif code == EXT_METHOD_SINGLE_ARG: + try: + tup = ormsgpack.unpackb( + data, ext_hook=ext_hook, option=ormsgpack.OPT_NON_STR_KEYS + ) + if not _check_allowed_method(tup[0], tup[1], tup[3]): + return tup[2] + # module, name, arg, method + return getattr( + getattr(importlib.import_module(tup[0]), tup[1]), tup[3] + )(tup[2]) + except Exception: + return None + elif code == EXT_PYDANTIC_V1: + try: + tup = ormsgpack.unpackb( + data, ext_hook=ext_hook, option=ormsgpack.OPT_NON_STR_KEYS + ) + if not _check_allowed(tup[0], tup[1]): + return tup[2] + # module, name, kwargs + cls = getattr(importlib.import_module(tup[0]), tup[1]) + try: + return cls(**tup[2]) + except Exception: + return cls.construct(**tup[2]) + except Exception: + # for pydantic objects we can't find/reconstruct + # let's return the kwargs dict instead + try: + return tup[2] + except NameError: + return None + elif code == EXT_PYDANTIC_V2: + try: + tup = ormsgpack.unpackb( + data, ext_hook=ext_hook, option=ormsgpack.OPT_NON_STR_KEYS + ) + if not _check_allowed(tup[0], tup[1]): + return tup[2] + # module, name, kwargs, method + cls = getattr(importlib.import_module(tup[0]), tup[1]) + try: + return cls(**tup[2]) + except Exception: + return cls.model_construct(**tup[2]) + except Exception: + # for pydantic objects we can't find/reconstruct + # let's return the kwargs dict instead + try: + return tup[2] + except NameError: + return None + elif code == EXT_NUMPY_ARRAY: + try: + import numpy as _np + + dtype_str, shape, order, buf = ormsgpack.unpackb( + data, ext_hook=ext_hook, option=ormsgpack.OPT_NON_STR_KEYS + ) + arr = _np.frombuffer(buf, dtype=_np.dtype(dtype_str)) + return arr.reshape(shape, order=order) + except Exception: + return None + return None + + return ext_hook + + +# Aliasing in case anyone imported it directly +_msgpack_ext_hook = _create_msgpack_ext_hook(allowed_modules=None) + + +def _msgpack_ext_hook_to_json(code: int, data: bytes) -> Any: + if code == EXT_CONSTRUCTOR_SINGLE_ARG: + try: + tup = ormsgpack.unpackb( + data, + ext_hook=_msgpack_ext_hook_to_json, + option=ormsgpack.OPT_NON_STR_KEYS, + ) + if tup[0] == "uuid" and tup[1] == "UUID": + hex_ = tup[2] + return ( + f"{hex_[:8]}-{hex_[8:12]}-{hex_[12:16]}-{hex_[16:20]}-{hex_[20:]}" + ) + # module, name, arg + return tup[2] + except Exception: + return + elif code == EXT_CONSTRUCTOR_POS_ARGS: + try: + tup = ormsgpack.unpackb( + data, + ext_hook=_msgpack_ext_hook_to_json, + option=ormsgpack.OPT_NON_STR_KEYS, + ) + if tup[0] == "langgraph.types" and tup[1] == "Send": + return _send_from_args(tup[2]) + # module, name, args + return tup[2] + except Exception: + return + elif code == EXT_CONSTRUCTOR_KW_ARGS: + try: + tup = ormsgpack.unpackb( + data, + ext_hook=_msgpack_ext_hook_to_json, + option=ormsgpack.OPT_NON_STR_KEYS, + ) + # module, name, args + return tup[2] + except Exception: + return + elif code == EXT_METHOD_SINGLE_ARG: + try: + tup = ormsgpack.unpackb( + data, + ext_hook=_msgpack_ext_hook_to_json, + option=ormsgpack.OPT_NON_STR_KEYS, + ) + # module, name, arg, method + return tup[2] + except Exception: + return + elif code == EXT_PYDANTIC_V1: + try: + tup = ormsgpack.unpackb( + data, + ext_hook=_msgpack_ext_hook_to_json, + option=ormsgpack.OPT_NON_STR_KEYS, + ) + # module, name, kwargs + return tup[2] + except Exception: + # for pydantic objects we can't find/reconstruct + # let's return the kwargs dict instead + return + elif code == EXT_PYDANTIC_V2: + try: + tup = ormsgpack.unpackb( + data, + ext_hook=_msgpack_ext_hook_to_json, + option=ormsgpack.OPT_NON_STR_KEYS, + ) + # module, name, kwargs, method + return tup[2] + except Exception: + return + elif code == EXT_NUMPY_ARRAY: + try: + import numpy as _np + + dtype_str, shape, order, buf = ormsgpack.unpackb( + data, + ext_hook=_msgpack_ext_hook_to_json, + option=ormsgpack.OPT_NON_STR_KEYS, + ) + arr = _np.frombuffer(buf, dtype=_np.dtype(dtype_str)) + return arr.reshape(shape, order=order).tolist() + except Exception: + return + + +class InvalidModuleError(Exception): + """Exception raised when a module is not in the allowlist.""" + + def __init__(self, message: str): + self.message = message + + +_option = ( + ormsgpack.OPT_NON_STR_KEYS + | ormsgpack.OPT_PASSTHROUGH_DATACLASS + | ormsgpack.OPT_PASSTHROUGH_DATETIME + | ormsgpack.OPT_PASSTHROUGH_ENUM + | ormsgpack.OPT_PASSTHROUGH_UUID + | ormsgpack.OPT_REPLACE_SURROGATES +) + + +def _msgpack_enc(data: Any) -> bytes: + return ormsgpack.packb(data, default=_msgpack_default, option=_option) + + +def _normalize_allowlist( + allowlist: AllowedMsgpackModules | Literal[True] | None, +) -> set[tuple[str, ...]] | Literal[True] | None: + if allowlist is True: + return allowlist + elif allowlist: + return _normalize_module_keys(allowlist) + else: + return None + + +def _normalize_module_keys( + modules: AllowedMsgpackModules, +) -> set[tuple[str, ...]]: + normalized: set[tuple[str, ...]] = set() + for module in modules: + if isclass(module): + normalized.add((module.__module__, module.__name__)) + else: + normalized.add(cast(tuple[str, ...], module)) + return normalized diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/checkpoint/serde/py.typed b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/checkpoint/serde/py.typed new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/checkpoint/serde/types.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/checkpoint/serde/types.py new file mode 100644 index 0000000000000000000000000000000000000000..72e37206462758bef1adf3abbe2d43e58a034532 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/checkpoint/serde/types.py @@ -0,0 +1,68 @@ +from collections.abc import Sequence +from typing import ( + Any, + NamedTuple, + Protocol, + TypeVar, + runtime_checkable, +) + +from typing_extensions import Self + +ERROR = "__error__" +SCHEDULED = "__scheduled__" +INTERRUPT = "__interrupt__" +RESUME = "__resume__" +TASKS = "__pregel_tasks" + + +class _DeltaSnapshot(NamedTuple): + """Snapshot blob for a DeltaChannel with finite snapshot_frequency. + + Stored in checkpoint_blobs via the `EXT_DELTA_SNAPSHOT` msgpack ext code. + The ancestor walk in `BaseCheckpointSaver.get_delta_channel_history` terminates + when it encounters this type (any non-empty channel_values entry stops + the walk for that channel). + + `from_checkpoint` reconstructs the channel value directly from `.value` + without replaying writes — the snapshot IS the accumulated state. + """ + + value: Any + + +Value = TypeVar("Value", covariant=True) +Update = TypeVar("Update", contravariant=True) +C = TypeVar("C") + + +class ChannelProtocol(Protocol[Value, Update, C]): + # Mirrors langgraph.channels.base.BaseChannel + @property + def ValueType(self) -> Any: ... + + @property + def UpdateType(self) -> Any: ... + + def checkpoint(self) -> C | None: ... + + def from_checkpoint(self, checkpoint: C | None) -> Self: ... + + def update(self, values: Sequence[Update]) -> bool: ... + + def get(self) -> Value: ... + + def consume(self) -> bool: ... + + +@runtime_checkable +class SendProtocol(Protocol): + # Mirrors langgraph.constants.Send + node: str + arg: Any + + def __hash__(self) -> int: ... + + def __repr__(self) -> str: ... + + def __eq__(self, value: object) -> bool: ... diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/checkpoint/sqlite/__init__.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/checkpoint/sqlite/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..6ca2448d08c4e160dbcf329326b93c379baf7197 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/checkpoint/sqlite/__init__.py @@ -0,0 +1,645 @@ +from __future__ import annotations + +import json +import random +import sqlite3 +import threading +from collections.abc import AsyncIterator, Iterator, Mapping, Sequence +from contextlib import closing, contextmanager +from typing import Any, cast + +from langchain_core.runnables import RunnableConfig +from langgraph.checkpoint.base import ( + WRITES_IDX_MAP, + BaseCheckpointSaver, + ChannelVersions, + Checkpoint, + CheckpointMetadata, + CheckpointTuple, + DeltaChannelHistory, + SerializerProtocol, + get_checkpoint_id, + get_checkpoint_metadata, +) +from langgraph.checkpoint.serde.jsonplus import JsonPlusSerializer + +from langgraph.checkpoint.sqlite._delta import ( + DELTA_STAGE1_SQL, + build_delta_channels_writes_history, + build_delta_stage2_sql, + step_walk_with_row, +) +from langgraph.checkpoint.sqlite.utils import search_where + +_AIO_ERROR_MSG = ( + "The SqliteSaver does not support async methods. " + "Consider using AsyncSqliteSaver instead.\n" + "from langgraph.checkpoint.sqlite.aio import AsyncSqliteSaver\n" + "Note: AsyncSqliteSaver requires the aiosqlite package to use.\n" + "Install with:\n`pip install aiosqlite`\n" + "See https://langchain-ai.github.io/langgraph/reference/checkpoints/#langgraph.checkpoint.sqlite.aio.AsyncSqliteSaver" + "for more information." +) + + +class SqliteSaver(BaseCheckpointSaver[str]): + """A checkpoint saver that stores checkpoints in a SQLite database. + + Note: + This class is meant for lightweight, synchronous use cases + (demos and small projects) and does not + scale to multiple threads. + For a similar sqlite saver with `async` support, + consider using [AsyncSqliteSaver][langgraph.checkpoint.sqlite.aio.AsyncSqliteSaver]. + + Args: + conn (sqlite3.Connection): The SQLite database connection. + serde (Optional[SerializerProtocol]): The serializer to use for serializing and deserializing checkpoints. Defaults to JsonPlusSerializerCompat. + + Examples: + + >>> import sqlite3 + >>> from langgraph.checkpoint.sqlite import SqliteSaver + >>> from langgraph.graph import StateGraph + >>> + >>> builder = StateGraph(int) + >>> builder.add_node("add_one", lambda x: x + 1) + >>> builder.set_entry_point("add_one") + >>> builder.set_finish_point("add_one") + >>> # Create a new SqliteSaver instance + >>> # Note: check_same_thread=False is OK as the implementation uses a lock + >>> # to ensure thread safety. + >>> conn = sqlite3.connect("checkpoints.sqlite", check_same_thread=False) + >>> memory = SqliteSaver(conn) + >>> graph = builder.compile(checkpointer=memory) + >>> config = {"configurable": {"thread_id": "1"}} + >>> graph.get_state(config) + >>> result = graph.invoke(3, config) + >>> graph.get_state(config) + StateSnapshot(values=4, next=(), config={'configurable': {'thread_id': '1', 'checkpoint_ns': '', 'checkpoint_id': '0c62ca34-ac19-445d-bbb0-5b4984975b2a'}}, parent_config=None) + """ # noqa + + conn: sqlite3.Connection + is_setup: bool + + def __init__( + self, + conn: sqlite3.Connection, + *, + serde: SerializerProtocol | None = None, + ) -> None: + super().__init__(serde=serde) + self.jsonplus_serde = JsonPlusSerializer() + self.conn = conn + self.is_setup = False + self.lock = threading.Lock() + + @classmethod + @contextmanager + def from_conn_string(cls, conn_string: str) -> Iterator[SqliteSaver]: + """Create a new SqliteSaver instance from a connection string. + + Args: + conn_string: The SQLite connection string. + + Yields: + SqliteSaver: A new SqliteSaver instance. + + Examples: + + In memory: + + with SqliteSaver.from_conn_string(":memory:") as memory: + ... + + To disk: + + with SqliteSaver.from_conn_string("checkpoints.sqlite") as memory: + ... + """ + with closing( + sqlite3.connect( + conn_string, + # https://ricardoanderegg.com/posts/python-sqlite-thread-safety/ + check_same_thread=False, + ) + ) as conn: + yield cls(conn) + + def setup(self) -> None: + """Set up the checkpoint database. + + This method creates the necessary tables in the SQLite database if they don't + already exist. It is called automatically when needed and should not be called + directly by the user. + """ + if self.is_setup: + return + + self.conn.executescript( + """ + PRAGMA journal_mode=WAL; + CREATE TABLE IF NOT EXISTS checkpoints ( + thread_id TEXT NOT NULL, + checkpoint_ns TEXT NOT NULL DEFAULT '', + checkpoint_id TEXT NOT NULL, + parent_checkpoint_id TEXT, + type TEXT, + checkpoint BLOB, + metadata BLOB, + PRIMARY KEY (thread_id, checkpoint_ns, checkpoint_id) + ); + CREATE TABLE IF NOT EXISTS writes ( + thread_id TEXT NOT NULL, + checkpoint_ns TEXT NOT NULL DEFAULT '', + checkpoint_id TEXT NOT NULL, + task_id TEXT NOT NULL, + idx INTEGER NOT NULL, + channel TEXT NOT NULL, + type TEXT, + value BLOB, + PRIMARY KEY (thread_id, checkpoint_ns, checkpoint_id, task_id, idx) + ); + """ + ) + + self.is_setup = True + + @contextmanager + def cursor(self, transaction: bool = True) -> Iterator[sqlite3.Cursor]: + """Get a cursor for the SQLite database. + + This method returns a cursor for the SQLite database. It is used internally + by the SqliteSaver and should not be called directly by the user. + + Args: + transaction (bool): Whether to commit the transaction when the cursor is closed. Defaults to True. + + Yields: + sqlite3.Cursor: A cursor for the SQLite database. + """ + with self.lock: + self.setup() + cur = self.conn.cursor() + try: + yield cur + finally: + if transaction: + self.conn.commit() + cur.close() + + def get_tuple(self, config: RunnableConfig) -> CheckpointTuple | None: + """Get a checkpoint tuple from the database. + + This method retrieves a checkpoint tuple from the SQLite database based on the + provided config. If the config contains a `checkpoint_id` key, the checkpoint with + the matching thread ID and checkpoint ID is retrieved. Otherwise, the latest checkpoint + for the given thread ID is retrieved. + + Args: + config: The config to use for retrieving the checkpoint. + + Returns: + The retrieved checkpoint tuple, or None if no matching checkpoint was found. + + Examples: + + Basic: + >>> config = {"configurable": {"thread_id": "1"}} + >>> checkpoint_tuple = memory.get_tuple(config) + >>> print(checkpoint_tuple) + CheckpointTuple(...) + + With checkpoint ID: + + >>> config = { + ... "configurable": { + ... "thread_id": "1", + ... "checkpoint_ns": "", + ... "checkpoint_id": "1ef4f797-8335-6428-8001-8a1503f9b875", + ... } + ... } + >>> checkpoint_tuple = memory.get_tuple(config) + >>> print(checkpoint_tuple) + CheckpointTuple(...) + """ # noqa + checkpoint_ns = config["configurable"].get("checkpoint_ns", "") + with self.cursor(transaction=False) as cur: + # find the latest checkpoint for the thread_id + if checkpoint_id := get_checkpoint_id(config): + cur.execute( + "SELECT thread_id, checkpoint_id, parent_checkpoint_id, type, checkpoint, metadata FROM checkpoints WHERE thread_id = ? AND checkpoint_ns = ? AND checkpoint_id = ?", + ( + str(config["configurable"]["thread_id"]), + checkpoint_ns, + checkpoint_id, + ), + ) + else: + cur.execute( + "SELECT thread_id, checkpoint_id, parent_checkpoint_id, type, checkpoint, metadata FROM checkpoints WHERE thread_id = ? AND checkpoint_ns = ? ORDER BY checkpoint_id DESC LIMIT 1", + (str(config["configurable"]["thread_id"]), checkpoint_ns), + ) + # if a checkpoint is found, return it + if value := cur.fetchone(): + ( + thread_id, + checkpoint_id, + parent_checkpoint_id, + type, + checkpoint, + metadata, + ) = value + if not get_checkpoint_id(config): + config = { + "configurable": { + "thread_id": thread_id, + "checkpoint_ns": checkpoint_ns, + "checkpoint_id": checkpoint_id, + } + } + # find any pending writes + cur.execute( + "SELECT task_id, channel, type, value FROM writes WHERE thread_id = ? AND checkpoint_ns = ? AND checkpoint_id = ? ORDER BY task_id, idx", + ( + str(config["configurable"]["thread_id"]), + checkpoint_ns, + str(config["configurable"]["checkpoint_id"]), + ), + ) + # deserialize the checkpoint and metadata + return CheckpointTuple( + config, + self.serde.loads_typed((type, checkpoint)), + cast( + CheckpointMetadata, + json.loads(metadata) if metadata is not None else {}, + ), + ( + { + "configurable": { + "thread_id": thread_id, + "checkpoint_ns": checkpoint_ns, + "checkpoint_id": parent_checkpoint_id, + } + } + if parent_checkpoint_id + else None + ), + [ + (task_id, channel, self.serde.loads_typed((type, value))) + for task_id, channel, type, value in cur + ], + ) + + def list( + self, + config: RunnableConfig | None, + *, + filter: dict[str, Any] | None = None, + before: RunnableConfig | None = None, + limit: int | None = None, + ) -> Iterator[CheckpointTuple]: + """List checkpoints from the database. + + This method retrieves a list of checkpoint tuples from the SQLite database based + on the provided config. The checkpoints are ordered by checkpoint ID in descending order (newest first). + + Args: + config: The config to use for listing the checkpoints. + filter: Additional filtering criteria for metadata. + before: If provided, only checkpoints before the specified checkpoint ID are returned. + limit: The maximum number of checkpoints to return. + + Yields: + An iterator of checkpoint tuples. + + Examples: + >>> from langgraph.checkpoint.sqlite import SqliteSaver + >>> with SqliteSaver.from_conn_string(":memory:") as memory: + ... # Run a graph, then list the checkpoints + >>> config = {"configurable": {"thread_id": "1"}} + >>> checkpoints = list(memory.list(config, limit=2)) + >>> print(checkpoints) + [CheckpointTuple(...), CheckpointTuple(...)] + + >>> config = {"configurable": {"thread_id": "1"}} + >>> before = {"configurable": {"checkpoint_id": "1ef4f797-8335-6428-8001-8a1503f9b875"}} + >>> with SqliteSaver.from_conn_string(":memory:") as memory: + ... # Run a graph, then list the checkpoints + >>> checkpoints = list(memory.list(config, before=before)) + >>> print(checkpoints) + [CheckpointTuple(...), ...] + """ + where, param_values = search_where(config, filter, before) + query = f"""SELECT thread_id, checkpoint_ns, checkpoint_id, parent_checkpoint_id, type, checkpoint, metadata + FROM checkpoints + {where} + ORDER BY checkpoint_id DESC""" + if limit is not None: + query += " LIMIT ?" + param_values = (*param_values, limit) + with self.cursor(transaction=False) as cur, closing(self.conn.cursor()) as wcur: + cur.execute(query, param_values) + for ( + thread_id, + checkpoint_ns, + checkpoint_id, + parent_checkpoint_id, + type, + checkpoint, + metadata, + ) in cur: + wcur.execute( + "SELECT task_id, channel, type, value FROM writes WHERE thread_id = ? AND checkpoint_ns = ? AND checkpoint_id = ? ORDER BY task_id, idx", + (thread_id, checkpoint_ns, checkpoint_id), + ) + yield CheckpointTuple( + { + "configurable": { + "thread_id": thread_id, + "checkpoint_ns": checkpoint_ns, + "checkpoint_id": checkpoint_id, + } + }, + self.serde.loads_typed((type, checkpoint)), + cast( + CheckpointMetadata, + json.loads(metadata) if metadata is not None else {}, + ), + ( + { + "configurable": { + "thread_id": thread_id, + "checkpoint_ns": checkpoint_ns, + "checkpoint_id": parent_checkpoint_id, + } + } + if parent_checkpoint_id + else None + ), + [ + (task_id, channel, self.serde.loads_typed((type, value))) + for task_id, channel, type, value in wcur + ], + ) + + def put( + self, + config: RunnableConfig, + checkpoint: Checkpoint, + metadata: CheckpointMetadata, + new_versions: ChannelVersions, + ) -> RunnableConfig: + """Save a checkpoint to the database. + + This method saves a checkpoint to the SQLite database. The checkpoint is associated + with the provided config and its parent config (if any). + + Args: + config: The config to associate with the checkpoint. + checkpoint: The checkpoint to save. + metadata: Additional metadata to save with the checkpoint. + new_versions: New channel versions as of this write. + + Returns: + RunnableConfig: Updated configuration after storing the checkpoint. + + Examples: + + >>> from langgraph.checkpoint.sqlite import SqliteSaver + >>> with SqliteSaver.from_conn_string(":memory:") as memory: + >>> config = {"configurable": {"thread_id": "1", "checkpoint_ns": ""}} + >>> checkpoint = {"ts": "2024-05-04T06:32:42.235444+00:00", "id": "1ef4f797-8335-6428-8001-8a1503f9b875", "channel_values": {"key": "value"}} + >>> saved_config = memory.put(config, checkpoint, {"source": "input", "step": 1, "writes": {"key": "value"}}, {}) + >>> print(saved_config) + {'configurable': {'thread_id': '1', 'checkpoint_ns': '', 'checkpoint_id': '1ef4f797-8335-6428-8001-8a1503f9b875'}} + """ + thread_id = config["configurable"]["thread_id"] + checkpoint_ns = config["configurable"]["checkpoint_ns"] + type_, serialized_checkpoint = self.serde.dumps_typed(checkpoint) + serialized_metadata = json.dumps( + get_checkpoint_metadata(config, metadata), ensure_ascii=False + ).encode("utf-8", "ignore") + with self.cursor() as cur: + cur.execute( + "INSERT OR REPLACE INTO checkpoints (thread_id, checkpoint_ns, checkpoint_id, parent_checkpoint_id, type, checkpoint, metadata) VALUES (?, ?, ?, ?, ?, ?, ?)", + ( + str(config["configurable"]["thread_id"]), + checkpoint_ns, + checkpoint["id"], + config["configurable"].get("checkpoint_id"), + type_, + serialized_checkpoint, + serialized_metadata, + ), + ) + return { + "configurable": { + "thread_id": thread_id, + "checkpoint_ns": checkpoint_ns, + "checkpoint_id": checkpoint["id"], + } + } + + def put_writes( + self, + config: RunnableConfig, + writes: Sequence[tuple[str, Any]], + task_id: str, + task_path: str = "", + ) -> None: + """Store intermediate writes linked to a checkpoint. + + This method saves intermediate writes associated with a checkpoint to the SQLite database. + + Args: + config: Configuration of the related checkpoint. + writes: List of writes to store, each as (channel, value) pair. + task_id: Identifier for the task creating the writes. + task_path: Path of the task creating the writes. + """ + query = ( + "INSERT OR REPLACE INTO writes (thread_id, checkpoint_ns, checkpoint_id, task_id, idx, channel, type, value) VALUES (?, ?, ?, ?, ?, ?, ?, ?)" + if all(w[0] in WRITES_IDX_MAP for w in writes) + else "INSERT OR IGNORE INTO writes (thread_id, checkpoint_ns, checkpoint_id, task_id, idx, channel, type, value) VALUES (?, ?, ?, ?, ?, ?, ?, ?)" + ) + with self.cursor() as cur: + cur.executemany( + query, + [ + ( + str(config["configurable"]["thread_id"]), + str(config["configurable"]["checkpoint_ns"]), + str(config["configurable"]["checkpoint_id"]), + task_id, + WRITES_IDX_MAP.get(channel, idx), + channel, + *self.serde.dumps_typed(value), + ) + for idx, (channel, value) in enumerate(writes) + ], + ) + + def delete_thread(self, thread_id: str) -> None: + """Delete all checkpoints and writes associated with a thread ID. + + Args: + thread_id: The thread ID to delete. + + Returns: + None + """ + with self.cursor() as cur: + cur.execute( + "DELETE FROM checkpoints WHERE thread_id = ?", + (str(thread_id),), + ) + cur.execute( + "DELETE FROM writes WHERE thread_id = ?", + (str(thread_id),), + ) + + def get_delta_channel_history( + self, *, config: RunnableConfig, channels: Sequence[str] + ) -> Mapping[str, DeltaChannelHistory]: + """Fast-path override of `BaseCheckpointSaver.get_delta_channel_history`. + + Two-stage query: + + * Stage 1 (paged): newest-first slice of `checkpoints` returning + `(checkpoint_id, parent_checkpoint_id, type, checkpoint)` per + ancestor. Sqlite has no JSONB, so we ship the full serialized + checkpoint blob and inspect `channel_values` in Python. Pages + newest-first by `checkpoint_id` with a `< cursor` predicate; + page size is `DELTA_PAGE_SIZE`. Stops paging when every channel + has found its seed or the chain is exhausted. + + * Stage 2 (per-channel UNION ALL): one branch per channel reading + `writes` filtered to that channel's specific `chain_cids`. No + separate seed-blob fetch — sqlite stores `channel_values` inline + in the checkpoint blob, so seeds come back from stage 1. + """ + if not channels: + return {} + channels = list(channels) + thread_id = str(config["configurable"]["thread_id"]) + checkpoint_ns = config["configurable"].get("checkpoint_ns", "") + checkpoint_id = get_checkpoint_id(config) + if checkpoint_id is None: + target = self.get_tuple(config) + if target is None: + return {ch: {"writes": []} for ch in channels} + checkpoint_id = target.config["configurable"]["checkpoint_id"] + + chain_by_ch: dict[str, list[str]] = {ch: [] for ch in channels} + seed_val_by_ch: dict[str, Any] = {} + walk_state: dict[str, Any] = {} + seeded: set[str] = set() + + with self.cursor(transaction=False) as cur: + cur.execute(DELTA_STAGE1_SQL, (thread_id, checkpoint_ns, checkpoint_id)) + for row in cur: + cid, parent_cid, type_tag, blob = row + if step_walk_with_row( + cid=cid, + parent_cid=parent_cid, + type_tag=type_tag, + blob=blob, + target_id=checkpoint_id, + serde=self.serde, + chain_by_ch=chain_by_ch, + seed_val_by_ch=seed_val_by_ch, + walk_state=walk_state, + seeded=seeded, + channels=channels, + ): + break + + channels_with_chain = [ch for ch in channels if chain_by_ch[ch]] + stage2_sql = build_delta_stage2_sql( + chain_lens=[len(chain_by_ch[ch]) for ch in channels_with_chain], + ) + if stage2_sql: + stage2_params: list[Any] = [] + for ch in channels_with_chain: + stage2_params.extend( + [thread_id, checkpoint_ns, ch, *chain_by_ch[ch]] + ) + cur.execute(stage2_sql, stage2_params) + stage2_rows = cast( + "list[tuple[str, str, str, int, str, bytes]]", cur.fetchall() + ) + else: + stage2_rows = [] + + return build_delta_channels_writes_history( + channels=channels, + chain_by_ch=chain_by_ch, + seed_val_by_ch=seed_val_by_ch, + seeded=seeded, + stage2_rows=stage2_rows, + serde=self.serde, + ) + + async def aget_tuple(self, config: RunnableConfig) -> CheckpointTuple | None: + """Get a checkpoint tuple from the database asynchronously. + + Note: + This async method is not supported by the SqliteSaver class. + Use get_tuple() instead, or consider using [AsyncSqliteSaver][langgraph.checkpoint.sqlite.aio.AsyncSqliteSaver]. + """ + raise NotImplementedError(_AIO_ERROR_MSG) + + async def alist( + self, + config: RunnableConfig | None, + *, + filter: dict[str, Any] | None = None, + before: RunnableConfig | None = None, + limit: int | None = None, + ) -> AsyncIterator[CheckpointTuple]: + """List checkpoints from the database asynchronously. + + Note: + This async method is not supported by the SqliteSaver class. + Use list() instead, or consider using [AsyncSqliteSaver][langgraph.checkpoint.sqlite.aio.AsyncSqliteSaver]. + """ + raise NotImplementedError(_AIO_ERROR_MSG) + yield + + async def aput( + self, + config: RunnableConfig, + checkpoint: Checkpoint, + metadata: CheckpointMetadata, + new_versions: ChannelVersions, + ) -> RunnableConfig: + """Save a checkpoint to the database asynchronously. + + Note: + This async method is not supported by the SqliteSaver class. + Use put() instead, or consider using [AsyncSqliteSaver][langgraph.checkpoint.sqlite.aio.AsyncSqliteSaver]. + """ + raise NotImplementedError(_AIO_ERROR_MSG) + + def get_next_version(self, current: str | None, channel: None) -> str: + """Generate the next version ID for a channel. + + This method creates a new version identifier for a channel based on its current version. + + Args: + current (Optional[str]): The current version identifier of the channel. + + Returns: + str: The next version identifier, which is guaranteed to be monotonically increasing. + """ + if current is None: + current_v = 0 + elif isinstance(current, int): + current_v = current + else: + current_v = int(current.split(".")[0]) + next_v = current_v + 1 + next_h = random.random() + return f"{next_v:032}.{next_h:016}" diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/checkpoint/sqlite/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/checkpoint/sqlite/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..27403e0957d292dd780ec59c2bfd71c502e876b0 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/checkpoint/sqlite/__pycache__/__init__.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/checkpoint/sqlite/__pycache__/_delta.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/checkpoint/sqlite/__pycache__/_delta.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ea66a365f72c9aa7a2221832c48338a8185b76ab Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/checkpoint/sqlite/__pycache__/_delta.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/checkpoint/sqlite/__pycache__/aio.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/checkpoint/sqlite/__pycache__/aio.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8171905a7e73db030e6e5c05a2adc419498f1c13 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/checkpoint/sqlite/__pycache__/aio.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/checkpoint/sqlite/__pycache__/utils.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/checkpoint/sqlite/__pycache__/utils.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8e34f846c45bafa12f4b7afb7a9394f409ae8b47 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/checkpoint/sqlite/__pycache__/utils.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/checkpoint/sqlite/_delta.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/checkpoint/sqlite/_delta.py new file mode 100644 index 0000000000000000000000000000000000000000..1fe617ff7dd1c09b0acfb30aff1b3e3be52aff55 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/checkpoint/sqlite/_delta.py @@ -0,0 +1,172 @@ +"""Shared helpers for `get_delta_channel_history` on sqlite savers. + +Mirrors the two-stage shape of `BasePostgresSaver` (ancestor walk + +per-channel UNION ALL writes fetch), but adapted for sqlite's +constraints. The structural differences: + +* No JSONB — to inspect `channel_values` for a checkpoint we must + deserialize the full blob. Stage 1 streams the cursor row-by-row and + deserializes only the rows the merged walk visits, freeing each blob + before advancing. +* No separate blob table — `channel_values` lives inline in the + checkpoint, so seeds come back from stage 1 with no second fetch. +* Single merged walk (not K independent walks): each visited cid is + deserialized exactly once, regardless of how many channels are still + seeking their seed. + +The streaming design keeps peak in-flight memory at roughly one +deserialized checkpoint at a time, instead of holding the entire +ancestor chain's worth of raw blobs as a `fetchall()`-materialized list. +""" + +from __future__ import annotations + +from collections.abc import Mapping, Sequence +from typing import Any + +from langgraph.checkpoint.base import DeltaChannelHistory, PendingWrite + +# Stage 1 streams ancestors of `target_cid` newest-first. The `<=` +# predicate keeps target itself in the stream so we can read its +# `parent_checkpoint_id` from the first row without a separate lookup; +# the caller skips target's own writes/seed (matches the +# `BaseCheckpointSaver` contract). +DELTA_STAGE1_SQL = ( + "SELECT checkpoint_id, parent_checkpoint_id, type, checkpoint " + "FROM checkpoints " + "WHERE thread_id = ? AND checkpoint_ns = ? AND checkpoint_id <= ? " + "ORDER BY checkpoint_id DESC" +) + + +def build_delta_stage2_sql(*, chain_lens: Sequence[int]) -> str: + """Stage-2 per-channel UNION ALL fetching writes from `writes`. + + One branch per channel with a non-empty chain. Each branch inlines its + own `IN (?, ?, ...)` placeholder list because sqlite has no array-bind + equivalent of postgres's `= ANY(%s)`. Caller passes parameters in + matching order: `[thread_id, checkpoint_ns, channel, *chain_cids]` per + branch. + + Returns an empty string when no channel has a chain (caller skips + executing in that case). Per-channel UNION ALL avoids the over-fetch + of a single `channel = ANY(channels)` filter when channels have + different chain depths — same rationale as postgres. + """ + branches: list[str] = [] + for n in chain_lens: + cid_placeholders = ",".join("?" * n) + branches.append( + "SELECT checkpoint_id, channel, task_id, idx, type, value " + "FROM writes " + "WHERE thread_id = ? AND checkpoint_ns = ? AND channel = ? " + f"AND checkpoint_id IN ({cid_placeholders})" + ) + return " UNION ALL ".join(branches) + + +def step_walk_with_row( + *, + cid: str, + parent_cid: str | None, + type_tag: str, + blob: bytes, + target_id: str, + serde: Any, + chain_by_ch: dict[str, list[str]], + seed_val_by_ch: dict[str, Any], + walk_state: dict[str, Any], + seeded: set[str], + channels: Sequence[str], +) -> bool: + """Process one streamed stage-1 row in the merged ancestor walk. + + The cursor returns (cid, parent_cid, type, blob) rows in + `checkpoint_id` DESC order starting at target. The first row is + target itself; we read its parent_cid to seed the walk and otherwise + skip it (target's own writes/seed are not part of the contract). + + For each subsequent row, if `cid` matches the walk's current + position, we deserialize the blob, append the cid to every + not-yet-seeded channel's chain, and check `channel_values` for + seeds. The deserialized checkpoint is dropped before advancing — no + cross-row cache, so peak in-flight is one deserialized checkpoint. + + Off-path rows (different branch on the same thread) advance the + cursor without doing any work. + + Returns True when every requested channel is seeded — the caller + can stop iterating and close the cursor. + """ + if "started" not in walk_state: + if cid == target_id: + walk_state["started"] = True + walk_state["cur_cid"] = parent_cid + walk_state["active"] = {ch for ch in channels if ch not in seeded} + # Not target yet (or target not present): keep streaming. + return False + active: set[str] = walk_state["active"] + if not active: + return True + if cid != walk_state["cur_cid"]: + # Off-path row from a sibling branch — skip without deserializing. + return False + for ch in active: + chain_by_ch[ch].append(cid) + ckpt = serde.loads_typed((type_tag, blob)) + channel_values: Mapping[str, Any] = ckpt.get("channel_values") or {} + for ch in [ch for ch in active if ch in channel_values]: + seed_val_by_ch[ch] = channel_values[ch] + seeded.add(ch) + active.discard(ch) + del ckpt, channel_values + walk_state["cur_cid"] = parent_cid + return not active + + +def build_delta_channels_writes_history( + *, + channels: Sequence[str], + chain_by_ch: Mapping[str, list[str]], + seed_val_by_ch: Mapping[str, Any], + seeded: set[str], + stage2_rows: Sequence[tuple[str, str, str, int, str, bytes]], + serde: Any, +) -> dict[str, DeltaChannelHistory]: + """Demux stage-2 rows per channel; produce per-channel histories. + + Stage-2 rows are `(checkpoint_id, channel, task_id, idx, type, value)`. + Final write order is oldest→newest globally and `(task_id, idx)` within + a checkpoint, matching the contract on `DeltaChannelHistory.writes`. + + `seed` is omitted when the walk reached a true root with no snapshot + found (channel never entered `seeded`); consumers treat absence as + "start empty". + """ + writes_by_ch_by_cid: dict[str, dict[str, list[tuple[str, bytes, str, int]]]] = { + ch: {} for ch in channels + } + for cid, ch, task_id, idx, type_tag, value_blob in stage2_rows: + writes_by_ch_by_cid.setdefault(ch, {}).setdefault(cid, []).append( + (type_tag, value_blob, task_id, idx) + ) + for cid_map in writes_by_ch_by_cid.values(): + for ws in cid_map.values(): + ws.sort(key=lambda w: (w[2], w[3])) + + result: dict[str, DeltaChannelHistory] = {} + for ch in channels: + chain_cids = chain_by_ch.get(ch, []) + cid_writes = writes_by_ch_by_cid.get(ch, {}) + collected: list[PendingWrite] = [] + # Chain is newest-first; iterate oldest-first for the public order. + for cid in reversed(chain_cids): + for type_tag, value_blob, task_id, _idx in cid_writes.get(cid, []): + collected.append( + (task_id, ch, serde.loads_typed((type_tag, value_blob))) + ) + entry: DeltaChannelHistory = {"writes": collected} + if ch in seeded: + entry["seed"] = seed_val_by_ch[ch] + result[ch] = entry + return result diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/checkpoint/sqlite/aio.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/checkpoint/sqlite/aio.py new file mode 100644 index 0000000000000000000000000000000000000000..368428c685469803f0d4b80785f5f6194df9692f --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/checkpoint/sqlite/aio.py @@ -0,0 +1,738 @@ +from __future__ import annotations + +import asyncio +import json +import random +import threading +from collections.abc import AsyncIterator, Callable, Iterator, Mapping, Sequence +from contextlib import asynccontextmanager +from typing import Any, TypeVar, cast + +import aiosqlite +from langchain_core.runnables import RunnableConfig +from langgraph.checkpoint.base import ( + WRITES_IDX_MAP, + BaseCheckpointSaver, + ChannelVersions, + Checkpoint, + CheckpointMetadata, + CheckpointTuple, + DeltaChannelHistory, + SerializerProtocol, + get_checkpoint_id, + get_checkpoint_metadata, +) +from langgraph.checkpoint.serde.jsonplus import JsonPlusSerializer + +from langgraph.checkpoint.sqlite._delta import ( + DELTA_STAGE1_SQL, + build_delta_channels_writes_history, + build_delta_stage2_sql, + step_walk_with_row, +) +from langgraph.checkpoint.sqlite.utils import search_where + +T = TypeVar("T", bound=Callable) + + +class AsyncSqliteSaver(BaseCheckpointSaver[str]): + """An asynchronous checkpoint saver that stores checkpoints in a SQLite database. + + This class provides an asynchronous interface for saving and retrieving checkpoints + using a SQLite database. It's designed for use in asynchronous environments and + offers better performance for I/O-bound operations compared to synchronous alternatives. + + Attributes: + conn (aiosqlite.Connection): The asynchronous SQLite database connection. + serde (SerializerProtocol): The serializer used for encoding/decoding checkpoints. + + Tip: + Requires the [aiosqlite](https://pypi.org/project/aiosqlite/) package. + Install it with `pip install aiosqlite`. + + Warning: + While this class supports asynchronous checkpointing, it is not recommended + for production workloads due to limitations in SQLite's write performance. + For production use, consider a more robust database like PostgreSQL. + + Tip: + Remember to **close the database connection** after executing your code, + otherwise, you may see the graph "hang" after execution (since the program + will not exit until the connection is closed). + + The easiest way is to use the `async with` statement as shown in the examples. + + ```python + async with AsyncSqliteSaver.from_conn_string("checkpoints.sqlite") as saver: + # Your code here + graph = builder.compile(checkpointer=saver) + config = {"configurable": {"thread_id": "thread-1"}} + async for event in graph.astream_events(..., config, version="v1"): + print(event) + ``` + + Examples: + Usage within StateGraph: + + ```pycon + >>> import asyncio + >>> + >>> from langgraph.checkpoint.sqlite.aio import AsyncSqliteSaver + >>> from langgraph.graph import StateGraph + >>> + >>> async def main(): + >>> builder = StateGraph(int) + >>> builder.add_node("add_one", lambda x: x + 1) + >>> builder.set_entry_point("add_one") + >>> builder.set_finish_point("add_one") + >>> async with AsyncSqliteSaver.from_conn_string("checkpoints.db") as memory: + >>> graph = builder.compile(checkpointer=memory) + >>> coro = graph.ainvoke(1, {"configurable": {"thread_id": "thread-1"}}) + >>> print(await asyncio.gather(coro)) + >>> + >>> asyncio.run(main()) + Output: [2] + ``` + Raw usage: + + ```pycon + >>> import asyncio + >>> import aiosqlite + >>> from langgraph.checkpoint.sqlite.aio import AsyncSqliteSaver + >>> + >>> async def main(): + >>> async with aiosqlite.connect("checkpoints.db") as conn: + ... saver = AsyncSqliteSaver(conn) + ... config = {"configurable": {"thread_id": "1", "checkpoint_ns": ""}} + ... checkpoint = {"ts": "2023-05-03T10:00:00Z", "data": {"key": "value"}, "id": "0c62ca34-ac19-445d-bbb0-5b4984975b2a"} + ... saved_config = await saver.aput(config, checkpoint, {}, {}) + ... print(saved_config) + >>> asyncio.run(main()) + {'configurable': {'thread_id': '1', 'checkpoint_ns': '', 'checkpoint_id': '0c62ca34-ac19-445d-bbb0-5b4984975b2a'}} + ``` + """ + + lock: asyncio.Lock + is_setup: bool + + def __init__( + self, + conn: aiosqlite.Connection, + *, + serde: SerializerProtocol | None = None, + ): + super().__init__(serde=serde) + self.jsonplus_serde = JsonPlusSerializer() + self.conn = conn + self.lock = asyncio.Lock() + self.loop = asyncio.get_running_loop() + self.is_setup = False + + @classmethod + @asynccontextmanager + async def from_conn_string( + cls, conn_string: str + ) -> AsyncIterator[AsyncSqliteSaver]: + """Create a new AsyncSqliteSaver instance from a connection string. + + Args: + conn_string: The SQLite connection string. + + Yields: + AsyncSqliteSaver: A new AsyncSqliteSaver instance. + """ + async with aiosqlite.connect(conn_string) as conn: + yield cls(conn) + + def get_tuple(self, config: RunnableConfig) -> CheckpointTuple | None: + """Get a checkpoint tuple from the database. + + This method retrieves a checkpoint tuple from the SQLite database based on the + provided config. If the config contains a `checkpoint_id` key, the checkpoint with + the matching thread ID and checkpoint ID is retrieved. Otherwise, the latest checkpoint + for the given thread ID is retrieved. + + Args: + config: The config to use for retrieving the checkpoint. + + Returns: + The retrieved checkpoint tuple, or None if no matching checkpoint was found. + """ + try: + # check if we are in the main thread, only bg threads can block + # we don't check in other methods to avoid the overhead + if asyncio.get_running_loop() is self.loop: + raise asyncio.InvalidStateError( + "Synchronous calls to AsyncSqliteSaver are only allowed from a " + "different thread. From the main thread, use the async interface. " + "For example, use `await checkpointer.aget_tuple(...)` or `await " + "graph.ainvoke(...)`." + ) + except RuntimeError: + pass + return asyncio.run_coroutine_threadsafe( + self.aget_tuple(config), self.loop + ).result() + + def list( + self, + config: RunnableConfig | None, + *, + filter: dict[str, Any] | None = None, + before: RunnableConfig | None = None, + limit: int | None = None, + ) -> Iterator[CheckpointTuple]: + """List checkpoints from the database asynchronously. + + This method retrieves a list of checkpoint tuples from the SQLite database based + on the provided config. The checkpoints are ordered by checkpoint ID in descending order (newest first). + + Args: + config: Base configuration for filtering checkpoints. + filter: Additional filtering criteria for metadata. + before: If provided, only checkpoints before the specified checkpoint ID are returned. + limit: Maximum number of checkpoints to return. + + Yields: + An iterator of matching checkpoint tuples. + """ + try: + # check if we are in the main thread, only bg threads can block + # we don't check in other methods to avoid the overhead + if asyncio.get_running_loop() is self.loop: + raise asyncio.InvalidStateError( + "Synchronous calls to AsyncSqliteSaver are only allowed from a " + "different thread. From the main thread, use the async interface. " + "For example, use `checkpointer.alist(...)` or `await " + "graph.ainvoke(...)`." + ) + except RuntimeError: + pass + aiter_ = self.alist(config, filter=filter, before=before, limit=limit) + while True: + try: + yield asyncio.run_coroutine_threadsafe( + anext(aiter_), # type: ignore[arg-type] # noqa: F821 + self.loop, + ).result() + except StopAsyncIteration: + break + + def put( + self, + config: RunnableConfig, + checkpoint: Checkpoint, + metadata: CheckpointMetadata, + new_versions: ChannelVersions, + ) -> RunnableConfig: + """Save a checkpoint to the database. + + This method saves a checkpoint to the SQLite database. The checkpoint is associated + with the provided config and its parent config (if any). + + Args: + config: The config to associate with the checkpoint. + checkpoint: The checkpoint to save. + metadata: Additional metadata to save with the checkpoint. + new_versions: New channel versions as of this write. + + Returns: + RunnableConfig: Updated configuration after storing the checkpoint. + """ + return asyncio.run_coroutine_threadsafe( + self.aput(config, checkpoint, metadata, new_versions), self.loop + ).result() + + def put_writes( + self, + config: RunnableConfig, + writes: Sequence[tuple[str, Any]], + task_id: str, + task_path: str = "", + ) -> None: + return asyncio.run_coroutine_threadsafe( + self.aput_writes(config, writes, task_id, task_path), self.loop + ).result() + + def delete_thread(self, thread_id: str) -> None: + """Delete all checkpoints and writes associated with a thread ID. + + Args: + thread_id: The thread ID to delete. + + Returns: + None + """ + try: + # check if we are in the main thread, only bg threads can block + # we don't check in other methods to avoid the overhead + if asyncio.get_running_loop() is self.loop: + raise asyncio.InvalidStateError( + "Synchronous calls to AsyncSqliteSaver are only allowed from a " + "different thread. From the main thread, use the async interface. " + "For example, use `checkpointer.alist(...)` or `await " + "graph.ainvoke(...)`." + ) + except RuntimeError: + pass + return asyncio.run_coroutine_threadsafe( + self.adelete_thread(thread_id), self.loop + ).result() + + def get_delta_channel_history( + self, *, config: RunnableConfig, channels: Sequence[str] + ) -> Mapping[str, DeltaChannelHistory]: + """Sync bridge to `aget_delta_channel_history`. + + Mirrors the same cross-thread guard as `get_tuple` / + `delete_thread` — calling from the loop thread raises rather than + deadlocking. + """ + try: + if asyncio.get_running_loop() is self.loop: + raise asyncio.InvalidStateError( + "Synchronous calls to AsyncSqliteSaver are only allowed from a " + "different thread. From the main thread, use the async interface. " + "For example, use `await checkpointer.aget_delta_channel_history(...)`." + ) + except RuntimeError: + pass + return asyncio.run_coroutine_threadsafe( + self.aget_delta_channel_history(config=config, channels=channels), + self.loop, + ).result() + + async def setup(self) -> None: + """Set up the checkpoint database asynchronously. + + This method creates the necessary tables in the SQLite database if they don't + already exist. It is called automatically when needed and should not be called + directly by the user. + """ + async with self.lock: + if self.is_setup: + return + await _ensure_connected(self.conn) + async with self.conn.executescript( + """ + PRAGMA journal_mode=WAL; + CREATE TABLE IF NOT EXISTS checkpoints ( + thread_id TEXT NOT NULL, + checkpoint_ns TEXT NOT NULL DEFAULT '', + checkpoint_id TEXT NOT NULL, + parent_checkpoint_id TEXT, + type TEXT, + checkpoint BLOB, + metadata BLOB, + PRIMARY KEY (thread_id, checkpoint_ns, checkpoint_id) + ); + CREATE TABLE IF NOT EXISTS writes ( + thread_id TEXT NOT NULL, + checkpoint_ns TEXT NOT NULL DEFAULT '', + checkpoint_id TEXT NOT NULL, + task_id TEXT NOT NULL, + idx INTEGER NOT NULL, + channel TEXT NOT NULL, + type TEXT, + value BLOB, + PRIMARY KEY (thread_id, checkpoint_ns, checkpoint_id, task_id, idx) + ); + """ + ): + await self.conn.commit() + + self.is_setup = True + + async def aget_tuple(self, config: RunnableConfig) -> CheckpointTuple | None: + """Get a checkpoint tuple from the database asynchronously. + + This method retrieves a checkpoint tuple from the SQLite database based on the + provided config. If the config contains a `checkpoint_id` key, the checkpoint with + the matching thread ID and checkpoint ID is retrieved. Otherwise, the latest checkpoint + for the given thread ID is retrieved. + + Args: + config: The config to use for retrieving the checkpoint. + + Returns: + The retrieved checkpoint tuple, or None if no matching checkpoint was found. + """ + await self.setup() + checkpoint_ns = config["configurable"].get("checkpoint_ns", "") + async with self.lock, self.conn.cursor() as cur: + # find the latest checkpoint for the thread_id + if checkpoint_id := get_checkpoint_id(config): + await cur.execute( + "SELECT thread_id, checkpoint_id, parent_checkpoint_id, type, checkpoint, metadata FROM checkpoints WHERE thread_id = ? AND checkpoint_ns = ? AND checkpoint_id = ?", + ( + str(config["configurable"]["thread_id"]), + checkpoint_ns, + checkpoint_id, + ), + ) + else: + await cur.execute( + "SELECT thread_id, checkpoint_id, parent_checkpoint_id, type, checkpoint, metadata FROM checkpoints WHERE thread_id = ? AND checkpoint_ns = ? ORDER BY checkpoint_id DESC LIMIT 1", + (str(config["configurable"]["thread_id"]), checkpoint_ns), + ) + # if a checkpoint is found, return it + if value := await cur.fetchone(): + ( + thread_id, + checkpoint_id, + parent_checkpoint_id, + type, + checkpoint, + metadata, + ) = value + if not get_checkpoint_id(config): + config = { + "configurable": { + "thread_id": thread_id, + "checkpoint_ns": checkpoint_ns, + "checkpoint_id": checkpoint_id, + } + } + # find any pending writes + await cur.execute( + "SELECT task_id, channel, type, value FROM writes WHERE thread_id = ? AND checkpoint_ns = ? AND checkpoint_id = ? ORDER BY task_id, idx", + ( + str(config["configurable"]["thread_id"]), + checkpoint_ns, + str(config["configurable"]["checkpoint_id"]), + ), + ) + # deserialize the checkpoint and metadata + return CheckpointTuple( + config, + self.serde.loads_typed((type, checkpoint)), + cast( + CheckpointMetadata, + (json.loads(metadata) if metadata is not None else {}), + ), + ( + { + "configurable": { + "thread_id": thread_id, + "checkpoint_ns": checkpoint_ns, + "checkpoint_id": parent_checkpoint_id, + } + } + if parent_checkpoint_id + else None + ), + [ + (task_id, channel, self.serde.loads_typed((type, value))) + async for task_id, channel, type, value in cur + ], + ) + + async def alist( + self, + config: RunnableConfig | None, + *, + filter: dict[str, Any] | None = None, + before: RunnableConfig | None = None, + limit: int | None = None, + ) -> AsyncIterator[CheckpointTuple]: + """List checkpoints from the database asynchronously. + + This method retrieves a list of checkpoint tuples from the SQLite database based + on the provided config. The checkpoints are ordered by checkpoint ID in descending order (newest first). + + Args: + config: Base configuration for filtering checkpoints. + filter: Additional filtering criteria for metadata. + before: If provided, only checkpoints before the specified checkpoint ID are returned. + limit: Maximum number of checkpoints to return. + + Yields: + An asynchronous iterator of matching checkpoint tuples. + """ + await self.setup() + where, params = search_where(config, filter, before) + query = f"""SELECT thread_id, checkpoint_ns, checkpoint_id, parent_checkpoint_id, type, checkpoint, metadata + FROM checkpoints + {where} + ORDER BY checkpoint_id DESC""" + if limit is not None: + query += " LIMIT ?" + params = (*params, limit) + async with ( + self.lock, + self.conn.execute(query, params) as cur, + self.conn.cursor() as wcur, + ): + async for ( + thread_id, + checkpoint_ns, + checkpoint_id, + parent_checkpoint_id, + type, + checkpoint, + metadata, + ) in cur: + await wcur.execute( + "SELECT task_id, channel, type, value FROM writes WHERE thread_id = ? AND checkpoint_ns = ? AND checkpoint_id = ? ORDER BY task_id, idx", + (thread_id, checkpoint_ns, checkpoint_id), + ) + yield CheckpointTuple( + { + "configurable": { + "thread_id": thread_id, + "checkpoint_ns": checkpoint_ns, + "checkpoint_id": checkpoint_id, + } + }, + self.serde.loads_typed((type, checkpoint)), + cast( + CheckpointMetadata, + (json.loads(metadata) if metadata is not None else {}), + ), + ( + { + "configurable": { + "thread_id": thread_id, + "checkpoint_ns": checkpoint_ns, + "checkpoint_id": parent_checkpoint_id, + } + } + if parent_checkpoint_id + else None + ), + [ + (task_id, channel, self.serde.loads_typed((type, value))) + async for task_id, channel, type, value in wcur + ], + ) + + async def aput( + self, + config: RunnableConfig, + checkpoint: Checkpoint, + metadata: CheckpointMetadata, + new_versions: ChannelVersions, + ) -> RunnableConfig: + """Save a checkpoint to the database asynchronously. + + This method saves a checkpoint to the SQLite database. The checkpoint is associated + with the provided config and its parent config (if any). + + Args: + config: The config to associate with the checkpoint. + checkpoint: The checkpoint to save. + metadata: Additional metadata to save with the checkpoint. + new_versions: New channel versions as of this write. + + Returns: + RunnableConfig: Updated configuration after storing the checkpoint. + """ + await self.setup() + thread_id = config["configurable"]["thread_id"] + checkpoint_ns = config["configurable"]["checkpoint_ns"] + type_, serialized_checkpoint = self.serde.dumps_typed(checkpoint) + serialized_metadata = json.dumps( + get_checkpoint_metadata(config, metadata), ensure_ascii=False + ).encode("utf-8", "ignore") + async with ( + self.lock, + self.conn.execute( + "INSERT OR REPLACE INTO checkpoints (thread_id, checkpoint_ns, checkpoint_id, parent_checkpoint_id, type, checkpoint, metadata) VALUES (?, ?, ?, ?, ?, ?, ?)", + ( + str(config["configurable"]["thread_id"]), + checkpoint_ns, + checkpoint["id"], + config["configurable"].get("checkpoint_id"), + type_, + serialized_checkpoint, + serialized_metadata, + ), + ), + ): + await self.conn.commit() + return { + "configurable": { + "thread_id": thread_id, + "checkpoint_ns": checkpoint_ns, + "checkpoint_id": checkpoint["id"], + } + } + + async def aput_writes( + self, + config: RunnableConfig, + writes: Sequence[tuple[str, Any]], + task_id: str, + task_path: str = "", + ) -> None: + """Store intermediate writes linked to a checkpoint asynchronously. + + This method saves intermediate writes associated with a checkpoint to the database. + + Args: + config: Configuration of the related checkpoint. + writes: List of writes to store, each as (channel, value) pair. + task_id: Identifier for the task creating the writes. + task_path: Path of the task creating the writes. + """ + query = ( + "INSERT OR REPLACE INTO writes (thread_id, checkpoint_ns, checkpoint_id, task_id, idx, channel, type, value) VALUES (?, ?, ?, ?, ?, ?, ?, ?)" + if all(w[0] in WRITES_IDX_MAP for w in writes) + else "INSERT OR IGNORE INTO writes (thread_id, checkpoint_ns, checkpoint_id, task_id, idx, channel, type, value) VALUES (?, ?, ?, ?, ?, ?, ?, ?)" + ) + await self.setup() + async with self.lock, self.conn.cursor() as cur: + await cur.executemany( + query, + [ + ( + str(config["configurable"]["thread_id"]), + str(config["configurable"]["checkpoint_ns"]), + str(config["configurable"]["checkpoint_id"]), + task_id, + WRITES_IDX_MAP.get(channel, idx), + channel, + *self.serde.dumps_typed(value), + ) + for idx, (channel, value) in enumerate(writes) + ], + ) + await self.conn.commit() + + async def adelete_thread(self, thread_id: str) -> None: + """Delete all checkpoints and writes associated with a thread ID. + + Args: + thread_id: The thread ID to delete. + + Returns: + None + """ + async with self.lock, self.conn.cursor() as cur: + await cur.execute( + "DELETE FROM checkpoints WHERE thread_id = ?", + (str(thread_id),), + ) + await cur.execute( + "DELETE FROM writes WHERE thread_id = ?", + (str(thread_id),), + ) + await self.conn.commit() + + async def aget_delta_channel_history( + self, *, config: RunnableConfig, channels: Sequence[str] + ) -> Mapping[str, DeltaChannelHistory]: + """Fast-path override of `BaseCheckpointSaver.aget_delta_channel_history`. + + See `SqliteSaver.get_delta_channel_history` for design notes; this + is the async equivalent using `aiosqlite` cursors. Stage 1 pages + the parent chain newest-first and Python-deserializes each + checkpoint blob to find per-channel snapshots; stage 2 fetches + only the relevant writes via per-channel UNION ALL. + """ + if not channels: + return {} + channels = list(channels) + await self.setup() + thread_id = str(config["configurable"]["thread_id"]) + checkpoint_ns = config["configurable"].get("checkpoint_ns", "") + checkpoint_id = get_checkpoint_id(config) + if checkpoint_id is None: + target = await self.aget_tuple(config) + if target is None: + return {ch: {"writes": []} for ch in channels} + checkpoint_id = target.config["configurable"]["checkpoint_id"] + + chain_by_ch: dict[str, list[str]] = {ch: [] for ch in channels} + seed_val_by_ch: dict[str, Any] = {} + walk_state: dict[str, Any] = {} + seeded: set[str] = set() + + async with self.lock, self.conn.cursor() as cur: + await cur.execute( + DELTA_STAGE1_SQL, (thread_id, checkpoint_ns, checkpoint_id) + ) + async for row in cur: + cid, parent_cid, type_tag, blob = row + if step_walk_with_row( + cid=cid, + parent_cid=parent_cid, + type_tag=type_tag, + blob=blob, + target_id=checkpoint_id, + serde=self.serde, + chain_by_ch=chain_by_ch, + seed_val_by_ch=seed_val_by_ch, + walk_state=walk_state, + seeded=seeded, + channels=channels, + ): + break + + channels_with_chain = [ch for ch in channels if chain_by_ch[ch]] + stage2_sql = build_delta_stage2_sql( + chain_lens=[len(chain_by_ch[ch]) for ch in channels_with_chain], + ) + if stage2_sql: + stage2_params: list[Any] = [] + for ch in channels_with_chain: + stage2_params.extend( + [thread_id, checkpoint_ns, ch, *chain_by_ch[ch]] + ) + await cur.execute(stage2_sql, stage2_params) + stage2_rows = cast( + "list[tuple[str, str, str, int, str, bytes]]", + await cur.fetchall(), + ) + else: + stage2_rows = [] + + return build_delta_channels_writes_history( + channels=channels, + chain_by_ch=chain_by_ch, + seed_val_by_ch=seed_val_by_ch, + seeded=seeded, + stage2_rows=stage2_rows, + serde=self.serde, + ) + + def get_next_version(self, current: str | None, channel: None) -> str: + """Generate the next version ID for a channel. + + This method creates a new version identifier for a channel based on its current version. + + Args: + current (Optional[str]): The current version identifier of the channel. + + Returns: + str: The next version identifier, which is guaranteed to be monotonically increasing. + """ + if current is None: + current_v = 0 + elif isinstance(current, int): + current_v = current + else: + current_v = int(current.split(".")[0]) + next_v = current_v + 1 + next_h = random.random() + return f"{next_v:032}.{next_h:016}" + + +async def _ensure_connected(conn: aiosqlite.Connection) -> None: + if not _CONN_STARTED_CHECK(conn): + await conn + + +def _build_conn_started_check() -> Callable[[aiosqlite.Connection], bool]: + is_alive = getattr(aiosqlite.Connection, "is_alive", None) + if callable(is_alive): + return lambda conn: conn.is_alive() # type: ignore[attr-defined] + + def _started(conn: aiosqlite.Connection) -> bool: + thread: threading.Thread | None = getattr(conn, "_thread", None) + return False if thread is None else thread.is_alive() + + return _started + + +_CONN_STARTED_CHECK = _build_conn_started_check() diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/checkpoint/sqlite/py.typed b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/checkpoint/sqlite/py.typed new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/checkpoint/sqlite/utils.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/checkpoint/sqlite/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..7c7e0600053ebb73eafa36d2e617c76eab547475 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/checkpoint/sqlite/utils.py @@ -0,0 +1,116 @@ +from __future__ import annotations + +import json +import re +from collections.abc import Sequence +from typing import Any + +from langchain_core.runnables import RunnableConfig +from langgraph.checkpoint.base import get_checkpoint_id + +_FILTER_PATTERN = re.compile(r"^[a-zA-Z0-9_.-]+$") + + +def _validate_filter_key(key: str) -> None: + """Validate that a filter key is safe for use in SQL queries. + + Args: + key: The filter key to validate + + Raises: + ValueError: If the key contains invalid characters that could enable SQL injection + """ + # Allow alphanumeric characters, underscores, dots, and hyphens + # This covers typical JSON property names while preventing SQL injection + if not _FILTER_PATTERN.match(key): + raise ValueError( + f"Invalid filter key: '{key}'. Filter keys must contain only alphanumeric characters, underscores, dots, and hyphens." + ) + + +def _metadata_predicate( + metadata_filter: dict[str, Any], +) -> tuple[Sequence[str], Sequence[Any]]: + """Return WHERE clause predicates for (a)search() given metadata filter. + + This method returns a tuple of a string and a tuple of values. The string + is the parametered WHERE clause predicate (excluding the WHERE keyword): + "column1 = ? AND column2 IS ?". The tuple of values contains the values + for each of the corresponding parameters. + """ + + def _where_value(query_value: Any) -> tuple[str, Any]: + """Return tuple of operator and value for WHERE clause predicate.""" + if query_value is None: + return ("IS ?", None) + elif ( + isinstance(query_value, str) + or isinstance(query_value, int) + or isinstance(query_value, float) + ): + return ("= ?", query_value) + elif isinstance(query_value, bool): + return ("= ?", 1 if query_value else 0) + elif isinstance(query_value, dict) or isinstance(query_value, list): + # query value for JSON object cannot have trailing space after separators (, :) + # SQLite json_extract() returns JSON string without whitespace + return ("= ?", json.dumps(query_value, separators=(",", ":"))) + else: + return ("= ?", str(query_value)) + + predicates = [] + param_values = [] + + # process metadata query + for query_key, query_value in metadata_filter.items(): + _validate_filter_key(query_key) + operator, param_value = _where_value(query_value) + predicates.append( + f"json_extract(CAST(metadata AS TEXT), '$.{query_key}') {operator}" + ) + param_values.append(param_value) + + return (predicates, param_values) + + +def search_where( + config: RunnableConfig | None, + filter: dict[str, Any] | None, + before: RunnableConfig | None = None, +) -> tuple[str, Sequence[Any]]: + """Return WHERE clause predicates for (a)search() given metadata filter + and `before` config. + + This method returns a tuple of a string and a tuple of values. The string + is the parametered WHERE clause predicate (including the WHERE keyword): + "WHERE column1 = ? AND column2 IS ?". The tuple of values contains the + values for each of the corresponding parameters. + """ + wheres = [] + param_values = [] + + # construct predicate for config filter + if config is not None: + wheres.append("thread_id = ?") + param_values.append(config["configurable"]["thread_id"]) + checkpoint_ns = config["configurable"].get("checkpoint_ns") + if checkpoint_ns is not None: + wheres.append("checkpoint_ns = ?") + param_values.append(checkpoint_ns) + + if checkpoint_id := get_checkpoint_id(config): + wheres.append("checkpoint_id = ?") + param_values.append(checkpoint_id) + + # construct predicate for metadata filter + if filter: + metadata_predicates, metadata_values = _metadata_predicate(filter) + wheres.extend(metadata_predicates) + param_values.extend(metadata_values) + + # construct predicate for `before` + if before is not None: + wheres.append("checkpoint_id < ?") + param_values.append(get_checkpoint_id(before)) + + return ("WHERE " + " AND ".join(wheres) if wheres else "", param_values) diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/func/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/func/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ce2e5150c4ae662da262e18f7f3e03796cbb8e21 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/func/__pycache__/__init__.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/graph/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/graph/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..417a9f68a4d976fc846e1e54f73f9781f7880760 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/graph/__pycache__/__init__.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/graph/__pycache__/_branch.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/graph/__pycache__/_branch.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6c30398f03b4153800b5e5a20521d9f548c286fd Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/graph/__pycache__/_branch.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/graph/__pycache__/_node.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/graph/__pycache__/_node.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e211e04ffc551b6b89986946ce032acaf399e6ce Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/graph/__pycache__/_node.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/graph/__pycache__/message.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/graph/__pycache__/message.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..545cf2d95045426efcb67927bced5b806c3150a6 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/graph/__pycache__/message.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/graph/__pycache__/state.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/graph/__pycache__/state.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f72270f6f47435d05c4384793dcce04d0d8019fd Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/graph/__pycache__/state.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/graph/__pycache__/ui.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/graph/__pycache__/ui.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..254895f4c28c990e2908c7fe8fcf0b3d9361cb52 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/graph/__pycache__/ui.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/pregel/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/pregel/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a028cab1b4a0a8465e33c1d9ea2dd2b1915aa530 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/pregel/__pycache__/__init__.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/pregel/__pycache__/_algo.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/pregel/__pycache__/_algo.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0207443e5cffbbab682c2f4fcccb286f7040a469 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/pregel/__pycache__/_algo.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/pregel/__pycache__/_call.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/pregel/__pycache__/_call.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c90f6a79c8de501991731cd98188d4b0b3ce54d3 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/pregel/__pycache__/_call.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/pregel/__pycache__/_checkpoint.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/pregel/__pycache__/_checkpoint.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..530f518a4e5414551df346b5e90c33ce873a01e6 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/pregel/__pycache__/_checkpoint.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/pregel/__pycache__/_config.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/pregel/__pycache__/_config.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9d44582dc3066dfc0d739962e6c842e06f8a3012 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/pregel/__pycache__/_config.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/pregel/__pycache__/_draw.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/pregel/__pycache__/_draw.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a3ae5576b85e1ca1d4c9f0db28d2a2176ab37f91 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/pregel/__pycache__/_draw.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/pregel/__pycache__/_executor.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/pregel/__pycache__/_executor.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..75a1c87ff9cf9cc3f52939930e0b80631d0ea615 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/pregel/__pycache__/_executor.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/pregel/__pycache__/_io.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/pregel/__pycache__/_io.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..994d4639de2bfb138948b9ec9f725255a61bfad8 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/pregel/__pycache__/_io.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/pregel/__pycache__/_log.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/pregel/__pycache__/_log.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5de92e763aada414ebeb4ee07700d4c19bbdd526 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/pregel/__pycache__/_log.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/pregel/__pycache__/_loop.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/pregel/__pycache__/_loop.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3e4c5763f59eb3174b93b4627e3c0efc056364f4 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/pregel/__pycache__/_loop.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/pregel/__pycache__/_messages.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/pregel/__pycache__/_messages.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f9a7aae06bbed45ab8104ba43da0fe242819b211 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/pregel/__pycache__/_messages.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/pregel/__pycache__/_read.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/pregel/__pycache__/_read.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e96f8b38b54b0e14dfcdf40112b373dc38dd9aef Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/pregel/__pycache__/_read.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/pregel/__pycache__/_retry.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/pregel/__pycache__/_retry.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1e4da85b56e0559a8634a4abb992655b53bfda3f Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/pregel/__pycache__/_retry.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/pregel/__pycache__/_runner.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/pregel/__pycache__/_runner.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c55e828b2697db1e31ede8383c779549609fd071 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/pregel/__pycache__/_runner.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/pregel/__pycache__/_tools.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/pregel/__pycache__/_tools.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f5045f2f85bd8cb924047fb89772376a6dc817f5 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/pregel/__pycache__/_tools.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/pregel/__pycache__/_utils.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/pregel/__pycache__/_utils.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..06b987b718fc5053dc9082849949ce955db126f4 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/pregel/__pycache__/_utils.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/pregel/__pycache__/_validate.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/pregel/__pycache__/_validate.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6da0b75682719493b7e0b91de423f2b6f6ae2c57 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/pregel/__pycache__/_validate.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/pregel/__pycache__/_write.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/pregel/__pycache__/_write.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..431fb13bb9913b29ee0ee75021ddd9e4fc5a0eca Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/pregel/__pycache__/_write.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/pregel/__pycache__/debug.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/pregel/__pycache__/debug.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..dcda4cec7b114d8a72d112a440ba352d015b4eac Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/pregel/__pycache__/debug.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/pregel/__pycache__/protocol.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/pregel/__pycache__/protocol.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e82748a78eb47518697fb97b07cfd445293a8ed1 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/pregel/__pycache__/protocol.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/pregel/__pycache__/remote.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/pregel/__pycache__/remote.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5210e6259d9b690ddc241cf9c476ecca1fc6d913 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/pregel/__pycache__/remote.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/pregel/__pycache__/types.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/pregel/__pycache__/types.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6ae5129056bb4b11deae14d2a5105765f4f6d23b Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/pregel/__pycache__/types.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/utils/__pycache__/config.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/utils/__pycache__/config.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..844dac0ae07ec7a5213777ff2cd21bf47f41d172 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/utils/__pycache__/config.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/utils/__pycache__/runnable.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/utils/__pycache__/runnable.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..aa6f71e6a6c0f49998c31ff4c2c39d1f816cf6f9 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/utils/__pycache__/runnable.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/scipy/ndimage/_fourier.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/scipy/ndimage/_fourier.py new file mode 100644 index 0000000000000000000000000000000000000000..bb5ffa6b9287cb740611aefba5f1f322011518cf --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/scipy/ndimage/_fourier.py @@ -0,0 +1,306 @@ +# Copyright (C) 2003-2005 Peter J. Verveer +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions +# are met: +# +# 1. Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# +# 2. Redistributions in binary form must reproduce the above +# copyright notice, this list of conditions and the following +# disclaimer in the documentation and/or other materials provided +# with the distribution. +# +# 3. The name of the author may not be used to endorse or promote +# products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS +# OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +# ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY +# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE +# GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, +# WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING +# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +import numpy as np +from scipy._lib._util import normalize_axis_index +from . import _ni_support +from . import _nd_image + +__all__ = ['fourier_gaussian', 'fourier_uniform', 'fourier_ellipsoid', + 'fourier_shift'] + + +def _get_output_fourier(output, input): + if output is None: + if input.dtype.type in [np.complex64, np.complex128, np.float32]: + output = np.zeros(input.shape, dtype=input.dtype) + else: + output = np.zeros(input.shape, dtype=np.float64) + elif type(output) is type: + if output not in [np.complex64, np.complex128, + np.float32, np.float64]: + raise RuntimeError("output type not supported") + output = np.zeros(input.shape, dtype=output) + elif output.shape != input.shape: + raise RuntimeError("output shape not correct") + return output + + +def _get_output_fourier_complex(output, input): + if output is None: + if input.dtype.type in [np.complex64, np.complex128]: + output = np.zeros(input.shape, dtype=input.dtype) + else: + output = np.zeros(input.shape, dtype=np.complex128) + elif type(output) is type: + if output not in [np.complex64, np.complex128]: + raise RuntimeError("output type not supported") + output = np.zeros(input.shape, dtype=output) + elif output.shape != input.shape: + raise RuntimeError("output shape not correct") + return output + + +def fourier_gaussian(input, sigma, n=-1, axis=-1, output=None): + """ + Multidimensional Gaussian fourier filter. + + The array is multiplied with the fourier transform of a Gaussian + kernel. + + Parameters + ---------- + input : array_like + The input array. + sigma : float or sequence + The sigma of the Gaussian kernel. If a float, `sigma` is the same for + all axes. If a sequence, `sigma` has to contain one value for each + axis. + n : int, optional + If `n` is negative (default), then the input is assumed to be the + result of a complex fft. + If `n` is larger than or equal to zero, the input is assumed to be the + result of a real fft, and `n` gives the length of the array before + transformation along the real transform direction. + axis : int, optional + The axis of the real transform. + output : ndarray, optional + If given, the result of filtering the input is placed in this array. + + Returns + ------- + fourier_gaussian : ndarray + The filtered input. + + Examples + -------- + >>> from scipy import ndimage, datasets + >>> import numpy.fft + >>> import matplotlib.pyplot as plt + >>> fig, (ax1, ax2) = plt.subplots(1, 2) + >>> plt.gray() # show the filtered result in grayscale + >>> ascent = datasets.ascent() + >>> input_ = numpy.fft.fft2(ascent) + >>> result = ndimage.fourier_gaussian(input_, sigma=4) + >>> result = numpy.fft.ifft2(result) + >>> ax1.imshow(ascent) + >>> ax2.imshow(result.real) # the imaginary part is an artifact + >>> plt.show() + """ + input = np.asarray(input) + output = _get_output_fourier(output, input) + axis = normalize_axis_index(axis, input.ndim) + sigmas = _ni_support._normalize_sequence(sigma, input.ndim) + sigmas = np.asarray(sigmas, dtype=np.float64) + if not sigmas.flags.contiguous: + sigmas = sigmas.copy() + + _nd_image.fourier_filter(input, sigmas, n, axis, output, 0) + return output + + +def fourier_uniform(input, size, n=-1, axis=-1, output=None): + """ + Multidimensional uniform fourier filter. + + The array is multiplied with the Fourier transform of a box of given + size. + + Parameters + ---------- + input : array_like + The input array. + size : float or sequence + The size of the box used for filtering. + If a float, `size` is the same for all axes. If a sequence, `size` has + to contain one value for each axis. + n : int, optional + If `n` is negative (default), then the input is assumed to be the + result of a complex fft. + If `n` is larger than or equal to zero, the input is assumed to be the + result of a real fft, and `n` gives the length of the array before + transformation along the real transform direction. + axis : int, optional + The axis of the real transform. + output : ndarray, optional + If given, the result of filtering the input is placed in this array. + + Returns + ------- + fourier_uniform : ndarray + The filtered input. + + Examples + -------- + >>> from scipy import ndimage, datasets + >>> import numpy.fft + >>> import matplotlib.pyplot as plt + >>> fig, (ax1, ax2) = plt.subplots(1, 2) + >>> plt.gray() # show the filtered result in grayscale + >>> ascent = datasets.ascent() + >>> input_ = numpy.fft.fft2(ascent) + >>> result = ndimage.fourier_uniform(input_, size=20) + >>> result = numpy.fft.ifft2(result) + >>> ax1.imshow(ascent) + >>> ax2.imshow(result.real) # the imaginary part is an artifact + >>> plt.show() + """ + input = np.asarray(input) + output = _get_output_fourier(output, input) + axis = normalize_axis_index(axis, input.ndim) + sizes = _ni_support._normalize_sequence(size, input.ndim) + sizes = np.asarray(sizes, dtype=np.float64) + if not sizes.flags.contiguous: + sizes = sizes.copy() + _nd_image.fourier_filter(input, sizes, n, axis, output, 1) + return output + + +def fourier_ellipsoid(input, size, n=-1, axis=-1, output=None): + """ + Multidimensional ellipsoid Fourier filter. + + The array is multiplied with the fourier transform of an ellipsoid of + given sizes. + + Parameters + ---------- + input : array_like + The input array. + size : float or sequence + The size of the box used for filtering. + If a float, `size` is the same for all axes. If a sequence, `size` has + to contain one value for each axis. + n : int, optional + If `n` is negative (default), then the input is assumed to be the + result of a complex fft. + If `n` is larger than or equal to zero, the input is assumed to be the + result of a real fft, and `n` gives the length of the array before + transformation along the real transform direction. + axis : int, optional + The axis of the real transform. + output : ndarray, optional + If given, the result of filtering the input is placed in this array. + + Returns + ------- + fourier_ellipsoid : ndarray + The filtered input. + + Notes + ----- + This function is implemented for arrays of rank 1, 2, or 3. + + Examples + -------- + >>> from scipy import ndimage, datasets + >>> import numpy.fft + >>> import matplotlib.pyplot as plt + >>> fig, (ax1, ax2) = plt.subplots(1, 2) + >>> plt.gray() # show the filtered result in grayscale + >>> ascent = datasets.ascent() + >>> input_ = numpy.fft.fft2(ascent) + >>> result = ndimage.fourier_ellipsoid(input_, size=20) + >>> result = numpy.fft.ifft2(result) + >>> ax1.imshow(ascent) + >>> ax2.imshow(result.real) # the imaginary part is an artifact + >>> plt.show() + """ + input = np.asarray(input) + if input.ndim > 3: + raise NotImplementedError("Only 1d, 2d and 3d inputs are supported") + output = _get_output_fourier(output, input) + if output.size == 0: + # The C code has a bug that can result in a segfault with arrays + # that have size 0 (gh-17270), so check here. + return output + axis = normalize_axis_index(axis, input.ndim) + sizes = _ni_support._normalize_sequence(size, input.ndim) + sizes = np.asarray(sizes, dtype=np.float64) + if not sizes.flags.contiguous: + sizes = sizes.copy() + _nd_image.fourier_filter(input, sizes, n, axis, output, 2) + return output + + +def fourier_shift(input, shift, n=-1, axis=-1, output=None): + """ + Multidimensional Fourier shift filter. + + The array is multiplied with the Fourier transform of a shift operation. + + Parameters + ---------- + input : array_like + The input array. + shift : float or sequence + The size of the box used for filtering. + If a float, `shift` is the same for all axes. If a sequence, `shift` + has to contain one value for each axis. + n : int, optional + If `n` is negative (default), then the input is assumed to be the + result of a complex fft. + If `n` is larger than or equal to zero, the input is assumed to be the + result of a real fft, and `n` gives the length of the array before + transformation along the real transform direction. + axis : int, optional + The axis of the real transform. + output : ndarray, optional + If given, the result of shifting the input is placed in this array. + + Returns + ------- + fourier_shift : ndarray + The shifted input. + + Examples + -------- + >>> from scipy import ndimage, datasets + >>> import matplotlib.pyplot as plt + >>> import numpy.fft + >>> fig, (ax1, ax2) = plt.subplots(1, 2) + >>> plt.gray() # show the filtered result in grayscale + >>> ascent = datasets.ascent() + >>> input_ = numpy.fft.fft2(ascent) + >>> result = ndimage.fourier_shift(input_, shift=200) + >>> result = numpy.fft.ifft2(result) + >>> ax1.imshow(ascent) + >>> ax2.imshow(result.real) # the imaginary part is an artifact + >>> plt.show() + """ + input = np.asarray(input) + output = _get_output_fourier_complex(output, input) + axis = normalize_axis_index(axis, input.ndim) + shifts = _ni_support._normalize_sequence(shift, input.ndim) + shifts = np.asarray(shifts, dtype=np.float64) + if not shifts.flags.contiguous: + shifts = shifts.copy() + _nd_image.fourier_shift(input, shifts, n, axis, output) + return output diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/scipy/ndimage/filters.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/scipy/ndimage/filters.py new file mode 100644 index 0000000000000000000000000000000000000000..e16d9d279a9585b2454c46ee09cf22143de833a6 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/scipy/ndimage/filters.py @@ -0,0 +1,27 @@ +# This file is not meant for public use and will be removed in SciPy v2.0.0. +# Use the `scipy.ndimage` namespace for importing the functions +# included below. + +from scipy._lib.deprecation import _sub_module_deprecation + + +__all__ = [ # noqa: F822 + 'correlate1d', 'convolve1d', 'gaussian_filter1d', + 'gaussian_filter', 'prewitt', 'sobel', 'generic_laplace', + 'laplace', 'gaussian_laplace', 'generic_gradient_magnitude', + 'gaussian_gradient_magnitude', 'correlate', 'convolve', + 'uniform_filter1d', 'uniform_filter', 'minimum_filter1d', + 'maximum_filter1d', 'minimum_filter', 'maximum_filter', + 'rank_filter', 'median_filter', 'percentile_filter', + 'generic_filter1d', 'generic_filter' +] + + +def __dir__(): + return __all__ + + +def __getattr__(name): + return _sub_module_deprecation(sub_package='ndimage', module='filters', + private_modules=['_filters'], all=__all__, + attribute=name) diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/scipy/ndimage/measurements.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/scipy/ndimage/measurements.py new file mode 100644 index 0000000000000000000000000000000000000000..22f76b01840ffb829205bd1d28a7ad1f9ac5db61 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/scipy/ndimage/measurements.py @@ -0,0 +1,24 @@ +# This file is not meant for public use and will be removed in SciPy v2.0.0. +# Use the `scipy.ndimage` namespace for importing the functions +# included below. + +from scipy._lib.deprecation import _sub_module_deprecation + + +__all__ = [ # noqa: F822 + 'label', 'find_objects', 'labeled_comprehension', + 'sum', 'mean', 'variance', 'standard_deviation', + 'minimum', 'maximum', 'median', 'minimum_position', + 'maximum_position', 'extrema', 'center_of_mass', + 'histogram', 'watershed_ift', 'sum_labels' +] + + +def __dir__(): + return __all__ + + +def __getattr__(name): + return _sub_module_deprecation(sub_package='ndimage', module='measurements', + private_modules=['_measurements'], all=__all__, + attribute=name)