mirror of
https://github.com/bytedance/deer-flow.git
synced 2026-11-27 17:00:37 +00:00
fix(runtime): stop replaying ambiguous subagent event writes (#7711)
* fix(runtime): stop replaying ambiguous subagent event writes * fix(runtime): classify safe retries and bound subagent persistence failures * fix(runtime): quarantine deterministic batch failures instead of retrying * fix(runtime): verify subagent batch rollback and producer completion Classify transient failures before database commit using driver codes. Restore JSONL appends in reverse order and propagate rollback uncertainty. Keep the SQL producer open when subagent persistence stops without confirmation. --------- Co-authored-by: Houston <347629597+HoustonJia@users.noreply.github.com> Co-authored-by: Nan Gao <thunderggnn@gmail.com>
This commit is contained in:
parent
5398a584c6
commit
5d9ee09df9
@ -68,6 +68,11 @@ make test-blocking-io
|
||||
|
||||
- **`RunJournal` is changed on its owning event loop only.** A recorder failure
|
||||
fails open, and a slow recorder must not delay tool state.
|
||||
- **Retry a sub-agent event batch only on `RunEventStoreNotCommittedError`.**
|
||||
Drain writes before propagating caller cancellation. Signal retry only for
|
||||
transient failures that committed no events. An uncertain outcome stops
|
||||
history writes to prevent duplicate steps. Close the SQL producer only when
|
||||
the final flush confirms all writes.
|
||||
- **Usage replay may enrich a message, never add or remove one.** A provider can
|
||||
report the end of the same model call twice.
|
||||
- **Event-store mutations of one thread share one fence** (an asyncio lock plus a
|
||||
|
||||
@ -11,11 +11,14 @@ import hashlib
|
||||
import json
|
||||
import logging
|
||||
import re
|
||||
import sqlite3
|
||||
import weakref
|
||||
from datetime import UTC, datetime
|
||||
from typing import Any
|
||||
|
||||
from sqlalchemy import and_, delete, func, or_, select, text, update
|
||||
from sqlalchemy.exc import DBAPIError
|
||||
from sqlalchemy.exc import TimeoutError as SqlTimeoutError
|
||||
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker
|
||||
|
||||
from deerflow.persistence.models.run_event import RunEventRow, RunEventThreadSeqRow
|
||||
@ -24,13 +27,32 @@ from deerflow.persistence.run.sql import RunRepository
|
||||
from deerflow.persistence.thread_meta.model import ThreadMetaRow
|
||||
from deerflow.runtime.events.message_identity import message_identity
|
||||
from deerflow.runtime.events.producer import HistorySeedAuthority, RunEventProducerRejected, current_producer
|
||||
from deerflow.runtime.events.store.base import RunEventLifecycleRejected, RunEventStore, SessionAwareRunEventLifecycleGuard
|
||||
from deerflow.runtime.events.store.base import RunEventLifecycleRejected, RunEventStore, RunEventStoreNotCommittedError, SessionAwareRunEventLifecycleGuard
|
||||
from deerflow.runtime.user_context import AUTO, _AutoSentinel, get_current_user, resolve_user_id
|
||||
from deerflow.utils.time import coerce_iso
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def _is_transient_db_error(exc: Exception) -> bool:
|
||||
if isinstance(exc, DBAPIError):
|
||||
if exc.connection_invalidated:
|
||||
return True
|
||||
exc = exc.orig
|
||||
if isinstance(exc, (ConnectionError, TimeoutError, SqlTimeoutError)):
|
||||
return True
|
||||
if isinstance(exc, sqlite3.Error):
|
||||
# Extended codes (e.g. SQLITE_BUSY_SNAPSHOT) keep the primary code in the low byte.
|
||||
return getattr(exc, "sqlite_errorcode", 0) & 0xFF in (sqlite3.SQLITE_BUSY, sqlite3.SQLITE_LOCKED)
|
||||
return getattr(exc, "sqlstate", None) in {
|
||||
"08003", # connection_does_not_exist
|
||||
"08006", # connection_failure
|
||||
"40001", # serialization_failure
|
||||
"40P01", # deadlock_detected
|
||||
"55P03", # lock_not_available
|
||||
}
|
||||
|
||||
|
||||
def _parse_created_at(value: str | None) -> datetime:
|
||||
timestamp = datetime.fromisoformat(value) if value else datetime.now(UTC)
|
||||
# SQLite drops tzinfo, so convert the clock value before it reaches storage.
|
||||
@ -336,36 +358,44 @@ class DbRunEventStore(RunEventStore):
|
||||
user_id = authority.user_id if authority is not None else self._user_id_from_context()
|
||||
# All events belong to the same thread (validated above).
|
||||
thread_id = events[0]["thread_id"]
|
||||
async with self._get_write_lock(thread_id):
|
||||
async with self._sf() as session:
|
||||
async with session.begin():
|
||||
await self._admit_events(session, events)
|
||||
max_seq = await self._max_seq_for_thread(session, thread_id)
|
||||
seq = max_seq or 0
|
||||
rows = []
|
||||
for e in events:
|
||||
seq += 1
|
||||
content = e.get("content", "")
|
||||
category = e.get("category", "trace")
|
||||
metadata = e.get("metadata")
|
||||
content, metadata = self._truncate_trace(category, content, metadata)
|
||||
db_content, metadata = self._content_to_db(content, metadata)
|
||||
row = RunEventRow(
|
||||
thread_id=e["thread_id"],
|
||||
run_id=e["run_id"],
|
||||
user_id=e.get("user_id", user_id),
|
||||
event_type=e["event_type"],
|
||||
category=category,
|
||||
content=db_content,
|
||||
content_sha256=hashlib.sha256(db_content.encode("utf-8")).hexdigest(),
|
||||
event_metadata=metadata,
|
||||
seq=seq,
|
||||
created_at=_parse_created_at(e.get("created_at")),
|
||||
)
|
||||
session.add(row)
|
||||
rows.append(row)
|
||||
await self._raise_seq_watermark(session, thread_id, seq)
|
||||
return [self._row_to_dict(r) for r in rows]
|
||||
commit_started = False
|
||||
try:
|
||||
async with self._get_write_lock(thread_id):
|
||||
async with self._sf() as session:
|
||||
async with session.begin():
|
||||
await self._admit_events(session, events)
|
||||
max_seq = await self._max_seq_for_thread(session, thread_id)
|
||||
seq = max_seq or 0
|
||||
rows = []
|
||||
for e in events:
|
||||
seq += 1
|
||||
content = e.get("content", "")
|
||||
category = e.get("category", "trace")
|
||||
metadata = e.get("metadata")
|
||||
content, metadata = self._truncate_trace(category, content, metadata)
|
||||
db_content, metadata = self._content_to_db(content, metadata)
|
||||
row = RunEventRow(
|
||||
thread_id=e["thread_id"],
|
||||
run_id=e["run_id"],
|
||||
user_id=e.get("user_id", user_id),
|
||||
event_type=e["event_type"],
|
||||
category=category,
|
||||
content=db_content,
|
||||
content_sha256=hashlib.sha256(db_content.encode("utf-8")).hexdigest(),
|
||||
event_metadata=metadata,
|
||||
seq=seq,
|
||||
created_at=_parse_created_at(e.get("created_at")),
|
||||
)
|
||||
session.add(row)
|
||||
rows.append(row)
|
||||
await self._raise_seq_watermark(session, thread_id, seq)
|
||||
await session.flush()
|
||||
commit_started = True
|
||||
return [self._row_to_dict(r) for r in rows]
|
||||
except Exception as exc:
|
||||
if not commit_started and _is_transient_db_error(exc):
|
||||
raise RunEventStoreNotCommittedError(f"DB batch failed before commit: {type(exc).__name__}: {exc}") from exc
|
||||
raise
|
||||
|
||||
async def put_if_absent(
|
||||
self,
|
||||
|
||||
@ -41,7 +41,7 @@ from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from deerflow.runtime.events.message_identity import message_identity
|
||||
from deerflow.runtime.events.store.base import RunEventLifecycleRejected, RunEventStore, match_ai_message_run_id, normalize_message_ids
|
||||
from deerflow.runtime.events.store.base import RunEventLifecycleRejected, RunEventStore, RunEventStoreNotCommittedError, match_ai_message_run_id, normalize_message_ids
|
||||
from deerflow.runtime.user_context import AUTO, _AutoSentinel
|
||||
from deerflow.utils.thread_id import validate_thread_id
|
||||
|
||||
@ -255,12 +255,13 @@ class JsonlRunEventStore(RunEventStore):
|
||||
write lock. Records are grouped by run_id and appended to their own
|
||||
run files while that lock is held. If a write fails and rollback
|
||||
succeeds, already-appended groups for the current thread are restored
|
||||
so callers (e.g. worker.py's flush-retry path) may safely re-buffer
|
||||
that thread's batch. When a batch contains multiple thread IDs, thread
|
||||
and RunEventStoreNotCommittedError permits retry of the entire batch
|
||||
only if no earlier thread group committed. For multiple thread IDs, thread
|
||||
groups are processed sequentially, so a later failure does not roll
|
||||
back earlier thread groups. Cancellation drains the current thread group
|
||||
before propagating, without starting subsequent groups. This rollback
|
||||
does not make a multi-file batch crash-atomic.
|
||||
does not make a multi-file batch crash-atomic. Unlocked readers may see
|
||||
rows before rollback and see them again at new seq values after retry.
|
||||
"""
|
||||
if not events:
|
||||
return []
|
||||
@ -268,11 +269,19 @@ class JsonlRunEventStore(RunEventStore):
|
||||
# Group by thread_id; each thread has its own write lock and seq counter.
|
||||
by_thread: dict[str, list[dict[str, Any]]] = {}
|
||||
for ev in events:
|
||||
# Keep invalid identifiers as validation errors, before any I/O.
|
||||
validate_thread_id(ev["thread_id"])
|
||||
self._validate_id(ev["run_id"], "run_id")
|
||||
by_thread.setdefault(ev["thread_id"], []).append(ev)
|
||||
|
||||
results: list[dict[str, Any]] = []
|
||||
for thread_id, batch in by_thread.items():
|
||||
records = await self._write_batch_async(thread_id, batch)
|
||||
try:
|
||||
records = await self._write_batch_async(thread_id, batch)
|
||||
except RunEventStoreNotCommittedError as exc:
|
||||
if results:
|
||||
raise RuntimeError("JSONL batch partially committed before a later thread failed") from exc
|
||||
raise
|
||||
results.extend(records)
|
||||
return results
|
||||
|
||||
@ -314,25 +323,28 @@ class JsonlRunEventStore(RunEventStore):
|
||||
|
||||
async def _write_batch_async(self, thread_id: str, batch: list[dict[str, Any]]) -> list[dict[str, Any]]:
|
||||
async def mutate():
|
||||
await self._ensure_seq_loaded(thread_id)
|
||||
records: list[dict[str, Any]] = []
|
||||
for ev in batch:
|
||||
seq = self._next_seq(thread_id)
|
||||
record = {
|
||||
"thread_id": thread_id,
|
||||
"run_id": ev["run_id"],
|
||||
"event_type": ev["event_type"],
|
||||
"category": ev["category"],
|
||||
"content": ev.get("content", ""),
|
||||
"metadata": ev.get("metadata") or {},
|
||||
"seq": seq,
|
||||
"created_at": ev.get("created_at") or datetime.now(UTC).isoformat(),
|
||||
}
|
||||
records.append(record)
|
||||
records_by_run: dict[str, list[dict[str, Any]]] = {}
|
||||
for record in records:
|
||||
records_by_run.setdefault(record["run_id"], []).append(record)
|
||||
run_batches = [(self._run_file(thread_id, run_id), run_records) for run_id, run_records in records_by_run.items()]
|
||||
try:
|
||||
await self._ensure_seq_loaded(thread_id)
|
||||
records: list[dict[str, Any]] = []
|
||||
for ev in batch:
|
||||
seq = self._next_seq(thread_id)
|
||||
record = {
|
||||
"thread_id": thread_id,
|
||||
"run_id": ev["run_id"],
|
||||
"event_type": ev["event_type"],
|
||||
"category": ev["category"],
|
||||
"content": ev.get("content", ""),
|
||||
"metadata": ev.get("metadata") or {},
|
||||
"seq": seq,
|
||||
"created_at": ev.get("created_at") or datetime.now(UTC).isoformat(),
|
||||
}
|
||||
records.append(record)
|
||||
records_by_run: dict[str, list[dict[str, Any]]] = {}
|
||||
for record in records:
|
||||
records_by_run.setdefault(record["run_id"], []).append(record)
|
||||
run_batches = [(self._run_file(thread_id, run_id), run_records) for run_id, run_records in records_by_run.items()]
|
||||
except OSError as exc:
|
||||
raise RunEventStoreNotCommittedError(f"JSONL batch preparation failed before append: {type(exc).__name__}: {exc}") from exc
|
||||
await asyncio.to_thread(self._append_record_groups, run_batches)
|
||||
return records
|
||||
|
||||
@ -352,26 +364,34 @@ class JsonlRunEventStore(RunEventStore):
|
||||
|
||||
def _append_record_groups(self, groups: list[tuple[Path, list[dict[str, Any]]]]) -> None:
|
||||
"""Append run groups and restore their original sizes if one fails."""
|
||||
original_sizes: dict[Path, int | None] = {}
|
||||
original_sizes: list[tuple[Path, int | None]] = []
|
||||
try:
|
||||
for path, records in groups:
|
||||
original_sizes[path] = path.stat().st_size if path.exists() else None
|
||||
try:
|
||||
original_size = path.stat().st_size
|
||||
except FileNotFoundError:
|
||||
original_size = None
|
||||
original_sizes.append((path, original_size))
|
||||
self._append_records(path, records)
|
||||
except Exception:
|
||||
for path, original_size in original_sizes.items():
|
||||
except Exception as exc:
|
||||
rolled_back = True
|
||||
# Undo in reverse append order because two run IDs may name the same file.
|
||||
for path, original_size in reversed(original_sizes):
|
||||
try:
|
||||
if original_size is None:
|
||||
if path.exists():
|
||||
path.unlink()
|
||||
path.unlink(missing_ok=True)
|
||||
else:
|
||||
with open(path, "r+b") as f:
|
||||
f.truncate(original_size)
|
||||
except OSError:
|
||||
rolled_back = False
|
||||
logger.error(
|
||||
"Failed to roll back JSONL batch append for %s; retrying the batch may create duplicate records",
|
||||
path,
|
||||
exc_info=True,
|
||||
)
|
||||
if rolled_back and isinstance(exc, OSError):
|
||||
raise RunEventStoreNotCommittedError(f"JSONL batch append rolled back: {type(exc).__name__}: {exc}") from exc
|
||||
raise
|
||||
|
||||
async def list_messages(self, thread_id, *, limit=50, before_seq=None, after_seq=None, user_id: str | None | _AutoSentinel = AUTO):
|
||||
|
||||
@ -73,6 +73,7 @@ from deerflow.runtime.context_keys import (
|
||||
)
|
||||
from deerflow.runtime.events.message_identity import attach_message_seq, message_identity
|
||||
from deerflow.runtime.events.producer import current_producer, publisher_scope, run_producer_context
|
||||
from deerflow.runtime.events.store.base import RunEventStoreNotCommittedError
|
||||
from deerflow.runtime.goal import (
|
||||
DEFAULT_MAX_GOAL_CONTINUATIONS,
|
||||
DEFAULT_MAX_NO_PROGRESS_CONTINUATIONS,
|
||||
@ -930,12 +931,18 @@ class _SubagentEventBuffer:
|
||||
#: Flush once this many events are buffered, bounding memory and reload lag on
|
||||
#: a single deep subagent without paying a per-step lock.
|
||||
FLUSH_THRESHOLD = 25
|
||||
MAX_WRITE_ATTEMPTS = 3
|
||||
|
||||
def __init__(self, event_store: Any | None, thread_id: str, run_id: str) -> None:
|
||||
self._event_store = event_store
|
||||
self._thread_id = thread_id
|
||||
self._run_id = run_id
|
||||
self._pending: list[dict[str, Any]] = []
|
||||
self._persistence_stopped = False
|
||||
self._consecutive_failures = 0
|
||||
self._unconfirmed_events = 0
|
||||
self._skipped_events = 0
|
||||
self._affected_tasks: set[str] = set()
|
||||
|
||||
async def add(self, chunk: Any) -> None:
|
||||
"""Buffer one custom stream chunk; flush on a terminal event or threshold."""
|
||||
@ -950,51 +957,91 @@ class _SubagentEventBuffer:
|
||||
record = subagent_run_event(chunk)
|
||||
if record is None:
|
||||
return
|
||||
if self._persistence_stopped:
|
||||
self._skipped_events += 1
|
||||
self._remember_task(record)
|
||||
return
|
||||
self._pending.append({"thread_id": self._thread_id, "run_id": self._run_id, **record})
|
||||
if record["event_type"] == "subagent.end" or len(self._pending) >= self.FLUSH_THRESHOLD:
|
||||
await self.flush()
|
||||
|
||||
async def flush(self) -> None:
|
||||
"""Persist buffered events in one ``put_batch`` call; swallow store errors."""
|
||||
"""Drain one batch; retry only a proven uncommitted write.
|
||||
|
||||
A failed acknowledgement can follow a successful commit. Release that
|
||||
batch and fence this buffer's later writes
|
||||
instead of duplicating history or overtaking an unknown predecessor.
|
||||
Live SSE delivery is independent and remains best-effort throughout.
|
||||
"""
|
||||
if self._event_store is None or not self._pending:
|
||||
return
|
||||
batch = self._pending
|
||||
self._pending = []
|
||||
write_task = asyncio.create_task(self._event_store.put_batch(batch))
|
||||
cancellation: asyncio.CancelledError | None = None
|
||||
failure: Exception | None = None
|
||||
while True:
|
||||
while not write_task.done():
|
||||
try:
|
||||
await asyncio.shield(write_task)
|
||||
break
|
||||
# wait() neither cancels the owned write nor raises its outcome.
|
||||
# This distinguishes caller cancellation from store cancellation
|
||||
# even when both happen during the same event-loop iteration.
|
||||
await asyncio.wait({write_task})
|
||||
except asyncio.CancelledError as exc:
|
||||
host_task = asyncio.current_task()
|
||||
if host_task is None or not host_task.cancelling():
|
||||
# The store task itself was cancelled. It did not confirm
|
||||
# durability, so retain the batch for a later flush.
|
||||
self._pending = batch + self._pending
|
||||
raise
|
||||
if cancellation is None:
|
||||
cancellation = exc
|
||||
while host_task.cancelling():
|
||||
while host_task is not None and host_task.cancelling():
|
||||
host_task.uncancel()
|
||||
except Exception as exc:
|
||||
failure = exc
|
||||
break
|
||||
|
||||
if failure is not None:
|
||||
# Re-buffer the failed batch (ahead of any events queued since) so a
|
||||
# transient store error does not silently drop subagent step events.
|
||||
self._pending = batch + self._pending
|
||||
try:
|
||||
write_task.result()
|
||||
except (Exception, asyncio.CancelledError) as failure:
|
||||
# Only this explicit store contract proves replay is safe. Generic
|
||||
# exceptions and store-originated cancellation are ambiguous, even
|
||||
# if they look like transient transport failures.
|
||||
self._consecutive_failures += 1
|
||||
retryable = isinstance(failure, RunEventStoreNotCommittedError)
|
||||
self._persistence_stopped = not retryable or self._consecutive_failures >= self.MAX_WRITE_ATTEMPTS
|
||||
if self._persistence_stopped:
|
||||
self._unconfirmed_events += len(batch) + len(self._pending)
|
||||
for event in batch + self._pending:
|
||||
self._remember_task(event)
|
||||
self._pending.clear()
|
||||
else:
|
||||
self._pending = batch + self._pending
|
||||
logger.warning(
|
||||
"Run %s: failed to persist %d subagent step event(s)",
|
||||
"Run %s: failed to persist %d subagent step event(s); %s",
|
||||
self._run_id,
|
||||
len(batch),
|
||||
"persistence stopped (unknown outcome or retry limit)" if self._persistence_stopped else "not committed, retained for retry",
|
||||
exc_info=(type(failure), failure, failure.__traceback__),
|
||||
)
|
||||
else:
|
||||
self._consecutive_failures = 0
|
||||
if cancellation is not None:
|
||||
raise cancellation
|
||||
|
||||
def _remember_task(self, event: dict[str, Any]) -> None:
|
||||
task_id = event.get("metadata", {}).get("task_id")
|
||||
if isinstance(task_id, str) and len(self._affected_tasks) < 20:
|
||||
self._affected_tasks.add(task_id)
|
||||
|
||||
@property
|
||||
def writes_confirmed(self) -> bool:
|
||||
"""Whether the producer can close after the final flush has settled."""
|
||||
return not self._persistence_stopped and not self._pending
|
||||
|
||||
def log_summary(self) -> None:
|
||||
if not self.writes_confirmed:
|
||||
for event in self._pending:
|
||||
self._remember_task(event)
|
||||
logger.warning(
|
||||
"Run %s: subagent history incomplete; unconfirmed=%d skipped=%d task_ids_sample=%s",
|
||||
self._run_id,
|
||||
self._unconfirmed_events + len(self._pending),
|
||||
self._skipped_events,
|
||||
sorted(self._affected_tasks),
|
||||
)
|
||||
|
||||
|
||||
def _bind_trace_id(config: dict[str, Any], runtime_ctx: dict[str, Any]) -> str:
|
||||
"""Record the current request trace id on the runtime context and metadata.
|
||||
@ -2257,7 +2304,10 @@ async def run_agent(
|
||||
# Persist any subagent step events still buffered (#3779) — including on
|
||||
# abort/exception paths, where the stream loop broke before its own flush.
|
||||
if not record.ownership_lost and subagent_events is not None:
|
||||
await subagent_events.flush()
|
||||
try:
|
||||
await subagent_events.flush()
|
||||
finally:
|
||||
subagent_events.log_summary()
|
||||
|
||||
if not record.ownership_lost and event_store is not None and pre_run_workspace_snapshot is not None:
|
||||
try:
|
||||
@ -2557,7 +2607,7 @@ async def run_agent(
|
||||
raise RuntimeError(evidence_failure)
|
||||
|
||||
evidence_receipt = await journal.finish_evidence(before_receipt=confirm_terminal)
|
||||
if evidence_receipt is not None and (subagent_events is None or not subagent_events._pending):
|
||||
if evidence_receipt is not None and (subagent_events is None or subagent_events.writes_confirmed):
|
||||
from deerflow.runtime.events.store.db import DbRunEventStore
|
||||
|
||||
if isinstance(event_store, DbRunEventStore) and current_producer() is not None:
|
||||
|
||||
@ -649,6 +649,60 @@ async def test_worker_seals_after_completion_hook_before_end(evidence, outcome):
|
||||
assert captured[0]._closed
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize(
|
||||
("subtasks", "write_outcomes", "producer_state"),
|
||||
[
|
||||
pytest.param(1, ["lost_ack"], "open", id="committed-but-unconfirmed"),
|
||||
pytest.param(1, ["rejected"] * 2, "open", id="retry-pending"),
|
||||
pytest.param(3, ["rejected"] * 3, "open", id="retries-exhausted"),
|
||||
pytest.param(1, ["rejected", "success"], "closed", id="retry-confirmed"),
|
||||
],
|
||||
)
|
||||
async def test_worker_closes_producer_only_after_subagent_writes_are_confirmed(evidence, monkeypatch, subtasks, write_outcomes, producer_state):
|
||||
from deerflow.runtime.events.store.base import RunEventStoreNotCommittedError
|
||||
from deerflow.runtime.runs.manager import RunManager
|
||||
from deerflow.runtime.runs.worker import RunContext, run_agent
|
||||
from deerflow.runtime.stream_bridge import MemoryStreamBridge
|
||||
|
||||
_, events, runs, _ = evidence
|
||||
manager = RunManager(store=runs, event_store=events)
|
||||
record = await manager.create("worker-thread", user_id="alice")
|
||||
bridge = MemoryStreamBridge()
|
||||
put_batch = events.put_batch
|
||||
attempts = 0
|
||||
|
||||
async def write(batch):
|
||||
nonlocal attempts
|
||||
if batch[0]["event_type"] != "subagent.end":
|
||||
return await put_batch(batch)
|
||||
attempts += 1
|
||||
outcome = write_outcomes[attempts - 1]
|
||||
if outcome == "rejected":
|
||||
raise RunEventStoreNotCommittedError("rejected before commit")
|
||||
rows = await put_batch(batch)
|
||||
if outcome == "lost_ack":
|
||||
raise OSError("lost acknowledgement after commit")
|
||||
return rows
|
||||
|
||||
class Agent:
|
||||
async def astream(self, *args, **kwargs):
|
||||
for i in range(subtasks):
|
||||
yield "custom", {"type": "task_completed", "task_id": f"child-{i}", "result": "done"}
|
||||
yield "values", {"messages": []}
|
||||
|
||||
monkeypatch.setattr(events, "put_batch", write)
|
||||
await run_agent(bridge, manager, record, ctx=RunContext(checkpointer=None, event_store=events), agent_factory=lambda **kwargs: Agent(), graph_input={}, config={}, stream_modes=["custom", "values"])
|
||||
|
||||
assert attempts == len(write_outcomes)
|
||||
row = await runs.get(record.run_id, user_id="alice")
|
||||
assert row["producer_state"] == producer_state
|
||||
assert row["status"] == "success"
|
||||
assert row["evidence_seal_state"] == "sealed"
|
||||
streamed = [event async for event in bridge.subscribe(record.run_id)]
|
||||
assert streamed[-1].event == "__end__"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_seal_failure_does_not_change_business_success(evidence, monkeypatch):
|
||||
from types import SimpleNamespace
|
||||
|
||||
@ -16,6 +16,7 @@ from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
from deerflow.runtime.events.store.base import RunEventStoreNotCommittedError
|
||||
from deerflow.runtime.events.store.jsonl import JsonlRunEventStore
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
@ -208,7 +209,7 @@ async def test_put_batch_failure_rolls_back_no_partial_records(monkeypatch):
|
||||
# First attempt — fails after partial output; expect raise. The
|
||||
# in-memory seq counter is advanced because reservation happens under
|
||||
# the lock, but the partial file contents must be rolled back.
|
||||
with pytest.raises(OSError):
|
||||
with pytest.raises(RunEventStoreNotCommittedError):
|
||||
await store.put_batch(events)
|
||||
|
||||
# Retry the full batch with the real append, matching worker.py's
|
||||
@ -259,7 +260,7 @@ async def test_mixed_run_batch_failure_restores_all_run_files(monkeypatch):
|
||||
{"thread_id": "t1", "run_id": "r1", "event_type": "trace", "category": "trace", "content": "new-r1"},
|
||||
{"thread_id": "t1", "run_id": "r2", "event_type": "trace", "category": "trace", "content": "new-r2"},
|
||||
]
|
||||
with pytest.raises(OSError, match="second-run"):
|
||||
with pytest.raises(RunEventStoreNotCommittedError, match="second-run"):
|
||||
await store.put_batch(events)
|
||||
|
||||
assert r1_path.read_bytes() == original_r1
|
||||
|
||||
@ -7,6 +7,7 @@ import threading
|
||||
|
||||
import pytest
|
||||
|
||||
from deerflow.runtime.events.store.base import RunEventStoreNotCommittedError
|
||||
from deerflow.runtime.events.store.jsonl import JsonlRunEventStore
|
||||
|
||||
|
||||
@ -136,10 +137,11 @@ async def test_old_batch_rollback_cannot_erase_later_acknowledged_write(tmp_path
|
||||
await _checkpoint()
|
||||
assert not writer.done(), "a new writer entered before rollback settled"
|
||||
paused.release.set()
|
||||
with pytest.raises(asyncio.CancelledError if cancel else OSError) as caught:
|
||||
with pytest.raises(asyncio.CancelledError if cancel else RunEventStoreNotCommittedError) as caught:
|
||||
await batch
|
||||
if cancel:
|
||||
assert isinstance(caught.value.__cause__, OSError)
|
||||
assert isinstance(caught.value.__cause__, RunEventStoreNotCommittedError)
|
||||
assert isinstance(caught.value.__cause__.__cause__, OSError)
|
||||
saved = await writer
|
||||
assert saved["content"] == "acknowledged-later"
|
||||
assert [row["content"] for row in await store.list_messages("t1")] == ["baseline", "acknowledged-later"]
|
||||
@ -341,7 +343,8 @@ async def test_cancelled_multithread_batch_drains_current_group_without_starting
|
||||
with pytest.raises(asyncio.CancelledError) as caught:
|
||||
await pending
|
||||
if fail_first_thread:
|
||||
assert isinstance(caught.value.__cause__, OSError)
|
||||
assert isinstance(caught.value.__cause__, RunEventStoreNotCommittedError)
|
||||
assert isinstance(caught.value.__cause__.__cause__, OSError)
|
||||
assert [row["content"] for row in await store.list_messages("t1")] == ["baseline"]
|
||||
assert await store.list_events("t1", "r2") == []
|
||||
else:
|
||||
|
||||
@ -3,9 +3,12 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
from deerflow.runtime.events.store.base import RunEventStoreNotCommittedError
|
||||
from deerflow.runtime.events.store.jsonl import JsonlRunEventStore
|
||||
|
||||
TAILS = {
|
||||
@ -88,7 +91,7 @@ async def test_batch_failure_restores_original_tail_bytes_before_retry(tmp_path,
|
||||
raise OSError("second group failed after writing")
|
||||
|
||||
monkeypatch.setattr(store, "_append_records", fail_second_group)
|
||||
with pytest.raises(OSError, match="second group failed"):
|
||||
with pytest.raises(RunEventStoreNotCommittedError, match="second group failed"):
|
||||
await store.put_batch([_event(), _event("r2")])
|
||||
|
||||
assert path.read_bytes() == original_bytes
|
||||
@ -100,3 +103,64 @@ async def test_batch_failure_restores_original_tail_bytes_before_retry(tmp_path,
|
||||
assert await store.list_messages("t1") == [old, *saved]
|
||||
assert saved[0]["seq"] > old["seq"]
|
||||
assert saved[1]["seq"] == saved[0]["seq"] + 1
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
@pytest.mark.parametrize("existing_file", [True, False], ids=["stat-before-append", "stat-during-rollback"])
|
||||
async def test_batch_stat_failure_preserves_original_file(tmp_path, monkeypatch, existing_file):
|
||||
store = JsonlRunEventStore(tmp_path)
|
||||
path = store._run_file("t1", "r1")
|
||||
if existing_file:
|
||||
await store.put(**_event())
|
||||
original = path.read_bytes() if existing_file else None
|
||||
fail_stat = existing_file
|
||||
stat = os.stat
|
||||
append = store._append_records
|
||||
|
||||
def unavailable_stat(target, *args, **kwargs):
|
||||
if fail_stat and target == path:
|
||||
raise OSError("cannot stat the run file")
|
||||
return stat(target, *args, **kwargs)
|
||||
|
||||
def fail_after_append(path, records):
|
||||
nonlocal fail_stat
|
||||
append(path, records)
|
||||
fail_stat = True
|
||||
raise OSError("append failed")
|
||||
|
||||
with monkeypatch.context() as patch:
|
||||
patch.setattr(os, "stat", unavailable_stat)
|
||||
# Match Python 3.14, where Path.exists() returns False for any OS error.
|
||||
patch.setattr(Path, "exists", os.path.exists)
|
||||
patch.setattr(store, "_append_records", fail_after_append)
|
||||
with pytest.raises(RunEventStoreNotCommittedError, match="cannot stat" if existing_file else "append failed"):
|
||||
await store.put_batch([_event()])
|
||||
|
||||
assert (path.read_bytes() if path.exists() else None) == original
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_batch_rollback_restores_run_file_shared_by_two_groups(tmp_path, monkeypatch):
|
||||
path, old = _seed(tmp_path, TAILS["lf"])
|
||||
original = path.read_bytes()
|
||||
store = JsonlRunEventStore(tmp_path)
|
||||
run_file = store._run_file
|
||||
append = store._append_records
|
||||
|
||||
# Both spellings address the same file on a case-insensitive filesystem.
|
||||
monkeypatch.setattr(store, "_run_file", lambda thread_id, run_id: run_file(thread_id, run_id.lower()))
|
||||
|
||||
def fail_second_group(path, records):
|
||||
append(path, records)
|
||||
if records[0]["run_id"] == "R1":
|
||||
raise OSError("second append failed")
|
||||
|
||||
events = [_event("r1"), _event("R1")]
|
||||
with monkeypatch.context() as patch:
|
||||
patch.setattr(store, "_append_records", fail_second_group)
|
||||
with pytest.raises(RunEventStoreNotCommittedError, match="second append failed"):
|
||||
await store.put_batch(events)
|
||||
|
||||
assert path.read_bytes() == original
|
||||
saved = await store.put_batch(events)
|
||||
assert await store.list_messages("t1") == [old, *saved]
|
||||
|
||||
@ -14,6 +14,7 @@ from test_run_producer_cutover import cutover_db as cutover_db
|
||||
|
||||
from deerflow.persistence.run.producer import activate_producer_fencing
|
||||
from deerflow.persistence.run.sql import RunRepository
|
||||
from deerflow.runtime.events.store.base import RunEventStoreNotCommittedError
|
||||
from deerflow.runtime.events.store.db import DbRunEventStore
|
||||
|
||||
INSERT = text("INSERT INTO run_events(thread_id,run_id,user_id,event_type,category,content,event_metadata,seq,created_at) VALUES ('thread','run','alice','middleware:off','trace','','{}',:seq,clock_timestamp())")
|
||||
@ -32,6 +33,31 @@ def peer_engine(schema, **kwargs):
|
||||
return create_async_engine(asyncpg_test_url(os.environ["TEST_POSTGRES_URI"]), pool_size=2, max_overflow=0, connect_args={"server_settings": {"search_path": schema, "statement_timeout": "6000"}}, **kwargs)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_store_retries_batch_after_postgres_lock_timeout(cutover_db):
|
||||
engine, sf, schema = cutover_db
|
||||
thread_id = schema # Advisory locks are shared across test schemas.
|
||||
await RunRepository(sf).put("run", thread_id=thread_id, user_id="alice", status="running")
|
||||
batch = [dict(thread_id=thread_id, run_id="run", user_id="alice", event_type="subagent.step", category="trace", content=step) for step in ("first", "second")]
|
||||
peer = peer_engine(schema)
|
||||
try:
|
||||
async with peer.connect() as writer:
|
||||
await writer.execute(text("SET lock_timeout = '100ms'"))
|
||||
await writer.commit()
|
||||
store = DbRunEventStore(async_sessionmaker(writer, expire_on_commit=False))
|
||||
async with engine.begin() as holder:
|
||||
await holder.execute(text("SELECT pg_advisory_xact_lock(hashtext(:thread_id)::bigint)"), {"thread_id": thread_id})
|
||||
with pytest.raises(RunEventStoreNotCommittedError) as caught:
|
||||
await store.put_batch(batch)
|
||||
assert caught.value.__cause__.orig.sqlstate == "55P03"
|
||||
assert await store.list_events(thread_id, "run", user_id="alice") == []
|
||||
await store.put_batch(batch)
|
||||
saved = await store.list_events(thread_id, "run", user_id="alice")
|
||||
assert [(row["seq"], row["content"]) for row in saved] == [(1, "first"), (2, "second")]
|
||||
finally:
|
||||
await peer.dispose()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize(("lock", "api"), [("thread", False), ("run", False), ("run", True)])
|
||||
async def test_off_insert_ignores_trigger_added_thread_and_run_locks(off_db, lock, api):
|
||||
|
||||
253
backend/tests/test_subagent_store_retry_contract.py
Normal file
253
backend/tests/test_subagent_store_retry_contract.py
Normal file
@ -0,0 +1,253 @@
|
||||
"""Real stores must distinguish retryable rejection from uncertain commits."""
|
||||
|
||||
import pytest
|
||||
import pytest_asyncio
|
||||
from sqlalchemy import event as sa_event
|
||||
from sqlalchemy.exc import DBAPIError, OperationalError
|
||||
from sqlalchemy.exc import TimeoutError as SqlTimeoutError
|
||||
|
||||
from deerflow.runtime.events.store.base import RunEventStoreNotCommittedError
|
||||
from deerflow.runtime.events.store.jsonl import JsonlRunEventStore
|
||||
from deerflow.runtime.events.store.memory import MemoryRunEventStore
|
||||
from deerflow.runtime.runs.worker import _SubagentEventBuffer
|
||||
|
||||
|
||||
def event(thread="t1", run="r1"):
|
||||
return dict(thread_id=thread, run_id=run, event_type="subagent.step", category="trace", content="step")
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_jsonl_rollback_allows_retry_without_duplicates(tmp_path, monkeypatch):
|
||||
store = JsonlRunEventStore(tmp_path)
|
||||
append = store._append_records
|
||||
|
||||
def fail_after_append(path, records):
|
||||
append(path, records)
|
||||
if path.stem == "r2":
|
||||
raise OSError("append failed")
|
||||
|
||||
monkeypatch.setattr(store, "_append_records", fail_after_append)
|
||||
with pytest.raises(RunEventStoreNotCommittedError):
|
||||
await store.put_batch([event(), event(run="r2")])
|
||||
assert await store.list_events("t1", "r1") == []
|
||||
assert await store.list_events("t1", "r2") == []
|
||||
monkeypatch.setattr(store, "_append_records", append)
|
||||
await store.put_batch([event(), event(run="r2")])
|
||||
assert len(await store.list_events("t1", "r1")) == 1
|
||||
assert len(await store.list_events("t1", "r2")) == 1
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_jsonl_previous_thread_commit_is_not_retryable(tmp_path, monkeypatch):
|
||||
store = JsonlRunEventStore(tmp_path)
|
||||
append = store._append_records
|
||||
|
||||
def fail_second_thread(path, records):
|
||||
if records[0]["thread_id"] == "t2":
|
||||
raise OSError("second thread rejected")
|
||||
append(path, records)
|
||||
|
||||
monkeypatch.setattr(store, "_append_records", fail_second_thread)
|
||||
with pytest.raises(Exception) as caught:
|
||||
await store.put_batch([event(), event(thread="t2")])
|
||||
assert not isinstance(caught.value, RunEventStoreNotCommittedError)
|
||||
assert len(await store.list_events("t1", "r1")) == 1
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_jsonl_failed_rollback_remains_ambiguous(tmp_path, monkeypatch):
|
||||
from pathlib import Path
|
||||
|
||||
store = JsonlRunEventStore(tmp_path)
|
||||
append = store._append_records
|
||||
|
||||
def fail_after_append(path, records):
|
||||
append(path, records)
|
||||
raise OSError("append acknowledgement lost")
|
||||
|
||||
def fail_unlink(self, *args, **kwargs):
|
||||
raise OSError("rollback failed")
|
||||
|
||||
monkeypatch.setattr(store, "_append_records", fail_after_append)
|
||||
monkeypatch.setattr(Path, "unlink", fail_unlink)
|
||||
with pytest.raises(OSError, match="acknowledgement lost"):
|
||||
await store.put_batch([event()])
|
||||
assert len(await store.list_events("t1", "r1")) == 1
|
||||
|
||||
|
||||
@pytest_asyncio.fixture
|
||||
async def sqlite_event_db(tmp_path):
|
||||
from sqlalchemy.ext.asyncio import async_sessionmaker, create_async_engine
|
||||
|
||||
from deerflow.persistence.models.run_event import RunEventRow, RunEventThreadSeqRow
|
||||
from deerflow.runtime.events.store.db import DbRunEventStore
|
||||
|
||||
engine = create_async_engine(f"sqlite+aiosqlite:///{tmp_path / 'events.db'}", connect_args={"timeout": 0})
|
||||
try:
|
||||
async with engine.begin() as connection:
|
||||
await connection.run_sync(lambda c: RunEventRow.__table__.create(c))
|
||||
await connection.run_sync(lambda c: RunEventThreadSeqRow.__table__.create(c))
|
||||
yield engine, DbRunEventStore(async_sessionmaker(engine, expire_on_commit=False))
|
||||
finally:
|
||||
await engine.dispose()
|
||||
|
||||
|
||||
def postgres_error(sqlstate):
|
||||
# SQLAlchemy's asyncpg adapter exposes these states through DBAPIError.orig.
|
||||
driver_error = Exception(sqlstate)
|
||||
driver_error.sqlstate = sqlstate
|
||||
return DBAPIError(None, None, driver_error)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize(
|
||||
("failure", "expected"),
|
||||
[
|
||||
(ConnectionError("checkout failed"), RunEventStoreNotCommittedError),
|
||||
(SqlTimeoutError("pool timed out"), RunEventStoreNotCommittedError),
|
||||
(DBAPIError(None, None, Exception("disconnect"), connection_invalidated=True), RunEventStoreNotCommittedError),
|
||||
(postgres_error("40001"), RunEventStoreNotCommittedError),
|
||||
(postgres_error("40P01"), RunEventStoreNotCommittedError),
|
||||
(postgres_error("55P03"), RunEventStoreNotCommittedError),
|
||||
(postgres_error("42P01"), DBAPIError),
|
||||
(ValueError("invalid timestamp"), ValueError),
|
||||
(UnicodeError("invalid content"), UnicodeError),
|
||||
],
|
||||
)
|
||||
async def test_db_precommit_failure_classification(sqlite_event_db, failure, expected):
|
||||
engine, store = sqlite_event_db
|
||||
|
||||
def fail_statement(*args):
|
||||
raise failure
|
||||
|
||||
sa_event.listen(engine.sync_engine, "before_cursor_execute", fail_statement)
|
||||
try:
|
||||
with pytest.raises(expected):
|
||||
await store.put_batch([event()])
|
||||
finally:
|
||||
sa_event.remove(engine.sync_engine, "before_cursor_execute", fail_statement)
|
||||
await store.put_batch([event()])
|
||||
assert len(await store.list_events("t1", "r1", user_id=None)) == 1
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_db_journal_retries_sqlite_contention_and_quarantines_schema_errors(sqlite_event_db):
|
||||
from deerflow.runtime.journal import RunJournal
|
||||
|
||||
engine, store = sqlite_event_db
|
||||
journal = RunJournal("r1", "t1", store, flush_threshold=100)
|
||||
try:
|
||||
journal._put(event_type="trace", category="trace", content="first")
|
||||
async with engine.connect() as writer:
|
||||
await writer.exec_driver_sql("BEGIN IMMEDIATE")
|
||||
with pytest.raises(RunEventStoreNotCommittedError):
|
||||
await journal.flush()
|
||||
await journal.flush()
|
||||
assert len(await store.list_events("t1", "r1", user_id=None)) == 1
|
||||
|
||||
async with engine.begin() as connection:
|
||||
await connection.exec_driver_sql("DROP TABLE run_events")
|
||||
journal._put(event_type="trace", category="trace", content="second")
|
||||
with pytest.raises(OperationalError, match="no such table"):
|
||||
await journal.flush()
|
||||
with pytest.raises(RuntimeError, match="unknown durable outcome"):
|
||||
await journal.flush()
|
||||
finally:
|
||||
await journal.close(flush=False)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_db_lost_commit_acknowledgement_remains_ambiguous(tmp_path):
|
||||
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_engine
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from deerflow.persistence.models.run_event import RunEventRow, RunEventThreadSeqRow
|
||||
from deerflow.runtime.events.store.db import DbRunEventStore
|
||||
|
||||
class LostAckSession(Session):
|
||||
pass
|
||||
|
||||
@sa_event.listens_for(LostAckSession, "after_commit")
|
||||
def lose_ack(session):
|
||||
raise ConnectionResetError("commit acknowledgement lost")
|
||||
|
||||
engine = create_async_engine(f"sqlite+aiosqlite:///{tmp_path / 'events.db'}")
|
||||
async with engine.begin() as connection:
|
||||
await connection.run_sync(lambda c: RunEventRow.__table__.create(c))
|
||||
await connection.run_sync(lambda c: RunEventThreadSeqRow.__table__.create(c))
|
||||
store = DbRunEventStore(async_sessionmaker(engine, class_=AsyncSession, sync_session_class=LostAckSession, expire_on_commit=False))
|
||||
try:
|
||||
with pytest.raises(ConnectionResetError, match="acknowledgement lost"):
|
||||
await store.put_batch([event()])
|
||||
assert len(await store.list_events("t1", "r1", user_id=None)) == 1
|
||||
finally:
|
||||
await engine.dispose()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_jsonl_preparation_failure_is_retryable(tmp_path, monkeypatch):
|
||||
store = JsonlRunEventStore(tmp_path)
|
||||
|
||||
async def fail_load(thread_id):
|
||||
raise OSError("read denied before append")
|
||||
|
||||
monkeypatch.setattr(store, "_ensure_seq_loaded", fail_load)
|
||||
with pytest.raises(RunEventStoreNotCommittedError):
|
||||
await store.put_batch([event()])
|
||||
assert await store.list_events("t1", "r1") == []
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_repeated_rejection_is_bounded_and_reported(caplog):
|
||||
class RejectStore(MemoryRunEventStore):
|
||||
calls = 0
|
||||
|
||||
async def put_batch(self, events):
|
||||
self.calls += 1
|
||||
raise RunEventStoreNotCommittedError("rejected")
|
||||
|
||||
store = RejectStore()
|
||||
buffer = _SubagentEventBuffer(store, "thread", "run")
|
||||
for index in range(1000):
|
||||
await buffer.add({"type": "task_running", "task_id": "child", "message_index": index, "message": {"type": "ai", "content": "step"}})
|
||||
await buffer.flush()
|
||||
assert store.calls == 3
|
||||
assert buffer._pending == []
|
||||
buffer.log_summary()
|
||||
assert "unconfirmed=27" in caplog.text
|
||||
assert "skipped=973" in caplog.text
|
||||
assert "child" in caplog.text
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("failure", [OSError("temporary read failure"), ValueError("corrupt watermark")])
|
||||
async def test_jsonl_journal_transient_retry_and_deterministic_quarantine(tmp_path, monkeypatch, failure):
|
||||
from deerflow.runtime.journal import RunJournal
|
||||
|
||||
store = JsonlRunEventStore(tmp_path)
|
||||
load = store._ensure_seq_loaded
|
||||
calls = 0
|
||||
|
||||
async def fail_once(thread_id):
|
||||
nonlocal calls
|
||||
calls += 1
|
||||
if calls == 1:
|
||||
raise failure
|
||||
await load(thread_id)
|
||||
|
||||
monkeypatch.setattr(store, "_ensure_seq_loaded", fail_once)
|
||||
journal = RunJournal("r1", "t1", store, flush_threshold=100)
|
||||
journal._put(event_type="trace", category="trace", content="first")
|
||||
with pytest.raises(RunEventStoreNotCommittedError if isinstance(failure, OSError) else ValueError):
|
||||
await journal.flush()
|
||||
if isinstance(failure, OSError):
|
||||
await journal.flush()
|
||||
assert len(await store.list_events("t1", "r1")) == 1
|
||||
assert calls == 2
|
||||
else:
|
||||
for _ in range(5):
|
||||
journal._put(event_type="trace", category="trace", content="later")
|
||||
with pytest.raises(RuntimeError, match="unknown durable outcome"):
|
||||
await journal.flush()
|
||||
assert calls == 1
|
||||
await journal.close(flush=False)
|
||||
@ -4,6 +4,7 @@ import asyncio
|
||||
|
||||
import pytest
|
||||
|
||||
from deerflow.runtime.events.store.base import RunEventStoreNotCommittedError
|
||||
from deerflow.runtime.runs.worker import _SubagentEventBuffer
|
||||
|
||||
|
||||
@ -18,7 +19,7 @@ class _BlockingStore:
|
||||
self.entered.set()
|
||||
await self.release.wait()
|
||||
if self.fail:
|
||||
raise RuntimeError("event store write failed")
|
||||
raise RunEventStoreNotCommittedError("event store rejected write")
|
||||
self.batches.append([dict(event) for event in events])
|
||||
return list(events)
|
||||
|
||||
|
||||
@ -17,6 +17,7 @@ import sys
|
||||
|
||||
import pytest
|
||||
|
||||
from deerflow.runtime.events.store.base import RunEventStoreNotCommittedError
|
||||
from deerflow.runtime.runs.worker import _SubagentEventBuffer
|
||||
|
||||
|
||||
@ -55,7 +56,7 @@ class _FakeStore:
|
||||
|
||||
class _BoomStore:
|
||||
async def put_batch(self, events):
|
||||
raise RuntimeError("db down")
|
||||
raise RunEventStoreNotCommittedError("db down before write")
|
||||
|
||||
|
||||
def _running_step(task_id="call_1", message_index=1):
|
||||
@ -177,7 +178,7 @@ class _FailOnceStore:
|
||||
async def put_batch(self, events):
|
||||
self.calls += 1
|
||||
if self.calls == 1:
|
||||
raise RuntimeError("transient db error")
|
||||
raise RunEventStoreNotCommittedError("transient db error before write")
|
||||
self.batches.append([dict(e) for e in events])
|
||||
return list(events)
|
||||
|
||||
|
||||
172
backend/tests/test_worker_subagent_write_outcome.py
Normal file
172
backend/tests/test_worker_subagent_write_outcome.py
Normal file
@ -0,0 +1,172 @@
|
||||
"""A lost batch acknowledgement must not duplicate persisted subagent history."""
|
||||
|
||||
import asyncio
|
||||
|
||||
import pytest
|
||||
|
||||
from deerflow.runtime.events.store.base import RunEventStoreNotCommittedError
|
||||
from deerflow.runtime.events.store.memory import MemoryRunEventStore
|
||||
from deerflow.runtime.runs.manager import RunManager
|
||||
from deerflow.runtime.runs.schemas import RunStatus
|
||||
from deerflow.runtime.runs.worker import RunContext, _publish_stream_item, _SubagentEventBuffer, run_agent
|
||||
from deerflow.runtime.stream_bridge import MemoryStreamBridge
|
||||
|
||||
|
||||
class OutcomeStore(MemoryRunEventStore):
|
||||
def __init__(self, outcome):
|
||||
super().__init__()
|
||||
self.outcome = outcome
|
||||
self.calls = 0
|
||||
self.committed = asyncio.Event()
|
||||
self.release = asyncio.Event()
|
||||
|
||||
async def put_batch(self, events):
|
||||
self.calls += 1
|
||||
if self.calls != 1:
|
||||
return await super().put_batch(events)
|
||||
if self.outcome == "not_committed":
|
||||
raise RunEventStoreNotCommittedError("rejected before writing")
|
||||
rows = await super().put_batch(events)
|
||||
self.committed.set()
|
||||
if self.outcome == "gated":
|
||||
await self.release.wait()
|
||||
if self.outcome == "cancelled":
|
||||
raise asyncio.CancelledError("store lost acknowledgement")
|
||||
if self.outcome != "success":
|
||||
raise OSError("lost acknowledgement after commit")
|
||||
return rows
|
||||
|
||||
|
||||
def step(index):
|
||||
return {
|
||||
"type": "task_running",
|
||||
"task_id": "child",
|
||||
"message_index": index,
|
||||
"message": {"type": "ai", "content": f"step {index}"},
|
||||
}
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("outcome", ["unknown", "cancelled"])
|
||||
async def test_streamed_subagent_events_are_not_replayed_after_unknown_write(outcome):
|
||||
store = OutcomeStore(outcome)
|
||||
buffer = _SubagentEventBuffer(store, "thread", "run")
|
||||
bridge = MemoryStreamBridge()
|
||||
events = [step(1), {"type": "task_completed", "task_id": "child", "result": "done"}]
|
||||
for event in events:
|
||||
await _publish_stream_item(
|
||||
bridge=bridge,
|
||||
run_id="run",
|
||||
mode="custom",
|
||||
chunk=event,
|
||||
namespace=(),
|
||||
file_tool_chunk_batcher=None,
|
||||
subagent_events=buffer,
|
||||
)
|
||||
await buffer.flush() # Worker finalization also flushes the same buffer.
|
||||
for index in range(2, 100):
|
||||
await buffer.add(step(index))
|
||||
await buffer.flush()
|
||||
await bridge.publish_end("run")
|
||||
|
||||
persisted = await store.list_events("thread", "run")
|
||||
assert [event["event_type"] for event in persisted] == ["subagent.step", "subagent.end"]
|
||||
assert store.calls == 1
|
||||
assert buffer._pending == []
|
||||
assert buffer._unconfirmed_events == 2
|
||||
assert buffer._skipped_events == 98
|
||||
streamed = [event.data async for event in bridge.subscribe("run") if event.event == "custom"]
|
||||
assert streamed == events # Persistence failure must not break live delivery.
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_known_uncommitted_batch_can_retry_before_successors():
|
||||
store = OutcomeStore("not_committed")
|
||||
buffer = _SubagentEventBuffer(store, "thread", "run")
|
||||
await buffer.add(step(1))
|
||||
await buffer.flush()
|
||||
await buffer.add(step(2))
|
||||
await buffer.flush()
|
||||
persisted = await store.list_events("thread", "run")
|
||||
assert [event["metadata"]["message_index"] for event in persisted] == [1, 2]
|
||||
assert store.calls == 2
|
||||
assert not buffer._pending
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("outcome", ["gated", "success"])
|
||||
async def test_host_cancellation_drains_write_without_replaying(outcome):
|
||||
store = OutcomeStore(outcome)
|
||||
buffer = _SubagentEventBuffer(store, "thread", "run")
|
||||
await buffer.add(step(1))
|
||||
task = asyncio.create_task(buffer.flush())
|
||||
try:
|
||||
await asyncio.wait_for(store.committed.wait(), 5)
|
||||
if outcome == "gated":
|
||||
task.cancel()
|
||||
await asyncio.sleep(0)
|
||||
task.cancel()
|
||||
await asyncio.sleep(0)
|
||||
assert not task.done()
|
||||
store.release.set()
|
||||
with pytest.raises(asyncio.CancelledError):
|
||||
await task
|
||||
else:
|
||||
await task
|
||||
await buffer.flush()
|
||||
assert store.calls == 1
|
||||
assert len(await store.list_events("thread", "run")) == 1
|
||||
finally:
|
||||
store.release.set()
|
||||
await asyncio.gather(task, return_exceptions=True)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("outcome", ["unknown", "cancelled", "success"])
|
||||
async def test_worker_keeps_business_success_and_stream_end_after_store_failure(outcome):
|
||||
store = OutcomeStore(outcome)
|
||||
manager = RunManager()
|
||||
record = await manager.create("thread")
|
||||
bridge = MemoryStreamBridge()
|
||||
|
||||
class Graph:
|
||||
async def astream(self, *args, **kwargs):
|
||||
yield "custom", step(1)
|
||||
yield "custom", {"type": "task_completed", "task_id": "child", "result": "done"}
|
||||
yield "values", {"messages": []}
|
||||
|
||||
await run_agent(
|
||||
bridge,
|
||||
manager,
|
||||
record,
|
||||
ctx=RunContext(checkpointer=None, event_store=store),
|
||||
agent_factory=lambda **kwargs: Graph(),
|
||||
graph_input={},
|
||||
config={},
|
||||
stream_modes=["custom", "values"],
|
||||
)
|
||||
assert record.status == RunStatus.success
|
||||
persisted = await store.list_events("thread", record.run_id, event_types=["subagent.step", "subagent.end"])
|
||||
assert [event["event_type"] for event in persisted] == ["subagent.step", "subagent.end"]
|
||||
streamed = [event async for event in bridge.subscribe(record.run_id)]
|
||||
assert streamed[-1].event == "__end__"
|
||||
assert len([event for event in streamed if event.event == "custom"]) == 2
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_jsonl_commit_survives_reopen_without_duplicate_replay(tmp_path):
|
||||
from deerflow.runtime.events.store.jsonl import JsonlRunEventStore
|
||||
|
||||
class LostAckStore(JsonlRunEventStore):
|
||||
async def put_batch(self, events):
|
||||
await super().put_batch(events)
|
||||
raise OSError("lost acknowledgement")
|
||||
|
||||
buffer = _SubagentEventBuffer(LostAckStore(tmp_path), "thread", "run")
|
||||
await buffer.add(step(1))
|
||||
await buffer.flush()
|
||||
await buffer.flush()
|
||||
reopened = JsonlRunEventStore(tmp_path)
|
||||
persisted = await reopened.list_events("thread", "run")
|
||||
assert len(persisted) == 1
|
||||
assert persisted[0]["metadata"]["message_index"] == 1
|
||||
@ -115,6 +115,16 @@ error and timeout policies. Repeated cancellation does not abandon this cleanup.
|
||||
Task-stop reports an interrupted execution as aborted, preserving any completed,
|
||||
failed or timed-out outcome already published before cancellation.
|
||||
|
||||
The worker saves sub-agent step history separately from the live stream. It
|
||||
retries a batch only when the store confirms that no event was committed, such
|
||||
as after a transient database error before commit or a successful JSONL rollback.
|
||||
After three consecutive failed attempts, an uncertain write, or cancellation by
|
||||
the store, the worker releases the buffer and stops saving sub-agent events for
|
||||
that run. Live events and task results still reach the caller, but reloading
|
||||
the run can show an incomplete history. The `subagent history incomplete` log
|
||||
lists the unconfirmed and skipped event counts and a sample of affected task IDs.
|
||||
Unconfirmed events may already be in the store.
|
||||
|
||||
Ordinary `task` calls accept `context_mode="isolated"` (default) or
|
||||
`context_mode="snapshot"`. Isolated tasks receive their delegated prompt as
|
||||
before. Snapshot tasks also receive the parent's retained conversation and
|
||||
|
||||
@ -46,7 +46,7 @@ The run worker persists those events to the run event store under the `subagent`
|
||||
| `subagent.step` | `task_id`, `message_index`, `kind` (`ai` or `tool`), `text`, `truncated`; assistant steps add `tool_calls`, tool steps add `tool_name` |
|
||||
| `subagent.end` | `task_id`, `status` (`completed` / `failed` / `cancelled` / `timed_out`), `model_name`, `usage`, and `result` or `error` with truncation flags |
|
||||
|
||||
Step text is capped at 8,192 characters. Events are written in batches of 25, `subagent.end` flushes immediately, and a failed write is re-buffered for the next attempt rather than dropped.
|
||||
Step text is capped at 8,192 characters. Events are written in batches of 25 and `subagent.end` flushes immediately. Only a write explicitly confirmed as uncommitted is re-buffered for retry (including transient DB pre-commit failures and successful JSONL I/O rollback). Three consecutive failed attempts, an ambiguous error, or store cancellation stops further subagent-event persistence for that run and releases pending payloads. Live streaming continues, but reloaded history may be incomplete. Finalization logs unconfirmed and skipped event counts plus a bounded sample of affected task IDs. An unconfirmed batch may already be stored; its count is not a count of definitely lost events.
|
||||
|
||||
Query endpoint:
|
||||
|
||||
|
||||
@ -168,7 +168,7 @@ Since [#3658](https://github.com/bytedance/deer-flow/pull/3658) usage is attribu
|
||||
|
||||
### Subtask steps disappear after a reload
|
||||
|
||||
Steps are backfilled from `subagent.step` run events ([#3845](https://github.com/bytedance/deer-flow/pull/3845)). Older versions dropped a batch when the event store write failed; since [#4082](https://github.com/bytedance/deer-flow/pull/4082) it is re-buffered and retried. Check that the run event store is writable.
|
||||
Steps are backfilled from `subagent.step` run events. Check that the event store is writable and inspect the run's `subagent history incomplete` finalization warning. Only a write explicitly confirmed as uncommitted is re-buffered for retry (including transient DB pre-commit failures and successful JSONL I/O rollback). Three consecutive failed attempts, an ambiguous error, or store cancellation stops further subagent-event persistence for that run and releases pending payloads. Live streaming continues, but reloaded history may be incomplete. Finalization logs unconfirmed and skipped event counts plus a bounded sample of affected task IDs. An unconfirmed batch may already be stored; its count is not a count of definitely lost events.
|
||||
|
||||
### The chat page suddenly shows only the subagent's conversation
|
||||
|
||||
|
||||
@ -46,7 +46,7 @@ Run worker 把上述事件持久化到运行事件存储,类别为 `subagent`
|
||||
| `subagent.step` | `task_id`、`message_index`、`kind`(`ai` 或 `tool`)、`text`、`truncated`;助手步骤附 `tool_calls`,工具步骤附 `tool_name` |
|
||||
| `subagent.end` | `task_id`、`status`(`completed` / `failed` / `cancelled` / `timed_out`)、`model_name`、`usage`、`result` 或 `error` 及其截断标记 |
|
||||
|
||||
步骤文本最多 8,192 字符。事件按 25 条一批写入,`subagent.end` 立即刷盘;写入失败时重新缓冲等待下次重试,不会丢步骤。
|
||||
步骤文本最多 8,192 字符。事件按 25 条一批写入,`subagent.end` 立即刷盘。只有存储明确确认整批未提交时才重新缓冲重试(包括数据库提交前的暂时性故障和 JSONL I/O 失败后的成功回滚)。连续三次写入失败、结果不确定的异常或存储自身取消,会停止该次运行后续子 Agent 事件的持久化并释放待写负载。实时流继续,但刷新后的历史可能不完整。收尾日志记录未确认与跳过的事件数量,以及有数量上限的受影响任务 ID 样本;未确认批次可能已经写入,不能把其数量当作确定丢失的事件数。
|
||||
|
||||
查询接口:
|
||||
|
||||
|
||||
@ -168,7 +168,7 @@ import { Callout } from "nextra/components";
|
||||
|
||||
### 刷新后子任务的步骤消失
|
||||
|
||||
步骤从 `subagent.step` 运行事件回填([#3845](https://github.com/bytedance/deer-flow/pull/3845))。若事件存储写入失败,旧版本会丢弃这批事件,[#4082](https://github.com/bytedance/deer-flow/pull/4082) 之后改为重新缓冲重试。检查运行事件存储是否可写。
|
||||
步骤从 `subagent.step` 运行事件回填。检查事件存储是否可写,以及该次运行收尾时的 `subagent history incomplete` 警告。只有存储明确确认整批未提交时才重新缓冲重试(包括数据库提交前的暂时性故障和 JSONL I/O 失败后的成功回滚)。连续三次写入失败、结果不确定的异常或存储自身取消,会停止该次运行后续子 Agent 事件的持久化并释放待写负载。实时流继续,但刷新后的历史可能不完整。收尾日志记录未确认与跳过的事件数量,以及有数量上限的受影响任务 ID 样本;未确认批次可能已经写入,不能把其数量当作确定丢失的事件数。
|
||||
|
||||
### 对话页面突然只显示子 Agent 的对话
|
||||
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user