mirror of
https://github.com/bytedance/deer-flow.git
synced 2026-07-27 16:37:55 +00:00
* feat(checkpoint): dual-mode checkpoint storage with LangGraph DeltaChannel
Add a restart-required database.checkpoint_channel_mode ("full" default,
"delta") that stores the messages channel via LangGraph 1.2 DeltaChannel,
cutting checkpoint storage from O(n^2) to O(n) for append-only history.
Existing full checkpoints seed delta state transparently; no data migration.
- config: mode schema + freeze-on-first-use with
CheckpointModeReconfigurationError; mode marker persisted in checkpoint
metadata; unsafe delta->full downgrade rejected fail-closed with
CheckpointModeMismatchError (run-level error, failed state read)
- state: delta message state schema; CheckpointStateAccessor centralizes
materialized reads for all consumers (threads API, branches,
regeneration, compaction, state updates, memory, goal workers)
- runtime: raw writers (run durations, interrupted title, thread goal)
parent their checkpoints to the checkpoint they derive from, preserving
delta ancestry; rollback forks the pre-run lineage through a state
mutation graph with Overwrite restores; InMemorySaver delta-history
override delegates to the base walk (fixes dropped first write after
migration, also present upstream)
- tests: conformance suite over {memory, sqlite, postgres} covering
migration replay, stable message IDs, storage shape and writer
preservation; conftest fixture isolates the frozen mode between tests;
stale config fakes refreshed
- ci: backend unit tests gain a postgres service
* fix(checkpoint): close materialization gaps in goal flow, guard public factory
- Route goal-continuation message reads through CheckpointStateAccessor:
raw channel_values reads see the delta sentinel in delta mode, which
disabled goal continuation (stand_down=no_durable_end_of_turn) after
durable assistant turns. Raw tuples remain for tuple-only metadata
(checkpoint id, pending_writes).
- Reject checkpoint_channel_mode='delta' + checkpointer in
create_deerflow_agent at construction: factory-built persisted graphs
bypass mode-marker injection and the fail-closed gate, reproducing
silent mixed-mode state loss. Delta without persistence stays allowed.
- Import the postgres saver lazily (pytest.importorskip in the fixture)
so the documented default install collects the suite; add a CI job
running pytest --collect-only on uv sync --group dev without extras.
- Fix test_checkpointer fallback test to patch get_app_config at its
use site (provider module), making it deterministic when a local
config.yaml selects a persistent backend.
* fix(gateway): preserve extension-owned channels in state mutations, bump config version
- build_state_mutation_graph / build_checkpoint_state_mutation_accessor
accept an explicit state_schema; branch and POST /state now compile the
mutation graph from the thread's effective schema
(graph_state_schema on the assistant graph). The base-ThreadState
fallback silently discarded channels contributed by custom
AgentMiddleware.state_schema on branch (data loss) and returned a
false-success 200 on POST /state.
- POST /state validates values keys against the mutation graph's
channels and rejects unknown fields with 422 instead of ignoring
them; reducer detection covers extension channels
(BinaryOperatorAggregate or DeltaChannel) so Overwrite replace
semantics work for middleware reducers in both modes.
- Endpoint regression: custom AgentMiddleware.state_schema value
survives branch, updates through POST /state, and an unknown field
receives 422.
- config_version 26 -> 27 for the new database.checkpoint_channel_mode
(example, Helm chart values + README, support-bundle fixture), so
existing installs get the outdated-config warning and
make config-upgrade merges the field; covered by a test driving the
real example file and the real config-upgrade script.
* fix(gateway): resolve assistant schema via one boundary, copy branch reducer values with Overwrite
GET /threads/{id}/state now resolves the thread's assistant_id through a
single reusable boundary (thread metadata -> assistant_id -> effective
graph), so channels contributed by a custom AgentMiddleware.state_schema
are materialized instead of dropped by the default lead schema. POST
/state uses the same boundary instead of resolving the schema ad hoc.
Branch writes wrap every copied reducer channel in Overwrite (derived
from the effective mutation graph: BinaryOperatorAggregate + DeltaChannel),
not just messages, so already-aggregated values are never re-merged.
Regression tests use a real AgentMiddleware.state_schema with a
non-identity reducer in both full and delta modes: GET /state returns the
extension value, POST /state replaces it, branch preserves it
byte-for-byte; the unknown-field 422 is a separate assertion.
* refactor(checkpoint): collapse read-path round-trips and ship dual-mode parity tests
Address review round 4 on PR #4292:
- Push ahistory/history limit through Pregel into checkpointer.alist
(SQL LIMIT) instead of materializing all rows and breaking in Python
- Fold the read-side mode-compat gate onto the returned snapshot's
metadata; only writes keep the pre-write tuple fetch (fail-closed)
- Cache factory-built accessor graphs per (assistant_id, mode) with
factory-identity revalidation; state reads no longer build a lead
agent per request
- get_thread: one snapshot fetch + one raw pending_writes fetch on the
resolved checkpoint (post-checkpoint __error__ writes never surface
in snapshot.tasks; verified empirically)
- DeerFlowClient.get_thread: single checkpointer.list walk collects
pending_writes per checkpoint instead of N get_tuple calls
- InMemorySaver delta-history patch: stand-down when the upstream
override disappears, try/except guard, validated-version warning,
guard tests
- make_lead_agent mode precedence: first freeze is owned by app_config
(client-supplied configurable key ignored); once frozen, injected
key/app_config must match or fail closed
- Rollback: lock in non-message channel restoration via fork
inheritance with a dedicated reducer-channel test
- Add tests/test_threads_checkpoint_mode.py and
tests/test_gateway_checkpoint_mode.py referenced by AGENTS.md and
the PR validation section: lifecycle parity (memory + sqlite),
per-step blob-count storage guard, gateway endpoint parity
Counted-saver tests pin checkpoint round-trips for aget/ahistory so
these regressions cannot silently return.
* fix(checkpoint): precise mode-mismatch HTTP mapping, gate E2E, and accessor resilience
- threads router: map CheckpointModeMismatchError to 409 (with cause and
thread id) and CheckpointModeReconfigurationError to 503 across all state
endpoints instead of swallowing both into a generic 500
- gate coverage: seed a real delta checkpoint into AsyncSqliteSaver and
assert aget/aupdate/ahistory fail closed; assert 409 at the HTTP boundary
through the real route stack
- rollback: compile the restore mutation graph with the thread's effective
state schema per the build_state_mutation_graph contract
- inheritance contract locks: rollback and manual compaction preserve
middleware-contributed channels via checkpoint fork cloning
- services: revalidate the accessor-graph cache against app_config identity
so config.yaml hot-reloads never serve a stale compiled graph
- services: degrade full-mode state reads to raw checkpointer reads when the
agent factory is unavailable (delta gate still applies; delta mode has no
fallback)
- deps: override websockets==16.0 (langgraph-sdk 0.4.2's <16 pin silently
downgraded 16.0 -> 15.0.1; pin is not grounded in any API incompatibility)
and bump the langchain lower bound to what the lockfile actually resolves
* fix(checkpoint): include anchor checkpoint in degraded history walk + cover get_thread
- _RawCheckpointReadAccessor.ahistory: alist(before=...) is exclusive while
pregel's get_state_history treats config.checkpoint_id as the inclusive
start; fetch the anchor explicitly so both read paths paginate identically
- extend the degraded-path gateway test: GET /thread returns raw values, and
POST /history with before starts at the anchor checkpoint
* fix(gateway): preserve degraded checkpoint timestamps
* fix(gateway): harden degraded checkpoint access
* fix(gateway): resolve assistants for checkpoint reads
---------
Co-authored-by: Willem Jiang <willem.jiang@gmail.com>
307 lines
12 KiB
Python
307 lines
12 KiB
Python
from __future__ import annotations
|
|
|
|
from copy import deepcopy
|
|
from types import SimpleNamespace
|
|
from typing import Annotated, Any, TypedDict
|
|
|
|
import pytest
|
|
from langchain_core.messages import AnyMessage
|
|
from langgraph.checkpoint.memory import InMemorySaver
|
|
from langgraph.graph.message import add_messages
|
|
|
|
from deerflow.runtime import CheckpointStateAccessor
|
|
from deerflow.runtime.checkpoint_mode import CHECKPOINT_MODE_METADATA_KEY, INTERNAL_CHECKPOINT_MODE_KEY
|
|
|
|
|
|
class FakeCheckpointer:
|
|
def __init__(self) -> None:
|
|
self.sync_configs: list[dict[str, Any]] = []
|
|
self.async_configs: list[dict[str, Any]] = []
|
|
|
|
def get_tuple(self, config: dict[str, Any]) -> None:
|
|
self.sync_configs.append(config)
|
|
return None
|
|
|
|
async def aget_tuple(self, config: dict[str, Any]) -> None:
|
|
self.async_configs.append(config)
|
|
return None
|
|
|
|
|
|
class FakeGraph:
|
|
def __init__(self) -> None:
|
|
self.checkpointer: Any = None
|
|
self.store: Any = None
|
|
self.calls: list[tuple[Any, ...]] = []
|
|
self.sync_history_yields = 0
|
|
self.async_history_yields = 0
|
|
|
|
def get_state(self, config: dict[str, Any]) -> SimpleNamespace:
|
|
self.calls.append(("get", config))
|
|
return SimpleNamespace(values={"messages": ["sync"]})
|
|
|
|
def get_state_history(self, config: dict[str, Any], *, limit: int | None = None):
|
|
self.calls.append(("history", config, limit))
|
|
for index in range(4):
|
|
if limit is not None and self.sync_history_yields >= limit:
|
|
return
|
|
self.sync_history_yields += 1
|
|
yield SimpleNamespace(values={"index": index})
|
|
|
|
def update_state(self, config: dict[str, Any], values: dict[str, Any], *, as_node: str | None = None) -> dict[str, Any]:
|
|
self.calls.append(("update", config, values, as_node))
|
|
return {"updated": values, "as_node": as_node}
|
|
|
|
async def aget_state(self, config: dict[str, Any]) -> SimpleNamespace:
|
|
self.calls.append(("aget", config))
|
|
return SimpleNamespace(values={"messages": ["async"]})
|
|
|
|
async def aget_state_history(self, config: dict[str, Any], *, limit: int | None = None):
|
|
self.calls.append(("ahistory", config, limit))
|
|
for index in range(4):
|
|
if limit is not None and self.async_history_yields >= limit:
|
|
return
|
|
self.async_history_yields += 1
|
|
yield SimpleNamespace(values={"index": index})
|
|
|
|
async def aupdate_state(
|
|
self,
|
|
config: dict[str, Any],
|
|
values: dict[str, Any],
|
|
*,
|
|
as_node: str | None = None,
|
|
) -> dict[str, Any]:
|
|
self.calls.append(("aupdate", config, values, as_node))
|
|
return {"updated": values, "as_node": as_node}
|
|
|
|
|
|
def _assert_delta_config_is_copied(original: dict[str, Any], forwarded: dict[str, Any]) -> None:
|
|
assert forwarded is not original
|
|
assert forwarded["configurable"] is not original["configurable"]
|
|
assert forwarded["metadata"] is not original["metadata"]
|
|
assert forwarded["configurable"][INTERNAL_CHECKPOINT_MODE_KEY] == "delta"
|
|
assert forwarded["metadata"][CHECKPOINT_MODE_METADATA_KEY] == "delta"
|
|
|
|
|
|
def test_sync_accessor_binds_persistence_guards_operations_and_preserves_input() -> None:
|
|
graph = FakeGraph()
|
|
saver = FakeCheckpointer()
|
|
store = object()
|
|
accessor = CheckpointStateAccessor.bind(graph, saver, store=store, mode="delta")
|
|
config = {
|
|
"configurable": {"thread_id": "thread-sync", "checkpoint_ns": ""},
|
|
"metadata": {"caller": "test"},
|
|
"tags": ["preserved"],
|
|
}
|
|
original = deepcopy(config)
|
|
|
|
snapshot = accessor.get(config)
|
|
history = accessor.history(config, limit=2)
|
|
update = accessor.update(config, {"messages": ["changed"]}, as_node="tools")
|
|
|
|
assert snapshot.values == {"messages": ["sync"]}
|
|
assert [item.values for item in history] == [{"index": 0}, {"index": 1}]
|
|
assert graph.sync_history_yields == 2
|
|
assert update == {"updated": {"messages": ["changed"]}, "as_node": "tools"}
|
|
assert graph.checkpointer is saver
|
|
assert graph.store is store
|
|
assert config == original
|
|
for call in graph.calls:
|
|
_assert_delta_config_is_copied(config, call[1])
|
|
assert graph.calls[-1][2:] == ({"messages": ["changed"]}, "tools")
|
|
|
|
|
|
@pytest.mark.anyio
|
|
async def test_async_accessor_binds_persistence_guards_operations_and_preserves_input() -> None:
|
|
graph = FakeGraph()
|
|
saver = FakeCheckpointer()
|
|
store = object()
|
|
accessor = CheckpointStateAccessor.bind(graph, saver, store=store, mode="delta")
|
|
config = {
|
|
"configurable": {"thread_id": "thread-async", "checkpoint_ns": ""},
|
|
"metadata": {"caller": "test"},
|
|
"tags": ["preserved"],
|
|
}
|
|
original = deepcopy(config)
|
|
|
|
snapshot = await accessor.aget(config)
|
|
history = await accessor.ahistory(config, limit=2)
|
|
update = await accessor.aupdate(config, {"messages": ["changed"]}, as_node="agent")
|
|
|
|
assert snapshot.values == {"messages": ["async"]}
|
|
assert [item.values for item in history] == [{"index": 0}, {"index": 1}]
|
|
assert graph.async_history_yields == 2
|
|
assert update == {"updated": {"messages": ["changed"]}, "as_node": "agent"}
|
|
assert graph.checkpointer is saver
|
|
assert graph.store is store
|
|
assert config == original
|
|
for call in graph.calls:
|
|
_assert_delta_config_is_copied(config, call[1])
|
|
assert graph.calls[-1][2:] == ({"messages": ["changed"]}, "agent")
|
|
|
|
|
|
def test_sync_history_zero_limit_guards_without_consuming_a_snapshot() -> None:
|
|
graph = FakeGraph()
|
|
saver = FakeCheckpointer()
|
|
accessor = CheckpointStateAccessor.bind(graph, saver)
|
|
config = {"configurable": {"thread_id": "thread-sync-zero"}}
|
|
|
|
assert accessor.history(config, limit=0) == []
|
|
# The read-side gate folds onto the returned snapshot: no standalone tuple fetch.
|
|
assert len(saver.sync_configs) == 0
|
|
assert graph.sync_history_yields == 0
|
|
|
|
|
|
@pytest.mark.anyio
|
|
async def test_async_history_zero_limit_guards_without_consuming_a_snapshot() -> None:
|
|
graph = FakeGraph()
|
|
saver = FakeCheckpointer()
|
|
accessor = CheckpointStateAccessor.bind(graph, saver)
|
|
config = {"configurable": {"thread_id": "thread-async-zero"}}
|
|
|
|
assert await accessor.ahistory(config, limit=0) == []
|
|
assert len(saver.async_configs) == 0
|
|
assert graph.async_history_yields == 0
|
|
|
|
|
|
@pytest.mark.anyio
|
|
async def test_full_accessor_gates_writes_and_checks_reads_on_the_returned_snapshot() -> None:
|
|
"""Full mode: only writes pay the pre-write tuple fetch; reads check the
|
|
marker on the materialized snapshot's metadata instead."""
|
|
graph = FakeGraph()
|
|
saver = FakeCheckpointer()
|
|
accessor = CheckpointStateAccessor.bind(graph, saver)
|
|
config = {"configurable": {"thread_id": "thread-full"}}
|
|
|
|
accessor.get(config)
|
|
accessor.history(config, limit=1)
|
|
accessor.update(config, {}, as_node=None)
|
|
await accessor.aget(config)
|
|
await accessor.ahistory(config, limit=1)
|
|
await accessor.aupdate(config, {}, as_node=None)
|
|
|
|
assert len(saver.sync_configs) == 1
|
|
assert len(saver.async_configs) == 1
|
|
for prepared in [*saver.sync_configs, *saver.async_configs]:
|
|
assert prepared["configurable"][INTERNAL_CHECKPOINT_MODE_KEY] == "full"
|
|
assert CHECKPOINT_MODE_METADATA_KEY not in prepared["metadata"]
|
|
assert config == {"configurable": {"thread_id": "thread-full"}}
|
|
|
|
|
|
@pytest.mark.anyio
|
|
async def test_full_accessor_raises_when_the_returned_snapshot_is_delta_marked() -> None:
|
|
"""A full-mode accessor must fail closed on a delta checkpoint, detected
|
|
via the returned snapshot metadata (no pre-read tuple fetch)."""
|
|
from deerflow.runtime.checkpoint_mode import CheckpointModeMismatchError
|
|
|
|
graph = FakeGraph()
|
|
saver = FakeCheckpointer()
|
|
accessor = CheckpointStateAccessor.bind(graph, saver, mode="full")
|
|
config = {"configurable": {"thread_id": "thread-delta-marked"}}
|
|
graph.get_state = lambda _config: SimpleNamespace(values={}, metadata={CHECKPOINT_MODE_METADATA_KEY: "delta"})
|
|
|
|
with pytest.raises(CheckpointModeMismatchError, match="requires delta mode"):
|
|
accessor.get(config)
|
|
assert len(saver.sync_configs) == 0
|
|
|
|
async def _delta_history(_config, *, limit=None):
|
|
yield SimpleNamespace(values={"index": 0}, metadata={})
|
|
yield SimpleNamespace(values={"index": 1}, metadata={CHECKPOINT_MODE_METADATA_KEY: "delta"})
|
|
|
|
graph.aget_state_history = _delta_history
|
|
with pytest.raises(CheckpointModeMismatchError, match="requires delta mode"):
|
|
await accessor.ahistory(config)
|
|
assert len(saver.async_configs) == 0
|
|
|
|
|
|
@pytest.mark.anyio
|
|
async def test_full_accessor_writes_still_check_compatibility_before_writing() -> None:
|
|
"""Writes cannot be un-applied, so the pre-write tuple fetch stays."""
|
|
from deerflow.runtime.checkpoint_mode import CheckpointModeMismatchError
|
|
|
|
graph = FakeGraph()
|
|
|
|
class DeltaMarkedSaver(FakeCheckpointer):
|
|
async def aget_tuple(self, config):
|
|
self.async_configs.append(config)
|
|
return SimpleNamespace(metadata={CHECKPOINT_MODE_METADATA_KEY: "delta"})
|
|
|
|
saver = DeltaMarkedSaver()
|
|
accessor = CheckpointStateAccessor.bind(graph, saver, mode="full")
|
|
config = {"configurable": {"thread_id": "thread-delta-write"}}
|
|
|
|
with pytest.raises(CheckpointModeMismatchError, match="requires delta mode"):
|
|
await accessor.aupdate(config, {"messages": []}, as_node=None)
|
|
assert len(saver.async_configs) == 1
|
|
assert graph.calls == []
|
|
|
|
|
|
class _CountingSaver(InMemorySaver):
|
|
"""InMemorySaver that counts checkpoint round-trips."""
|
|
|
|
def __init__(self) -> None:
|
|
super().__init__()
|
|
self.aget_tuple_calls = 0
|
|
self.alist_limits: list[int | None] = []
|
|
|
|
async def aget_tuple(self, config):
|
|
self.aget_tuple_calls += 1
|
|
return await super().aget_tuple(config)
|
|
|
|
async def alist(self, config, *, filter=None, before=None, limit=None):
|
|
self.alist_limits.append(limit)
|
|
async for item in super().alist(config, filter=filter, before=before, limit=limit):
|
|
yield item
|
|
|
|
|
|
def _build_counting_graph(saver):
|
|
from langchain_core.messages import HumanMessage
|
|
from langgraph.graph import StateGraph
|
|
|
|
class _State(TypedDict):
|
|
messages: Annotated[list[AnyMessage], add_messages]
|
|
|
|
async def _append(state):
|
|
return {"messages": [HumanMessage(content=f"turn-{len(state.get('messages') or [])}")]}
|
|
|
|
builder = StateGraph(_State)
|
|
builder.add_node("append", _append)
|
|
builder.set_entry_point("append")
|
|
builder.set_finish_point("append")
|
|
return builder.compile(checkpointer=saver)
|
|
|
|
|
|
@pytest.mark.anyio
|
|
async def test_ahistory_pushes_limit_into_alist_and_reads_each_snapshot_once() -> None:
|
|
"""The history limit must reach ``checkpointer.alist`` (SQL LIMIT), and the
|
|
read-side compat gate must not add a standalone tuple fetch per call."""
|
|
saver = _CountingSaver()
|
|
graph = _build_counting_graph(saver)
|
|
accessor = CheckpointStateAccessor.bind(graph, saver, mode="full")
|
|
config = {"configurable": {"thread_id": "thread-counted"}}
|
|
for _ in range(4):
|
|
await graph.ainvoke({}, config)
|
|
|
|
saver.aget_tuple_calls = 0
|
|
history = await accessor.ahistory(config, limit=2)
|
|
|
|
assert len(history) == 2
|
|
assert saver.alist_limits[-1] == 2
|
|
# get_state_history walks via alist only; no aget_tuple in the read path.
|
|
assert saver.aget_tuple_calls == 0
|
|
|
|
|
|
@pytest.mark.anyio
|
|
async def test_aget_fetches_the_checkpoint_exactly_once_in_full_mode() -> None:
|
|
"""Full-mode reads: one fetch inside aget_state; the folded gate adds none."""
|
|
saver = _CountingSaver()
|
|
graph = _build_counting_graph(saver)
|
|
accessor = CheckpointStateAccessor.bind(graph, saver, mode="full")
|
|
config = {"configurable": {"thread_id": "thread-counted-get"}}
|
|
await graph.ainvoke({}, config)
|
|
|
|
saver.aget_tuple_calls = 0
|
|
snapshot = await accessor.aget(config)
|
|
|
|
assert [message.content for message in snapshot.values["messages"]] == ["turn-0"]
|
|
assert saver.aget_tuple_calls == 1
|