deer-flow/backend/tests/test_checkpoint_mode.py
Vanzeren 42baed8c8c
feat(checkpoint): dual-mode checkpoint storage with LangGraph DeltaChannel (#4292)
* 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>
2026-07-22 08:33:29 +08:00

287 lines
10 KiB
Python

import os
from types import SimpleNamespace
from unittest.mock import AsyncMock, MagicMock
import pytest
from deerflow.runtime.checkpoint_mode import (
CHECKPOINT_MODE_METADATA_KEY,
CheckpointModeMismatchError,
aensure_checkpoint_mode_compatible,
checkpoint_metadata_uses_delta,
ensure_checkpoint_mode_compatible,
inject_checkpoint_mode,
)
def test_process_mode_change_requires_restart(monkeypatch: pytest.MonkeyPatch) -> None:
from deerflow.runtime import checkpoint_mode
monkeypatch.setattr(checkpoint_mode, "_frozen_checkpoint_channel_mode", None)
assert checkpoint_mode.freeze_checkpoint_channel_mode("full") == "full"
with pytest.raises(checkpoint_mode.CheckpointModeReconfigurationError, match="restart"):
checkpoint_mode.freeze_checkpoint_channel_mode("delta")
def _config() -> dict:
return {"configurable": {"thread_id": "thread-1", "checkpoint_ns": ""}}
def test_inject_delta_mode_sets_internal_key_and_metadata_marker() -> None:
config = _config()
inject_checkpoint_mode(config, "delta")
assert config["configurable"]["__deerflow_checkpoint_channel_mode"] == "delta"
assert config["metadata"][CHECKPOINT_MODE_METADATA_KEY] == "delta"
def test_inject_full_mode_does_not_claim_delta_metadata() -> None:
config = _config()
inject_checkpoint_mode(config, "full")
assert config["configurable"]["__deerflow_checkpoint_channel_mode"] == "full"
assert CHECKPOINT_MODE_METADATA_KEY not in config.get("metadata", {})
def test_sync_full_mode_rejects_delta_marker() -> None:
saver = MagicMock()
saver.get_tuple.return_value = SimpleNamespace(
metadata={CHECKPOINT_MODE_METADATA_KEY: "delta"},
checkpoint={"channel_values": {}},
)
with pytest.raises(CheckpointModeMismatchError, match="requires delta mode"):
ensure_checkpoint_mode_compatible(saver, _config(), "full")
saver.put.assert_not_called()
@pytest.mark.anyio
async def test_async_full_mode_rejects_langgraph_delta_counters() -> None:
saver = AsyncMock()
saver.aget_tuple.return_value = SimpleNamespace(
metadata={"counters_since_delta_snapshot": {"messages": (1, 1)}},
checkpoint={"channel_values": {}},
)
with pytest.raises(CheckpointModeMismatchError, match="requires delta mode"):
await aensure_checkpoint_mode_compatible(saver, _config(), "full")
saver.aput.assert_not_awaited()
@pytest.mark.anyio
async def test_delta_mode_accepts_plain_full_checkpoint() -> None:
saver = AsyncMock()
saver.aget_tuple.return_value = SimpleNamespace(
metadata={},
checkpoint={"channel_values": {"messages": ["legacy"]}},
)
await aensure_checkpoint_mode_compatible(saver, _config(), "delta")
@pytest.mark.anyio
async def test_full_mode_accessor_rejects_real_delta_checkpoint_on_sqlite(tmp_path) -> None:
"""Fail-closed gate against a real saver, not mocks.
Seeds a delta checkpoint (marker + LangGraph delta counters) into a real
AsyncSqliteSaver, reopens the thread with a full-mode accessor, and
asserts every accessor surface raises before state is read or written.
This is the integration boundary the corruption-prevention design relies
on; the mock-based tests above cannot catch a wiring regression between
the accessor, the marker, and a real backend.
"""
from langchain_core.messages import HumanMessage
from langgraph.checkpoint.sqlite.aio import AsyncSqliteSaver
from langgraph.types import Overwrite
from deerflow.runtime.checkpoint_state import CheckpointStateAccessor, build_state_mutation_graph
config = _config()
async with AsyncSqliteSaver.from_conn_string(str(tmp_path / "gate.db")) as saver:
await saver.setup()
delta_accessor = CheckpointStateAccessor.bind(build_state_mutation_graph("seed", "delta"), saver, mode="delta")
await delta_accessor.aupdate(
config,
{"messages": Overwrite([HumanMessage(content="hi", id="h1")])},
as_node="seed",
)
# Sanity: the seeded head really is a delta checkpoint.
seeded = await saver.aget_tuple(config)
assert checkpoint_metadata_uses_delta(seeded.metadata)
full_accessor = CheckpointStateAccessor.bind(build_state_mutation_graph("read", "full"), saver, mode="full")
with pytest.raises(CheckpointModeMismatchError, match="requires delta mode"):
await full_accessor.aget(config)
with pytest.raises(CheckpointModeMismatchError, match="requires delta mode"):
await full_accessor.aupdate(config, {"title": "x"}, as_node="read")
with pytest.raises(CheckpointModeMismatchError, match="requires delta mode"):
await full_accessor.ahistory(config)
def test_yaml_mode_change_is_rejected_when_graph_is_reconstructed(tmp_path, monkeypatch: pytest.MonkeyPatch) -> None:
from deerflow.agents.lead_agent import agent as lead_agent
from deerflow.config.app_config import reset_app_config
from deerflow.runtime import checkpoint_mode
config_path = tmp_path / "config.yaml"
def write_config(mode: str) -> None:
config_path.write_text(
"\n".join(
(
"sandbox:",
" use: deerflow.sandbox.local.provider:LocalSandboxProvider",
"database:",
f" checkpoint_channel_mode: {mode}",
)
)
+ "\n",
encoding="utf-8",
)
write_config("full")
monkeypatch.setenv("DEER_FLOW_CONFIG_PATH", str(config_path))
monkeypatch.setattr(checkpoint_mode, "_frozen_checkpoint_channel_mode", None)
monkeypatch.setattr(lead_agent, "_make_lead_agent", lambda config, *, app_config: object())
reset_app_config()
try:
lead_agent.make_lead_agent({"configurable": {}})
write_config("delta")
future_mtime = config_path.stat().st_mtime + 5
os.utime(config_path, (future_mtime, future_mtime))
with pytest.raises(checkpoint_mode.CheckpointModeReconfigurationError, match="restart"):
lead_agent.make_lead_agent({"configurable": {}})
finally:
reset_app_config()
@pytest.mark.asyncio
async def test_gateway_runtime_rejects_mode_different_from_frozen_process(
monkeypatch: pytest.MonkeyPatch,
) -> None:
from contextlib import asynccontextmanager
from fastapi import FastAPI
from app.gateway.deps import langgraph_runtime
from deerflow.runtime import checkpoint_mode
@asynccontextmanager
async def resource(_config):
yield object()
async def noop(*_args, **_kwargs):
return None
monkeypatch.setattr(
checkpoint_mode,
"_frozen_checkpoint_channel_mode",
"full",
)
monkeypatch.setattr(
"deerflow.runtime.checkpointer.async_provider.make_checkpointer",
resource,
)
monkeypatch.setattr("deerflow.runtime.make_stream_bridge", resource)
monkeypatch.setattr("deerflow.runtime.make_store", resource)
monkeypatch.setattr(
"deerflow.persistence.engine.init_engine_from_config",
noop,
)
monkeypatch.setattr("deerflow.persistence.engine.close_engine", noop)
monkeypatch.setattr(
"deerflow.persistence.engine.get_session_factory",
lambda: None,
)
monkeypatch.setattr(
"deerflow.runtime.events.store.make_run_event_store",
lambda _config: object(),
)
monkeypatch.setattr(
"deerflow.persistence.thread_meta.make_thread_store",
lambda _session_factory, _store: object(),
)
startup_config = SimpleNamespace(
database=SimpleNamespace(
backend="memory",
checkpoint_channel_mode="delta",
),
run_events=None,
)
with pytest.raises(
checkpoint_mode.CheckpointModeReconfigurationError,
match="restart",
):
async with langgraph_runtime(FastAPI(), startup_config):
pass
def test_direct_langgraph_request_cannot_select_delta_in_full_process(
monkeypatch: pytest.MonkeyPatch,
) -> None:
from deerflow.agents.lead_agent import agent as lead_agent
from deerflow.config.app_config import AppConfig
from deerflow.runtime import checkpoint_mode
from deerflow.runtime.checkpoint_mode import INTERNAL_CHECKPOINT_MODE_KEY
app_config = AppConfig.model_validate(
{
"sandbox": {"use": "deerflow.sandbox.local.provider:LocalSandboxProvider"},
"database": {"checkpoint_channel_mode": "full"},
}
)
config = {
"configurable": {
INTERNAL_CHECKPOINT_MODE_KEY: "delta",
}
}
monkeypatch.setattr(checkpoint_mode, "_frozen_checkpoint_channel_mode", None)
monkeypatch.setattr(lead_agent, "get_app_config", lambda: app_config)
monkeypatch.setattr(
lead_agent,
"_make_lead_agent",
lambda config, *, app_config: object(),
)
lead_agent.make_lead_agent(config)
assert checkpoint_mode._frozen_checkpoint_channel_mode == "full"
assert config["configurable"][INTERNAL_CHECKPOINT_MODE_KEY] == "full"
assert CHECKPOINT_MODE_METADATA_KEY not in config["metadata"]
def test_gateway_runtime_app_config_can_supply_its_frozen_internal_mode(
monkeypatch: pytest.MonkeyPatch,
) -> None:
from deerflow.agents.lead_agent import agent as lead_agent
from deerflow.config.app_config import AppConfig
from deerflow.runtime import checkpoint_mode
from deerflow.runtime.checkpoint_mode import INTERNAL_CHECKPOINT_MODE_KEY
reloaded_app_config = AppConfig.model_validate(
{
"sandbox": {"use": "deerflow.sandbox.local.provider:LocalSandboxProvider"},
"database": {"checkpoint_channel_mode": "delta"},
}
)
config = {
"configurable": {
INTERNAL_CHECKPOINT_MODE_KEY: "full",
},
"context": {"app_config": reloaded_app_config},
}
monkeypatch.setattr(
checkpoint_mode,
"_frozen_checkpoint_channel_mode",
"full",
)
monkeypatch.setattr(
lead_agent,
"_make_lead_agent",
lambda config, *, app_config: object(),
)
lead_agent.make_lead_agent(config)
assert config["configurable"][INTERNAL_CHECKPOINT_MODE_KEY] == "full"
assert CHECKPOINT_MODE_METADATA_KEY not in config["metadata"]