mirror of
https://github.com/bytedance/deer-flow.git
synced 2026-11-28 17:50:35 +00:00
feat(subagents): add read-only SQLite history inventory (#8520)
* feat(subagents): add read-only SQLite history inventory * docs: explain SQLite WAL sidecars for history inventory --------- Co-authored-by: Willem Jiang <willem.jiang@gmail.com>
This commit is contained in:
parent
12ca6379a9
commit
ecfe8264ea
@ -116,7 +116,7 @@ Each guide is the full reference for its topic. Open the one you need.
|
||||
| boxd machines, bounded output copies and cleanup retries | [boxd sandbox provider](backend/packages/harness/deerflow/community/boxd_sandbox/README.md) |
|
||||
| Skills, built-in tools, script workflows, Claude Code integration | [Skills & Tools](docs/guide/skills-and-tools.md) |
|
||||
| MCP servers | [MCP Server](docs/guide/mcp.md) |
|
||||
| Sub-agents, task delegation and optional SQLite checkpoint history | [Sub-Agents](docs/guide/subagents.md), [Tool restrictions](docs/guide/subagents.md#tool-restrictions) |
|
||||
| Sub-agents, task delegation and optional SQLite checkpoint history | [Sub-Agents](docs/guide/subagents.md), [Inspect one thread's child history](docs/guide/subagents.md#inspect-one-threads-child-history), [Tool restrictions](docs/guide/subagents.md#tool-restrictions) |
|
||||
| Agent teams, SQLite/PostgreSQL persistence and shutdown behavior | [Agent teams extension](examples/deerflow-extension-agent-teams/README.md) |
|
||||
| Long-term memory | [Long-Term Memory](docs/guide/memory.md) |
|
||||
| Session goals, context compaction, todo counters, task notes, evidence-based decisions | [Context, Goals and Agent Decisions](docs/guide/context.md) |
|
||||
|
||||
@ -24,6 +24,9 @@ Read the guide for an area before you change it.
|
||||
| Gateway, routers, IM channels | [gateway](app/gateway/AGENTS.md), [routers](app/gateway/routers/AGENTS.md), [channels](app/channels/AGENTS.md) |
|
||||
| Tests, benchmarks | [tests](tests/AGENTS.md), [benchmarks](scripts/benchmark/AGENTS.md) |
|
||||
|
||||
Keep the [child history inventory](../docs/guide/subagents.md#inspect-one-threads-child-history)
|
||||
read-only. Read identities and both row counts from one SQLite snapshot.
|
||||
|
||||
## Verify
|
||||
|
||||
```bash
|
||||
|
||||
100
backend/scripts/subagent_history_inventory.py
Normal file
100
backend/scripts/subagent_history_inventory.py
Normal file
@ -0,0 +1,100 @@
|
||||
"""Inspect ordinary task() checkpoint histories in one file-backed SQLite thread."""
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import sqlite3
|
||||
from contextlib import closing
|
||||
from itertools import groupby
|
||||
from operator import itemgetter
|
||||
from pathlib import Path
|
||||
|
||||
# Both aggregates belong to the same SELECT, so a WAL commit cannot split the
|
||||
# snapshot. Group each table independently: joining individual writes to
|
||||
# checkpoints would multiply counts and omit namespaces with writes alone.
|
||||
_INVENTORY = """
|
||||
WITH scoped AS (
|
||||
SELECT checkpoint_ns,
|
||||
CASE WHEN json_valid(CAST(metadata AS TEXT)) THEN CAST(metadata AS TEXT) END AS meta
|
||||
FROM checkpoints
|
||||
WHERE thread_id = :thread AND checkpoint_ns GLOB :pattern
|
||||
)
|
||||
SELECT checkpoint_ns,
|
||||
CASE WHEN json_type(meta, '$.deerflow_subagent_execution_id') = 'text'
|
||||
THEN CAST(json_extract(meta, '$.deerflow_subagent_execution_id') AS BLOB) END AS execution_id,
|
||||
CASE WHEN json_type(meta, '$.deerflow_parent_run_id') = 'text'
|
||||
THEN CAST(json_extract(meta, '$.deerflow_parent_run_id') AS BLOB) END AS parent_run_id,
|
||||
count(*) AS checkpoint_rows, 0 AS write_rows
|
||||
FROM scoped
|
||||
GROUP BY checkpoint_ns, execution_id, parent_run_id
|
||||
UNION ALL
|
||||
SELECT checkpoint_ns, NULL, NULL, 0, count(*)
|
||||
FROM writes
|
||||
WHERE thread_id = :thread AND checkpoint_ns GLOB :pattern
|
||||
GROUP BY checkpoint_ns
|
||||
ORDER BY checkpoint_ns
|
||||
"""
|
||||
|
||||
_CHILD_PREFIX = "deerflow_subagent:"
|
||||
|
||||
|
||||
def _decode_id(value: bytes | None) -> str | None:
|
||||
# SQLite JSON strings can contain invalid UTF-8, including lone surrogates.
|
||||
try:
|
||||
return value.decode("utf-8") if value is not None else None
|
||||
except UnicodeDecodeError:
|
||||
return None
|
||||
|
||||
|
||||
def inspect_thread(db_path: Path, thread_id: str) -> list[dict]:
|
||||
"""Return logical row counts for exact child namespaces, without loading payloads."""
|
||||
uri = db_path.resolve().as_uri() + "?mode=ro"
|
||||
with closing(sqlite3.connect(uri, uri=True)) as db:
|
||||
db.row_factory = sqlite3.Row
|
||||
rows = db.execute(_INVENTORY, {"thread": thread_id, "pattern": f"?*|{_CHILD_PREFIX}?*"}).fetchall()
|
||||
|
||||
histories = []
|
||||
for namespace, group in groupby(rows, key=itemgetter("checkpoint_ns")):
|
||||
# LangGraph appends a numeric subgraph counter for repeated graph
|
||||
# calls in a parent node. Keep it in the reported namespace.
|
||||
_, _, tail = namespace.rpartition(f"|{_CHILD_PREFIX}")
|
||||
namespace_id, separator, counter = tail.partition("|")
|
||||
if not namespace_id or (separator and not (counter.isascii() and counter.isdecimal())):
|
||||
continue
|
||||
counts = list(group)
|
||||
checkpoints = [row for row in counts if row["checkpoint_rows"]]
|
||||
execution_ids = {_decode_id(row["execution_id"]) for row in checkpoints}
|
||||
parent_ids = {_decode_id(row["parent_run_id"]) for row in checkpoints if row["parent_run_id"]}
|
||||
matches = execution_ids == {namespace_id}
|
||||
reason = "No durable record confirms the checkpoint writer has finished."
|
||||
if not matches:
|
||||
reason = "Checkpoint metadata is missing or disagrees with the execution namespace."
|
||||
elif len(parent_ids) > 1:
|
||||
reason = "Checkpoint metadata records conflicting parent run IDs."
|
||||
histories.append(
|
||||
{
|
||||
"checkpoint_ns": namespace,
|
||||
"execution_id": namespace_id if matches else None,
|
||||
"parent_run_id": next(iter(parent_ids)) if matches and len(parent_ids) == 1 else None,
|
||||
"checkpoint_rows": sum(row["checkpoint_rows"] for row in checkpoints),
|
||||
"write_rows": sum(row["write_rows"] for row in counts),
|
||||
"status": "unknown / retained",
|
||||
"reason": reason,
|
||||
}
|
||||
)
|
||||
return histories
|
||||
|
||||
|
||||
def main() -> None:
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--db", type=Path, required=True, help="path to the SQLite checkpoint database")
|
||||
parser.add_argument("--thread-id", required=True, help="parent thread to inspect")
|
||||
args = parser.parse_args()
|
||||
try:
|
||||
histories = inspect_thread(args.db, args.thread_id)
|
||||
except (OSError, sqlite3.Error) as exc:
|
||||
parser.exit(1, f"Could not inspect {args.db}: {exc}\n")
|
||||
print(json.dumps({"thread_id": args.thread_id, "histories": histories}, indent=2))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@ -9,11 +9,16 @@ from __future__ import annotations
|
||||
import asyncio
|
||||
import importlib
|
||||
import importlib.util
|
||||
import json
|
||||
import shutil
|
||||
import sqlite3
|
||||
import subprocess
|
||||
import sys
|
||||
import threading
|
||||
from collections import defaultdict
|
||||
from contextlib import asynccontextmanager
|
||||
from contextlib import asynccontextmanager, closing
|
||||
from pathlib import Path
|
||||
from uuid import uuid4
|
||||
|
||||
import pytest
|
||||
from langchain.agents.middleware import AgentMiddleware
|
||||
@ -23,12 +28,14 @@ from langchain_core.outputs import ChatGeneration, ChatResult
|
||||
from langchain_core.runnables import RunnableConfig
|
||||
from langchain_core.runnables.config import var_child_runnable_config
|
||||
from langchain_core.tools import tool
|
||||
from langgraph.checkpoint.sqlite import SqliteSaver
|
||||
from langgraph.graph import END, START, MessagesState, StateGraph
|
||||
|
||||
from deerflow.config.app_config import AppConfig
|
||||
from deerflow.config.paths import Paths
|
||||
from deerflow.config.subagent_runtime_config import SubagentRuntimeConfig
|
||||
from deerflow.runtime.checkpointer.async_provider import make_checkpointer
|
||||
from scripts.subagent_history_inventory import inspect_thread
|
||||
|
||||
|
||||
class _OfflineModel(BaseChatModel):
|
||||
@ -438,6 +445,139 @@ async def test_parallel_children_reopen_with_execution_identity(native_executor,
|
||||
assert any(message.content == "CHILD_FINAL" for message in messages)
|
||||
assert all(message.content not in {"Delegate", "PARENT_FINAL"} for message in messages if isinstance(message.content, str))
|
||||
|
||||
# Inspect the closed database through the operator entry point. LangGraph
|
||||
# can append a numeric segment to a second invocation's raw namespace.
|
||||
db_path = Path(app_config.database.sqlite_path)
|
||||
rows = inspect_thread(db_path, "history-thread")
|
||||
assert len(rows) == len(completed)
|
||||
assert {row["checkpoint_ns"] for row in rows} == namespaces
|
||||
assert {(row["parent_run_id"], row["execution_id"]) for row in rows} == set(completed)
|
||||
for row in rows:
|
||||
entries = groups[row["execution_id"]]
|
||||
assert row["checkpoint_ns"] == entries[0].config["configurable"]["checkpoint_ns"]
|
||||
assert row["checkpoint_rows"] == len(entries)
|
||||
assert row["write_rows"] == sum(len(entry.pending_writes) for entry in entries)
|
||||
assert row["status"] == "unknown / retained"
|
||||
assert row["reason"]
|
||||
assert inspect_thread(db_path, "another-thread") == []
|
||||
|
||||
|
||||
def test_inventory_uses_one_wal_snapshot(tmp_path, monkeypatch):
|
||||
db_path = tmp_path / "live.sqlite"
|
||||
execution_id = str(uuid4())
|
||||
namespace = f"delegate:parent|deerflow_subagent:{execution_id}"
|
||||
metadata = json.dumps({"deerflow_subagent_execution_id": execution_id}).encode()
|
||||
connect = sqlite3.connect
|
||||
|
||||
with closing(connect(db_path)) as writer:
|
||||
SqliteSaver(writer).setup()
|
||||
assert writer.execute("PRAGMA journal_mode").fetchone() == ("wal",)
|
||||
|
||||
def append_checkpoint(checkpoint_id):
|
||||
with writer:
|
||||
writer.execute(
|
||||
"INSERT INTO checkpoints(thread_id, checkpoint_ns, checkpoint_id, metadata) VALUES ('live', ?, ?, ?)",
|
||||
(namespace, checkpoint_id, metadata),
|
||||
)
|
||||
writer.executemany(
|
||||
"INSERT INTO writes(thread_id, checkpoint_ns, checkpoint_id, task_id, idx, channel) VALUES ('live', ?, ?, 'task', ?, ?)",
|
||||
[(namespace, checkpoint_id, 0, "messages"), (namespace, checkpoint_id, 1, "state")],
|
||||
)
|
||||
|
||||
append_checkpoint("one")
|
||||
committed = False
|
||||
|
||||
def on_row_read():
|
||||
nonlocal committed
|
||||
if not committed:
|
||||
append_checkpoint("two")
|
||||
committed = True
|
||||
return 1
|
||||
|
||||
def connect_reader(*args, **kwargs):
|
||||
reader = connect(*args, **kwargs)
|
||||
reader.create_function("on_row_read", 0, on_row_read)
|
||||
# The function fires during a real SQLite read, after its snapshot
|
||||
# exists. The separate writer can commit immediately in WAL mode.
|
||||
for table in ("checkpoints", "writes"):
|
||||
reader.execute(f"CREATE TEMP VIEW {table} AS SELECT * FROM main.{table} WHERE on_row_read()")
|
||||
return reader
|
||||
|
||||
with monkeypatch.context() as patch:
|
||||
patch.setattr(sqlite3, "connect", connect_reader)
|
||||
[before] = inspect_thread(db_path, "live")
|
||||
|
||||
assert committed
|
||||
assert before["parent_run_id"] is None
|
||||
assert (before["checkpoint_rows"], before["write_rows"]) == (1, 2)
|
||||
[after] = inspect_thread(db_path, "live")
|
||||
assert (after["checkpoint_rows"], after["write_rows"]) == (2, 4)
|
||||
|
||||
|
||||
def test_inventory_cli_reads_database_and_rejects_missing_path(tmp_path):
|
||||
script = shutil.copy(Path(__file__).resolve().parents[1] / "scripts" / "subagent_history_inventory.py", tmp_path)
|
||||
db_path = tmp_path / "existing #.sqlite"
|
||||
with closing(sqlite3.connect(db_path)) as db:
|
||||
SqliteSaver(db).setup()
|
||||
|
||||
def run_cli(path):
|
||||
return subprocess.run([sys.executable, script, "--db", path, "--thread-id", "thread-1"], cwd=tmp_path, capture_output=True, text=True)
|
||||
|
||||
ok = run_cli(db_path)
|
||||
assert ok.returncode == 0, ok.stderr
|
||||
assert json.loads(ok.stdout) == {"thread_id": "thread-1", "histories": []}
|
||||
|
||||
missing = tmp_path / "missing.sqlite"
|
||||
failed = run_cli(missing)
|
||||
assert failed.returncode != 0
|
||||
assert failed.stderr and not failed.stdout
|
||||
assert not missing.exists()
|
||||
|
||||
|
||||
def test_inventory_keeps_unverified_namespaces_separate(tmp_path):
|
||||
db_path = tmp_path / "partial.sqlite"
|
||||
execution_id = str(uuid4())
|
||||
valid = {"deerflow_subagent_execution_id": execution_id, "deerflow_parent_run_id": "parent"}
|
||||
# An exact namespace still identifies evidence when its metadata cannot
|
||||
# substantiate the execution. Preserve the counts without guessing its owner.
|
||||
conflict_ns = f"delegate:conflict|deerflow_subagent:{execution_id}"
|
||||
malformed_ns = f"delegate:malformed|deerflow_subagent:{uuid4()}"
|
||||
intact_ns = "delegate:intact|deerflow_subagent:intact"
|
||||
writes_only_ns = f"delegate:attempt|deerflow_subagent:{uuid4()}"
|
||||
with closing(sqlite3.connect(db_path)) as db:
|
||||
SqliteSaver(db).setup()
|
||||
db.executemany(
|
||||
"INSERT INTO checkpoints(thread_id, checkpoint_ns, checkpoint_id, metadata) VALUES (?, ?, ?, ?)",
|
||||
[
|
||||
("target", conflict_ns, "1", json.dumps(valid).encode()),
|
||||
("target", conflict_ns, "2", json.dumps({**valid, "deerflow_subagent_execution_id": str(uuid4())}).encode()),
|
||||
("target", malformed_ns, "3", b"{bad-json"),
|
||||
("target", malformed_ns, "4", b'{"deerflow_subagent_execution_id":"\xff"}'),
|
||||
("target", intact_ns, "5", rb'{"deerflow_subagent_execution_id":"intact","deerflow_parent_run_id":"\ud800"}'),
|
||||
("target", "", "root", b"{}"),
|
||||
("target", "ordinary-subgraph", "subgraph", b"{}"),
|
||||
("target", f"{conflict_ns}|unrelated-node:next", "descendant", json.dumps(valid).encode()),
|
||||
("other", conflict_ns, "1", json.dumps(valid).encode()),
|
||||
],
|
||||
)
|
||||
db.executemany(
|
||||
"INSERT INTO writes(thread_id, checkpoint_ns, checkpoint_id, task_id, idx, channel) VALUES (?, ?, '1', 'task', 0, 'messages')",
|
||||
[("target", writes_only_ns), ("other", conflict_ns)],
|
||||
)
|
||||
db.commit()
|
||||
|
||||
rows = inspect_thread(db_path, "target")
|
||||
assert {(r["checkpoint_ns"], r["checkpoint_rows"], r["write_rows"]) for r in rows} == {
|
||||
(conflict_ns, 2, 0),
|
||||
(malformed_ns, 2, 0),
|
||||
(intact_ns, 1, 0),
|
||||
(writes_only_ns, 0, 1),
|
||||
}
|
||||
for row in rows:
|
||||
assert row["execution_id"] == ("intact" if row["checkpoint_ns"] == intact_ns else None)
|
||||
assert row["parent_run_id"] is None
|
||||
assert row["status"] == "unknown / retained" and row["reason"]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("legacy", [False, True])
|
||||
|
||||
@ -61,6 +61,32 @@ The Gateway closes admission and drains child execution, stream cleanup and
|
||||
checkpoint writes before closing the child saver. The parent saver remains open
|
||||
through that drain.
|
||||
|
||||
### Inspect one thread's child history
|
||||
|
||||
To see how much history has accumulated for ordinary `task` delegations, run
|
||||
the following command from the repository root. Supply the path to the
|
||||
Gateway's SQLite checkpoint database and the thread ID.
|
||||
|
||||
```bash
|
||||
uv run --no-sync --project backend python backend/scripts/subagent_history_inventory.py \
|
||||
--db /path/to/deerflow.db --thread-id YOUR_THREAD_ID
|
||||
```
|
||||
|
||||
The command opens the database in read-only mode. For a database in WAL mode,
|
||||
SQLite may create `-wal` and `-shm` sidecar files in the database directory.
|
||||
If the directory is read-only, both sidecar files must already exist and be
|
||||
readable. See the [SQLite WAL documentation](https://sqlite.org/wal.html#read_only_databases).
|
||||
|
||||
The JSON report lists each child namespace in the thread with the available
|
||||
execution and parent run IDs.
|
||||
A namespace with only writes or conflicting execution metadata still appears
|
||||
with its counts and a null execution ID. Both counts measure logical rows at
|
||||
the same instant, even if another delegation commits during the read.
|
||||
|
||||
`unknown / retained` means the database has no conclusive record that the
|
||||
execution's checkpoint writer has finished. A completed or timed-out task can
|
||||
therefore still have this status. The inventory leaves the history in place.
|
||||
|
||||
### Checkpoint resource ownership
|
||||
|
||||
All native subagents share one persistent event loop. The Gateway installs the
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user