Skip to content

Self-improving AI Employees for everyone

fix(temporal): enforce agent + output contracts at execution boundaries

trohitga37a21d84eea
diff --git a/server/core/database.py b/server/core/database.py
index 1b7c0f0d..9082f4da 100644
--- a/server/core/database.py
+++ b/server/core/database.py
@@ -1,7 +1,9 @@
"""Modern async database service with SQLModel and SQLAlchemy 2.0."""
+import json
from datetime import datetime, timezone
from typing import Dict, Any, List, Optional
+from pydantic_core import to_jsonable_python
from sqlmodel import SQLModel, select
from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession, async_sessionmaker
from sqlalchemy.exc import IntegrityError
@@ -58,13 +60,23 @@ class Database:
logging.getLogger("sqlalchemy.dialects").setLevel(logging.WARNING)
logging.getLogger("sqlalchemy.pool").setLevel(logging.WARNING)
- # Create async engine
+ # Create async engine.
+ #
+ # ``json_serializer`` is SQLAlchemy's documented extension point
+ # for every JSON column on this engine (node_outputs.data,
+ # node_parameters, ...). ``pydantic_core.to_jsonable_python`` is
+ # Pydantic's official arbitrary-object → JSON coercion
+ # (dataclasses, BaseModel, datetime, enums, sets natively;
+ # ``fallback=str`` for true unknowns) — stdlib ``json.dumps``
+ # alone raised ``TypeError: Object of type X is not JSON
+ # serializable`` and silently dropped node-output persistence.
self.engine = create_async_engine(
self.settings.database_url,
echo=self.settings.database_echo,
pool_size=self.settings.database_pool_size,
max_overflow=self.settings.database_max_overflow,
future=True,
+ json_serializer=lambda obj: json.dumps(to_jsonable_python(obj, fallback=str)),
)
# Create session factory
diff --git a/server/nodes/filesystem/file_read/__init__.py b/server/nodes/filesystem/file_read/__init__.py
index 09caa7cf..c8e58e09 100644
--- a/server/nodes/filesystem/file_read/__init__.py
+++ b/server/nodes/filesystem/file_read/__init__.py
@@ -55,7 +55,7 @@ class FileReadNode(ActionNode):
backend = get_backend(params.model_dump(), ctx.raw)
file_path = normalize_virtual_path(params.file_path)
try:
- content = await asyncio.to_thread(
+ result = await asyncio.to_thread(
backend.read,
file_path,
offset=params.offset,
@@ -65,4 +65,16 @@ class FileReadNode(ActionNode):
# File doesn't exist / is a directory / bad offset — the
# LLM should retry with corrected input, not fail the run.
raise NodeUserError(str(e)) from e
- return {"content": content, "file_path": file_path}
+ # backend.read returns deepagents' ReadResult dataclass — unwrap
+ # it into the declared Output contract (same shape fileModify /
+ # fsSearch already return for their backend results). Returning
+ # the raw dataclass breaks JSON persistence of node_outputs.
+ if result.error:
+ raise NodeUserError(result.error)
+ file_data = result.file_data or {}
+ content = file_data.get("content", "")
+ return FileReadOutput(
+ content=content,
+ line_count=len(content.splitlines()),
+ file_path=file_path,
+ )
diff --git a/server/nodes/tool/write_todos/__init__.py b/server/nodes/tool/write_todos/__init__.py
index 74482ed3..9a44ac21 100644
--- a/server/nodes/tool/write_todos/__init__.py
+++ b/server/nodes/tool/write_todos/__init__.py
@@ -2,9 +2,10 @@
from __future__ import annotations
+import json
from typing import Any, List, Literal, Optional
-from pydantic import BaseModel, ConfigDict, Field
+from pydantic import BaseModel, ConfigDict, Field, field_validator
from services.plugin import NodeContext, Operation, TaskQueue, ToolNode
@@ -20,6 +21,26 @@ class WriteTodosParams(BaseModel):
model_config = ConfigDict(extra="allow")
+ @field_validator("todos", mode="before")
+ @classmethod
+ def _coerce_todos(cls, value: Any) -> Any:
+ """Accept a JSON-encoded string in the ``todos`` slot — LLM
+ providers (notably Gemini) sometimes stringify array arguments
+ in tool calls. Same boundary-coercion pattern as
+ ``AndroidServiceParams._coerce_parameters``. Malformed JSON
+ passes through unchanged so Pydantic raises a proper
+ ValidationError the LLM can correct."""
+ if isinstance(value, str):
+ stripped = value.strip()
+ if stripped:
+ try:
+ parsed = json.loads(stripped)
+ except (ValueError, TypeError):
+ return value
+ if isinstance(parsed, list):
+ return parsed
+ return value
+
class WriteTodosOutput(BaseModel):
todos: Optional[list] = None
@@ -84,8 +105,14 @@ class WriteTodosNode(ToolNode):
len(stored),
session_key,
)
+ # ``stored`` is the validated list — the declared Output contract
+ # (``todos: Optional[list]``). The pre-fix ``format_for_llm()``
+ # call leaked TodoService's raw JSON STRING into this key, which
+ # the Output validation now rejects; the LLM-facing serialization
+ # happens downstream anyway (``_serialise_tool_result`` /
+ # LangChain dump the whole dict to JSON).
return {
"message": f"Updated todo list ({len(stored)} items)",
- "todos": service.format_for_llm(session_key),
+ "todos": stored,
"count": len(stored),
}
diff --git a/server/nodes/utility/team_monitor/__init__.py b/server/nodes/utility/team_monitor/__init__.py
index 6e8ff338..ad916cd7 100644
--- a/server/nodes/utility/team_monitor/__init__.py
+++ b/server/nodes/utility/team_monitor/__init__.py
@@ -20,7 +20,9 @@ class TeamMonitorParams(BaseModel):
class TeamMonitorOutput(BaseModel):
team: Optional[dict] = None
members: Optional[list] = None
- tasks: Optional[list] = None
+ # Aggregate counts ({"total", "completed", "active", "pending",
+ # "failed"}) — the per-task list lives in the ``active_tasks`` extra.
+ tasks: Optional[dict] = None
model_config = ConfigDict(extra="allow")
diff --git a/server/services/handlers/todo.py b/server/services/handlers/todo.py
index 43ae6ae6..8ab6ea89 100644
--- a/server/services/handlers/todo.py
+++ b/server/services/handlers/todo.py
@@ -43,7 +43,10 @@ async def execute_write_todos(
"success": True,
"message": f"Updated todo list ({len(stored)} items)",
"count": len(stored),
- "todos": service.format_for_llm(session_key),
+ # Plain list — matches the plugin's WriteTodosOutput contract
+ # (``todos: Optional[list]``); the pre-fix ``format_for_llm()``
+ # leaked TodoService's raw JSON string here.
+ "todos": stored,
}
diff --git a/server/services/plugin/base.py b/server/services/plugin/base.py
index 911e55c4..85e92dda 100644
--- a/server/services/plugin/base.py
+++ b/server/services/plugin/base.py
@@ -582,12 +582,47 @@ class BaseNode:
return True, result.get("result", {}), None
return False, None, result.get("error")
+ def _serialize_result(self, result: Any) -> Any:
+ """Enforce the declared ``Output`` contract at the serialization
+ boundary — the same semantics FastAPI applies to ``response_model``
+ (validate, coerce, serialize). ``model_dump(mode="json")`` guarantees
+ the payload is JSON-compatible (datetimes → ISO strings, enums →
+ values) before it reaches node_outputs persistence and the WS
+ broadcast. Dict results from plugins without a declared ``Output``
+ pass through untouched.
+
+ Raises ``pydantic.ValidationError`` (or
+ ``pydantic_core.PydanticSerializationError``) when the operation
+ returned data violating its own declared contract — a plugin bug
+ that must fail loudly instead of silently corrupting downstream
+ stores (callers convert it to the standard error envelope).
+ """
+ if isinstance(result, BaseModel):
+ return result.model_dump(mode="json")
+ if isinstance(result, dict) and self.Output is not _EmptyOutput:
+ # ``exclude_unset`` preserves the producer's exact key set —
+ # declared-but-absent Optional fields must not materialise as
+ # ``None`` keys in the payload (validate + coerce + serialize,
+ # without reshaping what the operation chose to return).
+ return self.Output.model_validate(result).model_dump(mode="json", exclude_unset=True)
+ return result
+
def _wrap_success(self, *, start_time: float, result: Any) -> Dict[str, Any]:
"""95%-universal return shape. Subclasses (ToolNode) override."""
- if isinstance(result, BaseModel):
- result_data: Any = result.model_dump()
- else:
- result_data = result
+ from pydantic_core import PydanticSerializationError
+
+ try:
+ result_data = self._serialize_result(result)
+ except (ValidationError, PydanticSerializationError) as e:
+ logger.exception(
+ "[%s] operation result violates declared Output contract",
+ self.type,
+ )
+ return self._wrap_error(
+ start_time=start_time,
+ error=f"Output contract violation: {e}",
+ error_type="OutputValidationError",
+ )
return {
"success": True,
"result": result_data,
diff --git a/server/services/plugin/tool.py b/server/services/plugin/tool.py
index 37026f15..29b8cec2 100644
--- a/server/services/plugin/tool.py
+++ b/server/services/plugin/tool.py
@@ -42,12 +42,21 @@ class ToolNode(BaseNode, abstract=True):
def _wrap_success(self, *, start_time: float, result):
"""Tools return flat result (no success wrapper)."""
- from pydantic import BaseModel
+ from pydantic import BaseModel, ValidationError
+ from pydantic_core import PydanticSerializationError
- if isinstance(result, BaseModel):
- return result.model_dump()
- if isinstance(result, dict):
- return result
+ if isinstance(result, (BaseModel, dict)):
+ try:
+ # Same Output-contract enforcement as the base class —
+ # validate + dump(mode="json") so the flat tool payload
+ # is always JSON-compatible (see BaseNode._serialize_result).
+ return self._serialize_result(result)
+ except (ValidationError, PydanticSerializationError) as e:
+ return self._wrap_error(
+ start_time=start_time,
+ error=f"Output contract violation: {e}",
+ error_type="OutputValidationError",
+ )
return {"result": result}
@classmethod
diff --git a/server/services/temporal/agent_activities.py b/server/services/temporal/agent_activities.py
index c00cf306..1310155e 100644
--- a/server/services/temporal/agent_activities.py
+++ b/server/services/temporal/agent_activities.py
@@ -51,6 +51,32 @@ logger = logging.getLogger(__name__)
# {"kind": "tool_calls", "calls": [{"id": str, "name": str, "args": dict}], "usage": dict}
+def _ensure_llm_contents(messages: List[Any]) -> None:
+ """Fail fast when the filtered message list has no invokable content.
+
+ Providers require at least one non-system message (Gemini splits
+ SystemMessages into ``system_instruction`` and then rejects the empty
+ ``contents`` list with an opaque retryable ``ValueError: contents are
+ required``). An empty prompt is an invalid-input condition, so raise
+ Temporal's ``ApplicationError`` with ``non_retryable=True`` — the
+ documented mechanism for business-rule failures (see
+ docs.temporal.io/encyclopedia/retry-policies) — instead of burning
+ the retry budget on a deterministic failure.
+ """
+ if any(getattr(m, "type", "") in ("human", "ai", "tool") for m in messages):
+ return
+ from temporalio.exceptions import ApplicationError
+
+ raise ApplicationError(
+ "Agent has no invokable content: message list contains no user, "
+ "assistant, or tool messages. Provide a non-empty 'task' in the "
+ "delegate_to_* call, set the agent's 'prompt' parameter, or "
+ "connect an input trigger.",
+ type="EmptyAgentPrompt",
+ non_retryable=True,
+ )
+
+
@activity.defn(name="agent.execute_llm_step.v1")
async def execute_llm_step(payload: Dict[str, Any]) -> Dict[str, Any]:
"""Run one LLM turn with bound tools and return the structured response.
@@ -140,6 +166,7 @@ async def execute_llm_step(payload: Dict[str, Any]) -> Dict[str, Any]:
# Same filter ``_run_agent_loop`` runs in services/ai.py — empty-content
# messages trigger 400s on Gemini / Anthropic.
rehydrated = filter_empty_messages(rehydrated)
+ _ensure_llm_contents(rehydrated)
activity.heartbeat("LLM step: invoking model")
response = await chat_model.ainvoke(rehydrated)
@@ -434,6 +461,12 @@ async def prepare_agent_payload(context: Dict[str, Any]) -> Dict[str, Any]:
"nodes": list, # full canvas (for edge walking)
"edges": list,
"inputs": dict, # upstream node outputs
+ # Optional — present only for delegation children spawned by
+ # a parent AgentWorkflow's delegate_to_* call. Per-invocation
+ # input: applied AFTER config resolution, never overridden by
+ # stored node parameters (the node's persisted ``prompt`` is
+ # typically the empty Pydantic default).
+ "invocation": {"task": str, "context": str},
}
Returns the dict that ``AgentWorkflow.run`` expects (see its
@@ -493,6 +526,21 @@ async def prepare_agent_payload(context: Dict[str, Any]) -> Dict[str, Any]:
prompt = parameters.get("prompt", "")
system_message = parameters.get("system_message") or "You are a helpful assistant"
+ # Per-invocation input (delegation contract) beats stored configuration.
+ # The parent's delegate_to_* call passes {"task", "context"} as the
+ # child workflow's ``invocation`` input field. Faithful mirror of the
+ # legacy working path (``handlers.tools._execute_delegated_agent``,
+ # which applies the remap AFTER loading DB params so it always wins):
+ # ``task`` is the mission directive → system_message; ``context`` is
+ # the input data → prompt, falling back to task (DelegateToAgentSchema
+ # in services/ai.py declares task required, context optional). Applied
+ # after the config merge so the node's persisted empty default
+ # ``prompt`` can never clobber the delegated task.
+ invocation = context.get("invocation") or {}
+ if invocation.get("task") or invocation.get("context"):
+ system_message = invocation.get("task") or "You are a helpful assistant"
+ prompt = invocation.get("context") or invocation.get("task") or ""
+
api_key = flattened.get("api_key")
provider = parameters.get("provider", "openai")
model = parameters.get("model", "")
diff --git a/server/services/temporal/agent_workflow.py b/server/services/temporal/agent_workflow.py
index 95981341..82eab084 100644
--- a/server/services/temporal/agent_workflow.py
+++ b/server/services/temporal/agent_workflow.py
@@ -131,6 +131,13 @@ class AgentWorkflow:
"nodes": list, # full canvas (for edge walking)
"edges": list,
"inputs": dict, # upstream node outputs
+ # Present only when spawned as a delegation child by a
+ # parent AgentWorkflow's delegate_to_* tool call. This is
+ # the per-invocation input contract (Temporal's
+ # input-vs-config separation): it always wins over stored
+ # node configuration in prepare_agent_payload.
+ "invocation": {"task": str, "context": str}, # optional
+ "parent_node_id": str, # optional
}
The workflow's FIRST step is to schedule
@@ -338,20 +345,28 @@ class AgentWorkflow:
# Delegation tools (``delegate_to_<child>``) need different
# arg handling than regular tools:
#
- # 1. LLM passes ``{"task": "...", "context": "..."}`` — map
- # ``task → system_message`` and ``context → prompt`` so
- # the child agent's ``Params`` model parses correctly.
- # Without this remap Gemini fails with ``contents are
- # required`` because the child's prompt is empty.
+ # 1. LLM passes ``{"task": "...", "context": "..."}`` —
+ # this is per-invocation INPUT, not node configuration.
+ # For child AgentWorkflows it travels as the workflow
+ # input's ``invocation`` field (Temporal input-contract
+ # pattern); the prep activity applies it AFTER config
+ # resolution so stored params (e.g. the node's empty
+ # default ``prompt``) can never clobber the delegated
+ # task — without that guarantee Gemini fails with
+ # ``contents are required``. For bypass agents
+ # dispatched as plain activities (rlm_agent /
+ # claude_code_agent) the task is mapped into
+ # ``node_data`` (``task → system_message``,
+ # ``context-or-task → prompt``) because their activity
+ # consumes ``node_data`` verbatim with no DB re-merge.
# 2. The child agent needs the full canvas (``nodes`` +
# ``edges``) so its ``collect_agent_connections`` edge
# walk can find its own skills / memory / tools.
# Regular tools don't need this — they execute against
# their own params alone.
#
- # Same mapping the legacy fire-and-forget
- # ``handlers.tools._execute_delegated_agent`` applies to its
- # ``child_params`` before spawning the child task.
+ # Same task/context semantics as the legacy fire-and-forget
+ # ``handlers.tools._execute_delegated_agent``.
call_args = call.get("args") or {}
tool_name = call.get("name", "")
is_delegation = tool_name.startswith("delegate_to_")
@@ -359,13 +374,31 @@ class AgentWorkflow:
if is_delegation:
task_description = str(call_args.get("task", "") or "")
task_context = str(call_args.get("context", "") or "")
- delegation_params = {
- "system_message": task_description,
- "prompt": task_context or task_description,
- }
+ if not task_description and not task_context:
+ # Invalid invocation — reject at the call boundary
+ # instead of spawning a child that cannot run.
+ messages.append(
+ {
+ "type": "tool",
+ "data": {
+ "content": (
+ '{"error": "delegate_to_* requires a '
+ "non-empty 'task' argument describing "
+ 'what the agent should do."}'
+ ),
+ "tool_call_id": call.get("id", ""),
+ "name": tool_name,
+ },
+ }
+ )
+ continue
tool_node_data = {
**(tool_info.get("parameters") or {}),
- **delegation_params,
+ # Consumed only by the activity-dispatch fallback
+ # below (bypass agents); the child-AgentWorkflow
+ # path reads the ``invocation`` field instead.
+ "system_message": task_description,
+ "prompt": task_context or task_description,
}
child_nodes = context.get("nodes") or []
child_edges = context.get("edges") or []
@@ -415,7 +448,14 @@ class AgentWorkflow:
try:
if is_delegation and tool_info["node_type"] in AGENT_WORKFLOW_TYPES:
- child_context = {**tool_payload, "parent_node_id": agent_node_id}
+ child_context = {
+ **tool_payload,
+ "parent_node_id": agent_node_id,
+ "invocation": {
+ "task": task_description,
+ "context": task_context,
+ },
+ }
tool_result = await workflow.execute_child_workflow(
"AgentWorkflow",
args=[child_context],
diff --git a/server/tests/nodes/_compat.py b/server/tests/nodes/_compat.py
index aaacdcd7..71c29190 100644
--- a/server/tests/nodes/_compat.py
+++ b/server/tests/nodes/_compat.py
@@ -147,7 +147,8 @@ async def handle_write_todos(
"success": True,
"message": f"Updated todo list ({len(stored)} items)",
"count": len(stored),
- "todos": service.format_for_llm(session_key),
+ # Plain list — matches the plugin's WriteTodosOutput contract.
+ "todos": stored,
}
diff --git a/server/tests/nodes/test_ai_tools.py b/server/tests/nodes/test_ai_tools.py
index 2d292118..50cbeacd 100644
--- a/server/tests/nodes/test_ai_tools.py
+++ b/server/tests/nodes/test_ai_tools.py
@@ -419,6 +419,43 @@ class TestWriteTodos:
assert args[2]["todos"] == stored
assert kwargs.get("workflow_id") == "wf-42"
+ async def test_plugin_returns_list_todos_and_coerces_stringified_args(self):
+ """Regression for the Output contract violation surfaced by
+ ``_wrap_success`` enforcement: the plugin returned ``todos`` as
+ TodoService's raw JSON STRING (``format_for_llm``) while
+ ``WriteTodosOutput`` declares ``Optional[list]``. Also locks the
+ Params boundary coercion — Gemini sometimes stringifies array
+ args in tool calls, so a JSON-encoded ``todos`` string must
+ parse instead of failing validation."""
+ import json
+
+ from nodes.tool.write_todos import WriteTodosNode
+ from services.plugin import NodeContext
+ from services.todo_service import get_todo_service
+
+ node = WriteTodosNode()
+ ctx = NodeContext.from_legacy(
+ node_id="todo-node-2",
+ node_type="writeTodos",
+ context={"workflow_id": "wf-str"},
+ )
+ # LLM-stringified array arg (the Gemini failure mode).
+ result = await node.execute(
+ "todo-node-2",
+ {"todos": '[{"content": "From stringified args", "status": "in_progress"}]'},
+ ctx,
+ )
+
+ # ToolNode flat contract: no success wrapper, real list in todos.
+ assert "success" not in result
+ assert isinstance(result["todos"], list)
+ assert result["todos"] == [{"content": "From stringified args", "status": "in_progress"}]
+ assert result["count"] == 1
+ json.dumps(result) # whole payload JSON-safe for node_outputs
+
+ # Service state matches what the output reported.
+ assert get_todo_service().get("wf-str") == result["todos"]
+
async def test_invalid_items_are_silently_dropped_or_coerced(self):
from tests.nodes._compat import handle_write_todos
from services.todo_service import get_todo_service
diff --git a/server/tests/nodes/test_code_fs_process.py b/server/tests/nodes/test_code_fs_process.py
index fac3041a..f21126a6 100644
--- a/server/tests/nodes/test_code_fs_process.py
+++ b/server/tests/nodes/test_code_fs_process.py
@@ -59,6 +59,13 @@ class _FakeWriteResult(SimpleNamespace):
super().__init__(error=error, path=path, occurrences=occurrences)
+class _FakeReadResult(SimpleNamespace):
+ """Mimics deepagents ReadResult dataclass (error, file_data)."""
+
+ def __init__(self, error: str | None = None, file_data: dict | None = None):
+ super().__init__(error=error, file_data=file_data)
+
+
class _FakeExecuteResult(SimpleNamespace):
def __init__(self, output: str = "", exit_code: int = 0, truncated: bool = False):
super().__init__(output=output, exit_code=exit_code, truncated=truncated)
@@ -278,8 +285,15 @@ class TestTypescriptExecutor:
class TestFileRead:
async def test_happy_path_returns_content(self, harness):
+ # deepagents 0.5.x ``backend.read`` returns a ``ReadResult``
+ # dataclass — the plugin must unwrap ``file_data["content"]``
+ # instead of leaking the raw object into the output dict
+ # (regression: "Object of type ReadResult is not JSON
+ # serializable" at node_outputs persistence).
backend = MagicMock(name="LocalShellBackend")
- backend.read = MagicMock(return_value="line1\nline2\n")
+ backend.read = MagicMock(
+ return_value=_FakeReadResult(file_data={"content": "line1\nline2", "encoding": "utf-8"})
+ )
with _patch_fs_backend(backend):
result = await harness.execute(
@@ -290,11 +304,31 @@ class TestFileRead:
harness.assert_envelope(result, success=True)
harness.assert_output_shape(result, ["content", "file_path"])
payload = result["result"]
- assert payload["content"] == "line1\nline2\n"
+ assert payload["content"] == "line1\nline2"
+ assert payload["line_count"] == 2
# ``normalize_virtual_path`` prepends ``/`` to relative inputs so the
# path reaches deepagents in its canonical virtual-mode form.
assert payload["file_path"] == "/notes.txt"
backend.read.assert_called_once_with("/notes.txt", offset=0, limit=100)
+ # The whole envelope must be JSON-serializable — this is exactly
+ # what ``database.save_node_output`` needs to persist it.
+ import json
+
+ json.dumps(result)
+
+ async def test_backend_error_result_is_user_error(self, harness):
+ """A ``ReadResult`` carrying ``error`` is a failed read — it must
+ surface as a NodeUserError envelope, not pass as success with a
+ raw dataclass payload."""
+ backend = MagicMock(name="LocalShellBackend")
+ backend.read = MagicMock(return_value=_FakeReadResult(error="File '/missing.txt' not found"))
+
+ with _patch_fs_backend(backend):
+ result = await harness.execute("fileRead", {"file_path": "missing.txt"})
+
+ harness.assert_envelope(result, success=False)
+ assert "not found" in result["error"].lower()
+ assert result.get("error_type") == "NodeUserError"
async def test_missing_file_path_short_circuits(self, harness):
# No backend patch: we should short-circuit before reaching it.
diff --git a/server/tests/temporal/test_agent_workflow.py b/server/tests/temporal/test_agent_workflow.py
index fcc9760e..9192632c 100644
--- a/server/tests/temporal/test_agent_workflow.py
+++ b/server/tests/temporal/test_agent_workflow.py
@@ -306,6 +306,139 @@ class TestAutoRebindTools:
)
+class TestDelegationInvocationContract:
+ """Regression: the delegated task must survive the child's config
+ resolution. Pre-fix the parent remapped ``{task, context}`` into the
+ child's ``node_data`` (configuration channel) and
+ ``prepare_agent_payload`` merged ``{**node_data, **db_params}`` —
+ the child node's persisted ``prompt: ""`` (the Pydantic default the
+ frontend saves on drop) clobbered the delegated task, the child's
+ message list ended up system-only, and Gemini rejected it with
+ ``contents are required`` (3 wasted retries per call).
+
+ Post-fix the delegation travels as the child workflow input's
+ ``invocation`` field (Temporal input-vs-config separation; see
+ docs.temporal.io/develop/python/workflows single-object input
+ guidance) and ``prepare_agent_payload`` applies it AFTER the config
+ merge — mirroring the legacy working path
+ (``handlers.tools._execute_delegated_agent`` applies its remap after
+ loading DB params, so it always wins).
+
+ Source-introspection invariants — a live run needs a Temporal
+ WorkflowEnvironment, too heavy for unit tests (same rationale as
+ ``TestDelegationToolDispatch``).
+ """
+
+ def test_child_context_carries_invocation_field(self):
+ import inspect
+
+ from services.temporal.agent_workflow import AgentWorkflow
+
+ src = inspect.getsource(AgentWorkflow.run)
+ assert '"invocation"' in src, (
+ "AgentWorkflow delegation spawn must pass the per-invocation "
+ "{task, context} as the child workflow input's 'invocation' "
+ "field. Smuggling it through node_data lets the child's "
+ "persisted empty prompt clobber the delegated task."
+ )
+
+ def test_empty_task_rejected_before_spawn(self):
+ """A delegate_to_* call with neither task nor context must be
+ rejected at the call boundary (tool-error message back to the
+ LLM) instead of spawning a child workflow that cannot run."""
+ import inspect
+
+ from services.temporal.agent_workflow import AgentWorkflow
+
+ src = inspect.getsource(AgentWorkflow.run)
+ assert "non-empty 'task'" in src, (
+ "AgentWorkflow delegation branch must validate the invocation "
+ "(task/context both empty -> tool error, no child spawn)."
+ )
+
+ def test_prepare_payload_applies_invocation_after_config_merge(self):
+ """The invocation override must run AFTER the
+ ``{**node_data, **db_params}`` config merge — order is the whole
+ fix. If someone 'simplifies' it back into the merge, the DB's
+ empty prompt wins again."""
+ import inspect
+
+ from services.temporal.agent_activities import prepare_agent_payload
+
+ src = inspect.getsource(prepare_agent_payload)
+ assert 'context.get("invocation")' in src, (
+ "prepare_agent_payload must read the child workflow input's "
+ "'invocation' field."
+ )
+ assert src.index("**db_params") < src.index('context.get("invocation")'), (
+ "Invocation must be applied AFTER the node_data/db_params "
+ "config merge so stored parameters can never clobber the "
+ "delegated task."
+ )
+
+
+class TestEmptyPromptGuard:
+ """``execute_llm_step`` must fail fast — attempt 1, non-retryable —
+ when the filtered message list has no invokable content, instead of
+ letting Gemini raise an opaque retryable ``ValueError: contents are
+ required`` that burns the full retry budget on a deterministic
+ failure. Uses Temporal's documented mechanism for business-rule
+ failures: ``ApplicationError(..., non_retryable=True)``."""
+
+ def test_raises_non_retryable_on_system_only_list(self):
+ import pytest
+ from langchain_core.messages import SystemMessage
+ from temporalio.exceptions import ApplicationError
+
+ from services.temporal.agent_activities import _ensure_llm_contents
+
+ with pytest.raises(ApplicationError) as excinfo:
+ _ensure_llm_contents([SystemMessage(content="you are helpful")])
+ assert excinfo.value.non_retryable is True
+ assert excinfo.value.type == "EmptyAgentPrompt"
+
+ def test_raises_on_empty_list(self):
+ import pytest
+ from temporalio.exceptions import ApplicationError
+
+ from services.temporal.agent_activities import _ensure_llm_contents
+
+ with pytest.raises(ApplicationError):
+ _ensure_llm_contents([])
+
+ def test_passes_with_human_message(self):
+ from langchain_core.messages import HumanMessage, SystemMessage
+
+ from services.temporal.agent_activities import _ensure_llm_contents
+
+ _ensure_llm_contents([SystemMessage(content="sys"), HumanMessage(content="hi")])
+
+ def test_passes_with_tool_message(self):
+ """Mid-loop turns may legitimately be tool-result-only."""
+ from langchain_core.messages import SystemMessage, ToolMessage
+
+ from services.temporal.agent_activities import _ensure_llm_contents
+
+ _ensure_llm_contents(
+ [SystemMessage(content="sys"), ToolMessage(content="42", tool_call_id="c1")]
+ )
+
+ def test_guard_runs_after_empty_message_filter(self):
+ """The guard must see the POST-filter list — a whitespace-only
+ HumanMessage passes the workflow's truthiness check but gets
+ stripped by ``filter_empty_messages``, so guarding pre-filter
+ would miss exactly the failing case."""
+ import inspect
+
+ from services.temporal.agent_activities import execute_llm_step
+
+ src = inspect.getsource(execute_llm_step)
+ assert "_ensure_llm_contents(rehydrated)" in src
+ assert src.index("filter_empty_messages(rehydrated)") < src.index(
+ "_ensure_llm_contents(rehydrated)"
+ )
+
+
class TestNeedsCanvasDispatch:
"""Regression: regular (non-delegation) tools opt into canvas
propagation via the ``BaseNode.needs_canvas`` ClassVar. The F4.B
diff --git a/server/tests/test_output_contract.py b/server/tests/test_output_contract.py
new file mode 100644
index 00000000..e9018c23
--- /dev/null
+++ b/server/tests/test_output_contract.py
@@ -0,0 +1,203 @@
+"""Output-contract enforcement at the plugin serialization boundary.
+
+Regression suite for the "Object of type ReadResult is not JSON
+serializable" class of bug: a plugin operation returned a dict carrying
+a raw third-party dataclass, ``_wrap_success`` passed it through
+unvalidated, and the SQLAlchemy JSON column's stdlib ``json.dumps``
+raised at ``session.commit()`` — silently dropping node-output
+persistence (``save_node_output`` swallows the error).
+
+Two enforcement layers are locked here:
+
+1. ``BaseNode._serialize_result`` — dict results are validated against
+ the plugin's declared ``Output`` model and dumped with
+ ``mode="json"`` (the semantics FastAPI applies to ``response_model``:
+ validate, coerce, serialize). Contract violations become a loud
+ ``OutputValidationError`` envelope at the producer instead of silent
+ corruption downstream.
+2. Engine-level ``json_serializer`` on ``create_async_engine`` —
+ SQLAlchemy's documented extension point for every JSON column —
+ backed by ``pydantic_core.to_jsonable_python`` (official
+ arbitrary-object → JSON coercion; ``fallback=str`` for unknowns).
+"""
+
+from __future__ import annotations
+
+import time
+from typing import Optional
+
+from pydantic import BaseModel, ConfigDict
+
+
+def _action_stub(output_model=None):
+ """Throwaway ActionNode subclass; ``abstract=True`` skips registry
+ side-effects (same mechanism ToolNode itself uses)."""
+ from services.plugin import ActionNode
+
+ class _Stub(ActionNode, abstract=True):
+ type = "_testOutputContract"
+ display_name = "stub"
+
+ if output_model is not None:
+ _Stub.Output = output_model
+ return _Stub()
+
+
+def _tool_stub(output_model=None):
+ from services.plugin.tool import ToolNode
+
+ class _Stub(ToolNode, abstract=True):
+ type = "_testToolOutputContract"
+ display_name = "stub"
+
+ if output_model is not None:
+ _Stub.Output = output_model
+ return _Stub()
+
+
+class _ContentOutput(BaseModel):
+ content: Optional[str] = None
+ line_count: Optional[int] = None
+
+ model_config = ConfigDict(extra="allow")
+
+
+class TestActionNodeWrapSuccess:
+ def test_dict_violating_declared_field_fails_loudly(self):
+ """The original bug shape: a non-string object in a declared
+ ``content: Optional[str]`` field. Must become an error envelope
+ (plugin bug surfaced at the producer), never a success payload
+ carrying a non-serializable object."""
+ node = _action_stub(_ContentOutput)
+ result = node._wrap_success(
+ start_time=time.time(),
+ result={"content": object(), "file_path": "/x.txt"},
+ )
+ assert result["success"] is False
+ assert result["error_type"] == "OutputValidationError"
+
+ def test_dict_with_extra_keys_passes_and_keeps_extras(self):
+ """All plugin Output models use ``extra="allow"`` + Optional
+ fields — well-behaved plugins returning context keys beyond the
+ declared schema are unaffected by enforcement."""
+ node = _action_stub(_ContentOutput)
+ result = node._wrap_success(
+ start_time=time.time(),
+ result={"content": "hello", "file_path": "/x.txt"},
+ )
+ assert result["success"] is True
+ assert result["result"]["content"] == "hello"
+ assert result["result"]["file_path"] == "/x.txt"
+
+ def test_basemodel_result_dumps_json_mode(self):
+ """BaseModel returns must dump with ``mode="json"`` so the
+ payload is JSON-compatible (datetimes -> ISO strings, etc.)."""
+ import json
+ from datetime import datetime, timezone
+
+ class _Out(BaseModel):
+ when: datetime
+ model_config = ConfigDict(extra="allow")
+
+ node = _action_stub(_Out)
+ result = node._wrap_success(
+ start_time=time.time(),
+ result=_Out(when=datetime(2026, 1, 1, tzinfo=timezone.utc)),
+ )
+ assert result["success"] is True
+ json.dumps(result["result"]) # must not raise
+ assert isinstance(result["result"]["when"], str)
+
+ def test_dict_without_declared_output_passes_through(self):
+ """Plugins with the default ``_EmptyOutput`` keep the historical
+ pass-through behavior — enforcement only applies where a
+ contract is declared."""
+ node = _action_stub() # inherits _EmptyOutput
+ payload = {"anything": 1, "nested": {"x": [1, 2]}}
+ result = node._wrap_success(start_time=time.time(), result=payload)
+ assert result["success"] is True
+ assert result["result"] is payload
+
+
+class TestToolNodeWrapSuccess:
+ def test_flat_dict_validated_against_output(self):
+ node = _tool_stub(_ContentOutput)
+ result = node._wrap_success(
+ start_time=time.time(),
+ result={"content": "hi", "extra": True},
+ )
+ # ToolNode contract: flat dict, no success wrapper.
+ assert "success" not in result
+ assert result["content"] == "hi"
+ assert result["extra"] is True
+
+ def test_violation_becomes_error_envelope(self):
+ """A contract violation flips the flat-dict success shape into
+ the standard error envelope — ``interpret_result`` then reports
+ failure (a dict WITH ``success`` takes base-class semantics)."""
+ node = _tool_stub(_ContentOutput)
+ result = node._wrap_success(
+ start_time=time.time(),
+ result={"content": object()},
+ )
+ assert result["success"] is False
+ assert result["error_type"] == "OutputValidationError"
+ ok, _payload, error = type(node).interpret_result(result)
+ assert ok is False
+ assert "Output contract violation" in (error or "")
+
+
+class TestEngineJsonSerializer:
+ """Lock the engine-level serializer configuration. ``core.database``
+ is stubbed by conftest, so the source lock reads the file from disk."""
+
+ def test_engine_configures_pydantic_json_serializer(self):
+ from pathlib import Path
+
+ src = (Path(__file__).parent.parent / "core" / "database.py").read_text(encoding="utf-8")
+ assert "json_serializer" in src, (
+ "create_async_engine must set json_serializer — SQLAlchemy's "
+ "documented extension point for JSON-column serialization. "
+ "Without it, stdlib json.dumps raises on any non-primitive "
+ "object and node-output persistence silently drops data."
+ )
+ assert "to_jsonable_python" in src, (
+ "The serializer must coerce via pydantic_core.to_jsonable_python "
+ "(official arbitrary-object -> JSON handling), not ad-hoc "
+ "default=str round-trips."
+ )
+
+ def test_serializer_expression_handles_rich_payloads(self):
+ """Behavior of the exact expression used by the engine: stdlib
+ ``json.dumps`` over ``to_jsonable_python(..., fallback=str)``
+ must serialize dataclasses, datetimes, sets, enums, and unknown
+ objects without raising."""
+ import enum
+ import json
+ from dataclasses import dataclass
+ from datetime import datetime, timezone
+
+ from pydantic_core import to_jsonable_python
+
+ @dataclass
+ class _ReadResultLike:
+ error: Optional[str] = None
+ file_data: Optional[dict] = None
+
+ class _Color(enum.Enum):
+ RED = "red"
+
+ payload = {
+ "result": _ReadResultLike(file_data={"content": "x", "encoding": "utf-8"}),
+ "when": datetime(2026, 1, 1, tzinfo=timezone.utc),
+ "tags": {"a", "b"},
+ "color": _Color.RED,
+ "unknown": object(),
+ }
+ out = json.dumps(to_jsonable_python(payload, fallback=str))
+ decoded = json.loads(out)
+ assert decoded["result"]["file_data"]["content"] == "x"
+ assert decoded["when"].startswith("2026-01-01")
+ assert sorted(decoded["tags"]) == ["a", "b"]
+ assert decoded["color"] == "red"
+ assert isinstance(decoded["unknown"], str)