mirror of
https://github.com/bytedance/deer-flow.git
synced 2026-11-27 17:00:37 +00:00
fix(history): retain recaptured batches in checkpoint order (#8278)
* fix(history): retain recaptured batches in checkpoint order * fix(history): derive archive retention from checkpoint state --------- Co-authored-by: Willem Jiang <willem.jiang@gmail.com>
This commit is contained in:
parent
25a59aa5c7
commit
29c5a1d7d0
@ -23,6 +23,12 @@ and read tools.
|
||||
Source availability and policy denial are runtime outcomes, and the slots they
|
||||
leave unused are recalculated in the next batch.
|
||||
|
||||
## History retention
|
||||
|
||||
Select retained batches from the input checkpoint plus the current batch.
|
||||
Recaptures reorder references in the returned checkpoint update. Leave stored
|
||||
recency untouched because the update may be discarded.
|
||||
|
||||
## History search
|
||||
|
||||
- **The role filter belongs to `history_search` only.** `history_read` takes no
|
||||
|
||||
@ -150,6 +150,8 @@ def capture(state: dict, runtime, messages, config) -> dict:
|
||||
omitted = max(0, len(sources) - config.max_records_per_batch)
|
||||
sources = sources[-config.max_records_per_batch :]
|
||||
batch = digest([owner, sources])
|
||||
batches = [*[previous for previous in old if previous != batch], batch][-config.max_batches :]
|
||||
placeholders = ",".join("?" for _ in batches)
|
||||
path.parent.mkdir(parents=True, exist_ok=True, mode=0o700)
|
||||
with closing(sqlite3.connect(path, timeout=5)) as db, db:
|
||||
db.execute("PRAGMA max_page_count=32768") # 128 MiB at SQLite's default page size.
|
||||
@ -161,14 +163,18 @@ def capture(state: dict, runtime, messages, config) -> dict:
|
||||
db.execute("BEGIN IMMEDIATE")
|
||||
exists = db.execute("SELECT 1 FROM batches WHERE id=?", (batch,)).fetchone()
|
||||
created = db.execute("SELECT COALESCE(MAX(created) + 1, 1) FROM batches").fetchone()[0]
|
||||
expired = db.execute("SELECT id FROM batches WHERE id != ? ORDER BY created DESC LIMIT -1 OFFSET ?", (batch, config.max_batches - 1)).fetchall()
|
||||
# Retain the batches referenced by the next checkpoint first. An
|
||||
# earlier capture may have finished writing without publishing its checkpoint.
|
||||
expired = db.execute(
|
||||
f"SELECT id FROM batches WHERE id != ? ORDER BY (id IN ({placeholders})) DESC, created DESC LIMIT -1 OFFSET ?",
|
||||
[batch, *batches, config.max_batches - 1],
|
||||
).fetchall()
|
||||
for (expired_id,) in expired:
|
||||
db.execute("DELETE FROM sources WHERE batch=?", (expired_id,))
|
||||
db.execute("DELETE FROM batches WHERE id=?", (expired_id,))
|
||||
if not exists:
|
||||
db.execute("INSERT INTO batches VALUES (?, ?)", (batch, created))
|
||||
db.executemany("INSERT INTO sources VALUES (?, ?, ?, ?)", [(batch, r["id"], json.dumps(r, ensure_ascii=False), index_text(r["text"])) for r in sources])
|
||||
batches = [*[previous for previous in old if previous != batch], batch][-config.max_batches :]
|
||||
return {"scope": owner, "batches": batches, "omitted_records": omitted, "status": "available"}
|
||||
except (OSError, sqlite3.Error, ValueError):
|
||||
logger.warning("Task history capture unavailable; preserving ordinary compaction", exc_info=False)
|
||||
|
||||
@ -154,6 +154,55 @@ def test_retention_is_explicit_and_duplicate_capture_is_idempotent(scoped):
|
||||
assert archive.lookup(old, scoped, query="Citrine") == {"results": [], "status": "partially_expired"}
|
||||
|
||||
|
||||
def test_recaptured_batch_remains_readable_after_the_next_capture(scoped):
|
||||
config = TaskContinuityConfig(enabled=True, max_batches=2)
|
||||
state = {}
|
||||
for word in ("alpha", "beta", "alpha", "gamma"):
|
||||
message = HumanMessage(content=word, id=word)
|
||||
state["task_history"] = archive.capture(state, scoped, [message], config)
|
||||
|
||||
for word in ("alpha", "gamma"):
|
||||
result = archive.lookup(state, scoped, query=word)
|
||||
assert result["status"] == "available"
|
||||
assert [row["message_id"] for row in result["results"]] == [word]
|
||||
assert not archive.lookup(state, scoped, query="beta")["results"]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_cancelled_recapture_preserves_checkpoint_retention(scoped, monkeypatch):
|
||||
import asyncio
|
||||
|
||||
config = TaskContinuityConfig(enabled=True, max_batches=2)
|
||||
alpha, beta, gamma = (HumanMessage(content=word, id=word) for word in ("alpha", "beta", "gamma"))
|
||||
state = {"task_history": archive.capture({}, scoped, [alpha], config)}
|
||||
state["task_history"] = archive.capture(state, scoped, [beta], config)
|
||||
|
||||
started, release = asyncio.Event(), asyncio.Event()
|
||||
run_file_io = archive.run_file_io
|
||||
|
||||
async def gated_write(*args):
|
||||
started.set()
|
||||
await release.wait()
|
||||
return await run_file_io(*args)
|
||||
|
||||
monkeypatch.setattr(archive, "run_file_io", gated_write)
|
||||
task = asyncio.create_task(archive.acapture(state, scoped, [alpha], config))
|
||||
try:
|
||||
await asyncio.wait_for(started.wait(), timeout=5)
|
||||
finally:
|
||||
task.cancel()
|
||||
release.set()
|
||||
with pytest.raises(asyncio.CancelledError):
|
||||
await task
|
||||
|
||||
state["task_history"] = archive.capture(state, scoped, [gamma], config)
|
||||
for word in ("beta", "gamma"):
|
||||
result = archive.lookup(state, scoped, query=word)
|
||||
assert result["status"] == "available"
|
||||
assert [row["message_id"] for row in result["results"]] == [word]
|
||||
assert not archive.lookup(state, scoped, query="alpha")["results"]
|
||||
|
||||
|
||||
def test_serialization_allowlist_omits_reasoning_and_binary():
|
||||
source = AIMessage(
|
||||
content=[
|
||||
|
||||
@ -142,16 +142,18 @@ creation clears the parent archive references and status; inherited note citatio
|
||||
may consequently be unavailable and need fresh verification in the branch.
|
||||
|
||||
Retention is bounded by the configured batch/record/text limits and a 32,768-page
|
||||
SQLite ceiling (128 MiB for the default page size). The oldest physical batches
|
||||
expire as new ones are captured, even if an older checkpoint still refers to
|
||||
them. Read/search report `partially_expired` or `unavailable`; missing sources must
|
||||
be re-verified. `omitted_records` describes the latest capture's record limit,
|
||||
and each shortened source carries `truncated: true`.
|
||||
Eviction happens before replacement insertion in one write transaction.
|
||||
Competing captures serialize retention decisions; if insertion still exceeds
|
||||
capacity, rollback preserves the previous batches. Duplicate capture protects
|
||||
the current batch even when the configured retention limit is reduced.
|
||||
Storage failure preserves
|
||||
SQLite ceiling (128 MiB for the default page size). Each capture keeps its own
|
||||
batch and gives priority to the most recent references from the input
|
||||
checkpoint. Any remaining slots keep other stored batches in insertion order,
|
||||
newest first. A recapture moves its reference to the end of the next checkpoint
|
||||
without duplicating sources. If that checkpoint is never saved, later captures
|
||||
still use the last saved order. Older checkpoints may return
|
||||
`partially_expired` or `unavailable`; missing sources must be re-verified.
|
||||
`omitted_records` describes the latest capture's record limit, and each shortened
|
||||
source carries `truncated: true`.
|
||||
Eviction and replacement insertion share one write transaction. Competing
|
||||
captures serialize retention decisions, and a failed insertion rolls back
|
||||
evictions. Storage failure preserves
|
||||
ordinary compaction and marks history unavailable; it does not undo a successful
|
||||
summary. Async writes are offloaded and drained before cancellation returns.
|
||||
History tools preserve `unavailable` after a capture failure, even when older
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user