Self-improving AI Employees for everyone
Python ai-agentsai-employeeai-employeesassistantautonomous-agentsco-employeescompanygrok-botinstinctloop-agentsmuseown-your-datapersonalself-hosted
fix(temporal): a bug in workflow code fails the task, not the run (1b.13)
trohitg1416f5b53a21
diff --git a/docs-internal/TEMPORAL_ARCHITECTURE.md b/docs-internal/TEMPORAL_ARCHITECTURE.mdindex 1fe3949a..42a12b39 100644--- a/docs-internal/TEMPORAL_ARCHITECTURE.md+++ b/docs-internal/TEMPORAL_ARCHITECTURE.md@@ -81,7 +81,7 @@ This invokes `run_standalone_worker()` from `services/temporal/worker.py`. It al(node status, agent progress) still reach only its own process. Run as a module, it configures logging like thebackend (`configure_logging`), including the filters on the SDK's loggers: a failed workflow task, which the SDK logsat WARNING, is raised to ERROR (`core/logging.WorkflowTaskFailureFilter`), because it fails again on every retry-until the code changes.+until the code changes (see "A bug in workflow code fails the task" under the months-long durability contract below).## System Architecture@@ -1082,6 +1082,7 @@ guarantee applies to version 1 generations with their controller chain intact.- **No lifetime caps on new child runs.** Trigger/cron-spawned `MachinaWorkflow` runs, agent children, and delegated-task runners previously carried 1-2h `execution_timeout`/`run_timeout` — Temporal's timeout timers keep ticking through a cooperative pause, so any pause longer than the cap silently terminated the run (and a timed-out delegated runner skipped its compensation: leaked permit + stuck task row). New executions start children unbounded (no patch marker was retained for this change). The live `workflow.patched` markers are `machina-conditional-edges-v1`, `machina-run-record-v1`, `machina-chat-run-v1`, `workspace-node-cancellation-v1` and `workflow-node-user-action-error-v1` in `services/temporal/workflow.py`, `machina-trigger-listener-node-filter` in `services/temporal/trigger_listener_workflow.py`, and `workspace-task-activity-policy-v1`, `agent-user-action-error-v1` and `agent-blocked-tool-turn-save-v1` in `services/temporal/agent_workflow.py`; the list grows, so check it with `grep -rn "workflow.patched(" server/services/temporal`. `machina-run-record-v1` gates the `workflow_runs.record_completion` activity that trigger-spawned runs schedule when they finish, for Normal mode's "done today" (see [normal_mode.md](./normal_mode.md#done-today)). `machina-chat-run-v1` gates the `chat_run.start` / `chat_run.finish` activities a run spawned by the owner's chat message schedules to claim and finish its chat run; the run id is read only from an event whose source is `opencompany://services/chat` (see [chat_protocol.md](./chat_protocol.md#runs)). `workflow-node-user-action-error-v1` gates `MachinaWorkflow._node_failure`: when a node's activity or child workflow raises, it follows the error's causes to an `LLMError.*` or `MissingAgentProviderCredential` failure whose details carry `requires_user_action` (a missing or rejected key, billing, quota, permission, an unknown model or a wrong base URL) and returns a `NodeUserError` result with that message, its `hint` and `retryable: false` instead of the bare error text, so `chat_run.finish` records the hint and `workflow_control.pause_on_failure` pauses the deployment on that first failure rather than counting it toward the threshold. `agent-user-action-error-v1` gates the matching stop in `AgentWorkflow`: a tool result (a delegated agent's included) with an `error` and `requires_user_action` ends the run after that tool turn, before another model request or compaction, and the agent clears its active skills, emits `failed` and returns the error as a `NodeUserError`. `agent-blocked-tool-turn-save-v1` gates the `agent.persist_turn` activity that this stop runs first when the agent has a conversation key (a Context node in a started generation): it appends the turn's tool results to the stored conversation (`append_tool_results`), so the conversation does not end on unanswered tool calls. The two `workspace-*` markers are described under [Direct Workspace tasks](#direct-workspace-tasks). Liveness is the activity layer's job: node activities heartbeat every 30s against a 2-minute `heartbeat_timeout`; their `start_to_close` is a generous 24h ceiling, not 10 minutes. The subagent-permit wait uses `PERMIT_WAIT_RETRY` (unlimited attempts) so a queued delegation waits as long as admission takes instead of failing after ~3h.- **History-pressure continue-as-new everywhere.** Temporal terminates any workflow around ~51,200 history events. `WorkflowControlWorkflow` (which multiplexes all of a deployment's triggers into one history) now rolls over on `is_continue_as_new_suggested()` / a 10K-event soft cap, carrying trigger specs, per-trigger provider `seen_ids` (written back into the spec after every poll cycle), queued push events, the bounded dedup baseline, and the control state — a rollover works mid-pause too, since a paused controller still accretes signal history. `TriggerListenerWorkflow`/`PollingTriggerWorkflow` gained the same pressure check (the old `_processed_count >= 16_000` gate was unreachable: real spawns cost ~15-25 events each, and polling counted only emitted events while a quiet mailbox burned ~11 events/cycle — dead in ~3 days at the 60s default). Poll intervals are clamped to a 30s floor (`_MIN_POLL_INTERVAL_S` in `polling_trigger_workflow.py` and `workflow_control_workflow.py`), with no patch gate. Because run ids change on rollover, **controller handles are addressed by workflow id only, never run_id-pinned** (`_controller_handle`, manager `register_trigger`).+- **A bug in workflow code fails the task, not the run.** A plain exception from workflow code (anything but a Temporal `FailureError` or `asyncio.TimeoutError`, as `services/temporal/_exits.is_workflow_bug` decides) leaves the run open while the SDK retries its task, and a release that fixes the code replays it. So exit cleanup records nothing for a bug: the run methods of `MachinaWorkflow`, `EmployeeJobWorkflow`, `AgentWorkflow`, `DelegatedTaskWorkflow`, `PiInlineDelegationWorkflow`, `NodeInvocationWorkflow` and `PiCodingAgentWorkflow`, and AgentWorkflow's delegation-start arms, re-raise it before their cleanup. Cleanup recorded first would make the history unreplayable by the fixed code. The per-event handlers of the controller, the trigger listener and the polling listener re-raise it too, instead of logging it and skipping the event. The run then shows as stuck with failing tasks (the ERROR log above, the Temporal UI) until a fix ships or Reset ends it. A stuck run stays registered with its controller, so Stop waits on it; Reset is the way out. No patch marker: the cleanup changes only on paths that already end in a failed task, and no history recorded before the per-event change survives the fresh-start release that ships it (RFC-0006 §18.2).- **dispatch.emit controller narrowing.** Controllers advertise their push event types via the `ControlEventTypes` keyword-list Search Attribute (upserted as triggers register); `dispatch.emit` skips controllers with no matching trigger instead of signalling every running controller with every platform event (each unmatched signal was ~4 immutable history events — one busy deployment burned every other controller's rollover budget). Controllers without the attribute (pre-upgrade histories) keep match-all behaviour.- **Boot-time reconcile** (`reconcile_active_controls_on_boot`, called from the lifecycle module after workers start): runs the lazy `_reconcile_control` over every active control row, converges `starting` rows a crash left behind (controller alive with triggers registered → `running`; alive-but-empty for a graph that declares triggers → `failed` + controller closed; vanished → `failed`), and re-arms the process-local half of running/paused generations from the persisted graph snapshot — DeploymentManager state, in-process collectors for non-canary trigger types, cron pause posture. Idempotent by construction (controller `register_trigger` keyed by listener id, legacy starts use `USE_EXISTING`, cron creation preserves server-owned pause state).diff --git a/server/services/temporal/_exits.py b/server/services/temporal/_exits.pynew file mode 100644index 00000000..1ff16f08--- /dev/null+++ b/server/services/temporal/_exits.py@@ -0,0 +1,27 @@+"""Exit cleanup never runs for a bug in workflow code (RFC-0006 section 18.2).++A plain exception raised by workflow code fails the workflow task, not the+run: the run stays open, the task is retried, and a fixed release replays it+from where it stopped. Cleanup that schedules commands on the way out would+first record them in an activation that completes, and the fixed release+could then no longer replay that history. So exit cleanup and per-event+handlers re-raise a bug instead of recording cleanup or skipping the event.+"""++import asyncio++from temporalio.exceptions import FailureError+++def is_workflow_bug(exc: BaseException) -> bool:+ """True for an exception the SDK answers by failing the task, not the run.++ This is the SDK's rule when nothing configures failure exception types+ (``workflow_is_failure_exception`` in temporalio's worker): a+ ``FailureError`` or an ``asyncio.TimeoutError`` fails the run, any other+ ``Exception`` fails the task. Cancellation, continue-as-new and eviction+ are ``BaseException``s, so none of them is a bug. Kept pure (no workflow+ event loop needed); ``tests/temporal/test_workflow_bug_guard.py`` checks+ that nothing configures failure types.+ """+ return isinstance(exc, Exception) and not isinstance(exc, (FailureError, asyncio.TimeoutError))diff --git a/server/services/temporal/agent_workflow.py b/server/services/temporal/agent_workflow.pyindex 8bef45a0..0ec2bf21 100644--- a/server/services/temporal/agent_workflow.py+++ b/server/services/temporal/agent_workflow.py@@ -62,6 +62,7 @@ from services.node_registry import get_node_classfrom services.plugin.base import BaseNodefrom services.tool_output import bound_tool_output, tool_output_is_capped+from ._exits import is_workflow_bugfrom ._retry_policies import (BROWSER_TASK_CLAIM_RETRY,BROWSER_TASK_CLEANUP_RETRY,@@ -601,6 +602,7 @@ class DelegatedTaskWorkflow:root_id = lifecycle["root_execution_id"]acquired_permit_id: Optional[str] = Nonebegan = False+ bug = Falsecompletion_action_active = Falsetry:await self._wait_until_resumed()@@ -745,6 +747,9 @@ class DelegatedTaskWorkflow:)raiseexcept Exception as exc:+ if is_workflow_bug(exc):+ bug = True+ raiseif began:await workflow.execute_activity("agent.finish_delegation",@@ -756,31 +761,33 @@ class DelegatedTaskWorkflow:)raisefinally:- if acquired_permit_id:+ # A bug fails the task and records nothing on the way out (_exits).+ if not bug:+ if acquired_permit_id:+ try:+ await workflow.execute_activity(+ "agent.release_subagent_permit",+ args=[{+ "root_execution_id": root_id,+ "permit_id": acquired_permit_id,+ }],+ activity_id="release-permit-final",+ start_to_close_timeout=PERSIST_TURN_TIMEOUT,+ retry_policy=DELEGATION_CLEANUP_RETRY,+ **acquire_cancellation_options,+ )+ except Exception as release_exc:+ workflow.logger.error(+ "DelegatedTaskWorkflow final permit release failed "+ f"for {task_id}: {release_exc}"+ )try:- await workflow.execute_activity(- "agent.release_subagent_permit",- args=[{- "root_execution_id": root_id,- "permit_id": acquired_permit_id,- }],- activity_id="release-permit-final",- start_to_close_timeout=PERSIST_TURN_TIMEOUT,- retry_policy=DELEGATION_CLEANUP_RETRY,- **acquire_cancellation_options,- )- except Exception as release_exc:- workflow.logger.error(- "DelegatedTaskWorkflow final permit release failed "- f"for {task_id}: {release_exc}"- )- try:- await self._execution_control.unregister_root()- finally:- if completion_action_active:- self._execution_control.end_action()- if self._execution_control.enabled:- await workflow.wait_condition(workflow.all_handlers_finished)+ await self._execution_control.unregister_root()+ finally:+ if completion_action_active:+ self._execution_control.end_action()+ if self._execution_control.enabled:+ await workflow.wait_condition(workflow.all_handlers_finished)@workflow.defn(sandboxed=False, name="AgentWorkflow")@@ -942,6 +949,7 @@ class AgentWorkflow:if runtime_v2:await asyncio.shield(workflow.execute_activity("employee.job.failed", {**context, "cancelled": cancelled, "runtime_admission": True},activity_id="employee-runtime-failed", start_to_close_timeout=PERSIST_TURN_TIMEOUT, retry_policy=AGENT_ACTIVITY_RETRY))+ bug = Falsetry:result = await self._run_impl(context)if not result.get("success", True):@@ -951,27 +959,32 @@ class AgentWorkflow:await fail_job(cancelled=True)raiseexcept Exception as exc:+ if is_workflow_bug(exc):+ bug = True+ raisefrom temporalio.exceptions import is_cancelled_exceptionawait fail_job(cancelled=is_cancelled_exception(exc))raisefinally:- if not self._continuing:- for binding in reversed(self._browser_claims):- async def release(binding=binding):- await workflow.execute_activity(- "browser_tasks.release",- {"binding": binding, "task_id": context["_browser_task_id"]},- task_queue=binding.get("task_queue") or workflow.info().task_queue,- start_to_close_timeout=timedelta(seconds=120),- heartbeat_timeout=timedelta(seconds=30),- retry_policy=BROWSER_TASK_CLEANUP_RETRY,- cancellation_type=ActivityCancellationType.WAIT_CANCELLATION_COMPLETED,- )- # Owner absence leaves cleanup queued. Cancel/Reset wait for- # its receipt instead of releasing another task's claim.- await asyncio.shield(asyncio.create_task(release()))- if self._execution_control.enabled:- await workflow.wait_condition(workflow.all_handlers_finished)+ # A bug fails the task and records nothing on the way out (_exits).+ if not bug:+ if not self._continuing:+ for binding in reversed(self._browser_claims):+ async def release(binding=binding):+ await workflow.execute_activity(+ "browser_tasks.release",+ {"binding": binding, "task_id": context["_browser_task_id"]},+ task_queue=binding.get("task_queue") or workflow.info().task_queue,+ start_to_close_timeout=timedelta(seconds=120),+ heartbeat_timeout=timedelta(seconds=30),+ retry_policy=BROWSER_TASK_CLEANUP_RETRY,+ cancellation_type=ActivityCancellationType.WAIT_CANCELLATION_COMPLETED,+ )+ # Owner absence leaves cleanup queued. Cancel/Reset wait for+ # its receipt instead of releasing another task's claim.+ await asyncio.shield(asyncio.create_task(release()))+ if self._execution_control.enabled:+ await workflow.wait_condition(workflow.all_handlers_finished)async def _run_impl(self, context: Dict[str, Any]) -> Dict[str, Any]:"""Run the agent loop.@@ -1841,7 +1854,9 @@ class AgentWorkflow:# _cleanup_cancelled_delegations() sweep; releasing# here as well would double-release the permit.raise- except BaseException:+ except BaseException as exc:+ if is_workflow_bug(exc):+ raiseawait _release_delegation_permit(call_index)raisechild_id = _delegation_child_id(@@ -1875,7 +1890,9 @@ class AgentWorkflow:# Cancellation cleanup is owned by the caller's# _cleanup_cancelled_delegations() sweep.raise- except BaseException:+ except BaseException as exc:+ if is_workflow_bug(exc):+ raiseif team_id and call_index in delegation_permits:await _release_delegation_permit(call_index)raise@@ -2140,7 +2157,9 @@ class AgentWorkflow:]:await _start_delegation(delegation_index)next_delegation_to_start += 1- except BaseException:+ except BaseException as exc:+ if is_workflow_bug(exc):+ raiseawait _cleanup_cancelled_delegations()raise@@ -2388,7 +2407,9 @@ class AgentWorkflow:# Cancellation cleanup is owned by the outer# _cleanup_cancelled_delegations() sweep.raise- except BaseException:+ except BaseException as exc:+ if is_workflow_bug(exc):+ raiseself._execution_control.begin_bookkeeping()tool_action_active = self._execution_control.enabledawait _release_delegation_permit(call_index)diff --git a/server/services/temporal/employee_job_workflow.py b/server/services/temporal/employee_job_workflow.pyindex 48e061a7..01a93723 100644--- a/server/services/temporal/employee_job_workflow.py+++ b/server/services/temporal/employee_job_workflow.py@@ -5,6 +5,7 @@ from typing import Anyfrom temporalio import workflow, activityfrom temporalio.common import RetryPolicyfrom temporalio.exceptions import is_cancelled_exception+from services.temporal._exits import is_workflow_bugfrom services.temporal._retry_policies import REVIEWED_DELIVERY_RETRYfrom services.temporal.execution_control import ExecutionControl@@ -103,11 +104,17 @@ class EmployeeJobWorkflow:if not self._execution_control.enabled:return await self._run_job(context)await self._execution_control.register_root()+ bug = Falsetry:return await self._run_job(context)+ except Exception as exc:+ bug = is_workflow_bug(exc)+ raisefinally:- await self._execution_control.unregister_root()- await workflow.wait_condition(workflow.all_handlers_finished)+ # A bug fails the task and records nothing on the way out (_exits).+ if not bug:+ await self._execution_control.unregister_root()+ await workflow.wait_condition(workflow.all_handlers_finished)async def _run_job(self, context: dict[str, Any]) -> dict:from services.coding_agent_runtime import agent_workflow_name@@ -120,6 +127,8 @@ class EmployeeJobWorkflow:else:result = await workflow.execute_child_workflow(child_name, context, id=workflow.info().workflow_id + ":lead")except BaseException as exc:+ if is_workflow_bug(exc):+ raise# Cancellation must leave a durable terminal job record too.# Shield this short cleanup from the parent's cancellation.await asyncio.shield(workflow.execute_activity("employee.job.failed", {**context, "cancelled": isinstance(exc, asyncio.CancelledError) or is_cancelled_exception(exc)},diff --git a/server/services/temporal/node_invocation.py b/server/services/temporal/node_invocation.pyindex d2b264d0..af53eee5 100644--- a/server/services/temporal/node_invocation.py+++ b/server/services/temporal/node_invocation.py@@ -7,6 +7,8 @@ from typing import Anyfrom temporalio import workflowfrom temporalio.common import RetryPolicy+from services.temporal._exits import is_workflow_bug+# The parent Temporal package registers services on import. Match the other# framework workflows: orchestration remains deterministic, without re-importing@@ -26,6 +28,7 @@ class NodeInvocationWorkflow:self.metadata = {k: payload[k] for k in ("principal", "workflow_id", "node_id", "fingerprint")}self.status = "running"result: dict = {}+ bug = Falsetry:if payload.get("history_version") == 1:await self._record_status(payload)@@ -53,6 +56,9 @@ class NodeInvocationWorkflow:self.status = "cancelled"raiseexcept Exception as exc:+ if is_workflow_bug(exc):+ bug = True+ raiseif payload.get("dispatch_version") == 1:from temporalio.exceptions import is_cancelled_exceptionif is_cancelled_exception(exc):@@ -76,34 +82,35 @@ class NodeInvocationWorkflow:self.status = "failed"raisefinally:+ # A bug fails the task and records nothing on the way out (_exits).+ if not bug:+ if payload.get("history_version") == 1:+ # Cancellation waits for the attached child and its owner cleanup+ # before this terminal projection is persisted.+ try:+ await asyncio.shield(asyncio.create_task(self._record_status(payload, result)))+ except Exception as exc:+ workflow.logger.warning("Workspace task projection failed: %s", type(exc).__name__)++ async def record() -> None:+ await workflow.execute_activity(+ "workflow_runs.record_completion",+ {+ "workflow_id": payload["workflow_id"],+ "run_id": f"{workflow.info().workflow_id}:{workflow.info().run_id}",+ "generation": payload["context"].get("generation", 0),+ "status": "success" if self.status == "completed" else "failed",+ },+ start_to_close_timeout=timedelta(seconds=30),+ retry_policy=RetryPolicy(maximum_attempts=3),+ )- if payload.get("history_version") == 1:- # Cancellation waits for the attached child and its owner cleanup- # before this terminal projection is persisted.try:- await asyncio.shield(asyncio.create_task(self._record_status(payload, result)))+ await asyncio.shield(asyncio.create_task(record()))except Exception as exc:- workflow.logger.warning("Workspace task projection failed: %s", type(exc).__name__)-- async def record() -> None:- await workflow.execute_activity(- "workflow_runs.record_completion",- {- "workflow_id": payload["workflow_id"],- "run_id": f"{workflow.info().workflow_id}:{workflow.info().run_id}",- "generation": payload["context"].get("generation", 0),- "status": "success" if self.status == "completed" else "failed",- },- start_to_close_timeout=timedelta(seconds=30),- retry_policy=RetryPolicy(maximum_attempts=3),- )-- try:- await asyncio.shield(asyncio.create_task(record()))- except Exception as exc:- # A summary outage must not convert a completed device task into- # a failure that a user may replay. Temporal remains authoritative.- workflow.logger.warning("Workspace run summary failed: %s", type(exc).__name__)+ # A summary outage must not convert a completed device task into+ # a failure that a user may replay. Temporal remains authoritative.+ workflow.logger.warning("Workspace run summary failed: %s", type(exc).__name__)async def _record_status(self, payload: dict, result: dict | None = None) -> None:await workflow.execute_activity(diff --git a/server/services/temporal/pi_inline_delegation.py b/server/services/temporal/pi_inline_delegation.pyindex b863d205..95b13194 100644--- a/server/services/temporal/pi_inline_delegation.py+++ b/server/services/temporal/pi_inline_delegation.py@@ -16,6 +16,7 @@ from temporalio.common import WorkflowIDReusePolicyfrom temporalio.exceptions import ApplicationError, WorkflowAlreadyStartedErrorfrom temporalio.workflow import ActivityCancellationType, ChildWorkflowCancellationType, ParentClosePolicy+from services.temporal._exits import is_workflow_bugfrom services.temporal._retry_policies import DELEGATION_CLEANUP_RETRYfrom services.temporal.execution_control import ExecutionControlfrom services.temporal.pi_protocol import canonical_digest, canonical_json@@ -352,6 +353,7 @@ class PiInlineDelegationWorkflow:async def run(self, request: dict) -> dict:validate_inline_request(request)error = None+ bug = Falseadmission_verified = Falsetry:await self._control.register_root()@@ -374,32 +376,35 @@ class PiInlineDelegationWorkflow:error = "Coding delegation cancelled"raiseexcept Exception as exc:+ bug = is_workflow_bug(exc)error = f"{type(exc).__name__}: {exc}"raisefinally:- self._control.begin_bookkeeping()- try:- if not admission_verified:- # Registration may fail before the admission check. No- # cleanup mutation may trust an unverified external input.- await workflow.execute_activity("coding.inline_delegation_status", {"request": request, "status": "running"},- start_to_close_timeout=timedelta(seconds=60), retry_policy=DELEGATION_CLEANUP_RETRY,- cancellation_type=ActivityCancellationType.WAIT_CANCELLATION_COMPLETED)- if error:- await workflow.execute_activity("agent.cancel_delegation", {**request["lifecycle"], "reason": error,- "terminal_event_id": f"{request['lifecycle']['team_task_id']}:inline-terminal"},+ # A bug fails the task and records nothing on the way out (_exits).+ if not bug:+ self._control.begin_bookkeeping()+ try:+ if not admission_verified:+ # Registration may fail before the admission check. No+ # cleanup mutation may trust an unverified external input.+ await workflow.execute_activity("coding.inline_delegation_status", {"request": request, "status": "running"},+ start_to_close_timeout=timedelta(seconds=60), retry_policy=DELEGATION_CLEANUP_RETRY,+ cancellation_type=ActivityCancellationType.WAIT_CANCELLATION_COMPLETED)+ if error:+ await workflow.execute_activity("agent.cancel_delegation", {**request["lifecycle"], "reason": error,+ "terminal_event_id": f"{request['lifecycle']['team_task_id']}:inline-terminal"},+ start_to_close_timeout=timedelta(seconds=60), retry_policy=DELEGATION_CLEANUP_RETRY,+ cancellation_type=ActivityCancellationType.WAIT_CANCELLATION_COMPLETED)+ await workflow.execute_activity("coding.inline_delegation_status", {"request": request, "error": error},start_to_close_timeout=timedelta(seconds=60), retry_policy=DELEGATION_CLEANUP_RETRY,cancellation_type=ActivityCancellationType.WAIT_CANCELLATION_COMPLETED)- await workflow.execute_activity("coding.inline_delegation_status", {"request": request, "error": error},- start_to_close_timeout=timedelta(seconds=60), retry_policy=DELEGATION_CLEANUP_RETRY,- cancellation_type=ActivityCancellationType.WAIT_CANCELLATION_COMPLETED)- finally:- try:- await self._control.unregister_root()finally:- self._control.end_action()- if self._control.enabled:- await workflow.wait_condition(workflow.all_handlers_finished)+ try:+ await self._control.unregister_root()+ finally:+ self._control.end_action()+ if self._control.enabled:+ await workflow.wait_condition(workflow.all_handlers_finished)return {"task_id": request["lifecycle"]["team_task_id"], "status": "completed"}diff --git a/server/services/temporal/pi_workflow.py b/server/services/temporal/pi_workflow.pyindex f98e682d..6fb6ed37 100644--- a/server/services/temporal/pi_workflow.py+++ b/server/services/temporal/pi_workflow.py@@ -14,6 +14,7 @@ from temporalio import workflowfrom temporalio.common import RetryPolicyfrom temporalio.workflow import ActivityCancellationType+from ._exits import is_workflow_bugfrom .agent_workflow import AgentWorkflow, LLM_STEP_HEARTBEAT_TIMEOUT, LLM_STEP_RETRY, llm_attempt_timeoutfrom .pi_protocol import DRIVER_QUEUE, INLINE_LIMIT, OperationLedger, canonical_digest, canonical_json, conflict, tool_operation_idfrom .pi_control import PiDescendantExecutionControl, PiLocalExecutionControl@@ -128,6 +129,7 @@ class PiCodingAgentWorkflow(AgentWorkflow):if not context or context.get("pi_harness_version") != 1 or context.get("node_type") != "coding_agent":raise conflict("Pi workflow requires an admitted Coding Agent runtime marker")self._pi_context = context+ bug = Falsetry:try:result = await super().run(context)@@ -135,6 +137,9 @@ class PiCodingAgentWorkflow(AgentWorkflow):await self._clear_failed_skills(context)return resultexcept Exception as exc:+ if is_workflow_bug(exc):+ bug = True+ raisefrom temporalio.exceptions import is_cancelled_exceptionif is_cancelled_exception(exc):raise@@ -147,9 +152,11 @@ class PiCodingAgentWorkflow(AgentWorkflow):finally:# Cancellation and terminal failure cannot leave a driver process# occupying private capacity while native cleanup drains children.- await self._stop_driver(cancel=True)- self._pi_checkpointing = False- self._pi_receipt_checkpointing = False+ # A bug fails the task and records nothing on the way out (_exits).+ if not bug:+ await self._stop_driver(cancel=True)+ self._pi_checkpointing = False+ self._pi_receipt_checkpointing = Falseasync def _clear_failed_skills(self, context):await workflow.execute_activity("agent.skill.clear", {"workflow_id": context.get("workflow_id"),diff --git a/server/services/temporal/polling_trigger_workflow.py b/server/services/temporal/polling_trigger_workflow.pyindex 8a358c8d..b5b07f6f 100644--- a/server/services/temporal/polling_trigger_workflow.py+++ b/server/services/temporal/polling_trigger_workflow.py@@ -40,6 +40,7 @@ from temporalio import workflowfrom temporalio.common import WorkflowIDReusePolicyfrom temporalio.workflow import ParentClosePolicy+from ._exits import is_workflow_bugfrom ._retry_policies import DEFAULT_ACTIVITY_RETRYfrom .workflow import TEMPORAL_ROUTING_INPUT_KEY@@ -193,7 +194,11 @@ class PollingTriggerWorkflow:except Exception as exc: # noqa: BLE001# Activity exhausted its RetryPolicy. Log + continue —# don't terminate the listener over one bad cycle.- # Workflow Event History records the failure for ops.+ # Workflow Event History records the failure for ops. A+ # bug in workflow code is not a failure: it fails the+ # task (_exits).+ if is_workflow_bug(exc):+ raiseworkflow.logger.error(f"PollingTriggerWorkflow cycle failed (will retry next interval): {exc}")continue@@ -222,7 +227,9 @@ class PollingTriggerWorkflow:except Exception as spawn_exc: # noqa: BLE001# Per-event spawn failure logged; subsequent events# still try. Same isolation contract as the push- # listener.+ # listener, which re-raises a bug the same way.+ if is_workflow_bug(spawn_exc):+ raiseworkflow.logger.error(f"PollingTriggerWorkflow spawn failed for event.id={event_id}: {spawn_exc}")self._processed_count += 1diff --git a/server/services/temporal/trigger_listener_workflow.py b/server/services/temporal/trigger_listener_workflow.pyindex 01d69dd1..6d466b43 100644--- a/server/services/temporal/trigger_listener_workflow.py+++ b/server/services/temporal/trigger_listener_workflow.py@@ -45,6 +45,7 @@ from temporalio.workflow import ParentClosePolicyfrom services.run_graph import collect_downstream_node_ids+from ._exits import is_workflow_bugfrom .workflow import TEMPORAL_ROUTING_INPUT_KEY@@ -280,7 +281,10 @@ class TriggerListenerWorkflow:# Log and move on; the rejected event still counts as# "seen" so a producer retry with the same id won't# re-fire (correct: server-side dedup applies even on- # downstream failure).+ # downstream failure). A bug in workflow code is not a+ # failure: it fails the task (_exits).+ if is_workflow_bug(exc):+ raiseworkflow.logger.error(f"TriggerListener spawn failed for event.id={event.get('id')}: {exc}")self._processed_count += 1diff --git a/server/services/temporal/workflow.py b/server/services/temporal/workflow.pyindex 69a38217..76a4f51a 100644--- a/server/services/temporal/workflow.py+++ b/server/services/temporal/workflow.py@@ -16,6 +16,7 @@ from typing import Any, Dict, List, Optional, Setfrom temporalio import workflow+from ._exits import is_workflow_bugfrom ._retry_policies import DEFAULT_ACTIVITY_RETRY, QUICK_ACTIVITY_RETRYfrom .execution_control import ExecutionControl@@ -517,14 +518,20 @@ class MachinaWorkflow:if not self._execution_control.enabled:return await self._run_graph(workflow_data)await self._execution_control.register_root()+ bug = Falsetry:return await self._run_graph(workflow_data)+ except Exception as exc:+ bug = is_workflow_bug(exc)+ raisefinally:- for admission in self._action_contexts.values():- await admission.__aexit__(None, None, None)- self._action_contexts.clear()- await self._execution_control.unregister_root()- await workflow.wait_condition(workflow.all_handlers_finished)+ # A bug fails the task and records nothing on the way out (_exits).+ if not bug:+ for admission in self._action_contexts.values():+ await admission.__aexit__(None, None, None)+ self._action_contexts.clear()+ await self._execution_control.unregister_root()+ await workflow.wait_condition(workflow.all_handlers_finished)async def _run_graph(self, workflow_data: Dict[str, Any]) -> Dict[str, Any]:"""Execute workflow by orchestrating node activities.diff --git a/server/services/temporal/workflow_control_workflow.py b/server/services/temporal/workflow_control_workflow.pyindex 42469a77..3bebb2c1 100644--- a/server/services/temporal/workflow_control_workflow.py+++ b/server/services/temporal/workflow_control_workflow.py@@ -8,6 +8,7 @@ from temporalio import workflowfrom temporalio.common import SearchAttributeKey, SearchAttributePairfrom temporalio.exceptions import ApplicationError, WorkflowAlreadyStartedError+from services.temporal._exits import is_workflow_bugfrom services.temporal._retry_policies import DEFAULT_ACTIVITY_RETRYfrom services.temporal.execution_control import ExecutionControl@@ -468,9 +469,13 @@ class WorkflowControlWorkflow:except asyncio.CancelledError:raiseexcept Exception as exc: # noqa: BLE001 — per-event isolation- # One bad event (duplicate child id, exhausted broadcast+ # One failed event (duplicate child id, exhausted broadcast# retries) must not fail the deployment's entire control- # plane. Same isolation contract as the listener classes.+ # plane. Same isolation contract as the listener classes. A+ # bug in workflow code is not a failure: it fails the task+ # (_exits).+ if is_workflow_bug(exc):+ raiseif accumulator_v1 and isinstance(exc, WorkflowAlreadyStartedError):# The deterministic child ID is the durable dispatch key.# Temporal has already accepted this event's child start;diff --git a/server/tests/temporal/test_controller_accumulator.py b/server/tests/temporal/test_controller_accumulator.pyindex 023874a3..d4a84c4a 100644--- a/server/tests/temporal/test_controller_accumulator.py+++ b/server/tests/temporal/test_controller_accumulator.py@@ -5,7 +5,7 @@ from unittest.mock import MagicMockimport pytestfrom temporalio.converter import DefaultPayloadConverter-from temporalio.exceptions import WorkflowAlreadyStartedError+from temporalio.exceptions import ApplicationError, WorkflowAlreadyStartedErrorfrom services.temporal import workflow_control_workflow as modulefrom services.temporal.workflow_control_workflow import WorkflowControlWorkflow@@ -196,7 +196,7 @@ async def test_transient_failure_keeps_same_event_pending_until_success(wf, monkassert "mail:retry" in controller._pending_event_idsif len(calls) == 1:await controller.on_event(event)- raise RuntimeError("temporary dispatch failure")+ raise ApplicationError("temporary dispatch failure")controller._closed = Truemonkeypatch.setattr(controller, "_spawn_push_run", spawn)diff --git a/server/tests/temporal/test_controller_queue.py b/server/tests/temporal/test_controller_queue.pyindex 685e9dd1..f97c6733 100644--- a/server/tests/temporal/test_controller_queue.py+++ b/server/tests/temporal/test_controller_queue.py@@ -4,6 +4,7 @@ import jsonfrom types import SimpleNamespacefrom unittest.mock import MagicMockimport pytest+from temporalio.exceptions import ApplicationErrorfrom services.temporal.controller_queue import event_batches, spill_controller_events, read_controller_eventsfrom services.temporal.workflow_control_workflow import WorkflowControlWorkflow@@ -111,7 +112,7 @@ async def test_failed_accepted_spawn_requeues_the_same_event(wf, monkeypatch):async def spawn(event, _spec):calls.append(event["id"])if len(calls) == 1:- raise RuntimeError("temporary dispatch failure")+ raise ApplicationError("temporary dispatch failure")controller._closed = Truemonkeypatch.setattr(wf, "sleep", sleep)monkeypatch.setattr(controller, "_spawn_push_run", spawn)diff --git a/server/tests/temporal/test_durability_hardening.py b/server/tests/temporal/test_durability_hardening.pyindex 47615345..16f53cf2 100644--- a/server/tests/temporal/test_durability_hardening.py+++ b/server/tests/temporal/test_durability_hardening.py@@ -31,6 +31,7 @@ from types import SimpleNamespacefrom unittest.mock import AsyncMock, MagicMockimport pytest+from temporalio.exceptions import ApplicationErrorfrom services.temporal.polling_trigger_workflow import PollingTriggerWorkflowfrom services.temporal.trigger_listener_workflow import TriggerListenerWorkflow@@ -408,7 +409,8 @@ async def test_controller_push_spawn_failure_does_not_kill_the_run_loop(monkeypaasync def failing_spawn(_event, _spec):calls["n"] += 1if calls["n"] == 1:- raise RuntimeError("duplicate child id")+ # A failure (not a bug in workflow code, which fails the task).+ raise ApplicationError("duplicate child id")controller._closed = Truemonkeypatch.setattr(controller, "_spawn_push_run", failing_spawn)@@ -422,6 +424,60 @@ async def test_controller_push_spawn_failure_does_not_kill_the_run_loop(monkeypaassert result["generation"] == 1+async def test_controller_push_spawn_bug_fails_the_task(monkeypatch):+ # 1b.13: a bug in workflow code is not a failed event. It fails the task+ # instead of being logged and skipped, so a fixed release replays it.+ from services.temporal import workflow_control_workflow as control_module++ temporal_workflow = control_module.workflow+ monkeypatch.setattr(temporal_workflow, "logger", MagicMock())+ monkeypatch.setattr(temporal_workflow, "wait_condition", _predicate_wait)+ monkeypatch.setattr(temporal_workflow, "in_workflow", lambda: False)++ controller = WorkflowControlWorkflow()+ calls = {"n": 0}++ async def spawn(_event, _spec):+ calls["n"] += 1+ if calls["n"] == 1:+ raise RuntimeError("bug in workflow code")+ controller._closed = True # ends the loop if the bug was swallowed++ monkeypatch.setattr(controller, "_spawn_push_run", spawn)+ controller._triggers["l-push"] = _push_spec()+ controller._events.append(("l-push", {"id": "evt-1", "type": "t.x"}))+ controller._events.append(("l-push", {"id": "evt-2", "type": "t.x"}))++ with pytest.raises(RuntimeError, match="bug in workflow code"):+ await controller.run({"generation": 1, "state": "running"})+ assert calls["n"] == 1+++async def test_listener_spawn_bug_fails_the_task(monkeypatch):+ from services.temporal import trigger_listener_workflow as trigger_module++ temporal_workflow = trigger_module.workflow+ monkeypatch.setattr(temporal_workflow, "logger", MagicMock())+ monkeypatch.setattr(temporal_workflow, "patched", lambda _pid: True)+ monkeypatch.setattr(temporal_workflow, "info", _pressure_info)+ monkeypatch.setattr(temporal_workflow, "wait_condition", _predicate_wait)++ def fake_can(args=None):+ raise _CanFired++ monkeypatch.setattr(temporal_workflow, "continue_as_new", fake_can)+ instance = TriggerListenerWorkflow()+ monkeypatch.setattr(instance, "_spawn_child_run", AsyncMock(side_effect=RuntimeError("bug in workflow code")))+ listener_data = _listener_data()+ listener_data["pending_events"] = [{"id": "evt-1", "data": {}}]++ # Before 1b.13 the bug was logged and the listener rolled over.+ with pytest.raises(RuntimeError, match="bug in workflow code"):+ await instance.run(listener_data)++# ---------------------------------------------------------------------------# dispatch.emit controller narrowing.# ---------------------------------------------------------------------------diff --git a/server/tests/temporal/test_pi_inline_delegation.py b/server/tests/temporal/test_pi_inline_delegation.pyindex 60e55f7a..515f204a 100644--- a/server/tests/temporal/test_pi_inline_delegation.py+++ b/server/tests/temporal/test_pi_inline_delegation.py@@ -157,8 +157,16 @@ async def test_wrapper_does_not_start_or_cancel_work_from_unverified_input(runtiawait module.start_inline_pi_delegation({"task": "edit"}, runtime.config)request = runtime.client.start_workflow.await_args.args[1]instance = module.PiInlineDelegationWorkflow(request)++ @asynccontextmanager+ async def action():+ yield++ # The admission check itself refuses (an AttributeError from an incomplete+ # fake would be a bug in workflow code, which records no cleanup; 1b.13).instance._control = SimpleNamespace(register_root=AsyncMock(), unregister_root=AsyncMock(),- wait_until_running=AsyncMock(), begin_bookkeeping=MagicMock(), end_action=MagicMock(), enabled=False)+ wait_until_running=AsyncMock(), begin_bookkeeping=MagicMock(), end_action=MagicMock(), enabled=False,+ action=action)execute = AsyncMock(side_effect=ApplicationError("not admitted", type="PiProtocolConflict", non_retryable=True))start = AsyncMock()monkeypatch.setattr(module.workflow, "execute_activity", execute)diff --git a/server/tests/temporal/test_workflow_bug_guard.py b/server/tests/temporal/test_workflow_bug_guard.pynew file mode 100644index 00000000..44579811--- /dev/null+++ b/server/tests/temporal/test_workflow_bug_guard.py@@ -0,0 +1,141 @@+"""1b.13: a bug in workflow code fails the task and records no exit cleanup.++A plain exception from workflow code fails the workflow task, so the run+stays open and a fixed release replays it. Cleanup recorded on the way out+would break that replay, and a per-event handler that swallowed the bug would+hide it. ``services/temporal/_exits.is_workflow_bug`` names those exceptions.+"""++from __future__ import annotations++import asyncio+from types import SimpleNamespace+from unittest.mock import AsyncMock++import pytest+from temporalio import workflow+from temporalio.exceptions import ApplicationError, CancelledError as TemporalCancelledError, WorkflowAlreadyStartedError++from services.temporal._exits import is_workflow_bug+++class _Continued(BaseException):+ """Stands in for continue-as-new, which the SDK raises as a BaseException."""+++ "exc",+ [+ RuntimeError("bug"),+ ValueError("bug"),+ KeyError("bug"),+ AssertionError("bug"),+ workflow.NondeterminismError("bug"),+ workflow.ReadOnlyContextError("bug"),+ ],+)+def test_a_plain_exception_is_a_bug(exc):+ assert is_workflow_bug(exc)+++ "exc",+ [+ ApplicationError("failure"),+ WorkflowAlreadyStartedError("id", "type"),+ TemporalCancelledError("cancelled"),+ TimeoutError(),+ asyncio.TimeoutError(),+ asyncio.CancelledError(),+ _Continued(),+ GeneratorExit(),+ ],+)+def test_failures_cancellation_and_rollover_are_not_bugs(exc):+ assert not is_workflow_bug(exc)+++def test_nothing_configures_failure_exception_types():+ # The pure rule mirrors the SDK only while no workflow, worker or plugin+ # adds failure types; one that did would turn those bugs into failures.+ from pathlib import Path++ import nodes # noqa: F401 # plugins register their Temporal plugins on import+ from services.temporal.plugin_registry import temporal_plugins+ from tests._source_tree import server_python_files++ offenders = [+ path+ for path in server_python_files("tests", "scripts")+ if "failure_exception_types" in Path(path).read_text(encoding="utf-8", errors="ignore")+ ]+ assert offenders == []+ assert all(plugin.workflow_failure_exception_types is None for plugin in temporal_plugins())+++def no_handler_wait(monkeypatch):+ monkeypatch.setattr(workflow, "wait_condition", AsyncMock())+ monkeypatch.setattr(workflow, "all_handlers_finished", lambda: True)+++def _control():+ return SimpleNamespace(bind=lambda _data: None, enabled=True, register_root=AsyncMock(), unregister_root=AsyncMock())+++ ("exc", "cleaned_up"),+ [(RuntimeError("bug"), False), (ApplicationError("failure"), True), (asyncio.CancelledError(), True)],+)+async def test_a_finally_only_run_skips_its_cleanup_for_a_bug(no_handler_wait, exc, cleaned_up):+ from services.temporal.workflow import MachinaWorkflow++ run = MachinaWorkflow()+ run._execution_control = _control()+ run._run_graph = AsyncMock(side_effect=exc)+ with pytest.raises(type(exc)):+ await run.run({})+ assert run._execution_control.unregister_root.await_count == (1 if cleaned_up else 0)+++ ("exc", "cleaned_up"),+ [(RuntimeError("bug"), False), (ApplicationError("failure"), True)],+)+async def test_a_run_with_arms_records_no_job_failure_for_a_bug(monkeypatch, exc, cleaned_up):+ from services.temporal.agent_workflow import AgentWorkflow+ from tests.services.employees.test_runtime_v2 import admitted++ context, _ = admitted()+ context["employee_job_id"] = "job"+ agent = AgentWorkflow()+ agent._run_impl = AsyncMock(side_effect=exc)+ execute = AsyncMock(return_value={"saved": True})+ monkeypatch.setattr("services.temporal.agent_workflow.workflow.patched", lambda _: True)+ monkeypatch.setattr("services.temporal.agent_workflow.workflow.execute_activity", execute)+ with pytest.raises(type(exc)):+ await agent.run(context)+ assert [call.args[0] for call in execute.await_args_list] == (["employee.job.failed"] if cleaned_up else [])+++ ("exc", "stopped"),+ [(RuntimeError("bug"), False), (ApplicationError("conflict", type="PiProtocolConflict"), True), (_Continued(), True)],+)+async def test_pi_stops_its_driver_only_without_a_bug(exc, stopped):+ from services.temporal.pi_workflow import PiCodingAgentWorkflow++ context = {"node_type": "coding_agent", "pi_harness_version": 1, "node_id": "coder"}+ pi = PiCodingAgentWorkflow(context)+ pi._execution_control = SimpleNamespace(bind=lambda _data: None, enabled=False)+ pi._run_impl = AsyncMock(side_effect=exc)+ pi._clear_failed_skills = AsyncMock()+ pi._emit_phase = AsyncMock()+ pi._stop_driver = AsyncMock()+ if isinstance(exc, ApplicationError):+ # A protocol conflict still ends the turn as a failure result.+ assert (await pi.run(context))["error_type"] == "PiProtocolConflict"+ else:+ with pytest.raises(type(exc)):+ await pi.run(context)+ assert pi._stop_driver.await_count == (1 if stopped else 0)diff --git a/server/tests/test_polling_trigger_workflow.py b/server/tests/test_polling_trigger_workflow.pyindex 2240c2ae..707e5f7d 100644--- a/server/tests/test_polling_trigger_workflow.py+++ b/server/tests/test_polling_trigger_workflow.py@@ -472,7 +472,9 @@ class TestPollingTriggerWorkflowBody:return {"found": False}call_count[0] += 1if call_count[0] == 2: # second call fails- raise RuntimeError("transient API timeout")+ from temporalio.exceptions import ApplicationError++ raise ApplicationError("transient API timeout")if call_count[0] == 1:return {"events": [], "seen_ids": ["a"]} # baselinereturn {"events": [{"id": f"e{call_count[0]}", "x": 1}], "seen_ids": ["a"]}@@ -518,6 +520,46 @@ class TestPollingTriggerWorkflowBody:# we forced sleep to raise.assert call_count[0] == 3+ @pytest.mark.asyncio+ async def test_a_bug_in_workflow_code_fails_the_task(self, monkeypatch):+ """1b.13: a bug is not a failed cycle; it fails the task instead of+ being logged and skipped, so a fixed release replays the cycle."""+ from services.temporal import polling_trigger_workflow as pmod+ from temporalio import workflow as temporal_workflow++ class _Stop(BaseException):+ """Ends the loop if the bug was swallowed (no arm catches it)."""++ cycles = [0]++ async def fake_execute_activity(name, payload, **kwargs):+ cycles[0] += 1+ if cycles[0] == 1:+ return {"events": [], "seen_ids": ["a"]} # baseline+ if cycles[0] == 2:+ raise RuntimeError("bug in workflow code")+ raise _Stop()++ async def fake_sleep(td):+ return None++ monkeypatch.setattr(temporal_workflow, "execute_activity", fake_execute_activity)+ monkeypatch.setattr(temporal_workflow, "sleep", fake_sleep)++ listener_data = {+ "workflow_id": "wf-1",+ "trigger_node_id": "n",+ "node_type": "googleGmailReceive",+ "version": 1,+ "filter_params": {"poll_interval": 5},+ "nodes": [{"id": "n", "type": "googleGmailReceive", "data": {}}],+ "edges": [],+ "session_id": "s",+ "seen_ids": [],+ }+ with pytest.raises(RuntimeError, match="bug in workflow code"):+ await pmod.PollingTriggerWorkflow().run(listener_data)+# ---------------------------------------------------------------------------# C2e — DeploymentManager polling-vs-push dispatch