Build Agentic workflows, RAG pipelines, with rich AI model and tool support on one collaborative workspace. Deploy on cloud, VPC, or self-hosted, so teams move from prototype to production without rebuilding the stack.
Python agentagentic-aiagentic-frameworkagentic-workflowaiautomationclaudedeepseekgenaigptllmlow-codemcpnextjsno-codeopenaipythonskillsworkflow
fix(dify-agent): reject non-terminal event appends after the run stream is sealed (#45080)
梦想陆地的鱼0c82953c625a
diff --git a/dify-agent/src/dify_agent/runtime/event_sink.py b/dify-agent/src/dify_agent/runtime/event_sink.pyindex ea68a3e1948..044c5767aa0 100644--- a/dify-agent/src/dify_agent/runtime/event_sink.py+++ b/dify-agent/src/dify_agent/runtime/event_sink.py@@ -45,11 +45,30 @@ class RunFinalizationResult:event_id: str | None = None+class RunStreamSealedError(RuntimeError):+ """Raised when a non-terminal event arrives after the run stream was sealed.++ The first terminal transition seals the stream: later non-terminal appends+ must not persist, consume a cursor, or refresh retention. ``status``+ carries the winning terminal status so callers can coordinate without+ re-reading the run record.+ """++ def __init__(self, run_id: str, status: RunStatus) -> None:+ super().__init__(f"run {run_id} is already {status}; the stream no longer accepts non-terminal events")+ self.run_id = run_id+ self.status = status++class RunEventSink(Protocol):"""Boundary used by runtime code to publish observable run progress."""async def append_event(self, event: NonTerminalRunEvent) -> str:- """Persist a non-terminal event and return its cursor id."""+ """Persist a non-terminal event and return its cursor id.++ Raises ``RunStreamSealedError`` when the run already has a terminal+ status; the sealed stream must not accept further non-terminal events.+ """...async def finalize_run(self, event: TerminalRunEvent) -> RunFinalizationResult:@@ -73,6 +92,9 @@ class InMemoryRunEventSink:async def append_event(self, event: NonTerminalRunEvent) -> str:"""Store a non-terminal event and assign a monotonic per-run cursor."""+ current_status = self.statuses.get(event.run_id, "running")+ if current_status != "running":+ raise RunStreamSealedError(event.run_id, current_status)event_id = str(len(self.events[event.run_id]) + 1)stored = event.model_copy(update={"id": event_id})self.events[event.run_id].append(stored)@@ -196,6 +218,7 @@ __all__ = ["NonTerminalRunEvent","RunEventSink","RunFinalizationResult",+ "RunStreamSealedError","TerminalRunEvent","emit_pydantic_ai_event","emit_run_event",diff --git a/dify-agent/src/dify_agent/runtime/runner.py b/dify-agent/src/dify_agent/runtime/runner.pyindex 0bf85393e26..8c9bf2df1e1 100644--- a/dify-agent/src/dify_agent/runtime/runner.py+++ b/dify-agent/src/dify_agent/runtime/runner.py@@ -53,6 +53,7 @@ from dify_agent.runtime.event_coalescer import ()from dify_agent.runtime.event_sink import (RunEventSink,+ RunStreamSealedError,emit_pydantic_ai_event,emit_run_failed,emit_run_started,@@ -209,6 +210,11 @@ class AgentRunRunner:try:_ = await emit_run_started(self.sink, run_id=self.run_id)outcome = await self._run_agent()+ except RunStreamSealedError:+ # A terminal transition (typically a cancellation accepted by+ # another process) sealed the stream first; stop without+ # appending a second terminal event.+ returnexcept BaseException as exc:failure = excraisediff --git a/dify-agent/src/dify_agent/storage/redis_run_store.py b/dify-agent/src/dify_agent/storage/redis_run_store.pyindex 13e0129c85f..1add62ceae4 100644--- a/dify-agent/src/dify_agent/storage/redis_run_store.py+++ b/dify-agent/src/dify_agent/storage/redis_run_store.py@@ -31,6 +31,7 @@ from dify_agent.runtime.event_sink import (NonTerminalRunEvent,RunEventSink,RunFinalizationResult,+ RunStreamSealedError,TerminalRunEvent,terminal_event_status_fields,)@@ -82,6 +83,25 @@ return {1, ARGV[1], event_id}"""+_APPEND_EVENT_SCRIPT = """+local record_json = redis.call("GET", KEYS[1])+if not record_json then+ return {-1, ""}+end++local record = cjson.decode(record_json)+if record.status ~= "running" then+ return {0, tostring(record.status), ""}+end++local ttl = tonumber(ARGV[3])+local event_id = redis.call("XADD", KEYS[2], "MAXLEN", "~", ARGV[2], "*", "payload", ARGV[1])+redis.call("EXPIRE", KEYS[2], ttl)+redis.call("EXPIRE", KEYS[1], ttl)+return {1, "running", event_id}+"""++_REQUEST_CANCELLATION_SCRIPT = """local record_json = redis.call("GET", KEYS[1])if not record_json then@@ -200,21 +220,33 @@ class RedisRunStore(RunEventSink):@overrideasync def append_event(self, event: NonTerminalRunEvent) -> str:- """Append a non-terminal event JSON payload with refreshed TTLs."""- events_key = run_events_key(self.prefix, event.run_id)+ """Append a non-terminal event while the durable run status is still ``running``.++ The status check and the write share one linearization point with+ ``finalize_run``/``finalize_cancellation``: once a terminal transition+ wins, late non-terminal appends are rejected without consuming a+ cursor or refreshing retention.+ """payload = RUN_EVENT_ADAPTER.dump_json(event, exclude={"id"}).decode()- async with self.redis.pipeline(transaction=True) as pipeline:- _ = pipeline.xadd(- events_key,- {"payload": payload},- maxlen=self.run_event_stream_max_length,- approximate=True,- )- _ = pipeline.expire(events_key, self.run_retention_seconds)- _ = pipeline.expire(run_record_key(self.prefix, event.run_id), self.run_retention_seconds)- results = cast(list[object], await pipeline.execute())- event_id = results[0]- return event_id.decode() if isinstance(event_id, bytes) else str(event_id)+ evaluation = cast(+ Awaitable[object],+ self.redis.eval(+ _APPEND_EVENT_SCRIPT,+ 2,+ run_record_key(self.prefix, event.run_id),+ run_events_key(self.prefix, event.run_id),+ payload,+ str(self.run_event_stream_max_length),+ str(self.run_retention_seconds),+ ),+ )+ result = cast(list[object], await evaluation)+ applied = int(cast(int | bytes | str, result[0]))+ if applied == -1:+ raise RunNotFoundError(event.run_id)+ if applied == 0:+ raise RunStreamSealedError(event.run_id, cast(RunStatus, _decode_redis_text(result[1])))+ return _decode_redis_text(result[2])@overrideasync def finalize_run(self, event: TerminalRunEvent) -> RunFinalizationResult:diff --git a/dify-agent/tests/local/dify_agent/runtime/test_event_sink.py b/dify-agent/tests/local/dify_agent/runtime/test_event_sink.pynew file mode 100644index 00000000000..b0d4f3b4404--- /dev/null+++ b/dify-agent/tests/local/dify_agent/runtime/test_event_sink.py@@ -0,0 +1,20 @@+"""Contract tests for the in-memory RunEventSink adapter."""++import pytest++from dify_agent.protocol.schemas import RunFailedEvent, RunFailedEventData, RunStartedEvent+from dify_agent.runtime.event_sink import InMemoryRunEventSink, RunStreamSealedError+++async def test_append_event_after_terminal_finalization_is_rejected():+ sink = InMemoryRunEventSink()+ finalization = await sink.finalize_run(RunFailedEvent(run_id="run-1", data=RunFailedEventData(error="boom")))+ assert finalization.applied++ with pytest.raises(RunStreamSealedError) as sealed:+ await sink.append_event(RunStartedEvent(run_id="run-1"))++ assert sealed.value.run_id == "run-1"+ assert sealed.value.status == "failed"+ assert [type(event) for event in sink.events["run-1"]] == [RunFailedEvent]diff --git a/dify-agent/tests/local/dify_agent/runtime/test_runner.py b/dify-agent/tests/local/dify_agent/runtime/test_runner.pyindex 6a5252d8def..30ec790769e 100644--- a/dify-agent/tests/local/dify_agent/runtime/test_runner.py+++ b/dify-agent/tests/local/dify_agent/runtime/test_runner.py@@ -26,6 +26,7 @@ from dify_agent.protocol.schemas import (CreateRunRequest,RunComposition,RunFailedEvent,+ RunFailedEventData,RunLayerSpec,RunSucceededEvent,RunFailureType,@@ -244,6 +245,32 @@ async def test_run_started_store_failure_finalizes_run_as_failed(monkeypatch):assert terminal.data.error == "store unavailable"+async def test_sealed_stream_stops_runner_without_second_terminal_event(monkeypatch):+ async def stream(messages, info):+ pytest.fail("the model must not run when the stream is already sealed")+ yield "unreachable"++ async with httpx.AsyncClient() as client:+ model = FunctionModel(stream_function=stream)+ monkeypatch.setattr(llm_layer.Capability, "build_model", lambda self, deps: model)+ sink = InMemoryRunEventSink()+ sealed = await sink.finalize_run(+ RunFailedEvent(run_id="test", data=RunFailedEventData(error="cancelled elsewhere"))+ )+ assert sealed.applied+ runner = AgentRunRunner(+ sink=sink,+ request=request(),+ run_id="test",+ services=Services(client, client),+ run_timeout_seconds=10,+ )+ await runner.run()+ assert sink.statuses["test"] == "failed"+ assert [type(event) for event in sink.events["test"]] == [RunFailedEvent]++@pytest.mark.anyio@pytest.mark.parametrize("invalid_first", [False, True])async def test_native_structured_output_uses_output_module(monkeypatch, invalid_first):diff --git a/dify-agent/tests/local/dify_agent/storage/test_redis_run_store.py b/dify-agent/tests/local/dify_agent/storage/test_redis_run_store.pyindex 3b78bbf711a..ba9c5cf6b7f 100644--- a/dify-agent/tests/local/dify_agent/storage/test_redis_run_store.py+++ b/dify-agent/tests/local/dify_agent/storage/test_redis_run_store.py@@ -4,6 +4,7 @@ import jsonfrom typing import castimport pytest+from fakeredis.aioredis import FakeRedis as AsyncFakeRedisfrom pydantic import JsonValuefrom dify_agent.protocol.snapshot import SessionSnapshot@@ -22,7 +23,7 @@ from dify_agent.protocol.schemas import (utc_now,)from dify_agent.runtime.cancellation import RunCancellationIntent-from dify_agent.runtime.event_sink import RunFinalizationResult+from dify_agent.runtime.event_sink import RunFinalizationResult, RunStreamSealedErrorfrom dify_agent.storage.redis_run_store import (DEFAULT_RUN_EVENT_STREAM_MAX_LENGTH,DEFAULT_RUN_RETENTION_SECONDS,@@ -354,7 +355,10 @@ def test_wait_for_cancellation_ignores_public_events() -> None:redis.commands.clear()observer = asyncio.create_task(store.wait_for_cancellation(record.run_id))await asyncio.sleep(0)- _ = await store.append_event(RunStartedEvent(run_id=record.run_id))+ _ = redis._append_stream_entry(+ f"test:runs:{record.run_id}:events",+ {"payload": RUN_EVENT_ADAPTER.dump_json(RunStartedEvent(run_id=record.run_id), exclude={"id"}).decode()},+ )await asyncio.sleep(0)assert observer.done() is Falsexread_commands = [command for command in redis.commands if command[0] == "xread"]@@ -375,49 +379,139 @@ def test_wait_for_cancellation_ignores_public_events() -> None:assert asyncio.run(scenario()).reason == "cancelled"-def test_append_event_serializes_typed_event_without_id_and_expires_run_keys() -> None:+def test_append_event_maps_eval_script_arguments_and_result() -> None:redis = FakeRedis()+ redis.eval_result = [1, "running", "7-0"]store = RedisRunStore(redis, prefix="test", run_retention_seconds=60) # pyright: ignore[reportArgumentType]event_id = asyncio.run(store.append_event(RunStartedEvent(id="local", run_id="run-1")))- assert event_id == "1-0"- pipeline_commands = [command for command in redis.commands if command[0] == "pipeline"]- assert len(pipeline_commands) == 1- assert pipeline_commands[0][1] is True- xadd_commands = [command for command in redis.commands if command[0] == "xadd"]- assert len(xadd_commands) == 1- fields = xadd_commands[0][2]- assert isinstance(fields, dict)- assert '"id"' not in str(fields["payload"])- assert '"type":"run_started"' in str(fields["payload"])- assert xadd_commands[0][3:] == (DEFAULT_RUN_EVENT_STREAM_MAX_LENGTH, True)- expire_commands = {command for command in redis.commands if command[0] == "expire"}- assert expire_commands == {- ("expire", "test:runs:run-1:events", 60),- ("expire", "test:runs:run-1:record", 60),- }- assert ("execute",) in redis.commands+ assert event_id == "7-0"+ eval_commands = [command for command in redis.commands if command[0] == "eval"]+ assert len(eval_commands) == 1+ script, numkeys, record_key, events_key, payload, maxlen, ttl = eval_commands[0][1:]+ assert numkeys == 2+ assert (record_key, events_key) == ("test:runs:run-1:record", "test:runs:run-1:events")+ assert '"id"' not in payload+ assert '"type":"run_started"' in payload+ assert maxlen == str(DEFAULT_RUN_EVENT_STREAM_MAX_LENGTH)+ assert ttl == "60"-def test_append_event_keeps_only_the_configured_number_of_entries() -> None:- redis = FakeRedis()- store = RedisRunStore(- redis, # pyright: ignore[reportArgumentType]- prefix="test",- run_retention_seconds=60,- run_event_stream_max_length=2,- )+def test_append_event_persists_while_running_and_refreshes_ttls() -> None:+ async def scenario() -> None:+ client = AsyncFakeRedis()+ store = RedisRunStore(client, prefix="test", run_retention_seconds=60)+ record = await store.create_run()+ event_id = await store.append_event(RunStartedEvent(run_id=record.run_id))++ assert event_id.endswith("-0")+ page = await store.get_events(record.run_id)+ assert [event.type for event in page.events] == ["run_started"]+ assert page.events[0].id == event_id+ events_ttl = await client.ttl(f"test:runs:{record.run_id}:events")+ record_ttl = await client.ttl(f"test:runs:{record.run_id}:record")+ assert 0 < events_ttl <= 60+ assert 0 < record_ttl <= 60++ asyncio.run(scenario())+++def test_append_event_keeps_only_the_configured_number_of_entries() -> None:async def scenario() -> None:+ client = AsyncFakeRedis()+ store = RedisRunStore(+ client,+ prefix="test",+ run_retention_seconds=60,+ run_event_stream_max_length=2,+ )+ record = await store.create_run()+for _ in range(3):- _ = await store.append_event(RunStartedEvent(run_id="run-1"))+ _ = await store.append_event(RunStartedEvent(run_id=record.run_id))++ entries = await client.xrange(f"test:runs:{record.run_id}:events")+ assert len(entries) == 2asyncio.run(scenario())- assert len(redis.streams["test:runs:run-1:events"]) == 2- xadd_commands = [command for command in redis.commands if command[0] == "xadd"]- assert all(command[3:] == (2, True) for command in xadd_commands)++def test_append_event_winning_first_keeps_terminal_last() -> None:+ async def scenario() -> None:+ client = AsyncFakeRedis()+ store = RedisRunStore(client, prefix="test", run_retention_seconds=60)+ record = await store.create_run()++ first = await store.append_event(RunStartedEvent(run_id=record.run_id))+ finalization = await store.finalize_run(+ RunFailedEvent(run_id=record.run_id, data=RunFailedEventData(error="boom"))+ )++ assert finalization.applied+ assert finalization.event_id is not None and finalization.event_id > first+ page = await store.get_events(record.run_id)+ assert [event.type for event in page.events] == ["run_started", "run_failed"]++ asyncio.run(scenario())+++def test_append_event_is_rejected_after_terminal_finalization() -> None:+ async def scenario() -> None:+ client = AsyncFakeRedis()+ store = RedisRunStore(client, prefix="test", run_retention_seconds=60)+ record = await store.create_run()+ finalization = await store.finalize_run(+ RunFailedEvent(run_id=record.run_id, data=RunFailedEventData(error="boom"))+ )+ assert finalization.applied+ events_key = f"test:runs:{record.run_id}:events"+ _ = await client.expire(events_key, 30)++ with pytest.raises(RunStreamSealedError) as sealed:+ await store.append_event(RunStartedEvent(run_id=record.run_id))++ assert sealed.value.run_id == record.run_id+ assert sealed.value.status == "failed"+ page = await store.get_events(record.run_id)+ assert [event.type for event in page.events] == ["run_failed"]+ assert await client.ttl(events_key) == 30++ asyncio.run(scenario())+++def test_append_event_is_rejected_after_cancellation_wins() -> None:+ async def scenario() -> None:+ client = AsyncFakeRedis()+ store = RedisRunStore(client, prefix="test", run_retention_seconds=60)+ record = await store.create_run()+ _ = await store.request_cancellation(record.run_id, CancelRunRequest(reason="user"))+ intent = await store.get_cancellation_intent(record.run_id)+ assert intent is not None+ _ = await store.finalize_cancellation(record.run_id, intent)++ with pytest.raises(RunStreamSealedError) as sealed:+ await store.append_event(RunStartedEvent(run_id=record.run_id))++ assert sealed.value.status == "cancelled"+ page = await store.get_events(record.run_id)+ assert [event.type for event in page.events] == ["run_cancelled"]++ asyncio.run(scenario())+++def test_append_event_raises_when_run_record_is_missing() -> None:+ async def scenario() -> None:+ client = AsyncFakeRedis()+ store = RedisRunStore(client, prefix="test", run_retention_seconds=60)++ with pytest.raises(RunNotFoundError):+ await store.append_event(RunStartedEvent(run_id="missing"))++ assert not await client.exists("test:runs:missing:events")++ asyncio.run(scenario())def test_get_events_round_trips_run_succeeded_output_and_session_snapshot() -> None:@@ -523,8 +617,16 @@ def test_iter_events_ends_after_replaying_terminal_event(terminal_type: str) ->async def scenario() -> list[str]:record = await store.create_run()+ events_key = f"test:runs:{record.run_id}:events"for _ in range(101):- _ = await store.append_event(RunStartedEvent(run_id=record.run_id))+ _ = redis._append_stream_entry(+ events_key,+ {+ "payload": RUN_EVENT_ADAPTER.dump_json(+ RunStartedEvent(run_id=record.run_id), exclude={"id"}+ ).decode()+ },+ )terminal = _terminal_event(terminal_type, record.run_id)_ = redis._append_stream_entry(f"test:runs:{record.run_id}:events",@@ -550,7 +652,10 @@ def test_iter_events_ends_after_live_terminal_event(terminal_type: str) -> None:async def scenario() -> str:record = await store.create_run()- started_id = await store.append_event(RunStartedEvent(run_id=record.run_id))+ started_id = redis._append_stream_entry(+ f"test:runs:{record.run_id}:events",+ {"payload": RUN_EVENT_ADAPTER.dump_json(RunStartedEvent(run_id=record.run_id), exclude={"id"}).decode()},+ )events = store.iter_events(record.run_id)assert (await anext(events)).id == started_idnext_event = asyncio.ensure_future(anext(events))