Self-improving AI Employees for everyone
Python ai-agentsai-employeeai-employeesassistantautonomous-agentsco-employeescompanygrok-botinstinctloop-agentsmuseown-your-datapersonalself-hosted
refactor(canary): plugin self-registration via canary_registry + telegramReceive rollout (Wave 12 C1 #3)
trohitg688f686a2516
diff --git a/server/nodes/telegram/__init__.py b/server/nodes/telegram/__init__.pyindex 988999c7..39405e00 100644--- a/server/nodes/telegram/__init__.py+++ b/server/nodes/telegram/__init__.py@@ -30,6 +30,7 @@ underscore-prefixed modules are implementation detail.from __future__ import annotations+from services.deployment.canary_registry import register_canary_trigger_typefrom services.event_waiter import register_filter_builder, register_trigger_precheckfrom services.node_output_schemas import register_output_schemafrom services.status_broadcaster import register_service_refresh@@ -58,6 +59,14 @@ register_service_refresh(refresh_telegram_status)register_output_schema("telegramReceive", TelegramReceiveOutput)register_output_schema("telegramSend", TelegramSendOutput)+# Wave 12 C1 rollout #3: opt telegramReceive into the+# TriggerListenerWorkflow consumer path. Producer side:+# dispatch_telegram_message_received calls services.events.dispatch.emit+# unconditionally; emit() is gated by Settings.event_framework_enabled+# so the legacy path stays default. See+# services/deployment/canary_registry.py.+register_canary_trigger_type(TelegramReceiveNode.type)+__all__ = ["TelegramCredential","TelegramService",diff --git a/server/nodes/telegram/_events.py b/server/nodes/telegram/_events.pyindex 34be53fe..50759e23 100644--- a/server/nodes/telegram/_events.py+++ b/server/nodes/telegram/_events.py@@ -153,19 +153,33 @@ async def dispatch_telegram_message_received(event_data: Mapping[str, Any]) -> i"""Dispatch an incoming Telegram message to waiting``telegramReceive`` trigger nodes.- Replaces the direct ``event_waiter.dispatch("telegram_message_received",- event_data)`` call. Returns the count of resolved waiters.+ Two delivery paths (in priority order):++ 1. **Legacy event_waiter waiters** via :func:`event_waiter.dispatch`+ (in-process collector/processor; default while the canary flag+ is off).+ 2. **Temporal-durable listeners** via+ :func:`services.events.dispatch.emit` (Wave 12 C1 rollout #3).+ ``emit`` is a no-op pass-through when the feature flag is off,+ so the legacy path keeps working unchanged.++ Returns the count of legacy waiters resolved."""from services import event_waiter+ from services.events.dispatch import emit+ payload = dict(event_data)# Trigger nodes subscribe by event_type string; keep the legacy- # string so the `telegramReceive.event_type` ClassVar still- # matches (Phase C1 + B11 will swap to the typed- # `com.machinaos.telegram.message.received` form together).- resolved = event_waiter.dispatch(- _MESSAGE_LEGACY_EVENT_TYPE,- dict(event_data),+ # string so the `telegramReceive.event_type` ClassVar still matches.+ resolved = event_waiter.dispatch(_MESSAGE_LEGACY_EVENT_TYPE, payload)++ # Temporal-durable fan-out (Wave 12 C1 rollout #3). No-op when+ # event_framework_enabled is off.+ await emit(+ telegram_message_received(payload),+ wire_routing_key=_MESSAGE_LEGACY_EVENT_TYPE,)+return resolveddiff --git a/server/nodes/trigger/chat_trigger/__init__.py b/server/nodes/trigger/chat_trigger/__init__.pyindex cd5e25b7..0d7ed808 100644--- a/server/nodes/trigger/chat_trigger/__init__.py+++ b/server/nodes/trigger/chat_trigger/__init__.py@@ -17,6 +17,7 @@ from typing import Any, Callable, Dict, Optionalfrom pydantic import BaseModel, ConfigDict, Field+from services.deployment.canary_registry import register_canary_trigger_typefrom services.plugin import NodeContext, Operation, TaskQueue, TriggerNode@@ -69,3 +70,11 @@ class ChatTriggerNode(TriggerNode):raise NotImplementedError("Event triggers return via TriggerNode.execute, not the op body")+++# Wave 12 C1 rollout #1: opt this trigger into the TriggerListenerWorkflow+# consumer path. Producer side: dispatch_chat_message_received in+# ./_events.py calls dispatch.emit unconditionally; the canary registry+# tells DeploymentManager to start a listener for this type. See+# services/deployment/canary_registry.py.+register_canary_trigger_type(ChatTriggerNode.type)diff --git a/server/nodes/trigger/task_trigger/__init__.py b/server/nodes/trigger/task_trigger/__init__.pyindex 40a8686f..579cd39e 100644--- a/server/nodes/trigger/task_trigger/__init__.py+++ b/server/nodes/trigger/task_trigger/__init__.py@@ -11,6 +11,7 @@ from typing import Any, Callable, Dict, Literal, Optionalfrom pydantic import BaseModel, ConfigDict, Field+from services.deployment.canary_registry import register_canary_trigger_typefrom services.plugin import NodeContext, Operation, TaskQueue, TriggerNode@@ -78,3 +79,10 @@ class TaskTriggerNode(TriggerNode):raise NotImplementedError("Event triggers return via TriggerNode.execute, not the op body")+++# Wave 12 C1 rollout #2: opt this trigger into the TriggerListenerWorkflow+# consumer path. The producer side lives in nodes/agent/_events.py+# (broadcast_agent_task_completed / _failed dual-emit via dispatch.emit).+# See services/deployment/canary_registry.py for the contract.+register_canary_trigger_type(TaskTriggerNode.type)diff --git a/server/nodes/trigger/webhook_trigger/__init__.py b/server/nodes/trigger/webhook_trigger/__init__.pyindex e022df66..7c512622 100644--- a/server/nodes/trigger/webhook_trigger/__init__.py+++ b/server/nodes/trigger/webhook_trigger/__init__.py@@ -23,6 +23,7 @@ from typing import Any, Callable, Dict, Literal, Optionalfrom pydantic import BaseModel, ConfigDict, Field+from services.deployment.canary_registry import register_canary_trigger_typefrom services.plugin import NodeContext, Operation, TriggerNode, TaskQueue@@ -108,3 +109,10 @@ class WebhookTriggerNode(TriggerNode):raise NotImplementedError("Event triggers return via TriggerNode.execute, not the op body")+++# Wave 12 C1 canary: opt this trigger type into TriggerListenerWorkflow.+# Gated runtime by Settings.event_framework_enabled in DeploymentManager;+# the producer side (broadcast_webhook_received calling dispatch.emit) is+# unconditional. See services/deployment/canary_registry.py.+register_canary_trigger_type(WebhookTriggerNode.type)diff --git a/server/services/deployment/canary_registry.py b/server/services/deployment/canary_registry.pynew file mode 100644index 00000000..3d023f27--- /dev/null+++ b/server/services/deployment/canary_registry.py@@ -0,0 +1,88 @@+"""Wave 12 C1 canary registry — plugin-owned opt-in for Temporal-durable triggers.++Plugin packages call :func:`register_canary_trigger_type` from their+``__init__.py`` to opt their trigger node type into the+:class:`TriggerListenerWorkflow` consumer path inside+:class:`DeploymentManager`. The deployment manager queries via+:func:`is_canary_trigger_type` instead of hardcoding a per-plugin list.++This mirrors the established Wave-11.I plugin-self-registration pattern+(``register_filter_builder``, ``register_poll_coroutine_factory``,+``register_router``, ``register_ws_handlers``, etc.) — DeploymentManager+stays plugin-agnostic and never edits when a new canary trigger lands.++The producer side (each plugin's ``_events.py`` calling+``services.events.dispatch.emit``) is a separate, mechanical change+that doesn't touch this registry. The two together activate the+canary for one trigger type: the registry tells DeploymentManager to+start a ``TriggerListenerWorkflow`` for it; the dispatch.emit call+ensures events reach that listener.++Membership semantics (set-shaped):++ register_canary_trigger_type("webhookTrigger")+ register_canary_trigger_type("chatTrigger")+ is_canary_trigger_type("webhookTrigger") # True+ is_canary_trigger_type("whatsappReceive") # False (not yet opted in)++Idempotent on re-import (multiple registrations of the same type are a+no-op). No collision semantics because there's no "value" to conflict —+membership is the contract.+"""++from __future__ import annotations++from typing import FrozenSet, Iterator, Set+++_REGISTERED: Set[str] = set()+++def register_canary_trigger_type(node_type: str) -> None:+ """Opt this trigger node type into the Wave 12 C1 canary path.++ Called from a plugin's ``__init__.py``. Idempotent: re-importing the+ plugin module (e.g. during ``importlib.reload`` in the test suite)+ is a no-op.++ Args:+ node_type: The trigger node's ``BaseNode.type`` string. The+ string MUST match what the workflow JSON carries for nodes+ of this type — that's the key DeploymentManager looks up+ when deciding which trigger goes to the canary listener.++ Raises:+ TypeError: if ``node_type`` is not a non-empty string.+ """+ if not isinstance(node_type, str) or not node_type:+ raise TypeError(+ f"register_canary_trigger_type expected a non-empty str, "+ f"got {type(node_type).__name__}: {node_type!r}"+ )+ _REGISTERED.add(node_type)+++def is_canary_trigger_type(node_type: str) -> bool:+ """True iff ``node_type`` has been opted into the canary."""+ return node_type in _REGISTERED+++def canary_trigger_types() -> FrozenSet[str]:+ """Return an immutable snapshot of registered canary trigger types.++ Useful for diagnostics / ops dashboards. Don't iterate during a+ deploy — call :func:`is_canary_trigger_type` instead so a future+ plugin reload sees fresh registrations.+ """+ return frozenset(_REGISTERED)+++def __iter__() -> Iterator[str]: # pragma: no cover — module dunders only+ return iter(_REGISTERED)+++__all__ = [+ "register_canary_trigger_type",+ "is_canary_trigger_type",+ "canary_trigger_types",+]diff --git a/server/services/deployment/manager.py b/server/services/deployment/manager.pyindex 99058915..def5f979 100644--- a/server/services/deployment/manager.py+++ b/server/services/deployment/manager.py@@ -24,23 +24,19 @@ if TYPE_CHECKING:logger = get_logger(__name__)-# Wave 12 C1 canary: trigger types that route to TriggerListenerWorkflow-# instead of the in-process collector/processor. Gated by-# Settings.event_framework_enabled. When the flag is off the canary set-# is irrelevant; when on, types outside this set stay on the legacy path.-# Expansion path: add types here as each is proven Temporal-durable.-# Each entry requires its producer plugin's _events.py wrapper to call-# services.events.dispatch.emit so signals reach running listeners.-_CANARY_LISTENER_TRIGGER_TYPES = frozenset([- "webhookTrigger", # shipped 2026-05-14 (C1 canary)- "chatTrigger", # shipped 2026-05-14 (C1 rollout #1)- "taskTrigger", # shipped 2026-05-14 (C1 rollout #2)-])-# Listener Temporal workflow type-name. Used both for ``start_workflow``# and as the Visibility filter for cancellation discovery._LISTENER_WORKFLOW_TYPE = "TriggerListenerWorkflow"+# Wave 12 C1 canary: which trigger types route to TriggerListenerWorkflow+# instead of the legacy in-process collector/processor is owned by the+# plugins themselves via ``services.deployment.canary_registry``. Each+# canary-enabled plugin's ``__init__.py`` calls+# ``register_canary_trigger_type("<node_type>")`` and the deployment+# manager queries ``is_canary_trigger_type`` here — no framework-side+# allowlist to drift. Producer side (the plugin's ``_events.py`` calling+# ``services.events.dispatch.emit``) is the second half of opt-in.+class DeploymentManager:"""Manages event-driven workflow deployment.@@ -428,9 +424,11 @@ class DeploymentManager:Three dispatch paths (in priority order):1. **Wave 12 C1 canary**: when ``Settings.event_framework_enabled``- is on AND ``node_type`` is in :data:`_CANARY_LISTENER_TRIGGER_TYPES`,- start a Temporal-durable :class:`TriggerListenerWorkflow`.- Survives FastAPI process restart via Temporal Event-History replay.+ is on AND the plugin has opted into the canary via+ :func:`services.deployment.canary_registry.register_canary_trigger_type`+ (called from the plugin's ``__init__.py``), start a+ Temporal-durable :class:`TriggerListenerWorkflow`. Survives+ FastAPI process restart via Temporal Event-History replay.2. **Polling triggers** (Gmail, Twitter): API-polling factoryregistered by the plugin's ``PollingTriggerNode`` subclass.@@ -543,10 +541,18 @@ class DeploymentManager:async def _canary_listener_enabled_for(node_type: str) -> bool:"""Whether the C1 canary applies to this trigger type.- Lazy ``Settings()`` call so a runtime flag flip takes effect on- the next deploy without restart.+ Two conditions, both required:++ 1. Plugin has opted in via+ :func:`services.deployment.canary_registry.register_canary_trigger_type`+ — registry lookup, no framework-side allowlist.+ 2. ``Settings.event_framework_enabled`` is on — lazy ``Settings()``+ call so a runtime flag flip takes effect on the next deploy+ without process restart."""- if node_type not in _CANARY_LISTENER_TRIGGER_TYPES:+ from services.deployment.canary_registry import is_canary_trigger_type++ if not is_canary_trigger_type(node_type):return Falsefrom core.config import Settingsdiff --git a/server/tests/test_canary_registry.py b/server/tests/test_canary_registry.pynew file mode 100644index 00000000..950689b1--- /dev/null+++ b/server/tests/test_canary_registry.py@@ -0,0 +1,175 @@+"""Wave 12 C1: tests for the plugin-self-registered canary registry.++Locks two contracts:++1. The registry itself: idempotent registration, membership query,+ type-validation at register time.++2. The architectural invariant: ``services/deployment/manager.py``+ does NOT carry a framework-side allowlist of canary trigger types.+ Each plugin opts in from its own ``__init__.py``. This catches+ future regressions where someone re-introduces+ ``_CANARY_LISTENER_TRIGGER_TYPES = frozenset([...])`` as a+ convenience.++The pattern mirrors the existing ``test_plugin_self_containment.py``+invariants — source-introspection-driven, no live Temporal cluster+needed.+"""++from __future__ import annotations++import inspect+import re+import sys+import types+from unittest.mock import MagicMock++import pytest+++if "machina" not in sys.modules:+ _machina = types.ModuleType("machina")+ _machina.__path__ = []+ sys.modules["machina"] = _machina+ _machina_tcp = types.ModuleType("machina.tcp")+ _machina_tcp.probe_tcp_port = MagicMock(return_value=False)+ sys.modules["machina.tcp"] = _machina_tcp+++def fresh_registry(monkeypatch):+ """Reset the registry's backing set so each test runs in isolation."""+ from services.deployment import canary_registry++ monkeypatch.setattr(canary_registry, "_REGISTERED", set())+ return canary_registry+++class TestRegistryContract:+ """Surface API: register, query, snapshot."""++ def test_unregistered_type_is_not_canary(self, fresh_registry):+ assert fresh_registry.is_canary_trigger_type("webhookTrigger") is False++ def test_register_then_query_returns_true(self, fresh_registry):+ fresh_registry.register_canary_trigger_type("webhookTrigger")+ assert fresh_registry.is_canary_trigger_type("webhookTrigger") is True++ def test_register_is_idempotent(self, fresh_registry):+ fresh_registry.register_canary_trigger_type("chatTrigger")+ fresh_registry.register_canary_trigger_type("chatTrigger")+ fresh_registry.register_canary_trigger_type("chatTrigger")+ assert fresh_registry.canary_trigger_types() == frozenset({"chatTrigger"})++ def test_multiple_types_coexist(self, fresh_registry):+ for t in ("webhookTrigger", "chatTrigger", "taskTrigger"):+ fresh_registry.register_canary_trigger_type(t)+ assert fresh_registry.canary_trigger_types() == frozenset({+ "webhookTrigger", "chatTrigger", "taskTrigger",+ })++ def test_snapshot_is_immutable(self, fresh_registry):+ """``canary_trigger_types()`` returns a frozenset — mutating it+ must not leak back into the registry."""+ fresh_registry.register_canary_trigger_type("webhookTrigger")+ snap = fresh_registry.canary_trigger_types()+ assert isinstance(snap, frozenset)+ # frozenset has no add() — TypeError if attempted.+ with pytest.raises(AttributeError):+ snap.add("chatTrigger") # type: ignore[attr-defined]++ def test_rejects_non_string(self, fresh_registry):+ with pytest.raises(TypeError):+ fresh_registry.register_canary_trigger_type(None) # type: ignore[arg-type]+ with pytest.raises(TypeError):+ fresh_registry.register_canary_trigger_type(123) # type: ignore[arg-type]++ def test_rejects_empty_string(self, fresh_registry):+ with pytest.raises(TypeError):+ fresh_registry.register_canary_trigger_type("")+++class TestNoFrameworkSideAllowlist:+ """Architectural invariant: DeploymentManager must NOT carry a+ framework-side allowlist of canary trigger types. Each plugin owns+ its own opt-in via ``register_canary_trigger_type``.++ Regression catch: if someone re-introduces a frozenset / list /+ set literal of trigger types in ``services/deployment/manager.py``+ to "make things easier," this test fails at import time with a+ pointer to the canary registry pattern instead.+ """++ def test_manager_does_not_declare_canary_listener_trigger_types(self):+ from services.deployment import manager as manager_mod++ # The frozenset would appear either as a module-level attribute+ # (``_CANARY_LISTENER_TRIGGER_TYPES``) or inside the class. Both+ # paths reject.+ assert not hasattr(manager_mod, "_CANARY_LISTENER_TRIGGER_TYPES"), (+ "services/deployment/manager.py declared _CANARY_LISTENER_TRIGGER_TYPES "+ "again. Canary opt-in lives in the plugin folders via "+ "services.deployment.canary_registry.register_canary_trigger_type — "+ "the manager queries via is_canary_trigger_type. Drop the constant "+ "and call the registry function instead."+ )++ # Also catch the regex'd literal form — even if someone names it+ # differently. Heuristic: look for a frozenset / set literal+ # whose members include any current canary trigger string.+ src = inspect.getsource(manager_mod)+ suspicious = re.search(+ r"frozenset\s*\(\s*\[?\s*[\"'](webhookTrigger|chatTrigger|taskTrigger)",+ src,+ )+ assert suspicious is None, (+ f"services/deployment/manager.py contains a hardcoded canary "+ f"trigger-type literal (matched at offset {suspicious.start()}). "+ "Use services.deployment.canary_registry instead — plugins opt "+ "in from their own __init__.py."+ )++ def test_manager_queries_via_registry_function(self):+ """The gate helper must route through is_canary_trigger_type so+ the framework-vs-plugin boundary is preserved."""+ from services.deployment import manager as manager_mod++ src = inspect.getsource(manager_mod.DeploymentManager._canary_listener_enabled_for)+ assert "is_canary_trigger_type" in src, (+ "DeploymentManager._canary_listener_enabled_for must query "+ "is_canary_trigger_type from services.deployment.canary_registry. "+ "Hardcoded membership checks defeat the plugin-self-registration "+ "pattern (regression source: tribal allowlist re-creation)."+ )+++class TestPluginSelfRegistration:+ """Smoke: importing each canary plugin populates the registry.++ These tests intentionally do NOT use ``fresh_registry`` — they+ verify that real plugin import wires the registry. Run order+ matters only insofar as the plugin modules must be importable+ in the test env. If they aren't (heavy deps), the test xfails+ rather than masking the import failure.+ """++ @pytest.mark.parametrize("plugin_module,expected_type", [+ ("nodes.trigger.webhook_trigger", "webhookTrigger"),+ ("nodes.trigger.chat_trigger", "chatTrigger"),+ ("nodes.trigger.task_trigger", "taskTrigger"),+ ])+ def test_plugin_import_registers_its_type(self, plugin_module, expected_type):+ from services.deployment import canary_registry++ try:+ __import__(plugin_module)+ except ImportError as exc: # pragma: no cover — env-dependent+ pytest.xfail(f"plugin module {plugin_module} not importable: {exc}")++ assert canary_registry.is_canary_trigger_type(expected_type), (+ f"Importing {plugin_module} should call "+ f"register_canary_trigger_type({expected_type!r}). Check the "+ "module's __init__.py for the register_canary_trigger_type "+ "call at module scope."+ )diff --git a/server/tests/test_deployment_canary_listener.py b/server/tests/test_deployment_canary_listener.pyindex 7ca52c85..cab3ba41 100644--- a/server/tests/test_deployment_canary_listener.py+++ b/server/tests/test_deployment_canary_listener.py@@ -42,6 +42,23 @@ if "machina" not in sys.modules:sys.modules["machina.tcp"] = _machina_tcp+def fresh_canary_registry(monkeypatch):+ """Reset the canary-registry backing store to a known empty state.++ The production registry accumulates as plugin modules import — that's+ correct for runtime. Tests that assert canary scope must isolate+ from accumulating module state so a future plugin opt-in doesn't+ silently flip a test outcome. This fixture monkeypatches the+ underlying ``_REGISTERED`` set; ``monkeypatch`` restores it after+ the test.+ """+ from services.deployment import canary_registry++ monkeypatch.setattr(canary_registry, "_REGISTERED", set())+ return canary_registry++# ---------------------------------------------------------------------------# Helpers — build a DeploymentManager with the minimum scaffolding to drive# the canary code paths. Database / status broadcaster are pure mocks.@@ -113,13 +130,17 @@ class TestDeterministicListenerId:class TestCanaryScope:- """Canary only activates for whitelisted trigger types AND when the- feature flag is on."""+ """Canary only activates for trigger types opted in via+ :func:`register_canary_trigger_type` AND when the feature flag is on.+ Uses ``fresh_canary_registry`` so each test starts with an empty+ registry — no cross-test pollution from accumulated plugin imports."""@pytest.mark.asyncio- async def test_disabled_when_flag_off(self, monkeypatch):+ async def test_disabled_when_flag_off(self, monkeypatch, fresh_canary_registry):from services.deployment.manager import DeploymentManager+ fresh_canary_registry.register_canary_trigger_type("webhookTrigger")+class _Off:event_framework_enabled = False@@ -130,36 +151,27 @@ class TestCanaryScope:assert result is False@pytest.mark.asyncio- async def test_disabled_for_non_canary_type(self, monkeypatch):+ async def test_disabled_for_unregistered_type(self, monkeypatch, fresh_canary_registry):+ """Plugin must opt in via register_canary_trigger_type; types+ not in the registry stay on the legacy path even with the flag on."""from services.deployment.manager import DeploymentManager+ # Registry is empty (fresh fixture); whatsappReceive not registered.class _On:event_framework_enabled = Trueimport core.configmonkeypatch.setattr(core.config, "Settings", lambda: _On())- # whatsappReceive isn't in the canary set yet.result = await DeploymentManager._canary_listener_enabled_for("whatsappReceive")assert result is False@pytest.mark.asyncio- async def test_enabled_for_webhook_when_flag_on(self, monkeypatch):+ async def test_enabled_when_registered_and_flag_on(self, monkeypatch, fresh_canary_registry):from services.deployment.manager import DeploymentManager- class _On:- event_framework_enabled = True-- import core.config- monkeypatch.setattr(core.config, "Settings", lambda: _On())-- result = await DeploymentManager._canary_listener_enabled_for("webhookTrigger")- assert result is True-- @pytest.mark.asyncio- async def test_enabled_for_chat_trigger_when_flag_on(self, monkeypatch):- """C1 rollout #1: chatTrigger joined the canary set."""- from services.deployment.manager import DeploymentManager+ fresh_canary_registry.register_canary_trigger_type("webhookTrigger")+ fresh_canary_registry.register_canary_trigger_type("chatTrigger")class _On:event_framework_enabled = True@@ -167,8 +179,10 @@ class TestCanaryScope:import core.configmonkeypatch.setattr(core.config, "Settings", lambda: _On())- result = await DeploymentManager._canary_listener_enabled_for("chatTrigger")- assert result is True+ assert await DeploymentManager._canary_listener_enabled_for("webhookTrigger") is True+ assert await DeploymentManager._canary_listener_enabled_for("chatTrigger") is True+ # Sanity: still respects the registry boundary.+ assert await DeploymentManager._canary_listener_enabled_for("randomThing") is Falseclass TestTriggerKindDerivation:diff --git a/server/tests/test_telegram_trigger_canary_producer.py b/server/tests/test_telegram_trigger_canary_producer.pynew file mode 100644index 00000000..f0ad65ff--- /dev/null+++ b/server/tests/test_telegram_trigger_canary_producer.py@@ -0,0 +1,123 @@+"""Wave 12 C1 rollout #3: telegramReceive producer dual-emit invariant.++Locks the contract: ``nodes.telegram._events.dispatch_telegram_message_received``+must route incoming Telegram messages to BOTH the legacy+``event_waiter.dispatch`` and the Temporal-durable+``services.events.dispatch.emit`` path. Without the second call, a+canary-enabled telegramReceive deployment silently misses every+incoming message — the TriggerListenerWorkflow has no other event+source.++Same regex-introspection + runtime smoke pattern used for the+webhookTrigger / chatTrigger / taskTrigger producers in this series.+"""++from __future__ import annotations++import inspect+import re+import sys+import types+from typing import Any, Dict, List+from unittest.mock import AsyncMock, MagicMock++import pytest+++if "machina" not in sys.modules:+ _machina = types.ModuleType("machina")+ _machina.__path__ = []+ sys.modules["machina"] = _machina+ _machina_tcp = types.ModuleType("machina.tcp")+ _machina_tcp.probe_tcp_port = MagicMock(return_value=False)+ sys.modules["machina.tcp"] = _machina_tcp+++_EVENT_WAITER_DISPATCH_PATTERN = re.compile(r"event_waiter\.dispatch\s*\(")+_EVENTS_EMIT_PATTERN = re.compile(r"\bemit\s*\(")+++class TestTelegramProducerDualEmit:+ """Producer wrapper emits BOTH legacy and Temporal envelopes."""++ def test_dispatcher_is_async(self):+ from nodes.telegram._events import dispatch_telegram_message_received++ assert inspect.iscoroutinefunction(dispatch_telegram_message_received)++ def test_dispatcher_routes_both_legacy_and_temporal(self):+ from nodes.telegram import _events++ src = inspect.getsource(_events.dispatch_telegram_message_received)++ assert _EVENT_WAITER_DISPATCH_PATTERN.search(src), (+ "dispatch_telegram_message_received must still call "+ "event_waiter.dispatch(_MESSAGE_LEGACY_EVENT_TYPE, ...) for "+ "the in-process waiter path. Without it, canary-flag-off "+ "deployments lose their existing telegram dispatch."+ )+ assert _EVENTS_EMIT_PATTERN.search(src), (+ "dispatch_telegram_message_received must call "+ "services.events.dispatch.emit(envelope, ...) for the "+ "Temporal-durable canary path. Without it, telegramReceive "+ "TriggerListenerWorkflows receive nothing when the "+ "event_framework_enabled flag is on."+ )++ @pytest.mark.asyncio+ async def test_runtime_dual_emit_calls_both_paths(self, monkeypatch):+ from nodes.telegram import _events+ from services import event_waiter+ from services.events import dispatch as dispatch_mod++ legacy_calls: List[Dict[str, Any]] = []+ emit_calls: List[Any] = []++ def fake_dispatch(event_type, data):+ legacy_calls.append({"event_type": event_type, "data": data})+ return 0++ async def fake_emit(event, **kwargs):+ emit_calls.append({"event": event, **kwargs})+ return event++ monkeypatch.setattr(event_waiter, "dispatch", fake_dispatch)+ monkeypatch.setattr(dispatch_mod, "emit", fake_emit)++ result = await _events.dispatch_telegram_message_received({+ "chat_id": 12345,+ "text": "hello bot",+ "from_id": 999,+ "timestamp": "2026-05-14T00:00:00",+ })++ assert result == 0++ assert len(legacy_calls) == 1+ assert legacy_calls[0]["event_type"] == "telegram_message_received"+ assert legacy_calls[0]["data"]["chat_id"] == 12345++ assert len(emit_calls) == 1+ envelope = emit_calls[0]["event"]+ assert envelope.type == "com.machinaos.telegram.message.received"+ # subject is the chat_id cast to str — CloudEvents spec requires string.+ assert envelope.subject == "12345"+ assert emit_calls[0]["wire_routing_key"] == "telegram_message_received"+++class TestTelegramPluginSelfRegistersCanary:+ """Importing the telegram plugin opts telegramReceive into the canary."""++ def test_plugin_import_registers_telegram_receive(self):+ from services.deployment import canary_registry++ try:+ __import__("nodes.telegram")+ except ImportError as exc: # pragma: no cover+ pytest.xfail(f"nodes.telegram not importable: {exc}")++ assert canary_registry.is_canary_trigger_type("telegramReceive"), (+ "Importing nodes.telegram should call "+ "register_canary_trigger_type('telegramReceive') — see "+ "the __init__.py bottom section."+ )