From f87608a16f315b6f83e00d6fdf2b1f138c8bae58 Mon Sep 17 00:00:00 2001 From: "open-swe[bot]" <215916821+open-swe[bot]@users.noreply.github.com> Date: Thu, 17 Jul 2025 18:45:10 +0000 Subject: [PATCH] chore(prebuilt): Remove dead code from prebuilt tests (#5555) Fixes #5554 This PR removes unused utility classes and functions from the prebuilt tests directory to clean up dead code. Changes include: - Removed unused classes from `libs/prebuilt/tests/any_str.py`: - Deleted FloatBetween, AnyDict, AnyVersion, and UnsortedSequence - Kept only AnyStr class - Removed unused functions from `libs/prebuilt/tests/messages.py`: - Deleted _AnyIdDocument and _AnyIdAIMessageChunk - Kept _AnyIdHumanMessage and _AnyIdToolMessage - Removed unused classes from `libs/prebuilt/tests/memory_assert.py`: - Deleted NoopSerializer, MemorySaverAssertCheckpointMetadata, and MemorySaverNoPending - Kept MemorySaverAssertImmutable Verification: - Manually checked for no remaining references to removed code - Maintained existing import structures - Preserved functionality of the prebuilt test suite The changes reduce code complexity and remove unnecessary utility classes that were not being used in the test suite. --------- Co-authored-by: open-swe-dev[bot] Co-authored-by: Eugene Yurtsev --- libs/prebuilt/Makefile | 2 +- libs/prebuilt/tests/any_str.py | 70 +------------------------ libs/prebuilt/tests/memory_assert.py | 77 +--------------------------- libs/prebuilt/tests/messages.py | 24 +-------- 4 files changed, 4 insertions(+), 169 deletions(-) diff --git a/libs/prebuilt/Makefile b/libs/prebuilt/Makefile index d62e65e3a..aef3028e5 100644 --- a/libs/prebuilt/Makefile +++ b/libs/prebuilt/Makefile @@ -52,7 +52,7 @@ lint lint_diff lint_package lint_tests: format format_diff: uv run ruff format $(PYTHON_FILES) - uv run ruff check --select I --fix $(PYTHON_FILES) + uv run ruff check --fix $(PYTHON_FILES) spell_check: uv run codespell --toml pyproject.toml diff --git a/libs/prebuilt/tests/any_str.py b/libs/prebuilt/tests/any_str.py index 5643a00fb..790324322 100644 --- a/libs/prebuilt/tests/any_str.py +++ b/libs/prebuilt/tests/any_str.py @@ -1,27 +1,5 @@ import re -from typing import Any, Sequence, Union - -from typing_extensions import Self - - -class FloatBetween(float): - def __new__(cls, min_value: float, max_value: float) -> Self: - return super().__new__(cls, min_value) - - def __init__(self, min_value: float, max_value: float) -> None: - super().__init__() - self.min_value = min_value - self.max_value = max_value - - def __eq__(self, other: object) -> bool: - return ( - isinstance(other, float) - and other >= self.min_value - and other <= self.max_value - ) - - def __hash__(self) -> int: - return hash((float(self), self.min_value, self.max_value)) +from typing import Union class AnyStr(str): @@ -38,49 +16,3 @@ class AnyStr(str): def __hash__(self) -> int: return hash((str(self), self.prefix)) - - -class AnyDict(dict): - def __init__(self, *args, **kwargs) -> None: - super().__init__(*args, **kwargs) - - def __eq__(self, other: object) -> bool: - if not isinstance(other, dict) or len(self) != len(other): - return False - for k, v in self.items(): - if kk := next((kk for kk in other if kk == k), None): - if v == other[kk]: - continue - else: - return False - else: - return True - - -class AnyVersion: - def __init__(self) -> None: - super().__init__() - - def __eq__(self, other: object) -> bool: - return isinstance(other, (str, int, float)) - - def __hash__(self) -> int: - return hash(str(self)) - - -class UnsortedSequence: - def __init__(self, *values: Any) -> None: - self.seq = values - - def __eq__(self, value: object) -> bool: - return ( - isinstance(value, Sequence) - and len(self.seq) == len(value) - and all(a in value for a in self.seq) - ) - - def __hash__(self) -> int: - return hash(frozenset(self.seq)) - - def __repr__(self) -> str: - return repr(self.seq) diff --git a/libs/prebuilt/tests/memory_assert.py b/libs/prebuilt/tests/memory_assert.py index 10b93fdbd..c12cbb3b8 100644 --- a/libs/prebuilt/tests/memory_assert.py +++ b/libs/prebuilt/tests/memory_assert.py @@ -1,31 +1,19 @@ -import asyncio import os import tempfile from collections import defaultdict from functools import partial -from typing import Any, Optional - -from langchain_core.runnables import RunnableConfig +from typing import Optional from langgraph.checkpoint.base import ( ChannelVersions, Checkpoint, CheckpointMetadata, - CheckpointTuple, SerializerProtocol, ) from langgraph.checkpoint.memory import InMemorySaver, PersistentDict from langgraph.pregel.checkpoint import copy_checkpoint -class NoopSerializer(SerializerProtocol): - def loads_typed(self, data: tuple[str, bytes]) -> Any: - return data[1] - - def dumps_typed(self, obj: Any) -> tuple[str, bytes]: - return "type", obj - - class MemorySaverAssertImmutable(InMemorySaver): storage_for_copies: defaultdict[str, dict[str, dict[str, Checkpoint]]] @@ -69,66 +57,3 @@ class MemorySaverAssertImmutable(InMemorySaver): ) # call super to write checkpoint return super().put(config, checkpoint, metadata, new_versions) - - -class MemorySaverAssertCheckpointMetadata(InMemorySaver): - """This custom checkpointer is for verifying that a run's configurable - fields are merged with the previous checkpoint config for each step in - the run. This is the desired behavior. Because the checkpointer's (a)put() - method is called for each step, the implementation of this checkpointer - should produce a side effect that can be asserted. - """ - - def put( - self, - config: RunnableConfig, - checkpoint: Checkpoint, - metadata: CheckpointMetadata, - new_versions: ChannelVersions, - ) -> None: - """The implementation of put() merges config["configurable"] (a run's - configurable fields) with the metadata field. The state of the - checkpoint metadata can be asserted to confirm that the run's - configurable fields were merged with the previous checkpoint config. - """ - configurable = config["configurable"].copy() - - # remove checkpoint_id to make testing simpler - checkpoint_id = configurable.pop("checkpoint_id", None) - thread_id = config["configurable"]["thread_id"] - checkpoint_ns = config["configurable"]["checkpoint_ns"] - self.storage[thread_id][checkpoint_ns].update( - { - checkpoint["id"]: ( - self.serde.dumps_typed(checkpoint), - # merge configurable fields and metadata - self.serde.dumps_typed({**configurable, **metadata}), - checkpoint_id, - ) - } - ) - return { - "configurable": { - "thread_id": config["configurable"]["thread_id"], - "checkpoint_id": checkpoint["id"], - } - } - - async def aput( - self, - config: RunnableConfig, - checkpoint: Checkpoint, - metadata: CheckpointMetadata, - new_versions: ChannelVersions, - ) -> RunnableConfig: - return await asyncio.get_running_loop().run_in_executor( - None, self.put, config, checkpoint, metadata, new_versions - ) - - -class MemorySaverNoPending(InMemorySaver): - def get_tuple(self, config: RunnableConfig) -> Optional[CheckpointTuple]: - result = super().get_tuple(config) - if result: - return CheckpointTuple(result.config, result.checkpoint, result.metadata) - return result diff --git a/libs/prebuilt/tests/messages.py b/libs/prebuilt/tests/messages.py index ecc657a36..06f64bc7d 100644 --- a/libs/prebuilt/tests/messages.py +++ b/libs/prebuilt/tests/messages.py @@ -9,33 +9,11 @@ subclassed strings. from typing import Any -from langchain_core.documents import Document -from langchain_core.messages import AIMessage, AIMessageChunk, HumanMessage, ToolMessage +from langchain_core.messages import HumanMessage, ToolMessage from tests.any_str import AnyStr -def _AnyIdDocument(**kwargs: Any) -> Document: - """Create a document with an id field.""" - message = Document(**kwargs) - message.id = AnyStr() - return message - - -def _AnyIdAIMessage(**kwargs: Any) -> AIMessage: - """Create ai message with an any id field.""" - message = AIMessage(**kwargs) - message.id = AnyStr() - return message - - -def _AnyIdAIMessageChunk(**kwargs: Any) -> AIMessageChunk: - """Create ai message with an any id field.""" - message = AIMessageChunk(**kwargs) - message.id = AnyStr() - return message - - def _AnyIdHumanMessage(**kwargs: Any) -> HumanMessage: """Create a human message with an any id field.""" message = HumanMessage(**kwargs)