mirror of
https://github.com/langgenius/dify.git
synced 2026-10-04 13:47:55 +08:00
fix(dify-agent): preserve snapshots for failed and cancelled runs (#40876)
This commit is contained in:
1 parent
96809473fc
commit
a679ee5644
24 files changed
+1575
-440
No files matched your search
@@ -0,0 +1,19 @@
|
||||
"""Private cancellation coordination types shared by schedulers and run stores."""
|
||||
|
||||
from datetime import datetime
|
||||
from typing import ClassVar
|
||||
|
||||
from pydantic import BaseModel, ConfigDict
|
||||
|
||||
|
||||
class RunCancellationIntent(BaseModel):
|
||||
"""The first accepted request to cancel one running run."""
|
||||
|
||||
reason: str | None = None
|
||||
message: str | None = None
|
||||
requested_at: datetime
|
||||
|
||||
model_config: ClassVar[ConfigDict] = ConfigDict(extra="forbid")
|
||||
|
||||
|
||||
__all__ = ["RunCancellationIntent"]
|
||||
@@ -1,9 +1,10 @@
|
||||
"""Event sink contracts used by the runner and storage adapters.
|
||||
|
||||
Non-terminal events remain append-only. Terminal events use ``finalize_run`` so
|
||||
the event and matching run status are committed as one compare-and-set
|
||||
transition. Tests can use ``InMemoryRunEventSink`` without Redis; production
|
||||
storage implements the same contract with Redis streams in
|
||||
Non-terminal events remain append-only. Successful and failed terminal events
|
||||
use ``finalize_run`` so the event and matching run status are committed as one
|
||||
compare-and-set transition. Cancellation has a dedicated intent-aware finalizer.
|
||||
Tests can use ``InMemoryRunEventSink`` without Redis; production storage
|
||||
implements the same contract with Redis streams in
|
||||
``dify_agent.storage.redis_run_store``.
|
||||
"""
|
||||
|
||||
@@ -21,8 +22,6 @@ from dify_agent.protocol.schemas import (
|
||||
EmptyRunEventData,
|
||||
PydanticAIStreamRunEvent,
|
||||
RunEvent,
|
||||
RunCancelledEvent,
|
||||
RunCancelledEventData,
|
||||
RunFailedEvent,
|
||||
RunFailedEventData,
|
||||
RunFailureType,
|
||||
@@ -35,7 +34,7 @@ from dify_agent.protocol.schemas import (
|
||||
|
||||
|
||||
_UNSET = object()
|
||||
TerminalRunEvent: TypeAlias = RunSucceededEvent | RunFailedEvent | RunCancelledEvent
|
||||
TerminalRunEvent: TypeAlias = RunSucceededEvent | RunFailedEvent
|
||||
NonTerminalRunEvent: TypeAlias = RunStartedEvent | PydanticAIStreamRunEvent
|
||||
|
||||
|
||||
@@ -105,8 +104,6 @@ def terminal_event_status_fields(
|
||||
return "succeeded", None, None
|
||||
case RunFailedEvent():
|
||||
return "failed", event.data.error, event.data.error_type
|
||||
case RunCancelledEvent():
|
||||
return "cancelled", event.data.message or event.data.reason, None
|
||||
|
||||
|
||||
async def emit_run_event(
|
||||
@@ -188,29 +185,18 @@ async def emit_run_failed(
|
||||
error: str,
|
||||
error_type: RunFailureType | None = None,
|
||||
reason: str | None = None,
|
||||
session_snapshot: CompositorSessionSnapshot | None = None,
|
||||
) -> RunFinalizationResult:
|
||||
"""Finalize a run with a failed terminal event."""
|
||||
return await sink.finalize_run(
|
||||
RunFailedEvent(
|
||||
run_id=run_id,
|
||||
data=RunFailedEventData(error=error, error_type=error_type, reason=reason),
|
||||
created_at=utc_now(),
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
async def emit_run_cancelled(
|
||||
sink: RunEventSink,
|
||||
*,
|
||||
run_id: str,
|
||||
reason: str | None = None,
|
||||
message: str | None = None,
|
||||
) -> RunFinalizationResult:
|
||||
"""Finalize a run with a cancelled terminal event."""
|
||||
return await sink.finalize_run(
|
||||
RunCancelledEvent(
|
||||
run_id=run_id,
|
||||
data=RunCancelledEventData(reason=reason, message=message),
|
||||
data=RunFailedEventData(
|
||||
error=error,
|
||||
error_type=error_type,
|
||||
reason=reason,
|
||||
session_snapshot=session_snapshot,
|
||||
),
|
||||
created_at=utc_now(),
|
||||
),
|
||||
)
|
||||
@@ -223,7 +209,6 @@ __all__ = [
|
||||
"RunFinalizationResult",
|
||||
"TerminalRunEvent",
|
||||
"emit_pydantic_ai_event",
|
||||
"emit_run_cancelled",
|
||||
"emit_run_event",
|
||||
"emit_run_failed",
|
||||
"emit_run_started",
|
||||
|
||||
@@ -20,10 +20,11 @@ from typing import Protocol
|
||||
|
||||
import httpx
|
||||
|
||||
from agenton.compositor import LayerProviderInput
|
||||
from dify_agent.protocol.schemas import CancelRunRequest, CancelRunResponse, CreateRunRequest
|
||||
from agenton.compositor import CompositorSessionSnapshot, LayerProviderInput
|
||||
from dify_agent.protocol.schemas import CancelRunRequest, CancelRunResponse, CreateRunRequest, RunStatus
|
||||
from dify_agent.runtime.cancellation import RunCancellationIntent
|
||||
from dify_agent.runtime.compositor_factory import create_default_layer_providers
|
||||
from dify_agent.runtime.event_sink import RunEventSink, emit_run_cancelled, emit_run_failed
|
||||
from dify_agent.runtime.event_sink import RunEventSink, RunFinalizationResult, emit_run_failed
|
||||
from dify_agent.runtime.runner import DEFAULT_AGENT_RUN_TIMEOUT_SECONDS, AgentRunRunner
|
||||
from dify_agent.server.schemas import RunRecord
|
||||
|
||||
@@ -45,14 +46,37 @@ class RunStore(RunEventSink, Protocol):
|
||||
"""Persist a new run record and return it with status ``running``."""
|
||||
...
|
||||
|
||||
async def wait_for_cancellation(self, run_id: str) -> bool:
|
||||
"""Wait for a terminal state and report whether cancellation won."""
|
||||
async def request_cancellation(self, run_id: str, request: CancelRunRequest) -> RunStatus:
|
||||
"""Persist the first cancellation intent and return the current status."""
|
||||
...
|
||||
|
||||
async def get_cancellation_intent(self, run_id: str) -> RunCancellationIntent | None:
|
||||
"""Return the accepted cancellation intent, if one exists."""
|
||||
...
|
||||
|
||||
async def wait_for_cancellation(self, run_id: str) -> RunCancellationIntent | None:
|
||||
"""Wait for a cancellation intent or a different terminal state."""
|
||||
...
|
||||
|
||||
async def finalize_cancellation(
|
||||
self,
|
||||
run_id: str,
|
||||
intent: RunCancellationIntent,
|
||||
*,
|
||||
session_snapshot: CompositorSessionSnapshot | None = None,
|
||||
) -> RunFinalizationResult:
|
||||
"""Publish cancellation after the owner runner has exited."""
|
||||
...
|
||||
|
||||
|
||||
class RunnableRun(Protocol):
|
||||
"""Executable unit for one scheduled run."""
|
||||
|
||||
@property
|
||||
def terminal_session_snapshot(self) -> CompositorSessionSnapshot | None:
|
||||
"""Return the post-exit snapshot for the current invocation, if available."""
|
||||
...
|
||||
|
||||
async def run(self) -> None:
|
||||
"""Run until terminal status/events have been written or cancellation occurs."""
|
||||
...
|
||||
@@ -125,14 +149,9 @@ class RunScheduler:
|
||||
|
||||
async def cancel_run(self, run_id: str, request: CancelRunRequest) -> CancelRunResponse:
|
||||
"""Persist an idempotent cancellation without relying on local task ownership."""
|
||||
finalization = await emit_run_cancelled(
|
||||
self.store,
|
||||
run_id=run_id,
|
||||
reason=request.reason,
|
||||
message=request.message,
|
||||
)
|
||||
if finalization.status != "cancelled":
|
||||
raise RunCancellationConflictError(f"run already finished with status {finalization.status!r}")
|
||||
status = await self.store.request_cancellation(run_id, request)
|
||||
if status in {"succeeded", "failed"}:
|
||||
raise RunCancellationConflictError(f"run already finished with status {status!r}")
|
||||
return CancelRunResponse(run_id=run_id, status="cancelled")
|
||||
|
||||
async def shutdown(self) -> None:
|
||||
@@ -141,18 +160,14 @@ class RunScheduler:
|
||||
self.stopping = True
|
||||
if not self.active_tasks:
|
||||
return
|
||||
tasks_by_run_id = dict(self.active_tasks)
|
||||
done, pending = await asyncio.wait(tasks_by_run_id.values(), timeout=self.shutdown_grace_seconds)
|
||||
del done
|
||||
tasks = tuple(self.active_tasks.values())
|
||||
_done, pending = await asyncio.wait(tasks, timeout=self.shutdown_grace_seconds)
|
||||
if not pending:
|
||||
return
|
||||
|
||||
pending_run_ids = [run_id for run_id, task in tasks_by_run_id.items() if task in pending]
|
||||
for task in pending:
|
||||
_ = task.cancel()
|
||||
_ = await asyncio.gather(*pending, return_exceptions=True)
|
||||
for run_id in pending_run_ids:
|
||||
await self._mark_cancelled_run_failed(run_id)
|
||||
|
||||
async def _run_record(self, record: RunRecord, request: CreateRunRequest) -> None:
|
||||
"""Supervise one local runner and its durable cancellation observer."""
|
||||
@@ -163,41 +178,92 @@ class RunScheduler:
|
||||
self.store.wait_for_cancellation(record.run_id),
|
||||
name=f"dify-agent-cancellation-observer-{record.run_id}",
|
||||
)
|
||||
|
||||
async def cancel_runner_and_wait() -> None:
|
||||
if not cancel_requested.is_set() and not runner_task.done():
|
||||
cancel_requested.set()
|
||||
_ = runner_task.cancel()
|
||||
_ = await asyncio.shield(asyncio.gather(runner_task, return_exceptions=True))
|
||||
|
||||
try:
|
||||
_ = await asyncio.wait((runner_task, observer_task), return_when=asyncio.FIRST_COMPLETED)
|
||||
if observer_task.done():
|
||||
try:
|
||||
cancellation_won = observer_task.result()
|
||||
intent = observer_task.result()
|
||||
except Exception as exc:
|
||||
cancel_requested.set()
|
||||
await self._cancel_and_wait(runner_task, reinject=True)
|
||||
_ = await emit_run_failed(
|
||||
await cancel_runner_and_wait()
|
||||
finalization = await emit_run_failed(
|
||||
self.store,
|
||||
run_id=record.run_id,
|
||||
error=f"run cancellation observer failed: {exc}",
|
||||
reason="cancellation_observer",
|
||||
session_snapshot=runner.terminal_session_snapshot,
|
||||
)
|
||||
if not finalization.applied and finalization.status == "running":
|
||||
intent = await self.store.get_cancellation_intent(record.run_id)
|
||||
if intent is not None:
|
||||
_ = await self.store.finalize_cancellation(
|
||||
record.run_id,
|
||||
intent,
|
||||
session_snapshot=runner.terminal_session_snapshot,
|
||||
)
|
||||
raise
|
||||
|
||||
if cancellation_won:
|
||||
cancel_requested.set()
|
||||
await self._cancel_and_wait(runner_task, reinject=True)
|
||||
if intent is not None:
|
||||
await cancel_runner_and_wait()
|
||||
_ = await self.store.finalize_cancellation(
|
||||
record.run_id,
|
||||
intent,
|
||||
session_snapshot=runner.terminal_session_snapshot,
|
||||
)
|
||||
else:
|
||||
await runner_task
|
||||
else:
|
||||
await runner_task
|
||||
runner_error: Exception | None = None
|
||||
try:
|
||||
await runner_task
|
||||
except Exception as exc:
|
||||
runner_error = exc
|
||||
|
||||
intent = await self.store.get_cancellation_intent(record.run_id)
|
||||
if intent is not None:
|
||||
_ = await self.store.finalize_cancellation(
|
||||
record.run_id,
|
||||
intent,
|
||||
session_snapshot=runner.terminal_session_snapshot,
|
||||
)
|
||||
if runner_error is not None:
|
||||
raise runner_error
|
||||
except asyncio.CancelledError:
|
||||
cancel_requested.set()
|
||||
await self._cancel_and_wait(observer_task)
|
||||
await self._cancel_and_wait(runner_task, reinject=True)
|
||||
await cancel_runner_and_wait()
|
||||
intent = await self.store.get_cancellation_intent(record.run_id)
|
||||
if intent is not None:
|
||||
_ = await self.store.finalize_cancellation(
|
||||
record.run_id,
|
||||
intent,
|
||||
session_snapshot=runner.terminal_session_snapshot,
|
||||
)
|
||||
else:
|
||||
finalization = await self._mark_cancelled_run_failed(
|
||||
record.run_id,
|
||||
session_snapshot=runner.terminal_session_snapshot,
|
||||
)
|
||||
if finalization is not None and not finalization.applied and finalization.status == "running":
|
||||
intent = await self.store.get_cancellation_intent(record.run_id)
|
||||
if intent is not None:
|
||||
_ = await self.store.finalize_cancellation(
|
||||
record.run_id,
|
||||
intent,
|
||||
session_snapshot=runner.terminal_session_snapshot,
|
||||
)
|
||||
raise
|
||||
except Exception:
|
||||
logger.exception("scheduled run failed", extra={"run_id": record.run_id})
|
||||
finally:
|
||||
await self._cancel_and_wait(observer_task)
|
||||
if not runner_task.done():
|
||||
cancel_requested.set()
|
||||
await self._cancel_and_wait(runner_task, reinject=True)
|
||||
await cancel_runner_and_wait()
|
||||
|
||||
def _create_runner(
|
||||
self,
|
||||
@@ -234,25 +300,31 @@ class RunScheduler:
|
||||
_ = self.active_tasks.pop(run_id, None)
|
||||
|
||||
@staticmethod
|
||||
async def _cancel_and_wait(task: asyncio.Task[object], *, reinject: bool = False) -> None:
|
||||
"""Cancel and reap a child task, with bounded reinjection for runners."""
|
||||
async def _cancel_and_wait(task: asyncio.Task[object]) -> None:
|
||||
"""Cancel a child task once and await its complete exit."""
|
||||
if not task.done():
|
||||
_ = task.cancel()
|
||||
if reinject:
|
||||
for _attempt in range(2):
|
||||
await asyncio.sleep(0)
|
||||
if task.done():
|
||||
break
|
||||
_ = task.cancel()
|
||||
_ = await asyncio.gather(task, return_exceptions=True)
|
||||
|
||||
async def _mark_cancelled_run_failed(self, run_id: str) -> None:
|
||||
async def _mark_cancelled_run_failed(
|
||||
self,
|
||||
run_id: str,
|
||||
*,
|
||||
session_snapshot: CompositorSessionSnapshot | None = None,
|
||||
) -> RunFinalizationResult | None:
|
||||
"""Best-effort failure event/status for shutdown-cancelled runs."""
|
||||
message = "run cancelled during server shutdown"
|
||||
try:
|
||||
_ = await emit_run_failed(self.store, run_id=run_id, error=message, reason="shutdown")
|
||||
return await emit_run_failed(
|
||||
self.store,
|
||||
run_id=run_id,
|
||||
error=message,
|
||||
reason="shutdown",
|
||||
session_snapshot=session_snapshot,
|
||||
)
|
||||
except Exception:
|
||||
logger.exception("failed to mark cancelled run failed", extra={"run_id": run_id})
|
||||
return None
|
||||
|
||||
|
||||
__all__ = ["RunCancellationConflictError", "RunScheduler", "SchedulerStoppingError"]
|
||||
@@ -184,6 +184,7 @@ class AgentRunRunner:
|
||||
dify_api_http_client: httpx.AsyncClient
|
||||
is_cancelled: Callable[[], bool]
|
||||
run_timeout_seconds: float
|
||||
_terminal_session_snapshot: CompositorSessionSnapshot | None
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
@@ -205,9 +206,16 @@ class AgentRunRunner:
|
||||
self.layer_providers = layer_providers if layer_providers is not None else create_default_layer_providers()
|
||||
self.is_cancelled = is_cancelled or (lambda: False)
|
||||
self.run_timeout_seconds = run_timeout_seconds
|
||||
self._terminal_session_snapshot = None
|
||||
|
||||
@property
|
||||
def terminal_session_snapshot(self) -> CompositorSessionSnapshot | None:
|
||||
"""Return the snapshot captured after the current compositor context exited."""
|
||||
return self._terminal_session_snapshot
|
||||
|
||||
async def run(self) -> None:
|
||||
"""Execute the run and emit the documented event sequence."""
|
||||
self._terminal_session_snapshot = None
|
||||
if self.is_cancelled():
|
||||
return
|
||||
_ = await emit_run_started(self.sink, run_id=self.run_id)
|
||||
@@ -224,6 +232,7 @@ class AgentRunRunner:
|
||||
error=message,
|
||||
error_type=error_type,
|
||||
reason=reason,
|
||||
session_snapshot=self._terminal_session_snapshot,
|
||||
)
|
||||
if finalization.applied:
|
||||
raise
|
||||
@@ -287,6 +296,7 @@ class AgentRunRunner:
|
||||
deferred_tool_call: DeferredToolCallPayload | None = None
|
||||
result_kind: Literal["output", "deferred_tool_call"] | None = None
|
||||
usage: AgentRunUsage | None = None
|
||||
run = None
|
||||
try:
|
||||
async with compositor.enter(configs=layer_configs, session_snapshot=self.request.session_snapshot) as run:
|
||||
entered_run = True
|
||||
@@ -383,8 +393,11 @@ class AgentRunRunner:
|
||||
if not entered_run:
|
||||
raise AgentRunValidationError(str(exc)) from exc
|
||||
raise
|
||||
finally:
|
||||
if entered_run and run is not None:
|
||||
self._terminal_session_snapshot = run.session_snapshot
|
||||
|
||||
if run.session_snapshot is None:
|
||||
if run is None or run.session_snapshot is None:
|
||||
raise RuntimeError("Agenton run did not produce a session snapshot after exit.")
|
||||
if result_kind is None:
|
||||
raise RuntimeError("Agent run did not resolve either a final output or a deferred tool call.")
|
||||
|
||||
Reference in new issue
Block a user