diff --git a/docs/development.md b/docs/development.md index 81244202..c0851d3c 100644 --- a/docs/development.md +++ b/docs/development.md @@ -1,5 +1,5 @@ # Development navigation @@ -83,8 +83,17 @@ public surface. [code runtime tests](../tests/dsl/test_code_runtime.py). - **Human input:** inject the [HITLCallback](../src/graphon/nodes/human_input/entities.py) into [HumanInputNode](../src/graphon/nodes/human_input/human_input_node.py). - The host returns a pause, completed, or expired decision. See + The host returns a pause, completed, or expired decision. The built-in node + still emits the deprecated `HitlRequired` reason. See [human-input tests](../tests/nodes/human_input/) for the event contract. +- For new integrations, yield `PauseRequestedEvent` with + [`ExternalWait`](../src/graphon/entities/pause_reason.py), the general-purpose + pause reason for waits such as human input or an external service result. It requires + a `wait_type` of one or more dot-separated ASCII identifiers and an opaque + `wait_id` string whose meaning the host defines. Reserve `dify.*` for upstream + Dify producers. Include `node_id` and `node_title` to identify the node in the + graph, and `node_execution_id` and `frame_id` to identify the execution that + requested the pause. See the [round-trip tests](../tests/runtime/test_external_wait.py). ## Validate the behavior you changed diff --git a/src/graphon/entities/pause_reason.py b/src/graphon/entities/pause_reason.py index ee94849f..ede9fc50 100644 --- a/src/graphon/entities/pause_reason.py +++ b/src/graphon/entities/pause_reason.py @@ -2,6 +2,7 @@ from typing import Annotated, Literal, cast from pydantic import BaseModel, BeforeValidator, ConfigDict, Field +from typing_extensions import deprecated class PauseReasonType(StrEnum): @@ -14,9 +15,13 @@ class PauseReasonType(StrEnum): HITL_REQUIRED = auto() SCHEDULED_PAUSE = auto() + EXTERNAL_WAIT = auto() +@deprecated("Use ExternalWait for new pause reasons.", category=None) class HitlRequired(BaseModel): + """Deprecated human-input pause reason emitted by the built-in Human Input node.""" + model_config = ConfigDict(extra="forbid") TYPE: Literal[PauseReasonType.HITL_REQUIRED] = PauseReasonType.HITL_REQUIRED @@ -31,6 +36,37 @@ class SchedulingPause(BaseModel): message: str +class ExternalWait(BaseModel): + """General-purpose pause reason for a node awaiting a host-managed result. + + Nodes can use this reason to wait for human input or an external service. + The host defines the meaning of ``wait_id`` for each ``wait_type`` and + resumes the waiting execution when the result is ready. + """ + + model_config = ConfigDict(frozen=True) + + TYPE: Literal[PauseReasonType.EXTERNAL_WAIT] = PauseReasonType.EXTERNAL_WAIT + # Hosts use this type to interpret wait_id. The dify.* namespace is + # reserved for wait types defined by upstream Dify. + # PEG grammar for wait_type: + # WAIT_TYPE <- IDENTIFIER ('.' IDENTIFIER)* !. + # IDENTIFIER <- [A-Za-z_] [A-Za-z0-9_]* + wait_type: str = Field( + pattern=r"^[A-Za-z_][A-Za-z0-9_]*(\.[A-Za-z_][A-Za-z0-9_]*)*$" + ) + # Opaque identifier of the work the host is waiting for. + wait_id: str + # ID of the node in the graph definition, shared across its executions. + node_id: str = Field(min_length=1) + # Display title of the node at the time it requested the pause. + node_title: str + # ID of the specific node execution that requested the pause. + node_execution_id: str = Field(min_length=1) + # ID of the execution frame containing that node execution. + frame_id: str = Field(min_length=1) + + class _LegacyHumanInputRequired(BaseModel): """ This model serves as documentation purpose. DO NOT USE. @@ -71,7 +107,7 @@ def _decode_pause_reason(value: object) -> object: type PauseReason = Annotated[ - HitlRequired | SchedulingPause, + HitlRequired | SchedulingPause | ExternalWait, # ty: ignore[deprecated] Field(discriminator="TYPE"), BeforeValidator(_decode_pause_reason), ] diff --git a/src/graphon/nodes/human_input/human_input_node.py b/src/graphon/nodes/human_input/human_input_node.py index 486750df..1e4fcc88 100644 --- a/src/graphon/nodes/human_input/human_input_node.py +++ b/src/graphon/nodes/human_input/human_input_node.py @@ -3,7 +3,7 @@ from collections.abc import Generator, Mapping, Sequence from typing import Any, override -from graphon.entities.pause_reason import HitlRequired +from graphon.entities.pause_reason import HitlRequired # ty: ignore[deprecated] from graphon.enums import ( BuiltinNodeTypes, NodeExecutionType, @@ -72,7 +72,7 @@ def _run(self) -> Generator[NodeEventPayload, None, None]: match decision: case PauseRequested(session_id=session_id): yield PauseRequestedEvent( - reason=HitlRequired( + reason=HitlRequired( # ty: ignore[deprecated] session_id=session_id, node_id=self.id, node_title=self.title, diff --git a/tests/engine/test_dispatch_patterns.py b/tests/engine/test_dispatch_patterns.py index 47ef1823..b7bec3b9 100644 --- a/tests/engine/test_dispatch_patterns.py +++ b/tests/engine/test_dispatch_patterns.py @@ -61,7 +61,7 @@ GraphEdgeSkippedEvent, GraphEdgeTakenEvent, ) -from graphon.entities.pause_reason import HitlRequired, SchedulingPause +from graphon.entities.pause_reason import HitlRequired, SchedulingPause # ty: ignore[deprecated] from graphon.enums import ( BuiltinNodeTypes, ErrorHandleMode, @@ -1135,7 +1135,7 @@ def test_pause_requested_event_defers_current_task_for_resume() -> None: id="human-run", node_id="human", node_type=BuiltinNodeTypes.HUMAN_INPUT, - reason=HitlRequired( + reason=HitlRequired( # ty: ignore[deprecated] session_id="session-1", node_id="human", node_title="Human", @@ -1325,7 +1325,7 @@ def test_frame_registry_restores_child_frame() -> None: assert child_frame.graph.nodes["start"].state == NodeState.TAKEN graph_execution.pause( - HitlRequired( + HitlRequired( # ty: ignore[deprecated] session_id="session-1", node_id="start", node_title="Start", diff --git a/tests/engine/test_response_stream_pause.py b/tests/engine/test_response_stream_pause.py index c65abad3..0fd0776a 100644 --- a/tests/engine/test_response_stream_pause.py +++ b/tests/engine/test_response_stream_pause.py @@ -31,7 +31,7 @@ NodeRunStreamChunkEvent, NodeRunSucceededEvent, ) -from graphon.entities.pause_reason import HitlRequired, SchedulingPause +from graphon.entities.pause_reason import HitlRequired, SchedulingPause # ty: ignore[deprecated] from graphon.entities.workflow_start_reason import WorkflowStartReason from graphon.nodes.human_input.entities import ( Completed, @@ -200,7 +200,7 @@ def test_hitl_snapshots_resume_stream_without_replaying_prefix( ) -> None: saved = checkpoints.first if paused_at == "first" else checkpoints.second assert saved.pause.reasons == [ - HitlRequired( + HitlRequired( # ty: ignore[deprecated] session_id=f"session-{paused_at}", node_id=paused_at, node_title=f"{paused_at.title()} approval", diff --git a/tests/engine/test_runtime_state_serialization.py b/tests/engine/test_runtime_state_serialization.py index 71bc1871..2959573b 100644 --- a/tests/engine/test_runtime_state_serialization.py +++ b/tests/engine/test_runtime_state_serialization.py @@ -46,7 +46,7 @@ NodeRunSucceededEvent, ) from graphon.entities.graph_config import NodeConfigDict -from graphon.entities.pause_reason import HitlRequired +from graphon.entities.pause_reason import HitlRequired # ty: ignore[deprecated] from graphon.entities.workflow_start_reason import WorkflowStartReason from graphon.enums import ( BuiltinNodeTypes, @@ -875,7 +875,7 @@ def pause_after_one_round(context: HITLContext) -> Completed | PauseRequested: ] assert len(pause_requests) == 1 assert pause_requests[0].container_id == "loop" - assert pause_requests[0].reason == HitlRequired( + assert pause_requests[0].reason == HitlRequired( # ty: ignore[deprecated] session_id="session-human-input", node_id="human-input", node_title="Approve loop round", @@ -1082,7 +1082,7 @@ def pause_with_active_sibling( resume_tasks = [task for task in deferred_tasks if isinstance(task, ResumeTask)] assert len(pause_requests) == 1 assert pause_requests[0].container_id == "iteration" - assert pause_requests[0].reason == HitlRequired( + assert pause_requests[0].reason == HitlRequired( # ty: ignore[deprecated] session_id="session-beta", node_id="human-input", node_title="Approve iteration item", diff --git a/tests/entities/test_pause_reason.py b/tests/entities/test_pause_reason.py index 89a5f301..eb466a91 100644 --- a/tests/entities/test_pause_reason.py +++ b/tests/entities/test_pause_reason.py @@ -5,7 +5,7 @@ from pydantic import BaseModel, ValidationError from graphon.entities.pause_reason import ( - HitlRequired, + HitlRequired, # ty: ignore[deprecated] PauseReason, SchedulingPause, ) @@ -28,7 +28,7 @@ class TestPauseReasonDiscriminator: "node_title": "node_title", }, }, - HitlRequired( + HitlRequired( # ty: ignore[deprecated] session_id="session-1", node_id="node_id", node_title="node_title", @@ -58,7 +58,7 @@ def test_model_validate( @pytest.mark.parametrize( "reason", [ - HitlRequired( + HitlRequired( # ty: ignore[deprecated] session_id="session-1", node_id="node_id", node_title="node_title", @@ -122,7 +122,7 @@ def test_legacy_human_input_required_json_can_be_restored_via_pause_reason( holder = _Holder.model_validate_json(payload) - assert isinstance(holder.reason, HitlRequired) + assert isinstance(holder.reason, HitlRequired) # ty: ignore[deprecated] assert holder.reason.TYPE == "hitl_required" assert holder.reason.session_id == "form-1" assert holder.reason.node_id == "node_id" diff --git a/tests/nodes/human_input/test_human_input_node.py b/tests/nodes/human_input/test_human_input_node.py index 6d9192c8..dbe1dc1e 100644 --- a/tests/nodes/human_input/test_human_input_node.py +++ b/tests/nodes/human_input/test_human_input_node.py @@ -7,7 +7,7 @@ import pytest from graphon.engine_events.node import NodeRunPauseRequestedEvent, NodeRunSucceededEvent -from graphon.entities.pause_reason import HitlRequired +from graphon.entities.pause_reason import HitlRequired # ty: ignore[deprecated] from graphon.nodes.human_input.entities import ( Completed, Expired, @@ -70,7 +70,7 @@ def callback(ctx: HITLContext) -> HITLDecision: variable_pool=captured_contexts[0].variable_pool, ) ] - assert paused.reason == HitlRequired( + assert paused.reason == HitlRequired( # ty: ignore[deprecated] session_id="session-1", node_id="human-node", node_title="Collect Input", diff --git a/tests/runtime/test_external_wait.py b/tests/runtime/test_external_wait.py new file mode 100644 index 00000000..a5188866 --- /dev/null +++ b/tests/runtime/test_external_wait.py @@ -0,0 +1,169 @@ +"""Check host-owned wait data across engine events and runtime snapshots.""" + +import pytest +from pydantic import ValidationError + +from graphon.engine_events.graph import GraphRunPausedEvent +from graphon.engine_events.node import NodeRunPauseRequestedEvent +from graphon.entities.pause_reason import ExternalWait +from graphon.node_events.node import PauseRequestedEvent +from graphon.runtime import RuntimeState, VariablePool + + +@pytest.fixture +def reason_payload() -> dict[str, str]: + return { + "TYPE": "external_wait", + "wait_type": "dify.hitl", + "wait_id": "form-1", + "node_id": "worker", + "node_title": "", + "node_execution_id": "execution-1", + "frame_id": "root", + } + + +@pytest.mark.parametrize( + ("wait_type", "wait_id"), + [ + ("hitl", ""), + ("dify.hitl", "session:1"), + ("dify.hitl.v1", " 审核 / request\n"), + ("langgenius.scheduling_pause", "job:1"), + ("_owner.Custom_2", "job:2"), + ], +) +def test_external_wait_preserves_opaque_id( + reason_payload: dict[str, str], wait_type: str, wait_id: str +) -> None: + reason_payload.update(wait_type=wait_type, wait_id=wait_id) + pause_request = PauseRequestedEvent.model_validate({"reason": reason_payload}) + + assert isinstance(pause_request.reason, ExternalWait) + assert pause_request.reason.model_dump(mode="json") == reason_payload + + +def test_external_wait_reads_events_with_unknown_fields( + reason_payload: dict[str, str], +) -> None: + event = PauseRequestedEvent.model_validate({ + "reason": {**reason_payload, "future_field": "value"}, + }) + assert event.reason.model_dump(mode="json") == reason_payload + + +@pytest.mark.parametrize( + "wait_type", + [ + "", + "dify.", + ".dify", + "dify..hitl", + "dify.1hitl", + "dify.h-itl", + "dify.人", + "dify.hitl\n", + ], +) +def test_external_wait_type_requires_dot_separated_ascii_identifiers( + reason_payload: dict[str, str], wait_type: str +) -> None: + reason_payload["wait_type"] = wait_type + with pytest.raises(ValidationError) as error: + PauseRequestedEvent.model_validate({"reason": reason_payload}) + + assert {issue["loc"][-1] for issue in error.value.errors()} == {"wait_type"} + + +@pytest.mark.parametrize( + "field_name", + ["wait_type", "wait_id", "node_id", "node_title", "node_execution_id", "frame_id"], +) +def test_external_wait_requires_field( + reason_payload: dict[str, str], field_name: str +) -> None: + del reason_payload[field_name] + + with pytest.raises(ValidationError) as error: + PauseRequestedEvent.model_validate({"reason": reason_payload}) + + assert any( + issue["loc"][-1] == field_name and issue["type"] == "missing" + for issue in error.value.errors() + ) + + +@pytest.mark.parametrize("field_name", ["node_id", "node_execution_id", "frame_id"]) +def test_external_wait_rejects_empty_identity( + reason_payload: dict[str, str], field_name: str +) -> None: + reason_payload[field_name] = "" + with pytest.raises(ValidationError) as error: + PauseRequestedEvent.model_validate({"reason": reason_payload}) + + assert any( + issue["loc"][-1] == field_name and issue["type"] == "string_too_short" + for issue in error.value.errors() + ) + + +def test_external_wait_round_trips_in_pause_events_and_runtime_snapshot() -> None: + state = RuntimeState( + workflow_id="workflow", variable_pool=VariablePool(), start_at=0 + ) + expected_reason_payloads: list[dict[str, str]] = [] + expected_execution_ids: dict[str, str] = {} + for index, wait_type in enumerate(("dify.external_agent", "dify.hitl")): + frame_id = f"iteration:{index}" + execution = state.graph_execution.get_or_create_node_execution( + frame_id=frame_id, node_id="worker" + ) + reason_payload = { + "TYPE": "external_wait", + "wait_type": wait_type, + "wait_id": "opaque: / 等待", + "node_id": "worker", + "node_title": "Worker", + "node_execution_id": execution.execution_id, + "frame_id": frame_id, + } + pause_request = PauseRequestedEvent.model_validate({"reason": reason_payload}) + node_pause = NodeRunPauseRequestedEvent( + id=execution.execution_id, + node_id="worker", + node_type="worker", + frame_id=frame_id, + reason=pause_request.reason, + ) + restored_node_pause = NodeRunPauseRequestedEvent.model_validate_json( + node_pause.model_dump_json() + ) + assert restored_node_pause.reason.model_dump(mode="json") == reason_payload + assert restored_node_pause.frame_id == frame_id + assert restored_node_pause.id == execution.execution_id + state.graph_execution.pause(restored_node_pause.reason) + expected_reason_payloads.append(reason_payload) + expected_execution_ids[frame_id] = execution.execution_id + + graph_pause = GraphRunPausedEvent(reasons=state.graph_execution.pause_reasons) + restored_graph_pause = GraphRunPausedEvent.model_validate_json( + graph_pause.model_dump_json() + ) + assert ( + restored_graph_pause.model_dump(mode="json")["reasons"] + == expected_reason_payloads + ) + + restored_state = RuntimeState.from_snapshot(state.dumps()) + assert restored_state.graph_execution.paused + assert [ + reason.model_dump(mode="json") + for reason in restored_state.graph_execution.pause_reasons + ] == expected_reason_payloads + for frame_id, execution_id in expected_execution_ids.items(): + restored_execution = ( + restored_state.graph_execution.get_or_create_node_execution( + frame_id=frame_id, node_id="worker" + ) + ) + assert restored_execution.execution_id == execution_id