mirror of
https://github.com/bytedance/deer-flow.git
synced 2026-09-11 14:38:38 +00:00
* feat(extensions): let an out-of-tree extension observe what the agent did
DeerFlow's extension system can contribute middleware, services and routes,
but an extension cannot answer basic questions about a run without reaching
into host internals. Several of the facts it would need are destroyed by the
operations that produce them:
* The middleware chain injects and rewrites a lot of context — date
reminders, recalled memory, compaction summaries, durable-context data,
image payloads, activated skill bodies. Downstream, none of it is
attributable: at the model-call boundary an injected HumanMessage is
indistinguishable from the user's own, and anything wanting to tell them
apart has to pattern-match prompt wording, which breaks on the next copy
edit.
* Two runs of "the same agent" are only comparable if the chain enforced the
same limits, prompts and thresholds. Recovering that from outside means
reading private attributes and guessing which of them change behaviour — a
guess that rots silently as middlewares gain fields.
* The lead-agent factory resolves a model after runtime overrides, renders a
prompt, filters tools through authorization and composes a stack, all
inside one synchronous call, and none of it survives: a middleware sees its
neighbours but not the prompt, the run worker sees a graph but not what
went into it.
* Summarization is destructive by design. N messages leave the context and
one summary enters it; afterwards only the summary exists, so "which
messages became this?" is not reconstructible.
This adds seven neutral facilities so those facts are recorded where they are
still true, and releases the contract package as 0.2.0.
Message provenance
Producers stamp `deerflow_content_kind` / `deerflow_producer_kind` onto the
messages they inject or rewrite. Stamping is unconditional — a fact whose
presence depends on whether an observer is installed is not a fact — and the
keys are server-owned, so provenance cannot be forged from a request.
Middleware self-description
Twelve middlewares declare their own behaviour-affecting parameters through
a duck-typed `release_policy_parameters()`. Long text is hashed rather than
embedded: a declaration is an identity, not a copy of the prompt.
Agent assembly descriptor
`assemble_lead_agent()` returns the graph plus a descriptor whose fingerprint
answers "did anything about this agent change between these two runs?".
`make_lead_agent()` keeps its graph-only signature — it is the LangGraph
Server ABI declared in langgraph.json. Tools and skills are sorted before
hashing because their assembly order is incidental; middlewares are not,
because stack order decides what wraps what. Host build identity is reported
but excluded from the fingerprint, so a redeploy does not invalidate every
agent's identity.
Context compaction observation
Summarization emits the content hashes of the messages it is about to remove
joined to the summary that replaced them. Content is the only identity
available at that seam: the summary does not become a message, and what later
projects it into a request renders it bounded and escaped rather than
verbatim.
Neutral policy, transform and MCP-source facts
Guardrail decisions are published to runtime context under a `__`-prefixed
key; result-rewriting middlewares append a declared, ordered transform trail;
MCP tools carry their credential-free logical origin.
Extension route identity
Contributed routes are session-authenticated and cannot opt out, but
"logged in" and "administrator" are different questions. Extensions get a
neutral projection of the caller rather than the host's auth context, and
`require_admin` fails closed when identity cannot be determined.
Extension-owned tables
An extension that persists data owns its own MetaData and migration chain, so
its tables are absent from Base.metadata and `alembic revision --autogenerate`
proposes dropping them. Extensions declare a table prefix, which is rejected
at registration if it would shadow a host table.
The contract package stays dependency-free and imports no host code; every new
Protocol method has a default so later additions remain additive. The loader's
pre-1.0 rule requires an exact major.minor match, so extensions written against
0.1 are now refused at startup with an actionable install hint rather than
loading into a host that implements a different surface.
uv.lock records the contract package's new version, so `uv sync --locked` still
resolves on a fresh checkout.
* fix(backend): sort gateway service imports
239 lines
8.8 KiB
Python
239 lines
8.8 KiB
Python
"""Harness tests for the production-shaped checkpoint benchmark."""
|
|
|
|
from __future__ import annotations
|
|
|
|
import importlib.util
|
|
import sys
|
|
from pathlib import Path
|
|
|
|
import pytest
|
|
|
|
|
|
def _load_module():
|
|
path = Path(__file__).resolve().parents[1] / "scripts/benchmark/checkpoint/bench_production.py"
|
|
spec = importlib.util.spec_from_file_location("bench_production", path)
|
|
assert spec is not None
|
|
module = importlib.util.module_from_spec(spec)
|
|
assert spec.loader is not None
|
|
sys.modules[spec.name] = module
|
|
spec.loader.exec_module(module)
|
|
return module
|
|
|
|
|
|
bench = _load_module()
|
|
|
|
|
|
def test_expand_cases_sweeps_frequency_for_delta_only() -> None:
|
|
cases = bench.expand_cases(
|
|
modes=["full", "delta"],
|
|
turn_counts=[10],
|
|
payload_bytes=[128],
|
|
snapshot_frequencies=[10, 50],
|
|
repetitions=1,
|
|
)
|
|
delta = [c for c in cases if c.mode == "delta"]
|
|
full = [c for c in cases if c.mode == "full"]
|
|
assert sorted(c.snapshot_frequency for c in delta) == [10, 50]
|
|
assert [c.snapshot_frequency for c in full] == [None]
|
|
assert all(c.history_limits == (10, 50, 200) for c in cases)
|
|
|
|
|
|
def test_expand_cases_alternates_mode_order() -> None:
|
|
cases = bench.expand_cases(
|
|
modes=["full", "delta"],
|
|
turn_counts=[10, 100],
|
|
payload_bytes=[128],
|
|
snapshot_frequencies=[10],
|
|
repetitions=2,
|
|
seed=1,
|
|
)
|
|
grouped_modes: dict[tuple[int, int], list[str]] = {}
|
|
for case in cases:
|
|
grouped_modes.setdefault((case.repetition, case.turns), []).append(case.mode)
|
|
|
|
mode_orders = list(grouped_modes.values())
|
|
assert all(set(order) == {"full", "delta"} for order in mode_orders)
|
|
assert all(current == list(reversed(previous)) for previous, current in zip(mode_orders, mode_orders[1:], strict=False))
|
|
|
|
|
|
def test_case_rejects_nonpositive_turns() -> None:
|
|
with pytest.raises(ValueError, match="turns"):
|
|
bench.ProductionCase(
|
|
mode="full",
|
|
turns=0,
|
|
payload_bytes=128,
|
|
snapshot_frequency=None,
|
|
history_limits=(10,),
|
|
read_repetitions=5,
|
|
repetition=0,
|
|
seed=1,
|
|
)
|
|
|
|
|
|
@pytest.mark.parametrize("turns", [1, 2])
|
|
def test_case_rejects_turns_consumed_by_warmup(turns: int) -> None:
|
|
with pytest.raises(ValueError, match="warm-up"):
|
|
bench.ProductionCase(
|
|
mode="full",
|
|
turns=turns,
|
|
payload_bytes=128,
|
|
snapshot_frequency=None,
|
|
history_limits=(10,),
|
|
read_repetitions=5,
|
|
repetition=0,
|
|
seed=1,
|
|
)
|
|
|
|
|
|
def test_case_rejects_frequency_on_full_mode() -> None:
|
|
with pytest.raises(ValueError, match="snapshot_frequency"):
|
|
bench.ProductionCase(
|
|
mode="full",
|
|
turns=10,
|
|
payload_bytes=128,
|
|
snapshot_frequency=10,
|
|
history_limits=(10,),
|
|
read_repetitions=5,
|
|
repetition=0,
|
|
seed=1,
|
|
)
|
|
|
|
|
|
def test_cross_mode_digest_gate_fails_both_rows_on_mismatch() -> None:
|
|
base = {"turns": 10, "payload_bytes": 128, "repetition": 0, "success": True, "seed_content_sha256": "a", "state_wire_sha256": "b", "history_wire_sha256": "c"}
|
|
full = {**base, "mode": "full", "snapshot_frequency": None}
|
|
delta = {**base, "mode": "delta", "snapshot_frequency": 10}
|
|
rows = [dict(full), dict(delta)]
|
|
bench.validate_cross_mode_rows(rows)
|
|
assert all(r["success"] for r in rows)
|
|
|
|
delta_bad = {**delta, "seed_content_sha256": "DIFFERENT"}
|
|
rows = [dict(full), delta_bad]
|
|
bench.validate_cross_mode_rows(rows)
|
|
assert not any(r["success"] for r in rows)
|
|
assert all(r["error"] == "cross-mode materialized state mismatch" for r in rows)
|
|
|
|
|
|
def test_cross_mode_gate_tolerates_missing_pair() -> None:
|
|
row = {"mode": "full", "snapshot_frequency": None, "turns": 10, "payload_bytes": 128, "repetition": 0, "success": True, "seed_content_sha256": "a", "state_wire_sha256": "b", "history_wire_sha256": "c"}
|
|
rows = [dict(row)]
|
|
bench.validate_cross_mode_rows(rows)
|
|
assert rows[0]["success"] is True
|
|
|
|
|
|
def test_scripted_model_is_deterministic_across_instances() -> None:
|
|
from langchain_core.messages import HumanMessage
|
|
|
|
first = bench._ScriptedBenchModel(payload_bytes=16)
|
|
second = bench._ScriptedBenchModel(payload_bytes=16)
|
|
for _ in range(3):
|
|
a = first.invoke([HumanMessage(content="hi", id="h0")])
|
|
b = second.invoke([HumanMessage(content="hi", id="h0")])
|
|
assert a.id == b.id and a.content == b.content and len(a.content) == 16
|
|
|
|
|
|
def test_timing_saver_records_cumulative_ms() -> None:
|
|
import asyncio
|
|
|
|
from langgraph.checkpoint.base import empty_checkpoint
|
|
from langgraph.checkpoint.memory import InMemorySaver
|
|
|
|
timing = bench._TimingSaver(InMemorySaver())
|
|
config = {"configurable": {"thread_id": "t", "checkpoint_ns": "", "checkpoint_id": "c1"}}
|
|
|
|
async def go() -> None:
|
|
await timing.aput(config, empty_checkpoint(), {"source": "input", "step": 0, "writes": {}}, {})
|
|
await timing.aput_writes(config, [("ch", "v")], "task")
|
|
|
|
asyncio.run(go())
|
|
assert timing.timings_ms["aput"] >= 0
|
|
assert timing.timings_ms["aput_writes"] >= 0
|
|
assert timing._saver is not None
|
|
|
|
|
|
def _reset_checkpoint_freezes(monkeypatch: pytest.MonkeyPatch) -> None:
|
|
from deerflow.config.app_config import reset_app_config
|
|
from deerflow.runtime import checkpoint_mode
|
|
|
|
reset_app_config()
|
|
monkeypatch.setattr(checkpoint_mode, "_frozen_checkpoint_channel_mode", None)
|
|
monkeypatch.setattr(checkpoint_mode, "_frozen_checkpoint_snapshot_frequency", None)
|
|
|
|
|
|
@pytest.mark.parametrize("mode,frequency", [("full", None), ("delta", 10)])
|
|
def test_run_case_succeeds_end_to_end_small(tmp_path, monkeypatch, mode, frequency) -> None:
|
|
_reset_checkpoint_freezes(monkeypatch)
|
|
from app.gateway import services as gateway_services
|
|
from deerflow.config.app_config import reset_app_config
|
|
|
|
gateway_services._state_accessor_graph_cache.clear()
|
|
case = bench.ProductionCase(
|
|
mode=mode,
|
|
turns=3,
|
|
payload_bytes=32,
|
|
snapshot_frequency=frequency,
|
|
history_limits=(2,),
|
|
read_repetitions=2,
|
|
repetition=0,
|
|
seed=1,
|
|
)
|
|
row = bench._run_case(case, work_dir=tmp_path)
|
|
assert row["success"], row.get("error")
|
|
assert row["message_count"] > 0
|
|
assert row["seed_content_sha256"]
|
|
assert row["state_warm_p50_ms"] >= 0
|
|
# Wire digests must reflect real messages: a duck-typed checkpointer on
|
|
# app.state silently materializes delta channels as empty (Pregel gates
|
|
# replay behind isinstance(checkpointer, BaseCheckpointSaver)), which
|
|
# otherwise passes every assertion above vacuously.
|
|
empty_wire = bench._wire_messages_digest([])
|
|
assert row["state_wire_sha256"] != empty_wire
|
|
assert row["history_wire_sha256"] != bench._combined_digest([empty_wire])
|
|
assert row["wal_bytes"] > 0
|
|
assert row["shm_bytes"] > 0
|
|
# Write cost is merged busy time over concurrent write tasks: it must not
|
|
# exceed the turn wall clock the way a naive latency sum can.
|
|
assert row["checkpoint_write_p50_ms"] <= row["run_turn_p50_ms"]
|
|
gateway_services._state_accessor_graph_cache.clear()
|
|
reset_app_config()
|
|
|
|
|
|
def test_run_case_fails_when_warm_cache_is_not_hit(tmp_path, monkeypatch) -> None:
|
|
"""The cold/warm contract is structural: if the accessor cache never holds,
|
|
warm samples silently measure the cold path — the case row must fail."""
|
|
_reset_checkpoint_freezes(monkeypatch)
|
|
from app.gateway import services as gateway_services
|
|
from deerflow.config.app_config import reset_app_config
|
|
|
|
gateway_services._state_accessor_graph_cache.clear()
|
|
# Bypass the cache entirely: every accessor resolution rebuilds the graph,
|
|
# so warm reads trip the contract assertion. The factory returns a
|
|
# LeadAgentAssembly, so this stub unwraps it exactly as the real accessor
|
|
# does — the point here is the missing cache, not a different return shape.
|
|
monkeypatch.setattr(
|
|
gateway_services,
|
|
"_state_accessor_graph",
|
|
lambda agent_factory, assistant_id, mode, snapshot_frequency, config: agent_factory(config=config).graph,
|
|
)
|
|
case = bench.ProductionCase(
|
|
mode="full",
|
|
turns=3,
|
|
payload_bytes=32,
|
|
snapshot_frequency=None,
|
|
history_limits=(2,),
|
|
read_repetitions=2,
|
|
repetition=0,
|
|
seed=1,
|
|
)
|
|
row = bench._run_case(case, work_dir=tmp_path)
|
|
assert not row["success"]
|
|
assert "cache was not hit" in row["error"]
|
|
gateway_services._state_accessor_graph_cache.clear()
|
|
reset_app_config()
|
|
|
|
|
|
def test_merged_busy_ms_unions_overlapping_intervals() -> None:
|
|
intervals = [("aput", 0.0, 10.0), ("aput_writes", 5.0, 12.0), ("aput", 20.0, 25.0)]
|
|
assert bench._merged_busy_ms(iter(intervals)) == 17.0
|
|
assert bench._merged_busy_ms(iter([])) == 0.0
|