Skip to content

SessionsBus: must POST /agents/register before opening the SSE stream (sessions v0.4.0 dispatch gate breaks all deployed agents) #45

Description

@pajoma

What broke

sessions v0.4.0 gates the SSE job stream on the agent registry (avs.ai.idac.service-sessions#27/#82): GET /jobs/stream/sse returns 403 (JSON) unless the agent has previously called POST /agents/register. Blueprint's SessionsBus connects straight to the stream without registering — so after the v0.4.0 deploy (2026-07-05 21:58 UTC), all three deployed VerA agents (document-analyser, document-classifier, jmes-validator) went into an infinite 5-second reconnect loop:

httpx_sse._exceptions.SSEError: Expected response header Content-Type to contain 'text/event-stream', got 'application/json'
Reconnecting in 5 seconds...

(≈7.5 h × 3 agents × every 5 s before it was caught.)

Stopgap applied

Agents were registered manually via POST /api/agents/register (idempotent, X-Api-Key); their next retry connected and SSE keepalives now sustain the registry heartbeat ("an open stream does not expire"). This does not survive an agent restart or a stream gap longer than the TTL (60 s) — the agent then 403-loops again until someone re-registers it by hand.

Required fix

SessionsBus.on_startup / the reconnect loop must:

  1. POST {base_url}/agents/register with {agent_id, agent_type, capabilities} (all already present in sessions_service config) before opening the stream — and re-register before every reconnect attempt (cheap: idempotent, 200/201).
  2. Optionally surface the 403 body in the error log — the current SSEError hides the actual status/reason, which cost most of the diagnosis time.

Compatibility notes

Activity

  1. added
    enhancement
    on Jul 6, 2026
  2. self-assigned this
    on Jul 6, 2026
  3. added theissue type on Jul 6, 2026
  4. added this to the v0.7.0 milestone on Jul 6, 2026
  5. pajoma commented on Jul 6, 2026

    @pajoma
    ContributorAuthor

    Proposed design

    Worked this through as a brainstorm. Decisions taken: scope includes #44 (same code path), registration lives in SessionsApiClient (alongside start_job/complete_job), and graceful unregister on shutdown (the service exposes DELETE /agents/{agent_id}).

    Confirmed the server contract against service-sessions: route is POST {base_url}/agents/register (no /api prefix internally — the stopgap's /api was the ingress path), auth is X-Api-Key, returns 201 (new) or 200 (heartbeat refresh), body {agent_id, agent_type, capabilities[], version?, metadata?}.

    1. Overview

    Two client methods + a restructured reconnect loop. The dispatch gate is closed by registering before every stream open, reusing the existing reconnect/backoff machinery rather than adding new control flow.

    Every connection attempt becomes register → open stream. Registration failure is treated exactly like a connect failure (backoff + retry), so app-startup resilience is preserved — failures happen inside the SSE task, not on_startup (the existing test_app_starts_when_sessions_service_unreachable integration test still holds).

    2. SessionsApiClient — two new methods

    async def register_agent(agent_id, agent_type, capabilities, version=None, metadata=None) -> bool

    • POST {base_url}/agents/register, body {agent_id, agent_type, capabilities} (+ optional version/metadata). X-Api-Key already on the persistent client.
    • 200 / 201 → success, return True.
    • 404 → legacy server (< v0.4.0) with no register endpoint → log once at WARNING, return False; caller proceeds to open the stream anyway.
    • Any other non-2xx → log status and response body (the "surface the 403 body" requirement), then raise_for_status() → propagates to the reconnect loop → backoff.

    async def unregister_agent(agent_id) -> None

    • DELETE {base_url}/agents/{agent_id}, best-effort. Swallows all exceptions (including 404 on legacy servers) — shutdown must never fail on this.

    3. SessionsBus — reconnect loop, shutdown, and #44

    • Register-before-connect: at the top of _connect_and_consume(), await self._api_client.register_agent(...). Running on the per-attempt path satisfies "re-register before every reconnect" and covers the first connect — no separate on_startup call needed.
    • Unregister on shutdown: on_shutdown() calls await self._api_client.unregister_agent(self._agent_id) after cancelling the SSE task. Teardown order makes this safe — SessionsBus is a lifecycle component (torn down first) while SessionsApiClient is a service (torn down later), so the client is still open.
    • SessionsBus: 30s keepalive frames logged as 'Unknown SSE event type: message' WARNING #44 keepalive noise: treat a default-type message frame with empty data as a keepalive → logger.debug(...) and continue. Named events with a payload still hit the Unknown SSE event type WARNING.
    • 403 diagnostics: wrap aiter_sse() so an SSEError reads event_source.response.status_code + body and logs them before re-raising — makes any future non-SSE rejection diagnosable, not just this one.

    4. Error-handling semantics

    Event Outcome
    register 200/201 proceed to open stream
    register 404 log "legacy server", proceed to open stream
    register 4xx/5xx/network log status+body, raise → backoff, retry next cycle
    stream opens, then drops existing backoff → next cycle re-registers
    shutdown cancel SSE task → best-effort DELETE unregister

    5. Configuration

    No new required config — base_url, agent_id, agent_type, capabilities, api_key are all already loaded. version/metadata optional and left out unless wanted (YAGNI).

    6. Testing

    • Unit (SessionsApiClient): register 200/201 → True; 404 → False + no raise; 500 → raises + body logged; unregister swallows errors.
    • Unit (SessionsBus): _connect_and_consume registers before aconnect_sse; register raising propagates into the backoff loop; on_shutdown unregisters; keepalive empty message frame logs DEBUG not WARNING (closes SessionsBus: 30s keepalive frames logged as 'Unknown SSE event type: message' WARNING #44).
    • Integration: existing startup-resilience test must still pass (register failure inside the task doesn't block startup).

    7. Docs

    Short CHANGELOG.md entry under v0.7.0 + a note in docs/concepts/event-processing.md that SessionsBus registers before streaming. Closes #45 and #44 in one PR.

  6. pajoma commented on Jul 6, 2026

    @pajoma
    ContributorAuthor

    The proposed design is coherent and matches the current Blueprint lifecycle. Moving registration into SessionsApiClient keeps the sessions-service contract with the other REST calls, and calling it inside the per-attempt _connect_and_consume() path closes both the first-connect and reconnect gaps without making FastAPI startup depend on sessions-service availability.

    Non-blocking Concerns

    • Keep the unregister path truly best-effort in implementation: SessionsBus.on_shutdown() can be called after partial startup or after the SSE task has already failed, so it should guard a missing client/agent id and swallow/log failures without masking shutdown. The proposed teardown ordering is otherwise valid: AppBuilder shuts lifecycle components down before services, so SessionsApiClient is still open.
    • When logging register/SSE rejection bodies, avoid logging request headers or API keys. Response body logging is useful here, but the implementation should keep the diagnostic limited to status/body and tolerate body-read failures.

    Evidence Reviewed

    VERDICT: APPROVE

  7. pajoma commented on Jul 6, 2026

    @pajoma
    ContributorAuthor

    Detailed spec (committed)

    Written to docs/superpowers/specs/2026-07-06-sessions-agent-registration-design.md on branch feature/sessions-agent-registration (commit afff96f). Full implementation-ready design below.


    SessionsBus: register with the dispatch registry before opening the SSE stream

    • Date: 2026-07-06
    • Issues: #45 (register-before-connect), #44 (keepalive log noise) — both closed by this work
    • Milestone: v0.7.0

    Problem

    Sessions service v0.4.0 gates the SSE job stream on an explicit agent registry
    (service-sessions #27/#82). GET /jobs/stream/sse returns 403 (JSON) unless the
    agent has previously called POST /agents/register. SessionsBus connects straight to
    the stream without registering, so after the v0.4.0 deploy all deployed agents fell into
    an infinite 5-second reconnect loop:

    httpx_sse._exceptions.SSEError: Expected response header Content-Type to contain
    'text/event-stream', got 'application/json'
    Reconnecting in 5 seconds...
    

    The SSEError hides the real status/reason, which cost most of the diagnosis time.

    A related papercut (#44): the service emits an SSE keepalive comment frame (: keepalive
    with an id: and no event:/data:) every 30 s. SessionsBus dispatches it as a
    default-type message event with empty data, which falls through to a
    WARNING - Unknown SSE event type: message on every tick — one per keepalive, indefinitely.

    Server contract (verified against service-sessions)

    POST {base_url}/agents/register — no /api prefix internally (the manual stopgap's /api
    was the ingress path; relative to the configured base_url it is /agents/register, matching
    the existing SessionsApiClient endpoints such as /sessions/{id}/jobs/...).

    • Auth: service-wide X-Api-Key (same gate as /jobs/*). No session key.
    • Request body (AgentRegisterRequest): agent_id (str, required), agent_type (str, required),
      capabilities (list[str], default [] = all job types — this is the dispatch source of truth,
      not the SSE query string), version (str, optional), metadata (dict, optional).
    • Response: 201 on first (or post-expiry) registration; 200 when re-posting a still-live
      agent_id (heartbeat refresh that re-declares capabilities). Both are success.
    • Liveness: registrations live in RAM and lapse after a heartbeat TTL (~60 s) unless refreshed by
      a re-register or by SSE keepalives. An open stream does not expire.
    • Graceful teardown: DELETE {base_url}/agents/{agent_id} — idempotent, returns 204 whether or
      not the agent was registered.
    • Legacy servers (< v0.4.0) have no /agents/register route → the call returns 404.

    Design decisions

    1. Scope: fix SessionsBus: must POST /agents/register before opening the SSE stream (sessions v0.4.0 dispatch gate breaks all deployed agents) #45 and SessionsBus: 30s keepalive frames logged as 'Unknown SSE event type: message' WARNING #44 together — both touch the SSE connect/consume path (_connect_and_consume).
    2. Registration lives in SessionsApiClient, alongside start_job/complete_job/cancel_job. It
      already owns the persistent httpx.AsyncClient with the X-Api-Key header baked in, and is cleanly
      unit-testable.
    3. Register on the per-attempt path, not in on_startup. Registering at the top of
      _connect_and_consume() satisfies "re-register before every reconnect attempt" and covers the very
      first connect (the SSE task's first iteration), so no separate on_startup register call is needed.
    4. Registration failure == connection failure. A hard register failure raises and flows into the
      existing reconnect/backoff loop — no new control flow. This also preserves app-startup resilience:
      failures occur inside the background SSE task, never in on_startup.
    5. Graceful unregister on shutdown, using the DELETE endpoint (best-effort).

    Components

    SessionsApiClient.register_agent(...) (new)

    async def register_agent(
        self,
        agent_id: str,
        agent_type: str,
        capabilities: list[str],
        version: str | None = None,
        metadata: dict[str, Any] | None = None,
    ) -> bool:
        """Register the agent with the sessions dispatch registry (idempotent).
    
        Returns True when the server accepted the registration (200/201).
        Returns False when the server is a legacy (< v0.4.0) instance without the
        endpoint (404) — the caller may still open the stream. Raises on any other
        non-2xx so the reconnect loop backs off.
        """

    Behaviour:

    • POST {base_url}/agents/register with {agent_id, agent_type, capabilities} (+ version/metadata
      only if provided). No per-call auth header — X-Api-Key is already a default header on self._client.
    • 200 / 201 → log at INFO (include status), return True.
    • 404 → log once at WARNING ("sessions service has no /agents/register; legacy < v0.4.0, proceeding
      without registration"), return False.
    • Any other non-2xx → log status and response.text (satisfies "surface the 403 body"), then
      response.raise_for_status().
    • Guard for uninitialised client (mirror the other methods: raise ValueError if self._client is None).

    SessionsApiClient.unregister_agent(...) (new)

    async def unregister_agent(self, agent_id: str) -> None:
        """Best-effort graceful deregistration (idempotent DELETE). Never raises."""
    • DELETE {base_url}/agents/{agent_id}.
    • Swallow all exceptions (network error, 404 on legacy, closed client) — log at WARNING on failure,
      INFO on success. Shutdown must never fail because of this call.

    SessionsBus changes

    _connect_and_consume() — register before opening the stream:

    async def _connect_and_consume(self) -> None:
        # Register (or refresh) before opening the stream. On a legacy server this
        # is a no-op (404 → False); on a hard failure it raises → reconnect backoff.
        await self._api_client.register_agent(
            agent_id=self._agent_id,
            agent_type=self._agent_type,
            capabilities=self._capabilities,
        )
    
        url = f"{self._base_url}/jobs/stream/sse"
        ...  # existing connect logic unchanged below

    Keepalive handling (#44) in the event-dispatch branch — a default-type message frame with empty
    data is a keepalive comment, not an event:

    elif sse.event == "heartbeat":
        logger.debug("SSE heartbeat received")
    
    elif sse.event == "message" and not (sse.data or "").strip():
        logger.debug("SSE keepalive frame received")   # #44 — was WARNING
    
    else:
        logger.warning("Unknown SSE event type: %s", sse.event)

    Named events with a payload still reach the Unknown SSE event type WARNING.

    403 diagnostics — wrap the event iteration so a rejected stream surfaces its real status and body
    instead of an opaque SSEError:

    async with aconnect_sse(client, "GET", url, params=params, headers=headers) as event_source:
        logger.info("SSE connection established")
        try:
            async for sse in event_source.aiter_sse():
                ...
        except SSEError:
            resp = event_source.response
            body = (await resp.aread()).decode(errors="replace")[:500]
            logger.error("SSE stream rejected: status=%d body=%s", resp.status_code, body)
            raise   # let the reconnect loop back off

    on_shutdown() — unregister after cancelling the task:

    async def on_shutdown(self) -> None:
        self._shutdown_event.set()
        # cancel the SSE task (existing logic) ...
        if self._api_client and self._agent_id:
            await self._api_client.unregister_agent(self._agent_id)

    Teardown order makes the client available here: SessionsBus is registered as a lifecycle component
    (torn down first, app_builder.py line ~348), whereas SessionsApiClient is a service (torn down
    later, line ~392). The client's httpx.AsyncClient is therefore still open when on_shutdown runs.

    Error-handling semantics

    Event Outcome
    register 200 / 201 proceed to open stream
    register 404 log "legacy server", proceed to open stream
    register 4xx / 5xx / network error log status + body, raise → reconnect backoff, retry next cycle
    stream opens then drops existing backoff → next cycle re-registers
    SSE stream rejected (non-text/event-stream) log real status + body, raise → backoff
    keepalive message frame, empty data DEBUG log, ignored (#44)
    shutdown cancel SSE task → best-effort DELETE unregister

    Configuration

    No new required config. base_url, agent_id, agent_type, capabilities, api_key are all already
    loaded by SessionsBus.on_startup. version/metadata are intentionally not plumbed through
    (YAGNI) — they can be added later without changing the method signatures (both are optional kwargs).

    Testing

    Unit — SessionsApiClient (extend tests/unit/agents/services/sessions/test_api_client.py):

    • register_agent 201 → returns True, POSTs to /agents/register with the expected body.
    • register_agent 200 → returns True (heartbeat refresh).
    • register_agent 404 → returns False, does not raise, logs the legacy warning.
    • register_agent 500 → raises HTTPStatusError, response body appears in the log.
    • register_agent uninitialised client → ValueError.
    • unregister_agent 204 → no raise; network error → swallowed (no raise), logged at WARNING.

    Unit — SessionsBus (tests/unit/agents/io/api/eventing/test_sessions_bus.py):

    • _connect_and_consume calls register_agent before aconnect_sse (patch both; assert order).
    • register_agent raising propagates out of _connect_and_consume (so _consume_sse_stream backs off).
    • on_shutdown calls unregister_agent(agent_id) once, after task cancellation, and does not raise if it fails.
    • A message SSE frame with empty data logs at DEBUG and is not counted as an unknown event (SessionsBus: 30s keepalive frames logged as 'Unknown SSE event type: message' WARNING #44).
    • A named unknown event with a payload still logs the WARNING.

    Integration (tests/integration/test_sessions_startup_resilience.py):

    • Existing test_app_starts_when_sessions_service_unreachable must still pass unchanged — a register
      failure happens inside the background SSE task and must not block on_startup/lifespan completion.

    Docs

    Out of scope

    • Feeding registration status into SessionsServiceHealthChecker (health already tracks REST reachability
      • SSE heartbeat; registration failures surface via the reconnect-loop logs).
    • Any change to the SSE query-string params (agent_type/capabilities) — accepted but ignored by
      v0.4.0; left as-is for backward compatibility with older servers.
  8. pajoma commented on Jul 6, 2026

    @pajoma
    ContributorAuthor

    Update — Brooks-Lint review folded into the spec

    Ran a Brooks-Lint PR review over the two production files this work touches (sessions_bus.py,
    api_client.py). Health 84/100 — no Critical findings; the risks cluster in SessionsBus's
    job-processing path. All are pre-existing conditions in the code we're about to modify, not defects
    in the registration design.

    Folded the actionable findings into the spec as separately-committed refactors within this PR,
    sequenced so the core register-before-SSE fix stays a small, self-contained diff:

    # Refactor Finding Ships with fix?
    1 SessionsApiClient._request(...) shared helper (kills the per-method init-guard + request boilerplate) 🟢 Knowledge Duplication Yes — first, so the new register/unregister methods land clean
    2 Single dispatch seam — 403-retry routes through _dispatch_cloud_event instead of calling EventProcessingService.process_event directly (currently drops the mixin's result handling) 🟡 Knowledge Duplication Yes
    3 Extract the four error policies out of the ~80-line _process_job_notification 🟡 Cognitive Overload Yes (same branch as #2)
    4 JobNotification value object replacing the dict[str, Any] threaded through the bus 🟡 Primitive Obsession Yes — flagged as splittable to a follow-up if the diff gets heavy
    5 Shutdown drain for in-flight job tasks (today launched fire-and-forget via asyncio.create_task and orphaned on shutdown) robustness note Yes

    Also updated in the spec: the error-semantics table (malformed-payload + drain-on-shutdown rows), the
    test plan (regression guard for the _request migration, updated 403-retry test, malformed-payload and
    drain tests), and a scope guard noting #4 is the one to peel off if review gets large.

    Spec updated on branch feature/sessions-agent-registration (commit 04b0550); see the full spec
    comment above. Next step is the implementation plan.

  9. added a commit that references this issue on Jul 6, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

enhancement

Projects

No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions