The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(cron): relay DM deliveries carry the origin user_id so a cold routing cache still egresses
IAvecilla6cb3bab6b3bf
diff --git a/cron/scheduler_delivery.py b/cron/scheduler_delivery.pyindex 0d4f4b33f5d..4fdbd0305fa 100644--- a/cron/scheduler_delivery.py+++ b/cron/scheduler_delivery.py@@ -1462,12 +1462,9 @@ def _live_route_metadata(t: _TargetDelivery) -> tuple[Optional[str], dict, dict]if thread_id:media_metadata["thread_id"] = thread_id- # Relay egress needs metadata.scope_id (fail-closed tenant guard; scope cache is COLD after a- # restart; router stamps HOME only). Origin targets only: a wrong fan-out scope is worse than- # none.- if t.origin_target and t.origin.get("scope_id"):- route_metadata.setdefault("scope_id", str(t.origin["scope_id"]))- media_metadata.setdefault("scope_id", str(t.origin["scope_id"]))+ # Relay egress discriminators (scope_id / user_id) from the persisted origin: the adapter's caches are cold+ # after a restart. See cron/scheduler_delivery_origin.py.+ _origin.stamp_origin_discriminators(t, route_metadata, media_metadata)return route_thread_id, route_metadata, media_metadata@@ -2129,5 +2126,6 @@ def _deliver_result(# Late-bound origin namespace (see module docstring). Imported LAST so this module is fully# populated before ``scheduler`` re-exports from it.from cron import scheduler as _sched # noqa: E402+from cron import scheduler_delivery_origin as _origin # noqa: E402from cron import scheduler_preflight as _preflight # noqa: E402from cron import scheduler_script as _script # noqa: E402diff --git a/cron/scheduler_delivery_origin.py b/cron/scheduler_delivery_origin.pynew file mode 100644index 00000000000..ccc17f5191f--- /dev/null+++ b/cron/scheduler_delivery_origin.py@@ -0,0 +1,29 @@+"""Relay egress discriminators a cron fire carries from its persisted job origin."""++from __future__ import annotations++from typing import Any+++def stamp_origin_discriminators(t: Any, route_metadata: dict, media_metadata: dict) -> None:+ """Copy the origin's tenant discriminators onto a live send's text and media metadata.++ Relay egress is fail-closed on a discriminator in metadata: ``scope_id`` for a scoped chat (Slack+ workspace, Discord guild) and ``user_id`` (the recipient author) for a guild-less DM (Telegram,+ WhatsApp, Matrix, Signal), which has no route row. The RelayAdapter learns both from inbound+ events, so its caches are COLD after every process start, and a backend that stops the guest on+ sleep restarts the gateway on every wake. The router stamps only the HOME channel, so the+ persisted origin is the source for everything else.++ Origin targets only: ``origin_user_id`` is None for a fan-out target, whose tenant and recipient+ are not the origin's, and a wrong discriminator is worse than none. ``setdefault`` never overrides+ router or home stamping. ``user_id`` goes to relay transports only; native adapters never read it.+ """+ discriminators = (+ ("scope_id", t.origin.get("scope_id") if t.origin_target else None),+ ("user_id", t.origin_user_id if t.is_relay else None),+ )+ for key, value in discriminators:+ if value:+ route_metadata.setdefault(key, str(value))+ media_metadata.setdefault(key, str(value))diff --git a/tests/cron/test_cron_relay_dm_origin_user_id.py b/tests/cron/test_cron_relay_dm_origin_user_id.pynew file mode 100644index 00000000000..facdccea106--- /dev/null+++ b/tests/cron/test_cron_relay_dm_origin_user_id.py@@ -0,0 +1,88 @@+"""A cron fire into a relay DM carries the origin's ``user_id``, so a COLD routing cache still egresses.++The relay connector resolves a guild-less DM (Telegram, WhatsApp, Matrix, Signal) to a tenant ONLY from+``metadata.user_id``, the authentic recipient. The RelayAdapter fills it from a cache learned from inbound+events, which is empty after every process start. A backend that stops the guest on sleep restarts the+gateway on every wake, so the first cron fire after a wake sent the DM with no discriminator and the+connector declined it ("target is not an approved destination for this connection"). The persisted job+origin already holds the user, exactly as it holds ``scope_id`` for scoped chats.+"""++import asyncio+import threading++import pytest++import cron.scheduler_delivery as sd+from gateway.config import GatewayConfig, Platform+from gateway.platforms.base import SendResult++DM_USER = "861704526"+++class _Transport:+ adapter = type("Adapter", (), {})()++ def __init__(self, *, is_relay: bool):+ self.is_relay = is_relay+ self.sent: list[dict] = []++ async def send(self, platform, chat_id, content, metadata=None):+ self.sent.append(dict(metadata or {}))+ return SendResult(success=True, message_id="m1")+++def _target(transport, *, origin, origin_target=True, loop=None):+ fields = {name: None for name in sd._TargetDelivery.__dataclass_fields__}+ fields.update(+ job={"id": "job-1"}, platform=Platform.TELEGRAM, platform_name="telegram", chat_id=DM_USER,+ thread_id=None, transport=transport, config=GatewayConfig(), loop=loop, target_adapters={},+ notify_delivery=True, mirror_text="", origin=origin, origin_target=origin_target,+ origin_user_id=origin.get("user_id") if origin_target else None,+ )+ return sd._TargetDelivery(**fields)+++def test_origin_user_id_rides_relay_route_and_media_metadata():+ t = _target(_Transport(is_relay=True), origin={"platform": "telegram", "chat_id": DM_USER, "user_id": DM_USER})+ _thread, route_metadata, media_metadata = sd._live_route_metadata(t)+ assert route_metadata["user_id"] == DM_USER+ assert media_metadata["user_id"] == DM_USER+++def test_scoped_origin_carries_both_discriminators():+ t = _target(+ _Transport(is_relay=True),+ origin={"platform": "slack", "chat_id": "C123", "user_id": "U_HUMAN", "scope_id": "T0AAAA111"},+ )+ _thread, route_metadata, _media = sd._live_route_metadata(t)+ assert (route_metadata["user_id"], route_metadata["scope_id"]) == ("U_HUMAN", "T0AAAA111")++[email protected]("transport_is_relay, origin_target", [(False, True), (True, False)])+def test_no_user_id_off_the_relay_or_for_fan_out_targets(transport_is_relay, origin_target):+ """Native adapters never read it, and a fan-out target's recipient is not the origin's author."""+ t = _target(+ _Transport(is_relay=transport_is_relay),+ origin={"platform": "telegram", "chat_id": DM_USER, "user_id": DM_USER},+ origin_target=origin_target,+ )+ _thread, route_metadata, media_metadata = sd._live_route_metadata(t)+ assert "user_id" not in route_metadata and "user_id" not in media_metadata+++def test_cold_adapter_send_reaches_the_transport_with_user_id(monkeypatch):+ """End to end through the live lane: what the connector sees on the wire for a cold-cache relay DM."""+ monkeypatch.setattr(sd, "_maybe_mirror_cron_delivery", lambda *a, **k: None)+ loop = asyncio.new_event_loop()+ threading.Thread(target=loop.run_forever, daemon=True).start()+ try:+ transport = _Transport(is_relay=True)+ t = _target(+ transport, origin={"platform": "telegram", "chat_id": DM_USER, "user_id": DM_USER}, loop=loop)+ target_errors, delivery_errors = [], []+ sd._deliver_via_live_adapter(+ t, "hi", [], target_errors=target_errors, delivery_errors=delivery_errors, unverified_targets=[])+ finally:+ loop.call_soon_threadsafe(loop.stop)+ assert [m.get("user_id") for m in transport.sent] == [DM_USER]