Skip to content

feat: HTTP session events API (snapshots + SSE stream) - #371

Merged
huang195 merged 7 commits into
rossoctl:mainfrom
huang195:feat/session-events-api
May 5, 2026
Merged

huang195 merged 7 commits into
rossoctl:mainfrom
huang195:feat/session-events-api

Conversation

@huang195

@huang195 huang195 commented May 5, 2026

Copy link
Copy Markdown
Member

Summary

Adds an HTTP endpoint that externalizes AuthBridge's in-memory session store so operators can debug the plugin pipeline via kubectl port-forward and (in a follow-up PR) drive an interactive TUI.

Three endpoints on a new port (:9094 by default):

  • GET /v1/sessions - JSON list of active sessions with summaries
  • GET /v1/sessions/{id} - JSON snapshot of a single session events
  • GET /v1/events - SSE stream of new events, optional ?session= filter, 30-second heartbeat

Note: This PR is stacked on #370 (response-side parsers + session enrichment). The SSE stream only has rich content to show because of the event schema introduced in that PR. Once #370 merges, I will rebase this onto main.

What changes

session.Store

  • Subscribe() (*Subscription, func()) registers a consumer that receives every appended event via a buffered channel (cap 64). Non-blocking fan-out in Append; slow consumers drop events and increment a per-subscriber counter. Close() closes subscriber channels idempotently.
  • ListSessions() []SessionSummary returns metadata-only summaries (id, createdAt, updatedAt, eventCount, active) for the list endpoint, sorted most-recent-first.

Serialization (pipeline/)

  • Direction.String() replaces the local directionName helper.
  • SessionEvent.MarshalJSON emits direction/phase as strings and durationMs instead of raw nanoseconds.
  • Every extension struct (MCPExtension, A2AExtension, InferenceExtension, EventIdentity, EventError, SessionView, etc.) gets lower-camel json tags + omitempty for consistent wire format.

sessionapi/ (new package)

  • Mirrors observe/statserver.go shape: constructor New(addr, store, opts...), ListenAndServe, Shutdown. Uses http.ServeMux with method-qualified routes.
  • SSE handler subscribes on connect, flushes event:/id:/data: frames, sends heartbeat comments at the configured interval (WithHeartbeatInterval for tests), cancels subscription on client disconnect, logs WARN on accumulated drops.
  • httptest-driven tests cover empty list, populated list, 404, JSON enum readability, SSE delivery + framing, heartbeat cadence, and ?session= filtering.

Wiring

  • ListenerConfig.SessionAPIAddr string - new field, defaults to :9094 via ApplyPreset for all three modes.
  • main.go starts the server when SessionAPIAddr != "" AND sessions != nil. To disable, set session.enabled: false.
  • Docs: authbridge/CLAUDE.md updated with a Session Events API section; port table now lists :9093 (stats) and :9094 (session API); includes kubectl port-forward + curl examples.

Trust model

No authentication. Bind only on in-cluster addresses, never behind ingress. Payloads may contain raw user messages, LLM completions, and tool results. Matches the existing stats endpoint trust model.

Test plan

  • Unit tests: Store.Subscribe (5 cases), SessionEvent.MarshalJSON (2 cases), Direction.String, sessionapi.Server (8 cases covering each endpoint, SSE framing, heartbeat, filter).
  • Race detector clean across the whole module.
  • Live end-to-end on the weather-agent demo:
    • curl http://localhost:9094/v1/sessions is empty before any query, then lists the active session after.
    • curl -N http://localhost:9094/v1/events streamed 23 SSE frames during a "weather in new york" query, covering the full conversation: inbound request with user prompt, MCP handshake x2, tool call with city arg, two LLM calls with full completion text, inbound response with durationMs=4697 and the rekeyed contextId.
    • /v1/sessions/{id} returned 200 with 23 events; /v1/sessions/does-not-exist returned 404.

Out of scope

  • Bearer-token auth on the endpoint (tracked for v1.5).
  • abctl TUI - follow-up PR once this is merged.
  • Cluster-wide aggregation across multiple sidecars.

Assisted-By: Claude (Anthropic AI) [email protected]

@huang195
huang195 force-pushed the feat/session-events-api branch from a915e3e to 2ba43d4 Compare May 5, 2026 21:54
huang195 added a commit to huang195/kagenti-extensions that referenced this pull request May 5, 2026
PR rossoctl#371 added MarshalJSON for SessionEvent and String() for Direction
and SessionPhase so the wire format uses readable strings. It did not
add the matching Unmarshal side — so an off-process Go consumer trying
to decode the same payload back into a SessionEvent failed with
"cannot unmarshal string into Go struct field".

First surfaced while writing the abctl apiclient. Fixing it here
rather than shipping a client-side mirror struct so every future Go
consumer of the API gets round-trippable types from authlib.

- Direction: add MarshalJSON + UnmarshalJSON (string <-> enum).
- SessionPhase: same.
- SessionEvent: extract the wire layout into a shared sessionEventWire
  struct; Marshal writes to it, Unmarshal reads from it. durationMs
  <-> time.Duration symmetry is explicit.

Unknown direction/phase strings decode to the zero-value member
without error, keeping downstream consumers tolerant of future enum
additions.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Hai Huang <[email protected]>
huang195 added 7 commits May 5, 2026 17:57
recordInboundSession fell back to Store.ActiveSession() when the A2A
request had no contextId yet (first turn of a new conversation). After
a previous conversation had already rekeyed its bucket from "default"
to a real contextId, ActiveSession() returned that previous conversation's
bucket. The new conversation's request events then landed in the prior
session, contaminating it.

When the current conversation's response arrived with its own freshly
assigned contextId, rekeyInboundSession called Rekey("default", new-id) —
but "default" no longer existed (events went to the prior bucket
instead), so Rekey was a no-op. recordInboundResponseSession then
appended the final event to the new contextId, producing a
1-event orphan session.

Observed live as: four sessions of 45, 23, 23, and 1 events instead of
one session per conversation. abctl made it visible; the same bug
existed silently prior.

Fix: inbound events trust A2A.SessionID as-is. Empty means a new
conversation — bootstrap into DefaultSessionID so the rekey on the
response can cleanly migrate the bucket. Never fall back to
ActiveSession() for inbound events — that fallback is only sound for
outbound correlation. Extracted inboundSessionID() helper so the
request-phase and response-phase recorders share the same rule.

Regression test asserts the fix directly: seed ActiveSession with
"prev-ctx", record a fresh inbound request with empty SessionID,
assert it lands in DefaultSessionID and prev-ctx is untouched.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Hai Huang <[email protected]>
Prep for externalizing the session store over HTTP. Two additions:

- Subscribe() returns a *Subscription + cancel func. Internally holds
  a per-subscriber buffered channel (cap 64) and an atomic drop
  counter. Append publishes events non-blockingly via publishLocked;
  a full channel increments drops and discards the event. Append stays
  fast even with a stalled consumer. Close() fans out channel closes
  to every live subscriber so in-flight consumers unblock on shutdown,
  and closeOnce per subscriber keeps cancel + Close idempotent.

- ListSessions() returns a []SessionSummary (id, createdAt, updatedAt,
  eventCount, active) sorted by UpdatedAt descending. No event payload
  is copied, so the list endpoint stays cheap even with large
  sessions.

Unit tests cover receive after append, cancel stops delivery, slow
consumer drops without blocking Append, fan-out to multiple
subscribers, and Store.Close closing subscriber channels.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Hai Huang <[email protected]>
Prep for externalizing session events over HTTP. Three shapes change:

- Direction gets a String() method ("inbound"/"outbound"). Replaces
  the duplicate directionName helper from session/store.go, which
  now calls e.Direction.String() directly.
- SessionEvent gets a MarshalJSON that emits Direction and Phase as
  strings (Go's default stringifies ints and time.Duration as
  nanoseconds — both awkward for CLI consumption) and Duration as
  durationMs.
- Every extension struct and session-level struct (MCPExtension,
  A2AExtension, InferenceExtension, EventIdentity, EventError,
  SessionView, etc.) gets lower-camel JSON tags with omitempty so
  the wire format is consistent and compact.

Unit tests on the marshaler cover readable enums and omitempty.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Hai Huang <[email protected]>
New package authlib/sessionapi exposes AuthBridge's in-memory session
store over HTTP. Intended for operators debugging the plugin pipeline
via kubectl port-forward, and for a future abctl TUI.

Endpoints:
- GET /v1/sessions          — JSON list of active sessions
- GET /v1/sessions/{id}     — JSON snapshot of one session's events (404 if missing)
- GET /v1/events            — SSE stream of new events, optional ?session= filter
- GET /healthz              — liveness

The SSE handler subscribes to the store, emits event:/id:/data:
frames for each incoming event, and sends a keep-alive comment every
30s (configurable per-Server via WithHeartbeatInterval so tests don't
hang). On disconnect the subscription is cancelled to free the
buffered channel. Accumulated drop counts from a slow client are
surfaced at WARN each heartbeat.

Trust model: no auth. Addr comes from ListenerConfig.SessionAPIAddr;
binds should only be reachable in-cluster or via port-forward,
never behind ingress.

httptest-based coverage: each endpoint, SSE framing, session filter,
heartbeat cadence, and 404 behavior.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Hai Huang <[email protected]>
Final wiring for the session events HTTP server:

- ListenerConfig.SessionAPIAddr string: new field, yaml:"session_api_addr".
- ApplyPreset: default ":9094" across every mode. To disable, set
  session.enabled: false — main.go skips the API server whenever the
  session store itself is nil, so no separate API-only kill switch is
  needed in v1.
- main.go: after startStatServer, construct sessionapi.New when
  SessionAPIAddr is non-empty and sessions is non-nil, spawn the
  serve goroutine with the standard ErrServerClosed pattern, call
  Shutdown during the graceful-shutdown block.
- CLAUDE.md: bump the port-mapping table with :9093 (stats) and
  :9094 (session API), and add a Session Events API section with
  endpoint reference, trust-model note, and curl examples for
  port-forward usage.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Hai Huang <[email protected]>
Review feedback: the ?session= filter on /v1/events only fired when
the event had an A2A extension, because A2A was the only struct that
carried a session field. Outbound MCP and Inference events have no
protocol-native session, so the filter's `event.A2A != nil` guard
bailed and foreign-session events passed through. An operator
filtering to one session would still see cross-session tool calls
and LLM traffic mixed in.

Make SessionEvent self-describing:

- Add SessionEvent.SessionID. Stamped by Store.Append so every event
  knows its bucket, regardless of protocol.
- Store.Rekey rewrites SessionID on all already-recorded events so
  snapshot reads and live stream agree after a "default" -> contextId
  rekey.
- SSE handler filter simplifies to `event.SessionID != filter` and
  now works uniformly for A2A, MCP, Inference, and future protocols.

Also addressed same-batch:

- EventError.Message was missing a json tag, serializing as "Message"
  and breaking the lower-camel wire format.
- Local id counter in handleStream dropped atomic.AddUint64 (it's
  function-local, no concurrent reader) for plain id++.
- publishLocked gained a doc comment noting fan-out runs under the
  lock — fine for the 1-few-consumer debug load, flag for refactor
  if that assumption ever changes.

New tests: Append stamps SessionID; Rekey rewrites all event IDs;
SSE filter guards against regression on outbound MCP events.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Hai Huang <[email protected]>
Review feedback: preset default opens :9094 on every mode, so
upgrading authbridge silently starts a new network listener. The
trust model is documented in CLAUDE.md but the surface behavior is
surprising. Emit a WARN at startup naming the model:

    session API listening - UNAUTHENTICATED; contains raw user
    content; never expose via ingress

Cheap; gives operators a clear heads-up in pod logs. Matches the
stats-server precedent (:9093 is also all-interfaces by design).

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Hai Huang <[email protected]>
huang195 added a commit to huang195/kagenti-extensions that referenced this pull request May 5, 2026
PR rossoctl#371 added MarshalJSON for SessionEvent and String() for Direction
and SessionPhase so the wire format uses readable strings. It did not
add the matching Unmarshal side — so an off-process Go consumer trying
to decode the same payload back into a SessionEvent failed with
"cannot unmarshal string into Go struct field".

First surfaced while writing the abctl apiclient. Fixing it here
rather than shipping a client-side mirror struct so every future Go
consumer of the API gets round-trippable types from authlib.

- Direction: add MarshalJSON + UnmarshalJSON (string <-> enum).
- SessionPhase: same.
- SessionEvent: extract the wire layout into a shared sessionEventWire
  struct; Marshal writes to it, Unmarshal reads from it. durationMs
  <-> time.Duration symmetry is explicit.

Unknown direction/phase strings decode to the zero-value member
without error, keeping downstream consumers tolerant of future enum
additions.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Hai Huang <[email protected]>
@huang195
huang195 force-pushed the feat/session-events-api branch from 2ba43d4 to fb3d4de Compare May 5, 2026 21:58
@huang195
huang195 merged commit 4e2e274 into rossoctl:main May 5, 2026
17 checks passed
@huang195
huang195 deleted the feat/session-events-api branch May 5, 2026 23:10
huang195 added a commit to huang195/kagenti-extensions that referenced this pull request May 5, 2026
PR rossoctl#371 added MarshalJSON for SessionEvent and String() for Direction
and SessionPhase so the wire format uses readable strings. It did not
add the matching Unmarshal side — so an off-process Go consumer trying
to decode the same payload back into a SessionEvent failed with
"cannot unmarshal string into Go struct field".

First surfaced while writing the abctl apiclient. Fixing it here
rather than shipping a client-side mirror struct so every future Go
consumer of the API gets round-trippable types from authlib.

- Direction: add MarshalJSON + UnmarshalJSON (string <-> enum).
- SessionPhase: same.
- SessionEvent: extract the wire layout into a shared sessionEventWire
  struct; Marshal writes to it, Unmarshal reads from it. durationMs
  <-> time.Duration symmetry is explicit.

Unknown direction/phase strings decode to the zero-value member
without error, keeping downstream consumers tolerant of future enum
additions.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Hai Huang <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

Status: Done

Development

Successfully merging this pull request may close these issues.

2 participants