diff --git a/backend/app/gateway/routers/threads.py b/backend/app/gateway/routers/threads.py index 813d805678..95d11468d3 100644 --- a/backend/app/gateway/routers/threads.py +++ b/backend/app/gateway/routers/threads.py @@ -17,6 +17,7 @@ import inspect import logging import shutil import uuid +from collections.abc import Awaitable, Callable from pathlib import Path from typing import Any @@ -98,7 +99,7 @@ from deerflow.runtime.goal_synthesis import ( ) from deerflow.runtime.journal import build_branch_history_seed_events from deerflow.runtime.run_origin import DEERFLOW_ORIGIN_KEY, admit_origin -from deerflow.runtime.runs.manager import ConflictError +from deerflow.runtime.runs.manager import ConflictError, RunRecord from deerflow.runtime.runs.worker import RUN_MESSAGE_IDS_METADATA_KEY, valid_duration_entry, valid_run_message_id_entry from deerflow.runtime.secret_context import redact_metadata_secrets from deerflow.runtime.serialization import serialize_lc_object @@ -1272,26 +1273,6 @@ async def _branch_thread_with_reservation( "created_at": now, } new_config.setdefault("metadata", {}).update(checkpoint_metadata_updates) - try: - head_config = new_config - if replay_base_tuple is not None: - head_config = await branch_accessor.aupdate( - new_config, - branch_values(replay_base_tuple), - as_node="branch", - ) - head_config.setdefault("metadata", {}).update(checkpoint_metadata_updates) - await branch_accessor.aupdate( - head_config, - branch_values(snapshot, replaces=replay_base_tuple), - as_node="branch", - ) - except _CHECKPOINT_MODE_ERRORS as exc: - raise _checkpoint_mode_http_error(exc, new_thread_id) from exc - except Exception: - logger.exception("Failed to write branch checkpoint for thread %s", sanitize_log_param(new_thread_id)) - raise HTTPException(status_code=500, detail="Failed to create branch") from None - branch_assistant_id = source_record.get("assistant_id") try: custom_agent_name(branch_assistant_id) @@ -1300,9 +1281,14 @@ async def _branch_thread_with_reservation( # into a new thread. Preserve every valid spelling as create does. branch_assistant_id = None - async def _write_branch_row(project_id: str | None) -> dict: + branch_record = None + + async def _write_branch_row(project_id: str | None) -> None: + # Remember a committed insert even if the request is cancelled while + # draining it. Cleanup may only remove a row from this branch attempt. + nonlocal branch_record try: - return await thread_store.create( + branch_record = await thread_store.create( new_thread_id, assistant_id=branch_assistant_id, display_name=display_name, @@ -1313,17 +1299,76 @@ async def _branch_thread_with_reservation( except ProjectNotAssignableError: raise except Exception: - logger.exception("Failed to write branch thread_meta for %s", sanitize_log_param(new_thread_id)) - raise HTTPException(status_code=500, detail="Failed to create branch") from None + # An insert can commit before the caller receives its acknowledgement. + # Only resume if this owner's row describes this exact branch attempt. + record = await thread_store.get(new_thread_id, **thread_owner_kwargs) + if record is None or not all((record.get("metadata") or {}).get(key) == value for key, value in branch_metadata.items()): + raise + branch_record = record - try: - branch_record = await _write_branch_row(source_project_id) - except ProjectNotAssignableError: - # The source project became unassignable (archived, or deleted in a - # race that cleared the source row's membership after our read): keep - # the branch usable as an unassigned thread — the pre-inheritance - # behavior for sources without an active project. - branch_record = await _write_branch_row(None) + async def _persist_branch(reservation: RunRecord) -> None: + run_manager = get_run_manager(request) + + async def write_if_owned[**P, T](operation: Callable[P, Awaitable[T]], /, *args: P.args, **kwargs: P.kwargs) -> T: + owned = await run_manager.owns_active_admission(reservation) + + async def write() -> T: + # The heartbeat can fence the request between the durable check + # and the first event-loop turn of this individual write. + if not owned or reservation.ownership_lost: + raise ConflictError(f"Thread {new_thread_id} reservation lease was lost") + return await operation(*args, **kwargs) + + return await await_drained(write()) + + try: + try: + await write_if_owned(_write_branch_row, source_project_id) + except ProjectNotAssignableError: + # The source project was archived or deleted after the source read. + await write_if_owned(_write_branch_row, None) + + head_config = new_config + if replay_base_tuple is not None: + head_config = await write_if_owned( + branch_accessor.aupdate, + new_config, + branch_values(replay_base_tuple), + as_node="branch", + ) + head_config.setdefault("metadata", {}).update(checkpoint_metadata_updates) + await write_if_owned( + branch_accessor.aupdate, + head_config, + branch_values(snapshot, replaces=replay_base_tuple), + as_node="branch", + ) + except ConflictError: + raise + except (Exception, asyncio.CancelledError): + if branch_record is None: + raise + try: + # A failed head write may already have persisted the replay base. + # Keep the owner row if checkpoint removal itself fails. + await write_if_owned(get_checkpointer(request).adelete_thread, new_thread_id) + await write_if_owned(thread_store.delete, new_thread_id, **thread_owner_kwargs) + except ConflictError: + raise + except Exception: + logger.exception("Failed to clean up incomplete branch %s", sanitize_log_param(new_thread_id)) + raise + + async with reserve_checkpoint_write(request, new_thread_id, user_id=thread_owner_user_id or get_effective_user_id()) as child_reservation: + try: + await _persist_branch(child_reservation) + except ConflictError: + raise + except _CHECKPOINT_MODE_ERRORS as exc: + raise _checkpoint_mode_http_error(exc, new_thread_id) from exc + except Exception: + logger.exception("Failed to persist branch %s", sanitize_log_param(new_thread_id)) + raise HTTPException(status_code=500, detail="Failed to create branch") from None # The thread feed (GET /messages, /messages/page) reads the run-event # store, not checkpoints, and a fresh branch has no run_events — so the diff --git a/backend/app/gateway/services.py b/backend/app/gateway/services.py index 58c5908bb4..541d86f87d 100644 --- a/backend/app/gateway/services.py +++ b/backend/app/gateway/services.py @@ -146,7 +146,7 @@ async def reserve_checkpoint_write( thread_id: str, *, user_id: str | None = None, -) -> AsyncIterator[None]: +) -> AsyncIterator[RunRecord]: """Serialize an out-of-run checkpoint writer against all thread operations.""" run_manager = get_run_manager(request) async with goal_thread_lock(thread_id): @@ -154,8 +154,8 @@ async def reserve_checkpoint_write( thread_id, kind=ThreadOperationKind.checkpoint_write, user_id=user_id, - ): - yield + ) as reservation: + yield reservation _TERMINAL_RUN_STATUSES = { diff --git a/backend/docs/THREAD_LIFECYCLE.md b/backend/docs/THREAD_LIFECYCLE.md index 30b5dc9e49..f935b988e7 100644 --- a/backend/docs/THREAD_LIFECYCLE.md +++ b/backend/docs/THREAD_LIFECYCLE.md @@ -38,6 +38,15 @@ remains in thread state and replaces the source turn in history. Only a failed, timed-out or cancelled attempt restores the pre-edit checkpoint; once the pause is answered, the resume run is an ordinary run and its failure keeps the edit. +A branch reserves the child thread and creates its ownership record before +writing its replay base and head. The gateway checks the child reservation +before each write, including each step of rollback. If a peer takes over, +the old request drains the write already in progress and returns HTTP 409 +when it detects the loss. If a checkpoint write fails while the gateway still +holds the reservation, it removes the child checkpoints before removing the +ownership row. If cleanup stops early, the owner can delete the incomplete +branch through the regular thread deletion endpoint. + ### Chat archive `POST /api/threads/search` accepts an optional strict boolean `archived`: omitted diff --git a/backend/packages/harness/deerflow/runtime/runs/manager.py b/backend/packages/harness/deerflow/runtime/runs/manager.py index 3bfd45ac2b..50be7c6a07 100644 --- a/backend/packages/harness/deerflow/runtime/runs/manager.py +++ b/backend/packages/harness/deerflow/runtime/runs/manager.py @@ -3061,7 +3061,7 @@ class RunManager: if self.heartbeat_enabled: deadline = self._parse_lease_deadline(row.get("lease_expires_at")) if deadline is None or deadline <= datetime.now(UTC): - await self._mark_ownership_lost(record, reason="Scheduled goal cleanup lost its active run lease.", require_active=False) + await self._mark_ownership_lost(record, reason="The active admission lease is missing or expired.", require_active=False) return False return not record.ownership_lost diff --git a/backend/tests/test_threads_router.py b/backend/tests/test_threads_router.py index 0f947e66ad..75f4a75d1d 100644 --- a/backend/tests/test_threads_router.py +++ b/backend/tests/test_threads_router.py @@ -32,7 +32,7 @@ from deerflow.persistence.thread_meta import ( ThreadOwnershipConflictError, ) from deerflow.persistence.thread_meta.memory import THREADS_NS, MemoryThreadMetaStore -from deerflow.runtime import ConflictError, ThreadOperationKind +from deerflow.runtime import ConflictError, RunManager, ThreadOperationKind from deerflow.runtime.checkpoint_mode import CheckpointModeMismatchError, CheckpointModeReconfigurationError from deerflow.runtime.checkpoint_state import CheckpointStateAccessor from deerflow.runtime.context_keys import CHECKPOINT_AGENT_NAME_METADATA_KEY @@ -73,8 +73,9 @@ class _PermissiveThreadMetaStore(MemoryThreadMetaStore): return await super().search(metadata=metadata, status=status, limit=limit, offset=offset, user_id=None, archived=archived, project_id=project_id) -class _ThreadTestRunManager: +class _ThreadTestRunManager(RunManager): def __init__(self): + super().__init__() self.reservations: list[tuple[str, dict]] = [] async def list_by_thread(self, _thread_id: str, *, user_id=None, limit: int = 100) -> list: @@ -83,7 +84,8 @@ class _ThreadTestRunManager: @asynccontextmanager async def reserve_thread_operation(self, _thread_id: str, **_kwargs): self.reservations.append((_thread_id, _kwargs)) - yield + async with super().reserve_thread_operation(_thread_id, **_kwargs) as reservation: + yield reservation def _build_thread_app() -> tuple[FastAPI, InMemoryStore, InMemorySaver]: @@ -5667,6 +5669,152 @@ def _seed_branchable_thread(app: FastAPI, thread_id: str) -> None: asyncio.run(_seed(initial.config)) +@pytest.mark.parametrize("failure", ["metadata", "head", "cleanup", "commit_ack"]) +def test_branch_write_failure_keeps_checkpoints_owned(tmp_path, monkeypatch, failure): + app = _build_project_threads_app(tmp_path) + store, saver = app.state.thread_store, app.state.checkpointer + source = "source-branch-failure" + branch_ids = set() + writes = [] + injected = [] + create, put = store.create, saver.aput + + async def create_row(thread_id, **kwargs): + branch_ids.add(thread_id) + if failure == "metadata": + injected.append("metadata") + raise RuntimeError("metadata insert failed") + record = await create(thread_id, **kwargs) + if failure == "commit_ack": + injected.append("commit_ack") + raise RuntimeError("lost metadata commit acknowledgement") + return record + + async def put_checkpoint(config, *args, **kwargs): + branch_ids.add(config["configurable"]["thread_id"]) + if writes and failure in ("head", "cleanup"): + injected.append("head") + raise RuntimeError("branch head write failed") + result = await put(config, *args, **kwargs) + writes.append(result) + return result + + async def fail_cleanup(thread_id): + assert thread_id in branch_ids + injected.append("cleanup") + raise RuntimeError("checkpoint store unavailable on delete") + + with TestClient(app) as client: + assert client.post("/api/threads", json={"thread_id": source}).status_code == 200 + _seed_branchable_thread(app, source) + config = {"configurable": {"thread_id": source}} + original_head = asyncio.run(saver.aget_tuple(config)) + with monkeypatch.context() as faults: + faults.setattr(store, "create", create_row) + faults.setattr(saver, "aput", put_checkpoint) + if failure == "cleanup": + faults.setattr(saver, "adelete_thread", fail_cleanup) + response = client.post(f"/api/threads/{source}/branches", json={"message_id": "ai-1"}) + (child,) = branch_ids + assert child != source + row = asyncio.run(store.get(child, user_id=None)) + head = asyncio.run(saver.aget_tuple({"configurable": {"thread_id": child}})) + assert asyncio.run(saver.aget_tuple(config)).config == original_head.config + if failure == "commit_ack": + assert injected == ["commit_ack"] + assert response.status_code == 200, response.text + assert response.json()["thread_id"] == child + assert row is not None and head is not None + else: + assert response.status_code == 500, response.text + if failure == "cleanup": + assert injected == ["head", "cleanup"] + assert row is not None and head is not None + assert client.delete(f"/api/threads/{child}").status_code == 200 + else: + assert injected == [failure] + assert len(writes) == (0 if failure == "metadata" else 1) + assert asyncio.run(store.get(child, user_id=None)) is None + assert asyncio.run(saver.aget_tuple({"configurable": {"thread_id": child}})) is None + retry = client.post(f"/api/threads/{source}/branches", json={"message_id": "ai-1"}) + assert retry.status_code == 200, retry.text + assert retry.json()["thread_id"] != child + + +@pytest.mark.parametrize( + ("takeover_at", "expected_writes", "remaining_checkpoints"), + [ + ("owner", ["owner"], 0), + ("replay_base", ["owner", "replay_base"], 1), + ("head", ["owner", "replay_base", "head"], 1), + ("checkpoint_cleanup", ["owner", "replay_base", "head", "checkpoint_cleanup"], 0), + ], +) +def test_branch_stops_writing_after_child_takeover(tmp_path, monkeypatch, takeover_at, expected_writes, remaining_checkpoints): + from datetime import UTC, datetime + + from sqlalchemy import update + + from deerflow.config.run_ownership_config import RunOwnershipConfig + from deerflow.persistence.run.model import RunRow + from deerflow.persistence.run.sql import RunRepository + + app = _build_project_threads_app(tmp_path) + sessions = get_session_factory() + runs = RunRepository(sessions) + owner = RunManager(store=runs, worker_id="branch-worker", run_ownership_config=RunOwnershipConfig(heartbeat_enabled=True)) + peer = RunManager(store=runs, worker_id="peer") + app.state.run_manager = owner + store, saver = app.state.thread_store, app.state.checkpointer + create, put, delete_checkpoints = store.create, saver.aput, saver.adelete_thread + writes = [] + takeovers = [] + + async def at_write(stage, thread_id): + writes.append(stage) + if stage == takeover_at: + async with sessions.begin() as session: + await session.execute(update(RunRow).where(RunRow.thread_id == thread_id).values(lease_expires_at=datetime(2000, 1, 1, tzinfo=UTC))) + successor = await peer.create_or_reject(thread_id, multitask_strategy="interrupt", user_id="user-a") + if stage in ("owner", "head"): + # Deliver cancellation inside the write. In the other cases the + # next write must notice the takeover before the next heartbeat. + await owner._renew_leases() + takeovers.append(successor) + + async def create_row(thread_id, **kwargs): + record = await create(thread_id, **kwargs) + await at_write("owner", thread_id) + return record + + async def put_checkpoint(config, *args, **kwargs): + stage = "head" if "replay_base" in writes else "replay_base" + await at_write(stage, config["configurable"]["thread_id"]) + if stage == "head" and takeover_at in ("head", "checkpoint_cleanup"): + raise RuntimeError("branch head write failed") + return await put(config, *args, **kwargs) + + async def remove_checkpoints(thread_id): + await delete_checkpoints(thread_id) + await at_write("checkpoint_cleanup", thread_id) + + with TestClient(app) as client: + assert client.post("/api/threads", json={"thread_id": "source"}).status_code == 200 + _seed_branchable_thread(app, "source") + monkeypatch.setattr(threads, "build_checkpoint_state_mutation_accessor", gateway_services.build_checkpoint_state_mutation_accessor) + monkeypatch.setattr(store, "create", create_row) + monkeypatch.setattr(saver, "aput", put_checkpoint) + monkeypatch.setattr(saver, "adelete_thread", remove_checkpoints) + response = client.post("/api/threads/source/branches", json={"message_id": "ai-1"}) + + (successor,) = takeovers + assert writes == expected_writes + assert asyncio.run(store.get(successor.thread_id, user_id="user-a")) is not None + assert len(list(saver.list({"configurable": {"thread_id": successor.thread_id}}))) == remaining_checkpoints + assert asyncio.run(runs.get(successor.run_id, user_id="user-a"))["status"] == "pending" + assert response.status_code == 409, response.text + + def test_branch_inherits_source_project_membership(tmp_path): """A branch of a project thread stays in the source thread's project.