Skip to content

[feat]: Add SSE keepalive to keep idle streams alive through intermediaries - #2

Open
grmorozov wants to merge 15 commits into
devfrom
feat/sse-keepalive-heartbeat
Open

grmorozov wants to merge 15 commits into
devfrom
feat/sse-keepalive-heartbeat

Conversation

@grmorozov

Copy link
Copy Markdown

Summary

Adds an opt-in, config-driven server-side SSE keepalive. While a stream is otherwise idle, the HTTP transport emits an SSE comment frame (: keepalive) every configured interval so idle-timeout enforcing intermediaries (load balancers, reverse proxies, API gateways) do not drop a healthy-but-silent stream — for example during a slow first token, a long tool/thinking gap, or a server-buffered provider response.

The client cannot fix this itself: it is reading a response, not writing to it, so only the server writing the stream can keep intermediary idle timers alive. Today Bifrost emits nothing during idle gaps, and the per-chunk stream idle timeout (default 120s) only moves the cliff without keeping the connection warm.

Implements the feature requested in maximhq#5010.

Changes

  • SSEStreamReader keepalive. The keepalive timer lives inside Read (the single fasthttp write loop), so it needs no extra synchronization and cannot race Send/Done/Close. A real event resets the interval; if the interval elapses first, Read returns a keepalive frame instead of blocking. Exposed via functional options (WithKeepalive, WithKeepaliveFrame) so existing zero-arg callers are unchanged. Wire-level payload is an SSE comment (: keepalive\n\n), which clients ignore per the SSE spec — no client change, no provider payload mutation.
  • Config. New stream_keepalive_interval_seconds on the transport client config (0 = disabled, the default). Full persistence: DB column + migration, rdb.go conversions, and hash inclusion only when > 0 so existing configs keep the same config_hash after upgrade (no hash churn, no forced restart). Read per-stream via a new HandlerStore.GetStreamKeepaliveIntervalSeconds() accessor.
  • Producers wired. Enabled for the two Bifrost-generated text/event-stream producers (handlers/inference.go, integrations/router.go). The Bedrock binary AWS EventStream path is deliberately left without keepalives — an SSE comment would corrupt its wire framing; the reader supports WithKeepaliveFrame for a future protocol-correct keepalive there.
  • Schema (transports/config.schema.json), docs (client config + OpenAPI), UI types (TS + zod), and framework/transports changelogs updated.

Type of change

  • Bug fix
  • Feature
  • Refactor
  • Documentation
  • Chore/CI

Affected areas

  • Core (Go)
  • Transports (HTTP)
  • Providers/Integrations
  • Plugins
  • UI (React)
  • Docs

Also touches framework/configstore (client config field, DB table/migration, hash).

How to test

# Cross-module change — use the workspace so transports sees the local framework edits
make setup-workspace

go version   # 1.26.x

# Unit tests for the keepalive reader (includes new keepalive cases)
go test ./transports/bifrost-http/lib/ -run TestSSEStreamReader -count=1

# Config field: migration + hash behavior
go test ./framework/configstore/... -count=1

Expected: all pass. New reader tests cover keepalive-disabled-by-default, keepalive-emitted-when-idle, reset-by-real-event, EOF-on-done, and custom-frame.

Manual/e2e: with client.stream_keepalive_interval_seconds set (e.g. 15) and a stream that stalls before the first token, : keepalive comment frames arrive every ~interval and the connection survives past an intermediary idle timeout; with the field unset/0, behavior is byte-for-byte unchanged.

New config field documented in docs/deployment-guides/config-json/client.mdx, transports/config.schema.json, and the OpenAPI schema.

Screenshots/Recordings

N/A — no UI surface added (types only; a UI form control can follow separately).

Breaking changes

  • Yes
  • No

Disabled by default (0); the field only affects the config hash when set to a positive value, so existing deployments upgrade with no hash churn and no behavior change.

Related issues

Closes maximhq#5010

Security considerations

None. The keepalive is an SSE comment line with a fixed, non-sensitive payload (: keepalive); it carries no request/response data and is only emitted on already-established, already-authorized streams. It does not alter auth, secrets, or provider payloads.

Checklist

  • I read docs/contributing/README.md and followed the guidelines
  • I added/updated tests where appropriate
  • I updated documentation where needed
  • I verified the Go build succeeds and Go tests pass locally; UI build not run locally (types-only change), left for CI
  • I verified the CI pipeline passes locally if applicable — relies on CI for the UI embed build and the vector-DB integration services not available locally

akshaydeo and others added 15 commits July 6, 2026 15:44
## Summary

Bumps several indirect Go dependencies to their latest patch/minor versions across the `framework`, `tests/cmd/seed`, `tests/cmd/e2eseed`, and `tests/cmd/seedvks` modules.

## Changes

- `github.com/ClickHouse/ch-go` upgraded from `v0.61.5` → `v0.65.0`
- `github.com/hashicorp/go-version` upgraded from `v1.6.0` → `v1.7.0`
- `github.com/pierrec/lz4/v4` upgraded from `v4.1.21` → `v4.1.22`
- `github.com/maximhq/bifrost/core` upgraded from `v1.6.2` → `v1.6.3` (in `e2eseed`, `seed`, and `seedvks`)
- `go.sum` files updated with additional transitive dependency checksums introduced by the `ch-go` upgrade (e.g., `go-faster/city`, `go-faster/errors`, `segmentio/asm`, `shopspring/decimal`, `paulmach/orb`, and various `golang.org/x/*` historical entries)

## Type of change

- [ ] Bug fix
- [ ] Feature
- [ ] Refactor
- [ ] Documentation
- [x] Chore/CI

## Affected areas

- [x] Core (Go)
- [ ] Transports (HTTP)
- [ ] Providers/Integrations
- [ ] Plugins
- [ ] UI (React)
- [ ] Docs

## How to test

```sh
go version
go test ./...
```

## Screenshots/Recordings

N/A

## Breaking changes

- [ ] Yes
- [x] No

## Related issues

N/A

## Security considerations

No security implications. All changes are indirect dependency version bumps with no API surface changes.

## Checklist

- [ ] I read `docs/contributing/README.md` and followed the guidelines
- [ ] I added/updated tests where appropriate
- [ ] I updated documentation where needed
- [ ] I verified builds succeed (Go and UI)
- [ ] I verified the CI pipeline passes locally if applicable
## Summary

Adds the `v2.0.0` branch as a trigger for the release pipeline so that releases can be cut directly from that branch in addition to `main`.

## Changes

- Added `v2.0.0` to the list of branches that trigger the release pipeline on push, enabling the pipeline to run when changes are pushed to the `v2.0.0` branch.

## Type of change

- [ ] Bug fix
- [ ] Feature
- [ ] Refactor
- [ ] Documentation
- [x] Chore/CI

## Affected areas

- [ ] Core (Go)
- [ ] Transports (HTTP)
- [ ] Providers/Integrations
- [ ] Plugins
- [ ] UI (React)
- [ ] Docs

## How to test

Push a commit to the `v2.0.0` branch and verify the release pipeline is triggered automatically.

## Screenshots/Recordings

N/A

## Breaking changes

- [ ] Yes
- [x] No

## Related issues

N/A

## Security considerations

No security implications. This only affects which branches trigger the CI release pipeline.

## Checklist

- [ ] I read `docs/contributing/README.md` and followed the guidelines
- [ ] I added/updated tests where appropriate
- [ ] I updated documentation where needed
- [ ] I verified builds succeed (Go and UI)
- [ ] I verified the CI pipeline passes locally if applicable
## Summary

Bumps several indirect Go dependencies to their latest patch/minor versions across all modules in the repository.

## Changes

- `github.com/andybalholm/brotli`: `v1.2.1` → `v1.2.2`
- `github.com/ClickHouse/ch-go`: `v0.61.5` → `v0.65.0`
- `github.com/ClickHouse/clickhouse-go/v2`: `v2.30.0` → `v2.32.0`
- `github.com/hashicorp/go-version`: `v1.6.0` / `v1.7.0` → `v1.8.0`
- `github.com/pierrec/lz4/v4`: `v4.1.21` → `v4.1.22`
- `github.com/tidwall/pretty`: `v1.2.0` → `v1.2.1`
- `github.com/onsi/gomega` (transports only): `v1.35.1` → `v1.38.2`

## Type of change

- [ ] Bug fix
- [ ] Feature
- [ ] Refactor
- [ ] Documentation
- [x] Chore/CI

## Affected areas

- [x] Core (Go)
- [x] Transports (HTTP)
- [ ] Providers/Integrations
- [x] Plugins
- [ ] UI (React)
- [ ] Docs

## How to test

```sh
go test ./...
```

## Breaking changes

- [ ] Yes
- [x] No

## Security considerations

No security implications. These are routine dependency version bumps with no API surface changes.

## Checklist

- [ ] I read `docs/contributing/README.md` and followed the guidelines
- [ ] I added/updated tests where appropriate
- [ ] I updated documentation where needed
- [ ] I verified builds succeed (Go and UI)
- [ ] I verified the CI pipeline passes locally if applicable
… guardrails (maximhq#4169)

## Summary

This PR introduces reversible redaction support across the Bifrost stack, allowing enterprise guardrails plugins to redact PII from log content while preserving an encrypted reversible mapping that authorized users can later reveal inline in the log detail view.

## Changes

- Added `RedactionPayload` schema type and associated context helpers (`RedactionPayloadFromContext`, `SetRedactionPayloadOnContext`, `ApplyLiteralReplacements`) to carry request-scoped redaction data from guardrails to log sinks
- Added `BifrostContextKeyRedactionData` context key for guardrails plugins to attach redaction payloads (marked DO NOT SET MANUALLY)
- Added `RedactionData` (transient), `RedactionMapping` (persisted), and `HasReversibleRedaction` (virtual) fields to the `Log` table struct
- Added `migrationAddRedactionMappingColumn` to persist the reversible mapping alongside the log row so it shares the row's lifecycle
- Updated `FindByID` to use `ScopedDB` so point lookups honor caller-supplied query scope (e.g. Enterprise DAC), preventing out-of-scope ID access
- Added `attachLogRedactionData` in the logging plugin to copy guardrail redaction payloads into log entries before async writes, gated on content logging being enabled
- Exposed `HasReversibleRedaction` on log detail and list endpoints so the UI knows when a reveal toggle is applicable
- Added a `Reveal` RBAC operation and `canReveal` prop threading through `LogDetailSheet` → `LogDetailView`
- Added a "Show original values" toggle in the log detail header that calls a new `POST /logs/:id/reveal` endpoint and applies the returned mapping inline to all message text, reasoning, and refusal fields without mutating stored data
- Added `useRevealLogRedactionMappingMutation` RTK Query mutation and `LogRedactionRevealResponse` type
- Literal replacement applies longest-match-first ordering to avoid partial substitution of overlapping tokens

## Type of change

- [ ] Bug fix
- [x] Feature
- [ ] Refactor
- [ ] Documentation
- [ ] Chore/CI

## Affected areas

- [x] Core (Go)
- [x] Transports (HTTP)
- [ ] Providers/Integrations
- [x] Plugins
- [x] UI (React)
- [ ] Docs

## How to test

```sh
# Core/Transports
go test ./core/schemas/... ./framework/logstore/... ./plugins/logging/...

# UI
cd ui
pnpm i
pnpm build
```

To validate end-to-end:
1. Configure an enterprise guardrails plugin that sets `BifrostContextKeyRedactionData` with a `RedactionPayload` containing `ReversibleMappings`
2. Send a request containing PII through Bifrost
3. Open the log detail view — the "Show original values" toggle should appear only for users with the `Reveal` RBAC permission on `Logs`
4. Toggle reveal — placeholders like `[EMAIL-1]` should be replaced inline with their original values
5. Navigate to a different log — the toggle resets and the mapping is cleared from state

## Breaking changes

- [ ] Yes
- [x] No

## Security considerations

- The `RedactionMapping` column stores the reversible mapping encrypted when an encryption key is configured; the mapping is deleted when the log row is deleted, preventing orphaned sensitive data
- The reveal endpoint is gated behind a new `Reveal` RBAC operation so only authorized users can recover original PII values
- `BifrostContextKeyRedactionData` is explicitly marked DO NOT SET MANUALLY to prevent plugins from injecting arbitrary mappings
- `attachLogRedactionData` is a no-op when content logging is disabled, preventing sensitive payloads from leaking through the async write path
- `FindByID` now enforces query scope, closing a gap where a scoped caller could retrieve out-of-scope log rows by ID

## Checklist

- [x] I added/updated tests where appropriate
- [x] I verified builds succeed (Go and UI)
…4417)

## Summary

Adds trace-level redaction of span content attributes before traces are exported to observability plugins. Connectors can register raw-to-placeholder replacement maps on a trace; when the trace completes, all content-bearing span attributes (messages, prompts, tool arguments, etc.) are rewritten in-place before any plugin receives the trace. The replacement map is stored in an unexported field so it is never serialized or leaked to connectors.

## Changes

- Added `IsContentAttribute(key string) bool` to classify which span attribute keys may carry user or model content (messages, prompts, embeddings, tool arguments, reasoning text, etc.).
- Added `RedactAttributeValue(value any, replacements map[string]string) any` to apply literal replacements across `string`, `[]string`, and `[]any` attribute shapes.
- Added `redactionReplacements` as an unexported field on `Trace` so the map is never JSON-serialized and cannot be observed by connectors.
- Added `Trace.SetRedactionReplacements` to store a defensive copy of the replacement map, stripping empty keys.
- Added `Trace.ApplyRedactionReplacements` to walk every span, redact content attributes, and clear the map atomically.
- Added `Trace.Reset` cleanup to ensure pooled traces cannot carry redaction data across requests.
- Added `redactSpanAttributes` as a package-private helper that locks a single span and rewrites its content attributes.
- Added `SetTraceRedactionReplacements` to the `Tracer` interface and its `NoOpTracer` implementation.
- Wired `ApplyRedactionReplacements` into `Tracer.CompleteAndFlushTrace` so redaction runs before any observability plugin `Inject` call.
- Added `Tracer.SetTraceRedactionReplacements` in the framework tracing layer to look up the live trace and delegate to `Trace.SetRedactionReplacements`.

## Type of change

- [ ] Bug fix
- [x] Feature
- [ ] Refactor
- [ ] Documentation
- [ ] Chore/CI

## Affected areas

- [x] Core (Go)
- [ ] Transports (HTTP)
- [ ] Providers/Integrations
- [x] Plugins
- [ ] UI (React)
- [ ] Docs

## How to test

```sh
go test ./core/schemas/... ./framework/tracing/...
```

Key scenarios covered by new tests:

- `TestIsContentAttribute` — verifies the content attribute classifier includes message, prompt, embedding, and tool fields while excluding metadata fields like model name and session ID.
- `TestTraceApplyRedactionReplacementsRedactsContentAttributes` — verifies replacements are applied to all spans and that non-content attributes are left untouched.
- `TestTraceRedactionReplacementsDoNotSerialize` — verifies the replacement map never appears in JSON output.
- `TestTraceResetClearsRedactionReplacements` — verifies pooled traces cannot retain replacement data.
- `TestTracer_CompleteAndFlushTraceRedactsContentBeforeInject` — end-to-end: replacements set before span population are applied before the observability plugin receives the trace.
- `TestTracer_SetTraceRedactionReplacementsSurvivesLaterObservabilityPlugins` — replacements set before plugin registration still take effect at flush time.

## Breaking changes

- [x] Yes
- [ ] No

The `Tracer` interface gains a new method `SetTraceRedactionReplacements`. Any external implementation of `Tracer` must add this method. The `NoOpTracer` implementation is provided as a reference no-op.

## Security considerations

The replacement map is stored in an unexported struct field (`redactionReplacements`) and is explicitly cleared after `ApplyRedactionReplacements` runs and during `Reset`. This prevents PII or secret values used as redaction keys from being serialized into trace payloads, retained across pooled trace reuse, or observed by observability plugin authors inspecting the exported `Trace` struct.

## Checklist

- [ ] I read `docs/contributing/README.md` and followed the guidelines
- [x] I added/updated tests where appropriate
- [ ] I updated documentation where needed
- [x] I verified builds succeed (Go and UI)
- [ ] I verified the CI pipeline passes locally if applicable
## Summary

Adds documentation for Bifrost-managed guardrail redaction, two new PII guardrail providers (Microsoft Presidio and Azure AI Language PII), and a `POST /api/logs/{id}/reveal` endpoint for revealing reversible redaction mappings from Bifrost logs.

## Changes

- Added a new `Guardrail Redaction` reference page (`enterprise/guardrails/redaction.mdx`) covering the three redaction modes (`runtime`, `logs_only`, `runtime_reversible`), redaction strategies (`replace`, `mask`, `hash`), the reveal permission model, and connector export behavior.
- Added integration pages for Microsoft Presidio (`integrations/guardrails/presidio.mdx`) and Azure AI Language PII (`integrations/guardrails/azure-language-pii.mdx`), including configuration fields, authentication modes, and all four config formats (Web UI, API, config.json, Helm).
- Extended the Regex and Secrets Detection provider docs and config examples to include per-pattern `action`, `redaction_strategy`, `redaction_mode`, and `entity_type` fields.
- Updated the guardrails overview to list Presidio and Azure AI Language PII in the provider capability matrix, added a warning against combining provider-managed transformation with Bifrost-managed redaction on the same phase, and added a Redaction section summarizing the three modes.
- Updated the nav (`docs.json`) to add a `Providers` sub-group under Guardrails and surface the new Redaction, Presidio, and Azure AI Language PII pages.
- Added `POST /api/logs/{id}/reveal` to the OpenAPI spec (YAML and compiled JSON), gated by `Logs:Reveal`, returning a `LogRevealResponse` with a placeholder-to-original-value mapping. Added `has_reversible_redaction` to `LogEntry`.
- Added `Logs:Reveal` and `MCPToolGroups`/`MCPLogs` to the RBAC resource table.
- Added guardrail redaction notes to the Datadog connector, OTel, default observability, and log-exports pages explaining that exported content receives redacted or placeholderized values and that reveal mappings are not forwarded to connectors.

## Type of change

- [ ] Bug fix
- [ ] Feature
- [ ] Refactor
- [x] Documentation
- [ ] Chore/CI

## Affected areas

- [ ] Core (Go)
- [ ] Transports (HTTP)
- [x] Providers/Integrations
- [ ] Plugins
- [ ] UI (React)
- [x] Docs

## How to test

Review the rendered docs to confirm:

- The Guardrail Redaction page renders the mode matrix table and the redaction mode selector screenshot correctly.
- The Presidio and Azure AI Language PII pages appear under the Guardrails > Providers nav group.
- The `POST /api/logs/{id}/reveal` endpoint appears in the API reference with correct request/response schemas and a `403` for missing `Logs:Reveal` permission.
- The Regex and Secrets Detection config examples include `action`, `redaction_strategy`, and `redaction_mode` fields.
- Cross-links between the redaction page and provider pages resolve without 404s.

## Breaking changes

- [ ] Yes
- [x] No

## Security considerations

- The `POST /api/logs/{id}/reveal` endpoint returns original sensitive values and is gated by the `Logs:Reveal` RBAC permission. The response is marked `Cache-Control: no-store`.
- Reveal mappings are stored only in Bifrost logs and are never forwarded to trace-export connectors, object storage payloads, or external observability destinations.
- When an encryption key is configured, the reveal mapping is encrypted before storage.
- If `disable_content_logging` is enabled, no reveal data is persisted.

## Checklist

- [ ] I read `docs/contributing/README.md` and followed the guidelines
- [x] I added/updated tests where appropriate
- [x] I updated documentation where needed
- [ ] I verified builds succeed (Go and UI)
- [ ] I verified the CI pipeline passes locally if applicable
…hen forwarded on a content chunk (maximhq#4964)

The streaming chat accumulator reads finish_reason only from the highest-index
chunk (getLastChatChunkLocked). For providers that send finish_reason on the
final content chunk, the OpenAI-compatible handler forwards it on that chunk and
appends a synthetic terminal chunk (index + 1) whose finish_reason is nil to
avoid a duplicate client emission (the forwardedTerminalFinishReason guard from
maximhq#1995). The highest-index chunk therefore has a nil finish_reason while the real
one sits one index lower, so the accumulated response records null. Unlike the
sibling TokenUsage, Cost and CacheDebug fields at the same site, finish_reason
was assigned without a nil check. The accumulated value feeds the logging plugin
(entry.StopReason) and Maxim, so streaming logs recorded an empty stop reason
for these providers; non-streaming is unaffected.

Fall back to the newest chunk that actually carries a finish_reason only when the
highest-index chunk has none. Regression tests cover the content-chunk case and
the standard terminal-chunk case.

closes maximhq#4963

Signed-off-by: Akshay Deo <akshay@akshaydeo.com>
Co-authored-by: Akshay Deo <akshay@akshaydeo.com>
## Summary

Azure media endpoints (Speech, Transcription, ImageGeneration, ImageEdit, VideoGeneration) were hardcoding `Authorization: Bearer <key>` authentication, ignoring Azure-specific auth mechanisms such as service principal tokens or `api-key` headers. This PR propagates Azure auth headers through the shared OpenAI handler functions so that Azure's authentication flow is respected for all media request types.

## Changes

- Added an `authHeaders map[string]string` parameter to `HandleOpenAISpeechRequest`, `HandleOpenAITranscriptionRequest`, `HandleOpenAIImageGenerationRequest`, `HandleOpenAIImageEditRequest`, and `HandleOpenAIVideoGenerationRequest`.
- Each handler now prefers caller-supplied `authHeaders` over the default `Bearer` token fallback. If `authHeaders` is empty or nil, it falls back to `BearerAuthHeader(key)` as before.
- The Azure provider now calls `getAzureAuthHeaders` before invoking each of these handlers and passes the result through.
- Non-Azure providers (OpenAI, Groq, vLLM, xAI) pass `nil` for `authHeaders`, preserving existing behavior.

## Type of change

- [x] Bug fix
- [ ] Feature
- [ ] Refactor
- [ ] Documentation
- [ ] Chore/CI

## Affected areas

- [x] Core (Go)
- [ ] Transports (HTTP)
- [x] Providers/Integrations
- [ ] Plugins
- [ ] UI (React)
- [ ] Docs

## How to test

```sh
go test ./...
```

Validate by configuring an Azure provider with service principal credentials and invoking Speech, Transcription, ImageGeneration, ImageEdit, and VideoGeneration endpoints. Confirm that requests are authenticated using the Azure-specific headers rather than a `Bearer` token, and that non-Azure providers continue to authenticate with `Bearer` tokens as expected.

## Breaking changes

- [ ] Yes
- [x] No

## Security considerations

Auth headers sourced from `getAzureAuthHeaders` may contain short-lived tokens or API keys. These are passed only in-memory to the HTTP request headers and are not logged or persisted. Existing secret handling guarantees apply.

## Checklist

- [ ] I read `docs/contributing/README.md` and followed the guidelines
- [ ] I added/updated tests where appropriate
- [ ] I updated documentation where needed
- [ ] I verified builds succeed (Go and UI)
- [ ] I verified the CI pipeline passes locally if applicable
## Summary

Redaction replacements are now tracked separately for request-side (input) and response-side (output) content rather than in a single flat map. This prevents input-phase redaction tokens from being applied to output attributes and vice versa, ensuring each replacement set is scoped to the content it was derived from.

## Changes

- Introduced `RedactionPhase` (`input` / `output`) and `RedactionMapsByPhase` to replace the flat `map[string]string` used in `RedactionData` and `Trace.redactionReplacements`.
- `SetRedactionReplacements` and `SetTraceRedactionReplacements` now require a `RedactionPhase` argument so callers explicitly declare which lifecycle phase produced the replacements.
- Span attribute redaction (`redactSpanAttributes`) selects the correct replacement map per attribute using a new `traceContentAttributeScopeForKey` classifier:
    - Input-only attributes (e.g. `AttrInputMessages`, `AttrPrompt`) receive only input replacements.
    - Output-only attributes (e.g. `AttrOutputMessages`, `AttrRespReasoningText`) receive only output replacements.
    - Mixed attributes (e.g. `AttrToolCallArguments`, `AttrToolCallResult`) receive a merged map of both phases.
- `IsContentAttribute` is now derived from `traceContentAttributeScopeForKey` to keep the two in sync.
- `RevealRedactionMapping` on `logstore.Log` changed from `map[string]string` to `*schemas.RedactionMapsByPhase`, and `LogRedactionMappingResolver` returns the same type.
- The `redaction_mapping` field in the log API response and OpenAPI schema is now a `{ input, output }` object instead of a flat map.
- The UI `LogEntry` type reflects the new shape, and `logDetailView` applies input and output reveal mappings independently to the appropriate content sections (request body, input messages, response body, output messages, reasoning, refusals, Responses API items).

## Type of change

- [ ] Bug fix
- [x] Feature
- [x] Refactor
- [ ] Documentation
- [ ] Chore/CI

## Affected areas

- [x] Core (Go)
- [x] Transports (HTTP)
- [ ] Providers/Integrations
- [x] Plugins
- [x] UI (React)
- [x] Docs

## How to test

```sh
# Core/Transports
go test ./core/schemas/... ./framework/tracing/... ./plugins/logging/...

# UI
cd ui
pnpm i
pnpm build
```

Verify that:

- Input-phase redaction tokens (e.g. `[EMAIL-1]`) are applied only to input attributes and request bodies.
- Output-phase redaction tokens (e.g. `[EMAIL-2]`) are applied only to output attributes and response bodies.
- The log detail reveal toggle restores original values in the correct content sections.
- The `redaction_mapping` field in log detail API responses serializes as `{ "input": {...}, "output": {...} }`.

## Screenshots/Recordings

N/A

## Breaking changes

- [ ] Yes
- [x] No

`SetTraceRedactionReplacements` now requires a `RedactionPhase` argument. Any custom `Tracer` or `LogRedactionMappingResolver` implementations must be updated to match the new signatures. The `redaction_mapping` field in log detail API responses has changed shape from a flat object to a `{ input, output }` object; API consumers that read this field will need to handle the new structure.

## Related issues

N/A

## Security considerations

Scoping replacements by phase reduces the risk of a redaction token from one phase incorrectly masking or revealing content in another phase. The reversible mapping (used for the `Logs:Reveal` feature) is now also phase-scoped, so revealed values are only substituted back into the content section they originated from.

## Checklist

- [ ] I read `docs/contributing/README.md` and followed the guidelines
- [x] I added/updated tests where appropriate
- [x] I updated documentation where needed
- [ ] I verified builds succeed (Go and UI)
- [ ] I verified the CI pipeline passes locally if applicable
…iaries

Adds an opt-in, config-driven server-side SSE keepalive. While a stream is
otherwise idle, the transport emits an SSE comment frame (": keepalive") every
configured interval so idle-timeout enforcing intermediaries (load balancers,
reverse proxies, API gateways) do not drop a healthy-but-silent stream. Clients
ignore comment lines per the SSE spec, so no client change is required and no
provider payload is altered. Disabled by default (0). Implements maximhq#5010.

The keepalive timer lives in SSEStreamReader.Read (the single fasthttp write
loop), so it needs no extra synchronization and cannot race Send/Done/Close.
It is enabled only for text/event-stream producers; the Bedrock binary
EventStream path is left without keepalives to avoid corrupting its framing.

Affected packages:
- transports/bifrost-http/lib/ - SSEStreamReader keepalive timer + options,
  KeepaliveOptions helper, GetStreamKeepaliveIntervalSeconds accessor + tests
- transports/bifrost-http/handlers/ - wire keepalive into the inference SSE
  producer; add config update path; test-mock HandlerStore method
- transports/bifrost-http/integrations/ - wire keepalive into the router SSE
  producer (skip Bedrock binary EventStream)
- transports/config.schema.json - stream_keepalive_interval_seconds field
- framework/configstore/ - StreamKeepaliveIntervalSeconds client config field,
  DB table column + migration, hash inclusion (only when > 0, no legacy churn)
- ui/lib/types/ - config + zod schema types
- docs/ - client config docs + OpenAPI schema

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
The initial keepalive only covered text/event-stream producers and was gated
off for the Bedrock path (its binary AWS EventStream would be corrupted by an
SSE ": keepalive" comment) and absent on the passthrough producer.

- Bedrock: emit a pre-encoded EventStream keepalive message via WithKeepaliveFrame
  instead of the SSE comment. It carries :message-type "event" and a proprietary
  :event-type "bifrost-ping" with an empty payload, which every official SDK
  decoder (botocore, aws-sdk-go-v2, aws-sdk-js) ignores as an unmodeled event per
  the Smithy event-stream forward-compatibility contract.
- Passthrough: enable keepalive but gate on the resolved upstream Content-Type so
  the SSE comment is only injected into genuine text/event-stream bodies, never a
  JSON-array passthrough (e.g. Vertex :streamGenerateContent without ?alt=sse).
- Add unit tests asserting the Bedrock frame decodes cleanly and is never an
  exception/error message.

All streaming endpoints now keep idle connections warm through idle-timeout
enforcing intermediaries.
…okens

The SSE keepalive only starts once the stream is committed, but core held the
response uncommitted while CheckFirstStreamChunkForError blocked reading the
first chunk (to detect HTTP-200-embedded errors for retry/fallback). During a
slow first token that block spanned the whole pre-first-token gap, so no
keepalive could be emitted and an idle-timeout intermediary (NLB) could drop the
connection.

A keepalive is a response-body frame, so it cannot be sent before commit — the
first-chunk peek and the liveness heartbeat are in genuine tension only when the
first chunk is slower than the keepalive interval. Since embedded errors arrive
immediately, bounding the peek at that interval loses nothing: fast errors are
still caught and retried; a slow legitimate first token now commits in time to
be kept warm.

- core: CheckFirstStreamChunkForError takes a firstChunkTimeout. On timeout it
  commits and forwards every chunk verbatim (including the pending first one); a
  later error is delivered in-band, never retried (impossible post-commit).
  timeout<=0 waits unbounded — byte-for-byte the previous behavior.
- core: BifrostContextKeyFirstChunkTimeout + Set/GetFirstChunkTimeout, mirroring
  the existing stream-idle-timeout context-hint pair (transport sets policy,
  core applies mechanism).
- transports: the two keepalive-bearing SSE producers set the hint = keepalive
  interval before requesting the stream. No new user-facing config knob.
- tests: bounded-peek unit tests (timeout-forwards, timeout-then-error-in-band,
  fast-error-still-caught, empty-stream, ctx-cancel drain, no-leak) + accessor
  tests + transport-level handleStreaming keepalive-during-gap tests for the SSE
  and Bedrock binary paths and the disabled case. Existing peek tests pass
  unchanged (unbounded regression lock).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Feature]: Server-side SSE keepalive (comment heartbeat) to keep long-idle streams alive through intermediaries

5 participants