Skip to content

Self-improving AI Employees for everyone

feat(temporal): robust startup — health-check readiness gate, sweep retry, worker self-restart

trohitg6ed20af775d6
diff --git a/.env.template b/.env.template
index e31fde90..7793d196 100644
--- a/.env.template
+++ b/.env.template
@@ -86,6 +86,26 @@ TEMPORAL_GRACEFUL_SHUTDOWN_SECONDS=30
# didn't pre-cache it.
TEMPORAL_SERVER_READY_TIMEOUT_SECONDS=120
+# --- Startup resilience (server-ready-before-workers) ---
+# After the gRPC port binds, the client polls the WorkflowService gRPC
+# health check until it reports SERVING before starting the worker /
+# visibility sweep (the documented readiness probe; see
+# https://docs.temporal.io/troubleshooting/deadline-exceeded-error).
+# Bounded — the unbounded layer is main.py's 3s reconnect loop.
+TEMPORAL_HEALTH_CHECK_ATTEMPTS=5
+TEMPORAL_HEALTH_CHECK_DELAY_SECONDS=0.5
+TEMPORAL_HEALTH_CHECK_TIMEOUT_SECONDS=2.0
+# The boot-time terminate-running sweep issues a Visibility query that
+# races shard acquisition ("shard status unknown"). Retry it a few times
+# (linear backoff = attempt x base) before giving up for that boot.
+TEMPORAL_SWEEP_ATTEMPTS=4
+TEMPORAL_SWEEP_BACKOFF_SECONDS=0.5
+# The embedded worker self-restarts on a transient crash (the Temporal
+# worker shuts down on a poll failure rather than auto-retrying). Backoff
+# doubles from base up to max between restarts.
+TEMPORAL_WORKER_RESTART_BACKOFF_SECONDS=1.0
+TEMPORAL_WORKER_RESTART_BACKOFF_MAX_SECONDS=30.0
+
# Wave 12 event framework. ``true`` (default) routes trigger events
# through TriggerListenerWorkflow + Temporal Signal fan-out for the
# 8 canary-registered trigger types (webhook, chat, task, telegram,
diff --git a/server/core/config.py b/server/core/config.py
index ae83db95..2532cd2a 100644
--- a/server/core/config.py
+++ b/server/core/config.py
@@ -130,6 +130,52 @@ class Settings(BaseSettings):
env="TEMPORAL_TERMINATE_RUNNING_ON_STARTUP",
)
+ # Startup resilience (server-ready-before-workers). Unlike the core
+ # temporal fields above, these carry Python defaults (matching
+ # ``.env.template``) so an existing ``.env`` predating them keeps
+ # booting — same convention as ``dlq_enabled`` / ``event_framework_enabled``.
+ # Readiness gate: poll the WorkflowService gRPC health check until
+ # SERVING before the worker / visibility sweep act.
+ temporal_health_check_attempts: int = Field(
+ default=5,
+ env="TEMPORAL_HEALTH_CHECK_ATTEMPTS",
+ ge=1,
+ )
+ temporal_health_check_delay_seconds: float = Field(
+ default=0.5,
+ env="TEMPORAL_HEALTH_CHECK_DELAY_SECONDS",
+ ge=0,
+ )
+ temporal_health_check_timeout_seconds: float = Field(
+ default=2.0,
+ env="TEMPORAL_HEALTH_CHECK_TIMEOUT_SECONDS",
+ gt=0,
+ )
+ # Boot-time terminate-running sweep: retry the Visibility query that
+ # races shard acquisition ("shard status unknown") before giving up.
+ temporal_sweep_attempts: int = Field(
+ default=4,
+ env="TEMPORAL_SWEEP_ATTEMPTS",
+ ge=1,
+ )
+ temporal_sweep_backoff_seconds: float = Field(
+ default=0.5,
+ env="TEMPORAL_SWEEP_BACKOFF_SECONDS",
+ ge=0,
+ )
+ # Embedded worker self-restart backoff (doubles from base to max)
+ # when the Temporal worker shuts down on a transient poll failure.
+ temporal_worker_restart_backoff_seconds: float = Field(
+ default=1.0,
+ env="TEMPORAL_WORKER_RESTART_BACKOFF_SECONDS",
+ gt=0,
+ )
+ temporal_worker_restart_backoff_max_seconds: float = Field(
+ default=30.0,
+ env="TEMPORAL_WORKER_RESTART_BACKOFF_MAX_SECONDS",
+ gt=0,
+ )
+
# API Keys (all optional, injected at runtime)
google_maps_api_key: Optional[str] = Field(default=None, env="GOOGLE_MAPS_API_KEY")
openai_api_key: Optional[str] = Field(default=None, env="OPENAI_API_KEY")
diff --git a/server/services/temporal/client.py b/server/services/temporal/client.py
index bc905181..6628396c 100644
--- a/server/services/temporal/client.py
+++ b/server/services/temporal/client.py
@@ -4,16 +4,37 @@ Manages the Temporal client connection lifecycle with retry support.
"""
import asyncio
+from datetime import timedelta
from typing import Optional
from temporalio.api.workflowservice.v1 import DescribeNamespaceRequest
from temporalio.client import Client
from temporalio.runtime import LoggingConfig, Runtime, TelemetryConfig
+from core.config import Settings
from core.logging import get_logger
logger = get_logger(__name__)
+def _is_transient_visibility_error(exc: Exception) -> bool:
+ """True if ``exc`` is a transient server-warmup/visibility error a
+ retry is likely to clear (shard still acquiring, frontend briefly
+ unavailable). Keyed on the typed ``RPCError.status`` with a substring
+ backstop for non-RPCError wrappers."""
+ try:
+ from temporalio.service import RPCError, RPCStatusCode
+
+ if isinstance(exc, RPCError) and exc.status in (
+ RPCStatusCode.UNAVAILABLE,
+ RPCStatusCode.DEADLINE_EXCEEDED,
+ ):
+ return True
+ except Exception: # noqa: BLE001 — import/shape guard; fall through to substring
+ pass
+ msg = str(exc).lower()
+ return "shard" in msg or "unavailable" in msg or "context canceled" in msg
+
+
class TemporalClientWrapper:
"""Wrapper around Temporal client for lifecycle management."""
@@ -22,6 +43,14 @@ class TemporalClientWrapper:
self.namespace = namespace
self._client: Optional[Client] = None
self._runtime: Optional[Runtime] = None
+ # Startup-resilience knobs read once from Settings (env-driven,
+ # canonical defaults in .env.template). Readiness gate + sweep retry.
+ _s = Settings()
+ self._health_check_attempts = _s.temporal_health_check_attempts
+ self._health_check_delay_seconds = _s.temporal_health_check_delay_seconds
+ self._health_check_timeout_seconds = _s.temporal_health_check_timeout_seconds
+ self._sweep_attempts = _s.temporal_sweep_attempts
+ self._sweep_backoff_seconds = _s.temporal_sweep_backoff_seconds
@property
def client(self) -> Optional[Client]:
@@ -66,6 +95,28 @@ class TemporalClientWrapper:
# Verify namespace is ready (gRPC port may accept connections
# before the server finishes registering namespaces)
await client.service_client.workflow_service.describe_namespace(DescribeNamespaceRequest(namespace=self.namespace))
+ # Readiness gate: poll the WorkflowService gRPC health check
+ # until SERVING so "connected" means "frontend serving", not
+ # just "port bound". Documented readiness probe
+ # (https://docs.temporal.io/troubleshooting/deadline-exceeded-error).
+ # A miss raises and is caught by the ``except`` below, folding
+ # into both retry layers (this loop + main.py's 3s reconnect).
+ for hc_attempt in range(1, self._health_check_attempts + 1):
+ try:
+ serving = await client.service_client.check_health(
+ timeout=timedelta(seconds=self._health_check_timeout_seconds),
+ )
+ except Exception: # noqa: BLE001 — treat unreachable as not-serving
+ serving = False
+ if serving:
+ break
+ if hc_attempt < self._health_check_attempts:
+ await asyncio.sleep(self._health_check_delay_seconds)
+ else:
+ raise RuntimeError(
+ "Temporal frontend not SERVING after "
+ f"{self._health_check_attempts} health checks",
+ )
self._client = client
logger.info(f"Connected to Temporal server at {self.server_address}")
# Wave 12 A4: idempotently register the event-framework
@@ -120,19 +171,39 @@ class TemporalClientWrapper:
logger.warning("terminate_running_workflows called before connect; no-op")
return 0
+ # The Visibility query below races shard acquisition right after
+ # boot (visibility-queue-processor reports "shard status unknown"
+ # until shard-1 is acquired). Retry the whole query+iteration a
+ # few times so the sweep isn't silently abandoned for that boot.
+ # ``terminate`` is idempotent, so restarting the scan clean (count
+ # reset) on retry is safe — re-terminating an already-terminated
+ # workflow raises a benign error caught by the inner ``except``.
count = 0
- async for wf in self._client.list_workflows(
- "ExecutionStatus = 'Running'",
- ):
+ for sweep_attempt in range(1, self._sweep_attempts + 1):
try:
- handle = self._client.get_workflow_handle(
- wf.id,
- run_id=wf.run_id,
- )
- await handle.terminate(reason=reason)
- count += 1
- except Exception as exc: # noqa: BLE001 — best-effort sweep
- logger.debug(f"Failed to terminate workflow id={wf.id} " f"run_id={wf.run_id}: {exc}")
+ count = 0
+ async for wf in self._client.list_workflows(
+ "ExecutionStatus = 'Running'",
+ ):
+ try:
+ handle = self._client.get_workflow_handle(
+ wf.id,
+ run_id=wf.run_id,
+ )
+ await handle.terminate(reason=reason)
+ count += 1
+ except Exception as exc: # noqa: BLE001 — best-effort sweep
+ logger.debug(f"Failed to terminate workflow id={wf.id} " f"run_id={wf.run_id}: {exc}")
+ break # iteration completed cleanly
+ except Exception as list_exc: # noqa: BLE001 — Visibility query failed
+ if _is_transient_visibility_error(list_exc) and sweep_attempt < self._sweep_attempts:
+ logger.warning(
+ f"Visibility list_workflows transient "
+ f"({sweep_attempt}/{self._sweep_attempts}); retrying: {list_exc}",
+ )
+ await asyncio.sleep(self._sweep_backoff_seconds * sweep_attempt)
+ continue
+ raise
if count:
logger.info(f"Terminated {count} running workflow(s) at startup " "(history preserved; resumption disabled)")
return count
diff --git a/server/services/temporal/worker.py b/server/services/temporal/worker.py
index 3fa55009..93aa528f 100644
--- a/server/services/temporal/worker.py
+++ b/server/services/temporal/worker.py
@@ -202,14 +202,37 @@ class TemporalWorkerManager:
)
async def _run_worker(self) -> None:
- """Run the worker (background task)."""
- try:
- await self._worker.run()
- except asyncio.CancelledError:
- logger.info("Temporal worker cancelled")
- except Exception as e:
- logger.error(f"Temporal worker error: {str(e)}")
- raise
+ """Run the worker (background task), self-restarting on crash.
+
+ The Temporal worker shuts down on a poll failure rather than
+ auto-retrying (per the Python ``Worker`` docs), and this task is
+ detached — the startup retry loop in ``main.py`` has already
+ returned by the time it runs. So a transient crash (e.g. the
+ server briefly unavailable mid-poll) would otherwise leave the
+ worker permanently dead until a process restart. Re-run the SAME
+ worker instance with doubling backoff; cancellation (from
+ ``stop()``) always wins so shutdown is never delayed by a restart.
+ Backoff knobs are env-driven (canonical defaults in .env.template).
+ """
+ from core.config import Settings
+
+ _s = Settings()
+ backoff = _s.temporal_worker_restart_backoff_seconds
+ backoff_max = _s.temporal_worker_restart_backoff_max_seconds
+ while True:
+ try:
+ await self._worker.run()
+ return # clean shutdown only
+ except asyncio.CancelledError:
+ logger.info("Temporal worker cancelled")
+ raise
+ except Exception as e:
+ logger.error(f"Temporal worker crashed; restarting in {backoff:.1f}s: {e}")
+ try:
+ await asyncio.sleep(backoff)
+ except asyncio.CancelledError:
+ raise # cancellation during backoff still wins
+ backoff = min(backoff * 2, backoff_max)
async def stop(self) -> None:
"""Stop the Temporal worker and cleanup resources."""
diff --git a/server/tests/temporal/test_client_readiness.py b/server/tests/temporal/test_client_readiness.py
new file mode 100644
index 00000000..1b7d0d3f
--- /dev/null
+++ b/server/tests/temporal/test_client_readiness.py
@@ -0,0 +1,114 @@
+"""Readiness gate + transient-error classifier in TemporalClientWrapper.
+
+Locks the two startup-resilience contracts added to
+``services/temporal/client.py``:
+
+ - ``connect()`` polls the WorkflowService gRPC health check
+ (``service_client.check_health``) until SERVING before returning the
+ client, so "connected" means "frontend serving" — the documented
+ readiness probe. A never-SERVING server yields ``None`` (folds into
+ main.py's reconnect loop) instead of a half-ready client.
+ - ``_is_transient_visibility_error`` classifies the shard-warmup /
+ visibility races that the sweep retry (test_terminate_sweep) keys on.
+
+The conftest stubs ``core.config.Settings`` as a MagicMock, so the
+resilience knobs are injected directly on the instance (real ints/floats)
+rather than read from env.
+"""
+
+from __future__ import annotations
+
+from unittest.mock import AsyncMock, MagicMock
+
+import pytest
+
+import services.temporal.client as client_mod
+from services.temporal.client import (
+ TemporalClientWrapper,
+ _is_transient_visibility_error,
+)
+
+
+def _make_wrapper(*, attempts: int = 5, delay: float = 0.0, timeout: float = 1.0) -> TemporalClientWrapper:
+ w = TemporalClientWrapper("localhost:7233", "default")
+ # Override the MagicMock values the stubbed Settings produced.
+ w._health_check_attempts = attempts
+ w._health_check_delay_seconds = delay
+ w._health_check_timeout_seconds = timeout
+ return w
+
+
+def _fake_client(health) -> MagicMock:
+ """A fake Temporal client whose health check is scripted.
+
+ ``health`` is either a bool (constant) or a list of bools consumed
+ one per ``check_health`` call.
+ """
+ c = MagicMock()
+ if isinstance(health, list):
+ c.service_client.check_health = AsyncMock(side_effect=health)
+ else:
+ c.service_client.check_health = AsyncMock(return_value=health)
+ c.service_client.workflow_service.describe_namespace = AsyncMock()
+ return c
+
+
+def _patch_connect(monkeypatch, fake_client: MagicMock) -> None:
+ monkeypatch.setattr(client_mod, "Runtime", MagicMock())
+ fake_Client = MagicMock()
+ fake_Client.connect = AsyncMock(return_value=fake_client)
+ monkeypatch.setattr(client_mod, "Client", fake_Client)
+ # Reached only after the gate passes; keep it a no-op.
+ monkeypatch.setattr(
+ "services.temporal.search_attributes.register_search_attributes",
+ AsyncMock(),
+ )
+
+
+async def test_connect_returns_client_when_serving_first(monkeypatch):
+ fc = _fake_client(True)
+ _patch_connect(monkeypatch, fc)
+ w = _make_wrapper()
+
+ result = await w.connect(retries=1, delay=0)
+
+ assert result is fc
+ assert fc.service_client.check_health.await_count == 1
+
+
+async def test_connect_polls_until_serving(monkeypatch):
+ fc = _fake_client([False, False, False, False, True])
+ _patch_connect(monkeypatch, fc)
+ w = _make_wrapper(attempts=5, delay=0.0)
+
+ result = await w.connect(retries=1, delay=0)
+
+ assert result is fc
+ assert fc.service_client.check_health.await_count == 5
+
+
+async def test_connect_returns_none_when_never_serving(monkeypatch):
+ fc = _fake_client(False)
+ _patch_connect(monkeypatch, fc)
+ w = _make_wrapper(attempts=5, delay=0.0)
+
+ result = await w.connect(retries=1, delay=0)
+
+ assert result is None
+ assert w.is_connected is False
+ assert fc.service_client.check_health.await_count == 5
+
+
+def test_is_transient_visibility_error_status_codes():
+ from temporalio.service import RPCError, RPCStatusCode
+
+ assert _is_transient_visibility_error(RPCError("x", RPCStatusCode.UNAVAILABLE, b"")) is True
+ assert _is_transient_visibility_error(RPCError("x", RPCStatusCode.DEADLINE_EXCEEDED, b"")) is True
+ assert _is_transient_visibility_error(RPCError("x", RPCStatusCode.INVALID_ARGUMENT, b"")) is False
+
+
+def test_is_transient_visibility_error_substrings():
+ assert _is_transient_visibility_error(Exception('error="shard status unknown"')) is True
+ assert _is_transient_visibility_error(Exception("frontend temporarily unavailable")) is True
+ assert _is_transient_visibility_error(Exception("context canceled")) is True
+ assert _is_transient_visibility_error(Exception("genuine bug: KeyError 'x'")) is False
diff --git a/server/tests/temporal/test_terminate_sweep.py b/server/tests/temporal/test_terminate_sweep.py
new file mode 100644
index 00000000..d9aee405
--- /dev/null
+++ b/server/tests/temporal/test_terminate_sweep.py
@@ -0,0 +1,84 @@
+"""Visibility-sweep retry in TemporalClientWrapper.terminate_running_workflows.
+
+The boot-time terminate sweep issues a Visibility ``list_workflows`` query
+that races shard acquisition right after server start
+(visibility-queue-processor reports "shard status unknown" until shard-1
+is acquired). The sweep now retries the query on transient errors instead
+of being silently abandoned for that boot; per-workflow terminate failures
+are still swallowed (idempotent best-effort).
+"""
+
+from __future__ import annotations
+
+from types import SimpleNamespace
+from unittest.mock import AsyncMock, MagicMock
+
+import pytest
+
+from services.temporal.client import TemporalClientWrapper
+
+
+def _agen(items=None, raise_exc=None):
+ """Return a fresh async generator that yields ``items`` or raises."""
+
+ async def _g():
+ if raise_exc is not None:
+ raise raise_exc
+ for it in items or []:
+ yield it
+
+ return _g()
+
+
+def _make_wrapper(client: MagicMock, *, attempts: int = 4) -> TemporalClientWrapper:
+ w = TemporalClientWrapper("localhost:7233", "default")
+ w._client = client
+ w._sweep_attempts = attempts
+ w._sweep_backoff_seconds = 0.0
+ return w
+
+
+def _client_with(list_side_effect) -> MagicMock:
+ c = MagicMock()
+ c.list_workflows = MagicMock(side_effect=list_side_effect)
+ handle = MagicMock()
+ handle.terminate = AsyncMock()
+ c.get_workflow_handle = MagicMock(return_value=handle)
+ return c
+
+
+async def test_sweep_terminates_all_running():
+ wfs = [SimpleNamespace(id="wf1", run_id="r1"), SimpleNamespace(id="wf2", run_id="r2")]
+ client = _client_with([_agen(items=wfs)])
+ w = _make_wrapper(client)
+
+ count = await w.terminate_running_workflows()
+
+ assert count == 2
+ assert client.list_workflows.call_count == 1
+ assert client.get_workflow_handle.return_value.terminate.await_count == 2
+
+
+async def test_sweep_retries_transient_then_succeeds():
+ client = _client_with(
+ [
+ _agen(raise_exc=Exception('error="shard status unknown"')),
+ _agen(items=[SimpleNamespace(id="wf1", run_id="r1")]),
+ ]
+ )
+ w = _make_wrapper(client, attempts=4)
+
+ count = await w.terminate_running_workflows()
+
+ assert count == 1
+ assert client.list_workflows.call_count == 2
+
+
+async def test_sweep_propagates_non_transient():
+ client = _client_with([_agen(raise_exc=Exception("genuine visibility bug"))])
+ w = _make_wrapper(client, attempts=4)
+
+ with pytest.raises(Exception, match="genuine visibility bug"):
+ await w.terminate_running_workflows()
+
+ assert client.list_workflows.call_count == 1
diff --git a/server/tests/temporal/test_worker_restart.py b/server/tests/temporal/test_worker_restart.py
new file mode 100644
index 00000000..6276d8bd
--- /dev/null
+++ b/server/tests/temporal/test_worker_restart.py
@@ -0,0 +1,78 @@
+"""Worker self-restart in TemporalWorkerManager._run_worker.
+
+The Temporal worker shuts down on a transient poll failure rather than
+auto-retrying, and the run task is detached (main.py's startup retry loop
+has already returned). ``_run_worker`` now re-runs the same worker instance
+with doubling backoff on a crash, while cancellation (from ``stop()``)
+always wins so shutdown is never delayed by a restart. Backoff knobs come
+from Settings (env-driven); the conftest stubs Settings, so we patch it to
+a SimpleNamespace with tiny real backoffs.
+"""
+
+from __future__ import annotations
+
+import asyncio
+from types import SimpleNamespace
+from unittest.mock import MagicMock, patch
+
+import pytest
+
+from services.temporal.worker import TemporalWorkerManager
+
+
+def _patch_backoff():
+ return patch(
+ "core.config.Settings",
+ side_effect=lambda: SimpleNamespace(
+ temporal_worker_restart_backoff_seconds=0.001,
+ temporal_worker_restart_backoff_max_seconds=0.002,
+ ),
+ )
+
+
+def _manager_with_run(fake_run) -> TemporalWorkerManager:
+ mgr = TemporalWorkerManager(client=MagicMock(), task_queue="q")
+ worker = MagicMock()
+ worker.run = fake_run
+ mgr._worker = worker
+ return mgr
+
+
+async def test_worker_restarts_after_transient_crash():
+ calls = {"n": 0}
+
+ async def fake_run():
+ calls["n"] += 1
+ if calls["n"] == 1:
+ raise RuntimeError("transient poll failure")
+ await asyncio.Event().wait() # healthy run blocks
+
+ mgr = _manager_with_run(fake_run)
+
+ with _patch_backoff():
+ task = asyncio.create_task(mgr._run_worker())
+ await asyncio.sleep(0.05) # allow crash + restart
+ assert calls["n"] == 2 # restarted exactly once
+ task.cancel()
+ with pytest.raises(asyncio.CancelledError):
+ await task
+
+
+async def test_cancellation_does_not_restart():
+ calls = {"n": 0}
+
+ async def fake_run():
+ calls["n"] += 1
+ await asyncio.Event().wait() # healthy run blocks until cancelled
+
+ mgr = _manager_with_run(fake_run)
+
+ with _patch_backoff():
+ task = asyncio.create_task(mgr._run_worker())
+ await asyncio.sleep(0.02)
+ assert calls["n"] == 1
+ task.cancel()
+ with pytest.raises(asyncio.CancelledError):
+ await task
+
+ assert calls["n"] == 1 # cancellation wins; not restarted