The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
refactor(cron): fold the fire startup gate into one function and drop the timing assertion
IAvecilla660427e6be23
diff --git a/cron/scheduler_delivery_origin.py b/cron/scheduler_delivery_origin.pyindex ccc17f5191f..59da9181dfe 100644--- a/cron/scheduler_delivery_origin.py+++ b/cron/scheduler_delivery_origin.py@@ -6,18 +6,12 @@ from typing import Anydef 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.+ """Stamp the origin's ``scope_id`` / ``user_id`` onto a live send's 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.+ Relay egress is fail-closed on a discriminator and the RelayAdapter's caches are cold after every+ boot, so the persisted origin supplies them. Origin targets only (a fan-out target's recipient is not+ the origin's author); ``setdefault`` never overrides router or home stamping; ``user_id`` is read by+ relay transports only."""discriminators = (("scope_id", t.origin.get("scope_id") if t.origin_target else None),diff --git a/gateway/platforms/api_server.py b/gateway/platforms/api_server.pyindex 568103f37f8..369db7e51b5 100644--- a/gateway/platforms/api_server.py+++ b/gateway/platforms/api_server.py@@ -4036,7 +4036,7 @@ class APIServerAdapter(OpenAICompatRoutesMixin, BasePlatformAdapter):with suppress(Exception):from gateway.run import _gateway_runner_refrunner = _gateway_runner_ref()- from gateway.platforms.api_server_fire_startup import refuse_until_started # a mid-boot fire waits for adapters+ from gateway.platforms.api_server_fire_startup import refuse_until_startedif (refusal := await refuse_until_started(runner, job_id)) is not None: return refusaladapters = getattr(runner, "adapters", None) or Nonediff --git a/gateway/platforms/api_server_fire_startup.py b/gateway/platforms/api_server_fire_startup.pyindex 39f3c5bdafd..9041d070d35 100644--- a/gateway/platforms/api_server_fire_startup.py+++ b/gateway/platforms/api_server_fire_startup.py@@ -21,26 +21,16 @@ FIRE_STARTUP_WAIT_SECONDS = 10.0_POLL_SECONDS = 0.1-async def await_gateway_started(runner: Any, timeout: Optional[float] = None) -> bool:- """True once ``runner`` has finished starting (``_running``: every platform connect attempted and its+async def refuse_until_started(runner: Any, job_id: str) -> Optional["web.Response"]:+ """None once ``runner`` has finished starting (``_running``: every platform connect attempted and itsadapters published), or when there is no runner to ask (a self-hosted api_server, a test double).- False when it is still starting after ``timeout`` seconds; the caller answers a retryable 503."""- if runner is None or getattr(runner, "_running", True):- return True+ Otherwise the retryable 503, worded like the dashboard's own "gateway unreachable" so NAS classifies+ it the same."""loop = asyncio.get_running_loop()- deadline = loop.time() + (FIRE_STARTUP_WAIT_SECONDS if timeout is None else timeout)- while not runner._running:+ deadline = loop.time() + FIRE_STARTUP_WAIT_SECONDS+ while runner is not None and not getattr(runner, "_running", True):if loop.time() >= deadline:- return False+ return web.json_response(+ {"error": "gateway unreachable; retry", "job_id": job_id}, status=503, headers={"Retry-After": "2"})await asyncio.sleep(_POLL_SECONDS)- return True---async def refuse_until_started(runner: Any, job_id: str) -> Optional["web.Response"]:- """Wait out a cold boot so the fire's job gets the live adapters (E2EE and relay-fronted platforms have- no native credential, so without them delivery fails). None when the gateway is up; otherwise the- retryable 503, worded like the dashboard's own "gateway unreachable" so NAS classifies it the same."""- if await await_gateway_started(runner):- return None- return web.json_response(- {"error": "gateway unreachable; retry", "job_id": job_id}, status=503, headers={"Retry-After": "2"})+ return Nonediff --git a/tests/cron/test_cron_relay_dm_origin_user_id.py b/tests/cron/test_cron_relay_dm_origin_user_id.pyindex facdccea106..85a7169f337 100644--- a/tests/cron/test_cron_relay_dm_origin_user_id.py+++ b/tests/cron/test_cron_relay_dm_origin_user_id.py@@ -43,20 +43,14 @@ def _target(transport, *, origin, origin_target=True, loop=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():+def test_origin_discriminators_ride_relay_route_and_media_metadata():t = _target(_Transport(is_relay=True),- origin={"platform": "slack", "chat_id": "C123", "user_id": "U_HUMAN", "scope_id": "T0AAAA111"},+ origin={"platform": "slack", "chat_id": "C123", "user_id": DM_USER, "scope_id": "T0AAAA111"},)- _thread, route_metadata, _media = sd._live_route_metadata(t)- assert (route_metadata["user_id"], route_metadata["scope_id"]) == ("U_HUMAN", "T0AAAA111")+ _thread, route_metadata, media_metadata = sd._live_route_metadata(t)+ for metadata in (route_metadata, media_metadata):+ assert (metadata["user_id"], metadata["scope_id"]) == (DM_USER, "T0AAAA111")@pytest.mark.parametrize("transport_is_relay, origin_target", [(False, True), (True, False)])diff --git a/tests/gateway/test_cron_fire_startup_gate.py b/tests/gateway/test_cron_fire_startup_gate.pyindex 1d109ae488f..1d9ccb94ca2 100644--- a/tests/gateway/test_cron_fire_startup_gate.py+++ b/tests/gateway/test_cron_fire_startup_gate.py@@ -103,12 +103,9 @@ async def test_fire_is_retryable_and_never_claimed_when_startup_does_not_finish(@pytest.mark.asyncio-async def test_started_gateway_is_not_delayed(adapter, provider):+async def test_started_gateway_is_accepted_immediately(adapter, provider):runner = SimpleNamespace(_draining=False, _external_drain_active=False, _running=True, adapters={"relay": object()})- loop = asyncio.get_running_loop()- started = loop.time()resp = await _post_fire(adapter, runner)assert resp.status == 202- assert loop.time() - started < 1.0