Self-improving AI Employees for everyone
Python ai-agentsai-employeeai-employeesassistantautonomous-agentsco-employeescompanygrok-botinstinctloop-agentsmuseown-your-datapersonalself-hosted
fix(temporal): a capped poll deadline; annotated credential errors fail fast (1b.17)
trohitgc6c554511c0f
diff --git a/docs-internal/TEMPORAL_ARCHITECTURE.md b/docs-internal/TEMPORAL_ARCHITECTURE.mdindex 8691d6a5..05c9d386 100644--- a/docs-internal/TEMPORAL_ARCHITECTURE.md+++ b/docs-internal/TEMPORAL_ARCHITECTURE.md@@ -1081,7 +1081,7 @@ control changes use the version gates below. The strongest Stop/Resumeguarantee 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`).+- **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. Each poll attempt runs under `min(180 s, 4 x the interval)` (`POLL_ACTIVITY_MAX_S`), because Stop and rollover wait for an admitted poll through all three attempts of its retry policy. 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/docs-internal/node-logic-flows/microsoft/msMailReceive.md b/docs-internal/node-logic-flows/microsoft/msMailReceive.mdindex 52dbb9c7..4cd5eb2a 100644--- a/docs-internal/node-logic-flows/microsoft/msMailReceive.md+++ b/docs-internal/node-logic-flows/microsoft/msMailReceive.md@@ -105,8 +105,10 @@ flowchart TDevery cycle (both the activity and the coroutine), so a message thatleaves the 25-item window and re-enters it later fires again. On thebaseline pass nothing is emitted.-- **Temporal activity** (`as_poll_activity`): `setup_service` failure- re-raises (Temporal retry policy owns it); a `fetch_detail` failure skips+- **Temporal activity** (`as_poll_activity`): a `setup_service` or+ `fetch_ids` failure re-raises (Temporal retry policy owns it), except the+ "not connected" `PermissionError` annotated with `provider` (see Auth),+ which is raised as `NodeUserError` and not retried; a `fetch_detail` failure skipsthat id with a warning; `post_emit` failures are swallowed; the result is`{"events": [...], "seen_ids": list(current)}`.- **Legacy coroutine** (`_build_poll_coroutine`): setup failure ends thediff --git a/server/services/plugin/polling.py b/server/services/plugin/polling.pyindex 1d19ee10..7a566238 100644--- a/server/services/plugin/polling.py+++ b/server/services/plugin/polling.py@@ -49,6 +49,7 @@ import asynciofrom typing import Any, Callable, ClassVar, Dict, Set, Tuplefrom core.logging import get_logger+from services.plugin.base import NodeUserErrorfrom services.plugin.trigger import TriggerNodelogger = get_logger(__name__)@@ -197,7 +198,9 @@ class PollingTriggerNode(TriggerNode, abstract=True):I/O, mutable state) — the workflow body only sees the serialisedresult so replay stays deterministic. Per-cycle errors raiseout of the activity; the workflow's ``RetryPolicy`` / try-except- owns retry semantics.+ owns retry semantics. A credential failure annotated at its+ source (a ``PermissionError`` with ``provider``) is raised as+ ``NodeUserError``, which the policy does not retry."""from temporalio import activity@@ -213,17 +216,28 @@ class PollingTriggerNode(TriggerNode, abstract=True):instance = cls()try:service = await instance.setup_service(params)+ current = await instance.fetch_ids(service, params)except Exception as exc: # noqa: BLE001+ if isinstance(exc, PermissionError) and getattr(exc, "provider", None):+ # A missing or rejected credential, annotated at its+ # source with .provider: reconnecting fixes it, a retry+ # cannot. A bare PermissionError (the OS refusing a+ # file) stays retryable.+ logger.warning(+ "Polling activity credential failure",+ node_id=node_id,+ node_type=cls.type,+ error=str(exc),+ )+ raise NodeUserError(str(exc)) from exclogger.error(- "Polling activity setup failed",+ "Polling activity setup or fetch_ids failed",node_id=node_id,node_type=cls.type,error=str(exc),)raise- current = await instance.fetch_ids(service, params)-if baseline_only:# First call after workflow start: establish the seen# baseline without emitting anything. Matches thediff --git a/server/services/temporal/polling_trigger_workflow.py b/server/services/temporal/polling_trigger_workflow.pyindex b5b07f6f..d91dafa2 100644--- a/server/services/temporal/polling_trigger_workflow.py+++ b/server/services/temporal/polling_trigger_workflow.py@@ -55,10 +55,12 @@ _MAX_EVENTS_BEFORE_CONTINUE_AS_NEW = 16_000# Mirrors PollingTriggerNode.default_poll_interval defaults._DEFAULT_POLL_INTERVAL_S = 60-# Activity timeout: 4× the poll interval gives the activity plenty of-# headroom for slow Gmail / Twitter responses without hanging forever.-# Workflow ``RetryPolicy`` (default) handles transient failures.+# Activity deadline: 4x the poll interval for slow responses, never more than+# POLL_ACTIVITY_MAX_S (1b.17). Stop and rollover wait for an admitted poll+# through all three attempts of DEFAULT_ACTIVITY_RETRY, so an hours-long+# deadline at a long interval meant an hours-long wait behind a hung poll._ACTIVITY_TIMEOUT_MULT = 4+POLL_ACTIVITY_MAX_S = 180# Child runs may execute — or stay cooperatively paused — for months,# so they start without lifetime caps; Temporal's timeout timer keeps# ticking through a pause. Liveness comes from activity heartbeats.@@ -142,7 +144,7 @@ class PollingTriggerWorkflow:params = listener_data.get("filter_params", {}) or {}poll_interval = int(params.get("poll_interval") or _DEFAULT_POLL_INTERVAL_S)poll_interval = max(_MIN_POLL_INTERVAL_S, poll_interval)- activity_timeout_s = max(30, poll_interval * _ACTIVITY_TIMEOUT_MULT)+ activity_timeout_s = min(POLL_ACTIVITY_MAX_S, max(30, poll_interval * _ACTIVITY_TIMEOUT_MULT))# Carry seen_ids across continueAsNew. First-start payload has# ``seen_ids=[]`` and the first activity call is baseline-only.diff --git a/server/services/temporal/workflow_control_workflow.py b/server/services/temporal/workflow_control_workflow.pyindex 428e925a..0680c22b 100644--- a/server/services/temporal/workflow_control_workflow.py+++ b/server/services/temporal/workflow_control_workflow.py@@ -805,6 +805,7 @@ class WorkflowControlWorkflow:async def _poll_trigger(self, listener_id: str, spec: Dict[str, Any]) -> None:from services.temporal.polling_trigger_workflow import (+ POLL_ACTIVITY_MAX_S,PollingTriggerWorkflow,_ACTIVITY_TIMEOUT_MULT,_DEFAULT_POLL_INTERVAL_S,@@ -820,7 +821,7 @@ class WorkflowControlWorkflow:poll_interval = int(params.get("poll_interval") or _DEFAULT_POLL_INTERVAL_S)# A few-second user-supplied interval overflows history in hours.poll_interval = max(_MIN_POLL_INTERVAL_S, poll_interval)- activity_timeout_s = max(30, poll_interval * _ACTIVITY_TIMEOUT_MULT)+ activity_timeout_s = min(POLL_ACTIVITY_MAX_S, max(30, poll_interval * _ACTIVITY_TIMEOUT_MULT))seen_ids: set[str] = set(listener_data.get("seen_ids") or [])baseline = not seen_idsrunner = PollingTriggerWorkflow()diff --git a/server/tests/nodes/test_microsoft.py b/server/tests/nodes/test_microsoft.pyindex 9fbb7157..d5c68abc 100644--- a/server/tests/nodes/test_microsoft.py+++ b/server/tests/nodes/test_microsoft.py@@ -334,6 +334,19 @@ class TestEnsureFreshToken:await _auth_helper.ensure_fresh_microsoft_token("owner")assert getattr(exc.value, "provider", None) == "microsoft"+ async def test_a_disconnected_mailbox_fails_the_poll_cycle_without_retries(self):+ # 1b.17: the poll activity turns this annotated error into NodeUserError,+ # which the poll's retry policy does not retry.+ from nodes.microsoft.mail_receive import MailReceiveNode+ from services.plugin import NodeUserError++ auth = AsyncMock()+ auth.get_oauth_tokens = AsyncMock(return_value=None)+ poll = MailReceiveNode.as_poll_activity()+ with patch("services.plugin.deps.get_auth_service", return_value=auth):+ with pytest.raises(NodeUserError):+ await poll({"node_id": "n", "params": {}, "seen_ids": [], "baseline_only": True})+async def test_refresh_persists_new_token(self):from nodes.microsoft import _auth_helperdiff --git a/server/tests/temporal/test_durability_hardening.py b/server/tests/temporal/test_durability_hardening.pyindex 16f53cf2..52a79f18 100644--- a/server/tests/temporal/test_durability_hardening.py+++ b/server/tests/temporal/test_durability_hardening.py@@ -368,6 +368,63 @@ async def test_controller_seeds_carried_state_and_restarts_poll_loops(monkeypatccontroller._poll_tasks["l-poll"].cancel()[email protected](("interval", "expected"), [(5, 120), (45, 180), (60, 180), (3600, 180)])+async def test_the_legacy_poll_deadline_is_capped(monkeypatch, interval, expected):+ # 1b.17: a hung poll holds Stop and rollover for minutes, not hours.+ from services.temporal import polling_trigger_workflow as polling_module+ from services.temporal._retry_policies import DEFAULT_ACTIVITY_RETRY++ temporal_workflow = polling_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, "sleep", AsyncMock())+ activity = AsyncMock(return_value={"seen_ids": ["prior"], "events": []})+ monkeypatch.setattr(temporal_workflow, "execute_activity", activity)++ def fake_can(_listener_data):+ raise _CanFired++ monkeypatch.setattr(temporal_workflow, "continue_as_new", fake_can)+ listener_data = _listener_data()+ listener_data["node_type"] = "googleGmailReceive"+ listener_data["seen_ids"] = ["prior"]+ listener_data["filter_params"] = {"poll_interval": interval}+ with pytest.raises(_CanFired):+ await PollingTriggerWorkflow().run(listener_data)+ assert activity.await_args.kwargs["start_to_close_timeout"] == timedelta(seconds=expected)+ assert activity.await_args.kwargs["retry_policy"] is DEFAULT_ACTIVITY_RETRY++[email protected](("interval", "expected"), [(5, 120), (60, 180), (3600, 180)])+async def test_the_controller_poll_deadline_is_capped(monkeypatch, interval, expected):+ # Also runs the poll loop's function-local import: a name missing there+ # would end every poll loop silently (it runs in its own asyncio task).+ 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, "sleep", AsyncMock())+ controller = WorkflowControlWorkflow()+ controller._can_enabled = False+ spec = _poll_spec()+ spec["listener_args"]["filter_params"] = {"poll_interval": interval}+ controller._triggers[spec["listener_id"]] = spec+ options = {}++ async def poll_activity(*_args, **kwargs):+ options.update(kwargs)+ controller._closed = True # one cycle, then exit+ return {"seen_ids": ["provider-1"], "events": []}++ monkeypatch.setattr(temporal_workflow, "execute_activity", poll_activity)+ await controller._poll_trigger(spec["listener_id"], spec)+ assert options["start_to_close_timeout"] == timedelta(seconds=expected)++@pytest.mark.asyncioasync def test_controller_poll_loop_writes_seen_ids_back_into_the_spec(monkeypatch):"""The provider baseline must live in the carried spec so a rolloverdiff --git a/server/tests/test_polling_trigger_workflow.py b/server/tests/test_polling_trigger_workflow.pyindex 707e5f7d..76bd28e3 100644--- a/server/tests/test_polling_trigger_workflow.py+++ b/server/tests/test_polling_trigger_workflow.py@@ -76,6 +76,8 @@ def _make_fake_polling_class(current_ids: Set[str],detail_payload_fn=None,fail_on_post_emit: bool = False,+ setup_error: BaseException | None = None,+ fetch_ids_error: BaseException | None = None,):"""Build a PollingTriggerNode subclass with override-able hooks.@@ -92,9 +94,13 @@ def _make_fake_polling_class(# abstract=True suppresses registrationasync def setup_service(self, params):+ if setup_error is not None:+ raise setup_errorreturn _FakeService()async def fetch_ids(self, service, params):+ if fetch_ids_error is not None:+ raise fetch_ids_errorreturn set(current_ids)async def fetch_detail(self, service, msg_id, params):@@ -126,6 +132,39 @@ class TestAsPollActivity:return innerreturn activity_fn+ @staticmethod+ def _credential_error():+ error = PermissionError("Microsoft not connected. Reconnect it in Credentials.")+ error.provider, error.reason, error.auth = "microsoft", "missing", "oauth2"+ return error++ @pytest.mark.asyncio+ @pytest.mark.parametrize("hook", ["setup_error", "fetch_ids_error"])+ async def test_an_annotated_credential_failure_is_not_retried(self, hook):+ # 1b.17: reconnecting fixes it; a retry cannot.+ from services.plugin import NodeUserError+ from services.temporal._retry_policies import DEFAULT_ACTIVITY_RETRY++ original = self._credential_error()+ cls = _make_fake_polling_class("test.credential", current_ids={"a"}, **{hook: original})+ inner = self._underlying(cls.as_poll_activity())+ with pytest.raises(NodeUserError) as raised:+ await inner({"node_id": "n1", "params": {}, "seen_ids": [], "baseline_only": True})+ assert raised.value.__cause__ is original+ assert type(raised.value).__name__ in DEFAULT_ACTIVITY_RETRY.non_retryable_error_types++ @pytest.mark.asyncio+ @pytest.mark.parametrize("hook", ["setup_error", "fetch_ids_error"])+ @pytest.mark.parametrize("error", [PermissionError("the OS refused a file"), ValueError("Google Workspace not connected")])+ async def test_other_failures_raise_unchanged(self, hook, error):+ # A bare PermissionError, or an unannotated "not connected" (Gmail,+ # IMAP), keeps the policy's retries.+ cls = _make_fake_polling_class("test.unchanged", current_ids={"a"}, **{hook: error})+ inner = self._underlying(cls.as_poll_activity())+ with pytest.raises(type(error)) as raised:+ await inner({"node_id": "n1", "params": {}, "seen_ids": [], "baseline_only": True})+ assert raised.value is error+@pytest.mark.asyncioasync def test_baseline_only_returns_no_events(self):cls = _make_fake_polling_class("test.baseline", current_ids={"a", "b", "c"})