Skip to content

feat: Add response-side parsers and session enrichment - #370

Merged
huang195 merged 14 commits into
rossoctl:mainfrom
huang195:feat/response-side-parsers
May 5, 2026
Merged

huang195 merged 14 commits into
rossoctl:mainfrom
huang195:feat/response-side-parsers

Conversation

@huang195

@huang195 huang195 commented May 5, 2026

Copy link
Copy Markdown
Member

Summary

  • Adds OnResponse to all three parsers (a2a, mcp, inference) so downstream plugins can inspect server replies, tool results, and LLM completions — not just inbound requests.
  • Enriches the session store with per-event identity, HTTP status, error state, target host, OAuth audience, and latency, and starts recording response-phase events (previously only request-phase events were written).
  • Flips session tracking to on-by-default with tightened caps (ttl 30m, 100 sessions × 100 events) so the parser work is actually usable out of the box.

What was broken before this PR

  1. Response-phase parsing didn't exist. Every parser's OnResponse was a no-op. Tool results, LLM completions, assigned A2A contextIds — all observed by Envoy, all thrown away before anything could act on them.
  2. ext_proc didn't set pctx.Path on outbound, so inference-parser's gate (/v1/chat/completions) never matched and the request path was dead for the entire outbound direction.
  3. MCP Streamable HTTP responses come back as SSE (event: message\ndata: {...}). The parser only understood plain JSON-RPC and silently dropped every real response with "invalid character 'e'".
  4. Inference-parser crashed on follow-up requests after a tool call because the tool-result message uses array-shaped content, which broke json.Unmarshal into Content string and zeroed out the entire Inference extension.
  5. Session events never carried response data even though SessionPhase.SessionResponse and helpers like ToolResponses() existed in the schema. All recording sites used Phase: SessionRequest.
  6. First-turn A2A events landed under "default" because the client has no contextId yet, and subsequent turns that carried the real contextId wrote to a different bucket — fragmenting one conversation across two sessions.
  7. Session events had no Identity, StatusCode, Error, Host, TargetAudience, or Duration, so a SessionView couldn't answer "who made this call?", "did it succeed?", "to which tool?", or "how long did it take?"
  8. Session tracking was off by default, so all of the above improvements were inert unless the operator explicitly opted in.

What this PR changes

Parsers (authlib/plugins/)

  • a2a-parser: OnResponse extracts contextId (spec-current) or sessionId (legacy) from both JSON-RPC responses and SSE event streams, stamps it on Extensions.A2A.SessionID. OnRequest fix: prefer contextId over sessionId in params so resume-turn correlation works.
  • mcp-parser: OnResponse stores the parsed result map (or error map) on Extensions.MCP.Result. Handles both JSON-RPC and SSE response shapes.
  • inference-parser: OnResponse populates Completion, FinishReason, PromptTokens, CompletionTokens, TotalTokens for both non-streaming JSON and SSE streams (concatenates deltas). OnRequest fix: custom UnmarshalJSON on inferenceMessage accepts both content: "string" and content: [{"type":"text",...}]; non-text parts (images, tool_use) dropped.
  • DEBUG logs: every parser now emits truncated content at DEBUG (part text, message content, completion, bodies — capped at 512 chars via a shared debugBodyMax).

Pipeline / extensions (authlib/pipeline/)

  • MCPExtension.Result map[string]any — parsed response payload.
  • InferenceExtension.Completion / FinishReason / PromptTokens / CompletionTokens / TotalTokens.
  • Context.StartedAt time.Time — stamped on every pctx construction so response-time Duration is trivial to compute.
  • SessionEvent extended with Identity, StatusCode, Error, Host, TargetAudience, Duration.
  • SessionView.FailedEvents() / LastError() — convenience queries over Error.

Session store (authlib/session/)

  • Store.Rekey(oldID, newID) — renames a session in place, preserving events and updating activeID. No-op when oldID is absent, newID is taken, or either is empty. Called on inbound response to migrate "default" → server-assigned contextId.
  • Every Append emits a structured DEBUG line summarizing the event (sessionId, direction, phase, host, OAuth aud, status, durationMs, identity, protocol, error kind) so operators can verify the store is populated correctly.

ext_proc listener (cmd/authbridge/listener/extproc/)

  • Path: getHeader(headers, ":path") added to both outbound pctx constructions. Unblocks inference-parser in production.
  • New helpers recordInboundResponseSession, recordOutboundResponseSession, snapshotIdentity, deriveError, routeAudience, durationSince, rekeyInboundSession. All four record paths (in/out × req/resp) now snapshot identity; response paths also carry status/error/duration.
  • handleResponseBody calls rekeyInboundSession before recording the inbound response event so the event lands under the real contextId rather than being orphaned in "default".
  • handleResponseHeaders records response events for the headers-only path (plugins without BodyAccess).

Config / defaults (authlib/config/, cmd/authbridge/main.go)

  • SessionConfig.Enabled is now *bool. Unset → enabled; explicit false → disabled. New helper SessionEnabled().
  • Defaults tightened: ttl: 5m → 30m, maxSessions: 1000 → 100, maxEvents: 100 (unchanged). Upper bound with defaults: ~10k events in memory — well under a typical sidecar limit. Operators wanting more raise the caps explicitly; operators wanting zero overhead set session.enabled: false.

Envoy config (demos/webhook/k8s/configmaps-webhook.yaml)

  • response_header_mode: SKIP → SEND on both the inbound and outbound listeners so Envoy actually forwards response headers to ext_proc.

Test plan

  • Unit tests for every new helper + field: Rekey (including edge cases), snapshotIdentity, deriveError, routeAudience, durationSince, recordInboundResponseSession, recordOutboundResponseSession, SessionEnabled, parser OnResponse (JSON + SSE + error + multipart), inference request multipart content, SessionView.FailedEvents / LastError.
  • Live end-to-end on the weather-agent demo with all three parsers firing, session tracking enabled by default, rekey observed on the inbound response, full response content logged at DEBUG including the LLM's final answer.
  • Verified token accounting (e.g., 167+18 prompt/completion tokens on the tool-calling LLM turn, 169+49 on the formulation turn).
  • Verified per-call latencies (MCP handshake ~1-2 ms, LLM ~500-1600 ms, end-to-end inbound ~3-5 s for a weather query with one tool hop).

Follow-ups (not in this PR)

  • pctx.Agent is never populated anywhere in the codebase — pre-existing dangling field; plumbing it from the SPIFFE ID at startup is a separate PR.
  • Multi-tenant session correctness: the rekey assumes single-conversation-per-pod; two concurrent first-turn requests would both land in "default" and one rekey would strand the other. Acceptable for the current sidecar model; revisit when sharing an agent pod across callers becomes a real deployment target.
  • Non-text A2A parts (file, data) are captured but could use a typed accessor for guardrail plugins.

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

huang195 added 12 commits May 5, 2026 13:41
Implement OnResponse for both parsers so downstream plugins can inspect
server responses, not just requests:

- mcp-parser: parse JSON-RPC response body and store result (or error)
  payload on MCPExtension.Result. Covers tools/list, tools/call, and
  any other MCP method that returns a result map.
- a2a-parser: extract the server-assigned contextId (or legacy sessionId)
  from the response body and write it to A2AExtension.SessionID. Handles
  both plain JSON-RPC responses (message/send) and SSE event streams
  (message/stream). Also fixes OnRequest to read contextId — clients
  resuming a conversation send contextId, not sessionId, per the current
  A2A spec.

Switch response_header_mode from SKIP to SEND in the demo Envoy config
so response headers are forwarded to ext_proc; without this, the new
OnResponse hooks never fire in the sidecar deployment.

Add MCPExtension.Result field to carry the parsed response payload.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Hai Huang <[email protected]>
Implement OnResponse for inference-parser so the third parser is symmetric
with mcp-parser and a2a-parser. Populates response fields on
InferenceExtension: Completion, FinishReason, and token usage.

- Non-streaming: parse choices[0].message.content and usage block directly.
- Streaming (SSE): concatenate content deltas across events, capture the
  last finish_reason, and read usage from the trailing chunk when
  stream_options.include_usage is set. Skips the "data: [DONE]" sentinel.

Extend InferenceExtension with Completion, FinishReason, PromptTokens,
CompletionTokens, TotalTokens.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Hai Huang <[email protected]>
OpenAI-compatible clients send messages[].content as an array when the
message carries multi-modal input or tool results:

  {"role":"tool","content":[{"type":"text","text":"sunny, 72F"}]}

Previously inferenceMessage typed Content as string, so json.Unmarshal
failed on the whole request and pctx.Extensions.Inference was silently
left nil. Downstream policy plugins never saw the second LLM call in any
tool-using agent flow.

Give inferenceMessage a custom UnmarshalJSON that accepts both shapes:
plain strings pass through, arrays are flattened by concatenating text
parts and dropping non-text parts (images, tool_use blocks, etc.). null
content (assistant messages carrying only tool_calls) maps to "".

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Hai Huang <[email protected]>
The session store records inbound A2A events during the request phase,
before the server has assigned a contextId. Those events land under the
DefaultSessionID bucket. When the response reveals the contextId, the
client's next turn arrives carrying that contextId, and recordInbound-
Session appends under a different key — fragmenting one conversation
across two sessions.

Add Store.Rekey(old, new) to rename a session in place, preserving
events and updating activeID when it matches the old key. The method is
a no-op when oldID is absent, newID is already taken, either ID is
empty, or the two IDs are equal — so callers can invoke it
unconditionally after the response phase.

Call Rekey from extproc.handleResponseBody after inbound RunResponse
whenever a2a-parser has populated a non-default SessionID. This
assumes single-tenant, single-conversation-per-pod semantics: two
concurrent first-turn requests would both land under "default" and one
rekey would strand the other's events. Acceptable for the current
sidecar deployment model; multi-tenant support is a future concern.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Hai Huang <[email protected]>
Two gaps that block the outbound parsers from firing in a real pod:

1. extproc's handleOutbound and handleOutboundBody build pctx without
   setting Path — only the inbound handlers populate it. inference-parser
   gates on pctx.Path matching /v1/chat/completions, so it always
   short-circuited. Copy the same ":path" header lookup the inbound
   handlers use.

2. MCP servers that speak the Streamable HTTP transport return responses
   as SSE (event:/data: lines), not plain JSON-RPC. mcp-parser's
   OnResponse was rejecting those bodies with "invalid character 'e'".
   Add SSE fallback in parseMCPResponse: if direct JSON unmarshal yields
   no result or error, scan data: lines for the first JSON-RPC frame
   that carries one.

Confirmed both from live weather-agent traffic:
- before: inference-parser never logged "model=..."; mcp-parser logged
  "response is not valid JSON-RPC" for every tools/list and tools/call
- after: both parsers populate their extensions on real responses

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Hai Huang <[email protected]>
Operators turning on DEBUG were seeing counts but not content, so the
actual user query, LLM messages, and assistant completion were
invisible at the authbridge layer.

Log truncated content for each parser:

- a2a-parser: log each extracted Part (kind + truncated text) on the
  request side, and the first 512 chars of the response body on the
  response side alongside the sessionId extraction.
- mcp-parser: raise the existing request/response body truncation cap
  from 128/256 to 512 and route both through the shared debugBodyMax
  constant.
- inference-parser: log each message (role + truncated content) on the
  request side, and truncated assistant completion text on the response
  side alongside finishReason/tokens.

Add a shared debugBodyMax=512 constant in mcpparser.go (already has
truncate) so all three parsers cap consistently.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Hai Huang <[email protected]>
The session store schema has always supported SessionResponse events —
helpers like SessionView.ToolResponses() assume they exist — but no
call site ever produced one. Every event written by ext_proc used
Phase: SessionRequest. That left all response-side data the parsers
extract (MCP tool results, inference completions, token usage, A2A
contextId) on the transient pctx, invisible to any plugin inspecting
the session store after the request returned.

Add recordInboundResponseSession and recordOutboundResponseSession and
invoke them from both handleResponseHeaders (headers-only fast path)
and handleResponseBody (body path). In the body path, call them after
rekeyInboundSession so the response event lands under the
server-assigned contextId rather than the bootstrap "default" bucket.

A downstream plugin viewing a session for one weather query now sees
the tool result (82.4°F, windspeed 25.9), the final LLM answer, and
the token cost — not just the user prompt and the intent to call a
tool.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Hai Huang <[email protected]>
Session events recorded the "what" of each pipeline step (A2A/MCP/Inference
extensions) but not the "who" (caller identity, handling agent) or the
"how did it go" (HTTP status, guardrail blocks, backend errors). A
downstream plugin viewing a session couldn't tell whose tool calls they
were, whether the LLM rate-limited us, or whether a guardrail replaced
the response — all information that was already on pctx and then thrown
away.

Extend SessionEvent with three new fields:

- Identity *EventIdentity: Subject / Scopes / ClientID copied from
  pctx.Claims, plus AgentID from pctx.Agent.WorkloadID. Snapshotted at
  record time so the event survives pctx disposal. Nil when neither
  Claims nor Agent is populated (pre-JWT paths).
- StatusCode int: pctx.StatusCode copied on response events so views
  can answer "which calls failed" without re-parsing bodies.
- Error *EventError: synthesized from response signals — Kind "blocked"
  when Security.Blocked is set (takes precedence), Kind "backend_error"
  with the HTTP code string for any 4xx/5xx, nil otherwise.

Two helpers centralize the snapshot logic: snapshotIdentity(pctx) and
deriveError(pctx). All four record*Session helpers (inbound/outbound ×
request/response) now use them, so identity is captured on every event
and status/error on every response event.

Scopes are deep-copied rather than aliased, so mutations to pctx.Claims
after record don't corrupt the stored event.

Add SessionView.FailedEvents() and LastError() so plugins can query
failure state directly without filtering the full event stream.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Hai Huang <[email protected]>
A session view showing "outbound MCP call" didn't say which service the
agent talked to — and in multi-target agents (weather-tool + github-tool
+ ...) that is the most useful attribution signal. It also did not say
how long anything took.

Extend SessionEvent with three self-describing fields:

- Host: pctx.Host (HTTP :authority) captured on every event. For
  inbound events it's the agent's own address; for outbound events
  it's the target — which is the useful case.
- TargetAudience: the OAuth audience the outbound route resolved to,
  or "" when no route matched (passthrough) or the event is inbound.
  Useful for policy plugins that reason in terms of OAuth scopes
  rather than host names (which may be globbed).
- Duration: wall-clock elapsed from request entry into the listener
  to response recording. Zero on request-phase events.

To compute Duration without walking session history, add StartedAt to
pipeline.Context and stamp it in all four pctx-construction sites
(handleInbound, handleInboundBody, handleOutbound, handleOutboundBody).
The record helpers then compute time.Since(pctx.StartedAt) at response
time. durationSince() guards against zero StartedAt (e.g., unit tests)
so the field stays zero rather than showing 50+ years.

routeAudience() respects Route.Matched so passthrough calls do not
inherit a stale audience from a partially-populated Route struct.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Hai Huang <[email protected]>
Make session store evolution observable: every Append emits a DEBUG
line summarizing the event (sessionId, direction, phase, host, OAuth
audience, status, duration, identity, protocol, error kind). Extension
payloads are intentionally omitted because the parsers already log
their own bodies.

Lets operators verify end-to-end that the new SessionEvent fields
(Identity, StatusCode, Error, Host, TargetAudience, Duration) are
populated as expected in production traffic, not just in unit tests.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Hai Huang <[email protected]>
The initial log omitted JWT ClientID (azp claim) and scope count, so
client_credentials flows — which have no Subject — showed up with no
caller info at all. ClientID is the actual caller identity for those
flows; log it whenever present.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Hai Huang <[email protected]>
Session tracking is the whole point of the parser pipeline — events on
the store are what policy plugins read to reason about conversation
history. Leaving it off by default forced every operator to opt in and
silently disabled all the response-side work when they forgot.

Flip the default to on, overridable. SessionConfig.Enabled is now a
*bool so the loader can tell "unset" (apply default) from "explicitly
false" (user opted out). Expose SessionEnabled() which returns true
when Enabled is nil, and the stored value otherwise. Existing configs
with "enabled: true" and "enabled: false" keep working.

Tighten the built-in defaults so default-on is cheap:
- ttl: 5m → 30m (longer conversations survive idle gaps)
- maxSessions: 1000 → 100 (bounds per-pod memory)
- maxEvents: 100 (unchanged; already a reasonable per-session ceiling)

Upper bound with defaults: 100 sessions × 100 events = 10k events
retained for up to 30 min. At a few KB per event that caps at ~tens of
MB per pod — well under typical sidecar limits. Operators wanting the
old ceiling can raise the limits explicitly. Operators wanting zero
overhead can set session.enabled: false.

Also log "session tracking disabled" on the opt-out path so operators
can confirm their override took effect.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Hai Huang <[email protected]>
huang195 added 2 commits May 5, 2026 15:48
Review feedback: storing the JSON-RPC error object in the same
Result map[string]any that carries successful results forced
callers into untyped map walks to tell the two shapes apart. A
plugin asking "did this tool call fail?" had to poke at key
presence heuristics.

Give MCPExtension distinct fields:
- Result map[string]any for successful results
- Err *MCPError { Code, Message, Data } for JSON-RPC errors

Parser populates exactly one. Internal jsonRPCResponse now
decodes error into a typed struct too, so we no longer pass a
raw map through and retype it at the boundary.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Hai Huang <[email protected]>
Three small review items bundled together:

- Malformed SSE data frames were silently skipped in both mcp-parser
  (parseMCPResponse) and inference-parser (parseInferenceSSE). A broken
  upstream would lose the final usage chunk with no trace. Log the
  unmarshal error + a truncated copy of the bad data at DEBUG so it
  surfaces when someone turns debug on.
- session.Store.Rekey silently truncated long newIDs to 256 chars.
  Two long IDs sharing a prefix would collide on the same truncated
  key and the second Rekey would be a silent no-op. Warn on truncation
  so that's diagnosable (current A2A contextIds are UUIDs nowhere near
  256, so this is theoretical — still worth the log).
- Added a field-level comment on SessionConfig.Enabled *bool warning
  future maintainers not to "fix" the nil-means-enabled convention
  by changing the zero value.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Hai Huang <[email protected]>

@cwiklik cwiklik left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Strong PR that fills a significant gap — response-side parsing was entirely absent. The session store's Rekey method is well-designed with clear concurrency model documentation and good edge-case coverage in tests. The *bool sentinel for SessionConfig.Enabled is the right pattern. Test coverage is comprehensive.

Areas reviewed: Go (parsers, session store, ext_proc server, config), YAML (Envoy config), Tests
Commits: 14 commits, all signed-off
CI status: All 17 checks passing

sess.UpdatedAt = now
s.activeID = sessionID

logAppended(sessionID, &event)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: logAppended is called inside the mutex lock. Since it only reads event fields and calls slog.Debug, it could be moved after s.mu.Unlock() to reduce lock hold time slightly. Not urgent — slog is fast — but worth noting for high-throughput paths.

// No body phase will run; record the response event here. A2A responses
// need the body to extract contextId, so the rekey path is body-only;
// skip it on this header-only path.
if direction == "inbound" {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

suggestion: Response events are recorded here in handleResponseHeaders ("No body phase will run"). When BodyAccess is true, handleResponseBody also records a response event. Is there a guard ensuring only one of these paths fires per request? If both could fire (e.g., Envoy sends both response_headers and response_body phases), this would produce duplicate response events in the session store.

@huang195
huang195 merged commit 314875e into rossoctl:main May 5, 2026
17 checks passed
@huang195
huang195 deleted the feat/response-side-parsers branch May 5, 2026 20:18
boazdavid added a commit to boazdavid/cortex that referenced this pull request Nov 24, 2026
…known, and fix a real regression in the zero-prompt-total gate

Two more findings from clawgenti's re-review:

- The currency fix only gated PluginSpendMicros (basis usd). PluginSpendUnknownMicros
  is "not money", but it is still one number, and a USD figure and a differently-
  priced currency's figure summed into it is just as mixed. Same gate now applies there.

- The zero-prompt-total gate in InferenceParser.accountant asked whenever
  pctx.ReportedOps() was non-empty, reasoning that the pass before any data arrives
  has no ops either. That was wrong: a structural op (tool-prune's removal, say)
  reports during OnRequest, before the response exists, so that pass's ops list is
  not empty either — and asking there calls Host.Compute with an inference extension
  that is still all zeros, which Compute latches forever, so the real counts that
  arrive on a later pass are never priced at all. Reproduced by clawgenti; fixed by
  gating on pctx.StatusCode (set once, when the response is read) instead of on
  ReportedOps. Added a regression test pinning the exact two-pass sequence.

Also dismissed the same 2 alerts' re-raised instances (rossoctl#365, rossoctl#370) after they shifted
line following the rebase onto main — the earlier dismissal (rossoctl#372, rossoctl#373) stopped
applying once that commit was superseded.

Assisted-By: Claude Sonnet 5 <[email protected]>
Signed-off-by: DAVID BOAZ <[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