From 080ea19a778db195da8c78c554bb6d8e9f934a0c Mon Sep 17 00:00:00 2001 From: Jan-Stefan Janetzky Date: Fri, 27 Nov 2026 02:50:09 +0100 Subject: [PATCH 01/27] feat(gateway): a consumer a server-admin sets to record keeps every request and answer whole in the LLM log, readable by server-admins only (migration 197) context_model_consumers.record_bodies (default off) is the switch: on is server-admin only, also with self-service, and needs confirm_record_bodies; off is open to the tenant-admin; every change is audited, ctx_model_auth carries it to the door as its last column, the read form names it. A recorded row stores the whole request and answer (a stream's relayed lines; no vectors, no scores) whatever gateway.body_logging, the alias, the floor, the scan or Ctx-Sensitivity say, without the 64 KiB cut and the seal, marked metadata.gw.recorded. The texts are held against a 128 MiB account of their own, never against the in-flight budget: the request path is unchanged, and an unrecorded consumer's rows are byte-identical to the base (golden of 864 rows). A text the account cannot take is named in record_lost. ctx-llmlog-export seals recorded rows (fail-closed without a readable marker); the detail stays server-admin-only for gateway rows; status lists the recording consumers. Co-Authored-By: Claude Opus 5.5 --- docs/api.md | 18 +- docs/operations.md | 44 +- docs/security.md | 7 +- go/cmd/ctxd/v1_record_integration_test.go | 262 ++++++ go/internal/auth/consumer.go | 13 +- go/internal/cli/models.go | 1 + go/internal/handler/llmlog.go | 10 +- go/internal/handler/model_consumers.go | 98 +- go/internal/handler/model_consumers_read.go | 21 +- ...model_consumers_record_integration_test.go | 187 ++++ go/internal/handler/status.go | 8 +- go/internal/handler/status_gateway.go | 27 +- .../llmlog/body_readers_census_test.go | 108 +++ go/internal/llmlog/gateway.go | 93 +- go/internal/llmlog/gateway_recorded_test.go | 214 +++++ .../llmlog/gateway_unrecorded_golden_test.go | 131 +++ go/internal/llmlog/llmlog.go | 8 + go/internal/llmlog/recorded.go | 121 +++ .../llmlog/recorded_integration_test.go | 118 +++ .../llmlog/testdata/gateway_unrecorded.golden | 864 ++++++++++++++++++ go/internal/llmlogexport/export.go | 37 +- go/internal/oai/chat.go | 56 +- go/internal/oai/chat_stream.go | 3 + go/internal/oai/embeddings.go | 17 +- go/internal/oai/forced.go | 1 + go/internal/oai/record.go | 156 ++++ go/internal/oai/record_test.go | 195 ++++ go/internal/oai/rerank.go | 39 +- go/internal/schemacontract/manifest.json | 18 +- .../store/audit_classification_test.go | 10 + ...ecord_bodies_migration_integration_test.go | 258 ++++++ go/internal/store/model_keys.go | 86 +- .../197_model_consumer_record_bodies.sql | 194 ++++ 33 files changed, 3326 insertions(+), 97 deletions(-) create mode 100644 go/cmd/ctxd/v1_record_integration_test.go create mode 100644 go/internal/handler/model_consumers_record_integration_test.go create mode 100644 go/internal/llmlog/body_readers_census_test.go create mode 100644 go/internal/llmlog/gateway_recorded_test.go create mode 100644 go/internal/llmlog/gateway_unrecorded_golden_test.go create mode 100644 go/internal/llmlog/recorded.go create mode 100644 go/internal/llmlog/recorded_integration_test.go create mode 100644 go/internal/llmlog/testdata/gateway_unrecorded.golden create mode 100644 go/internal/oai/record.go create mode 100644 go/internal/oai/record_test.go create mode 100644 go/internal/store/model_consumer_record_bodies_migration_integration_test.go create mode 100644 go/migrations/197_model_consumer_record_bodies.sql diff --git a/docs/api.md b/docs/api.md index a00b121a6..b4adfcee7 100644 --- a/docs/api.md +++ b/docs/api.md @@ -35,12 +35,12 @@ hit it. Not a settings key: changing it is a rebuild, deliberately. | `POST /webhooks/github/{project_id}` | **Unauthenticated** GitHub inbound (workflow W13) — HMAC-SHA256 over the raw body against the per-project sealed secret replaces the api key. Bad/absent signature or unknown project ⇒ uniform **401** with ZERO DB write; valid ⇒ **202** and one redelivery-idempotent inbox row; per-project rate limit ⇒ **429**. The inbox is a debounced sync **trigger**, never an authority (see [Webhooks (inbound)](#webhooks-inbound-workflow-w13)). | | `GET\|PUT\|DELETE /api/settings[/{key}]` | Runtime config overrides, **admin-gated incl. reads** (see [Settings API](#settings-api)). | | `GET\|PUT\|DELETE /api/secrets[/{name}]` | Write-only sealed credentials, **admin-gated**: PUT creates/rotates (value never returned), GET lists metadata + `referenced_by`, DELETE 409s while referenced — by a `secret_ref` setting or a backend pool row's `api_key_ref` (entries prefixed `backend:`, remediation text per reference type) (see [security](security.md#sealed-secrets--break-glass)). | -| `GET /api/status` | **Admin dashboard** aggregate from the process-wide status collector: health, backend pool (`pool.Status()` shape), dream queue + mode, 24h LLM telemetry (with an `llm_24h_complete` attribution flag), and the disable-profile registry line (`profiles`: slim `{name, scope, label, active, member_count}` rows, U01-W7 — replaced the retired `gaming:{active}` field; member names load on-demand via `disable-profile-list`). A server-admin additionally sees `advisories` (`[{subject, state}]`, omitted when empty): named reasons for states the frame can only show as an absence — today exactly `backend_pool: empty` (fresh install, nobody seeded yet; deliberately NOT in the public `/health` body), and `llmlog` (`{insert_failures, insert_dropped}`, present even at 0): the process-wide count of `context_llm_log` rows that never landed — inserts the database refused or that timed out, and rows dropped by the bounded insert queue ([operations](operations.md#shutdown-and-the-llm-log-write-path)), and `foreign_load` (present only while an enabled, not profile-parked `_global` backend row carries `metadata.foreign_load_probe`): one row per probed engine origin, `{target, probe, backends, running, active, held, delta, suspected, since, suspected_hourly, hourly{hour, engine_requests, ctx_requests}, probe_error, probed_at}` — the requests the engine holds (read from its own `GET /metrics` every `status.foreign_load_interval` and on each hour boundary, whether or not anyone reads the status) against the dispatcher's held leases, and hourly its finished responses against ctx's logged calls; evidence that ctx is the only load source of the GPU ([operations](operations.md#foreign-load-detector)), and `query_synthesize` (`{p95_ms, avg_ms, samples, since}`, present with no sample too): the latency of query synthesis from an in-memory ring of the last 512 syntheses since process start — per synthesis the wait-free wire duration of the backend that answered (or failed last) — the calls with a wire time among those `llm_24h` averages for pipeline `query-synthesize` (a call that reached no backend is not timed), the dispatcher's queue wait not included; `p95_ms` (nearest rank) is `null` below 20 samples, `avg_ms` without a sample; `since` (RFC3339, UTC, whole seconds) is where the window starts — the process start, or the oldest retained sample once more than 512 were seen. Read from process memory, never from the database. Never on the tenant view. The server-admin `dispatch` section carries per target `held` (ALL slot-holding leases, internal and external — the number the foreign-load detector compares) split into `held_internal` / `held_external`, `inflight_internal`, the external offer (`internal_reserved`, `external_offered`, `external_capacity`), the external class's wait view `external` and its refusals `external_rejects {cap, not_offered}`, the same two for the external bulk class (`external_bulk`, `external_bulk_rejects {cap, not_offered}`; `held_external` counts the leases of both external classes), and buckets with `tenant_id` and `class` (`interactive` \| `external` \| `external_bulk`; an external consumer's bucket key is `_consumer:` in either external class). The tenant-admin `dispatch_tenant` view never shows external load: `busy` and `depth` read only the internal leases and queues, and no external bucket appears. Served from a cache (N pollers cost one collection). Carries hostnames, so it is admin-gated where `/health` stays anonymous. Opens to a tenant-admin with a reduced own-tenant view (see [multi-tenancy](multi-tenancy.md#telemetry-per-tenant-views)). | +| `GET /api/status` | **Admin dashboard** aggregate from the process-wide status collector: health, backend pool (`pool.Status()` shape), dream queue + mode, 24h LLM telemetry (with an `llm_24h_complete` attribution flag), and the disable-profile registry line (`profiles`: slim `{name, scope, label, active, member_count}` rows, U01-W7 — replaced the retired `gaming:{active}` field; member names load on-demand via `disable-profile-list`). A server-admin additionally sees `advisories` (`[{subject, state}]`, omitted when empty): named reasons for states the frame can only show as an absence — today exactly `backend_pool: empty` (fresh install, nobody seeded yet; deliberately NOT in the public `/health` body), and `llmlog` (`{insert_failures, insert_dropped, recorded_bodies_lost}`, present even at 0): the process-wide count of `context_llm_log` rows that never landed — inserts the database refused or that timed out, and rows dropped by the bounded insert queue ([operations](operations.md#shutdown-and-the-llm-log-write-path)) — and of the rows of recording consumers written without a body they should carry (`metadata.gw.record_lost`, [operations](operations.md#recording-a-consumer)), and `foreign_load` (present only while an enabled, not profile-parked `_global` backend row carries `metadata.foreign_load_probe`): one row per probed engine origin, `{target, probe, backends, running, active, held, delta, suspected, since, suspected_hourly, hourly{hour, engine_requests, ctx_requests}, probe_error, probed_at}` — the requests the engine holds (read from its own `GET /metrics` every `status.foreign_load_interval` and on each hour boundary, whether or not anyone reads the status) against the dispatcher's held leases, and hourly its finished responses against ctx's logged calls; evidence that ctx is the only load source of the GPU ([operations](operations.md#foreign-load-detector)), and `query_synthesize` (`{p95_ms, avg_ms, samples, since}`, present with no sample too): the latency of query synthesis from an in-memory ring of the last 512 syntheses since process start — per synthesis the wait-free wire duration of the backend that answered (or failed last) — the calls with a wire time among those `llm_24h` averages for pipeline `query-synthesize` (a call that reached no backend is not timed), the dispatcher's queue wait not included; `p95_ms` (nearest rank) is `null` below 20 samples, `avg_ms` without a sample; `since` (RFC3339, UTC, whole seconds) is where the window starts — the process start, or the oldest retained sample once more than 512 were seen. Read from process memory, never from the database. Never on the tenant view. The server-admin `dispatch` section carries per target `held` (ALL slot-holding leases, internal and external — the number the foreign-load detector compares) split into `held_internal` / `held_external`, `inflight_internal`, the external offer (`internal_reserved`, `external_offered`, `external_capacity`), the external class's wait view `external` and its refusals `external_rejects {cap, not_offered}`, the same two for the external bulk class (`external_bulk`, `external_bulk_rejects {cap, not_offered}`; `held_external` counts the leases of both external classes), and buckets with `tenant_id` and `class` (`interactive` \| `external` \| `external_bulk`; an external consumer's bucket key is `_consumer:` in either external class). The tenant-admin `dispatch_tenant` view never shows external load: `busy` and `depth` read only the internal leases and queues, and no external bucket appears. Served from a cache (N pollers cost one collection). Carries hostnames, so it is admin-gated where `/health` stays anonymous. Opens to a tenant-admin with a reduced own-tenant view (see [multi-tenancy](multi-tenancy.md#telemetry-per-tenant-views)). | | `POST /api/manage` (`eject-mode`, alias `gaming-mode`) | Canonical shim for the reserved disable-profile `eject` (092): read = legacy gaming shape, mutation = server-admin toggle with implicit blackout confirm. Since U01-W5 a profile-only write (the legacy `gaming.active` settings dual-write was retired); the eject profile is the single source of truth. A toggle whose backend-pool or settings reload fails after the write answers `500` `{"success": false, "persisted": true, "error": "persisted but reload failed — …"}`: the toggle is written. | | `POST /api/manage` (`disable-profile-list/create/update/delete/toggle`) | Disable-profile registry (tenant-admin; tenant profiles may only contain own-scope backends, `_global` profiles are operator-owned). Toggle returns `{profile, impact, as_of}`; blacking out a whole role requires `confirm_role_blackout` (else 422; `dry_run` supported); the reserved `eject` profile is not deletable. | | `POST /api/manage` (`backend-create`/`backend-update`, field `disable_profiles`) | Profile membership as a backend property: list of profile NAMES (key absent = unchanged, `[]` = detach all); joins sync in the same transaction as the backend write. A tenant-admin may attach its OWN backend to `_global` profiles (self-disable) or its own tenant profiles; a scoped profile never contains foreign-scope backends. `backend-list` echoes `disable_profiles` including inactive membership. | | `GET\|PUT\|DELETE /api/graph/category-hues[/{category}]` | Per-category graph HUE overrides (093, AM-2): GET (**any valid key** — the graph is a member surface) returns the resolved sparse map `{category: hue}` for the caller's `{_global, tenant}` view, tenant beating `_global` per category; PUT `{"hue":0–359}`/DELETE (**tenant-admin**) write the caller's own scope (operator → `_global`), never a client-supplied one. Only the hue is overridden — sat/lum stay theme tokens, so every choice sits inside the G1a contrast sweep. Absent override = seeded hash colour. UI: the hue wheel at `/settings/hues` (U02-W6) — markers sit at perceptual OKLCH angles for distance judgement, the stored value is always the HSL degree. | -| `GET /api/llmlog` | **Admin** LLM telemetry table (`?limit=`/`pipeline=`/`errors_only=`). NEVER returns the `request_system`/`request_user`/`response_content` body columns (the prompt shadow corpus); the `error` is normalized to a class + 256-char-capped detail. Tenant-admin sees only its own tenant's rows. `?consumer_id=` narrows the list to one model consumer (a malformed id answers `400 invalid consumer_id`); every entry carries `consumer_id` (`null` for knowledge-key and background rows). A tenant-admin sees the last 30 days of its own knowledge keys’ and model consumers’ rows; a foreign or unknown `consumer_id` answers the same empty list. The detail `GET /api/llmlog/{id}` of a consumer row stays server-admin-only (uniform 404) — see [usage API](#usage-api-get-apiusage-get-apiusageconsumers). | +| `GET /api/llmlog` | **Admin** LLM telemetry table (`?limit=`/`pipeline=`/`errors_only=`). NEVER returns the `request_system`/`request_user`/`response_content` body columns (the prompt shadow corpus); the `error` is normalized to a class + 256-char-capped detail. Tenant-admin sees only its own tenant's rows. `?consumer_id=` narrows the list to one model consumer (a malformed id answers `400 invalid consumer_id`); every entry carries `consumer_id` (`null` for knowledge-key and background rows). A tenant-admin sees the last 30 days of its own knowledge keys’ and model consumers’ rows; a foreign or unknown `consumer_id` answers the same empty list. The detail `GET /api/llmlog/{id}` of a consumer row stays server-admin-only (uniform 404) — see [usage API](#usage-api-get-apiusage-get-apiusageconsumers); its `detail` carries `recorded` (`true` for the row of a recording consumer, whose bodies are whole and can hold credentials in clear text). | | `GET /api/audit` | **Admin or tenant-admin** history of the access-deciding tables ([security](security.md#audit-trail)): `?entity=` (required) one of `api_key`, `tenant_quota`, `gateway_limits`, `model_alias`, `model_consumer`, `model_key`, `model_grant`, `consumer_usage`, `scope_purge`, `forge_sync`, `instance`; `id=` an exact `entity_key` (a key id, a quota scope); `since=` RFC 3339, rows strictly newer; `limit=` a positive integer, clamped to `audit.max_limit` (default `200`, also the page size without `limit`; a configured `0` falls back to the default). Newest first (`created_at`, then `id`). `400` for a missing or unknown `entity`, for `setting`/`secret`/`backend` (their history stays on their own surfaces, e.g. `GET /api/settings/{key}`), for an `id` that is not valid UTF-8 or carries NUL, for a malformed `since` and a non-positive or non-numeric `limit`. Response `{success, entity, rows:[{id, entity_key, scope, action, old_value, new_value, api_key_id, actor_label, metadata, created_at}]}`. `model_consumer` and `model_key` rows are written by the triggers of migration 161, `model_alias` rows by those of migration 162 (a `_global` alias carries no tenant, so its rows are server-admin-only), `instance` rows by those of migration 163 (`entity_key` `self`; a rotation is a `rotate` row with the old and the new `instance_id`, never the secret); `model_grant` rows by the trigger of migration 164 (`entity_key` `:`, actions `grant`/`ungrant`, `scope` the consumer's `tenant_scope`); `scope_purge` rows are written by `manage purge`, one per run (`entity_key` the scope, action `purge`); `forge_sync` rows by `forge-conflict-resolve` and `forge-stamp-reset` (`entity_key` the block, or the project for a reset of all its mappings; actions `resolve-local`, `resolve-remote`, `stamp-reset`; `metadata.tenant_id` the project's tenant, [forge sync](#forge-sync-manage-actions-workflow-i-f)); `gateway_limits` and `consumer_usage` answer `rows: []` until their writers ship. A server-admin reads every row unredacted. A tenant-admin reads only rows whose `metadata.tenant_id` is its own tenant (filtered in SQL): another tenant's id answers the same `200` with `rows: []` as an id that does not exist, rows of a scope no tenant owns are server-admin-only, and so is `instance` (`rows: []` for a tenant-admin). For a tenant-admin the actor is **redacted** unless it provably is a non-server-admin key of the reader's own tenant: `actor_label` becomes `"server-admin"`, `api_key_id` `null`, `metadata.actor_principal` is dropped; `metadata.actor_tenant_id`/`actor_server_admin` (the inputs of that decision) and every other `actor_*` key (any letter case) are never sent to a tenant-admin, and neither are `is_admin` and `principal_id` inside the `old_value`/`new_value` of `api_key` rows (dropped on every key row — `api-key-list` shows neither). An `api_key` `update` whose only change lies in those two fields is left out of a tenant-admin's answer; the rows are filtered after `limit`, so such a page can hold fewer than `limit` rows while older rows exist — fewer rows than `limit` is not the end of the history. | | `GET /api/events` | **Admin-only** SSE live stream (`text/event-stream`) for the dashboard. The collector diffs its snapshot ONCE per tick and fans `status`/`backends`/`llmcalls` events to every connection; a new connection gets the full state first, then diffs. The pull path additionally carries `guard_review_by_scope` (S6): one four-tuple per scope the CALLER may read, out of the same per-tick generation (0 extra queries), per-credential and therefore never in the shared snapshot or the push frame — the /guard page polls and compares this vector (list and counter run on two different scope predicates: `ReadScopes` vs. home scope) and reloads when it moves; absent section renders '—', never '0'. The `status` frame carries the `guard_review` section (same generation as the pull paths, S2): present-with-zeros means a freshly measured empty queue, an ABSENT section means no fresh generation — and its `built_at` stamp is diff-neutral (zeroed in the diff key like `as_of`), so a walking stamp alone never fires a frame. One tick costs at most ONE frame per event kind: the telemetry rows of a tick ride a single `llmcalls` frame `{rows, count}`, and above `events.llmcall_coalesce_threshold` it degrades to the content-free `{kind:"llmcalls-bulk", count, cursor}` refetch signal (the client reloads over `GET /api/llmlog`) — the same coalescing doctrine `project.events.coalesce_threshold` runs on the domain-event hub. `hb` keepalive event (`CTX_EVENTS_PING_INTERVAL`) carrying `{last_good_at, degraded, health}` — a REAL named event, not an SSE comment, so the client can observe it: `last_good_at` is the newest tick whose DB-backed reads all answered, so a stream that keeps arriving while that stamp freezes means "transport fine, server blind" (`as_of` cannot say this — it advances on failed reads too). The SPA consumes it (S4): the `/status` SSE client arms a payload+transport watchdog (2.5 × ping interval) that flips its state to `stale` when the stamp stops advancing or frames stop entirely — `stale ≠ open` reactivates the page's poll fallback with no call-site change, and a `ConnState` live-region indicator (dot + word, `degraded>0` → `partial`) renders it in the page head. The watchdog is opt-in per stream: `/api/project/events` keeps its comment keepalive and stays unwatched. A rolling 90s write deadline that outlives the absolute server `WriteTimeout`, the `CTX_EVENTS_MAX_CONNECTIONS` cap → 429 (client degrades to polling), and an in-stream re-auth every 12th tick that ends the stream on key revocation. | | `GET /api/project/events` | **Member** SSE domain-event stream (`text/event-stream`, workflow W9) for live board / issue-list updates. A key receives IDS-ONLY frames — `project` events `{kind, project_id, op, block_ids}` or the coalesced `{kind:"issues-bulk", project_id, count}`; NEVER title/content/body (the client refetches over the read API). Frames are **scope-filtered at the fan-out**: only the caller's readable project scopes, never another tenant's. Optional `?project_id=` pins the stream to one project (foreign/unknown ⇒ 404 uniform). Per-**tenant** connection cap (`project.events.max_connections`) → 429; `: ping` keepalive; a 10k-import burst collapses to one `issues-bulk` frame per tick (`project.events.flush_interval` / `coalesce_threshold`). In-stream re-auth recomputes the caller's scope tags from the FRESH read set every ~12 flush ticks: a revoked key or a tenant change ends the stream, and a revoked cross-tenant **scope grant** (tenant/role unchanged) drops that scope's frames — separate from the server-admin telemetry `/api/events`. | @@ -258,10 +258,10 @@ A **model consumer** is an external caller of the models ctx serves (`/v1`, not | Action | Tier | `data` | Answer | |---|---|---|---| -| `model-consumer-create` | self-service | `label`, `description?`, `tenant_id?` (server-admin only), `tenant_scope?`, `kind?` (`app` default, `ctx-peer`), `all_models?`, `models?` (model alias ids to grant), `prompt_sensitivity?`, `fair_weight?`, `admission_lane?`, `allowed_cidrs?`, `allow_plaintext?`, `expires_at?`, `limits?` (starting limits per op, see below) | `{consumer, api_key, effective_limits}` — the consumer with its first key, the key's plaintext **once** | +| `model-consumer-create` | self-service | `label`, `description?`, `tenant_id?` (server-admin only), `tenant_scope?`, `kind?` (`app` default, `ctx-peer`), `all_models?`, `models?` (model alias ids to grant), `prompt_sensitivity?`, `fair_weight?`, `admission_lane?`, `allowed_cidrs?`, `allow_plaintext?`, `record_bodies?` (server-admin only, with `confirm_record_bodies: true` — see below), `expires_at?`, `limits?` (starting limits per op, see below) | `{consumer, api_key, effective_limits}` — the consumer with its first key, the key's plaintext **once** | | `model-consumer-list` | tenant-admin | `tenant_id?` (server-admin only), `status?`, `q?`, `cursor?`, `limit?` | `{consumers, next_cursor}` | | `model-consumer-get` | tenant-admin | `id` | `{consumer, keys_truncated, audit, effective_limits}` | -| `model-consumer-update` | tenant-admin | `id` + any of `label`, `description`, `tenant_scope` (null = `_global` backends only), `all_models`, `models` (the granted model alias ids — the whole target set; `[]` = none), `prompt_sensitivity`, `fair_weight`, `admission_lane`, `allowed_cidrs` (null = any source), `allow_plaintext`, `active` | `{consumer}` | +| `model-consumer-update` | tenant-admin | `id` + any of `label`, `description`, `tenant_scope` (null = `_global` backends only), `all_models`, `models` (the granted model alias ids — the whole target set; `[]` = none), `prompt_sensitivity`, `fair_weight`, `admission_lane`, `allowed_cidrs` (null = any source), `allow_plaintext`, `record_bodies` (switching on: with `confirm_record_bodies: true`), `active` | `{consumer}` | | `model-consumer-delete` | tenant-admin | `id` | `{cancelled_inflight}` | | `model-key-rotate` | self-service | `consumer_id`, `grace?` (seconds), `expires_at?` | `{key, api_key}` — the new key and its plaintext **once** | | `model-key-revoke` | tenant-admin | `key_id` | `{cancelled_inflight}` | @@ -269,7 +269,9 @@ A **model consumer** is an external caller of the models ctx serves (`/v1`, not **Tiers.** *self-service* is the stage `tierSelfService` of the dispatch table: a server-admin, or a tenant-admin of its own tenant only while `gateway.enabled` **and** `gateway.tenant_self_service` are on (both ship off: server-admin only). *tenant-admin* is a server-admin or a tenant-admin of the consumer's tenant; a member gets `403` on all eight. Every tier refusal is the shared `403 admin key required` ([security](security.md#admin-tier)). -**Field rule — revoking is always allowed, granting needs a release.** On `model-consumer-update` each field is compared with the consumer as it stands (under its row lock, so a concurrent write is what the comparison sees): narrowing `allowed_cidrs` (a list whose every prefix lies inside a current one, or a list where there was none), `tenant_scope` → null, `all_models` → false, `allow_plaintext` → false, a higher `prompt_sensitivity`, a lower `fair_weight`, `admission_lane` `urgent` → `bulk`, deactivating (`active` false), `label` and `description` — always open to a tenant-admin. Removing an id from `models` is revoking too. Setting or changing `tenant_scope`, `all_models` true, adding an id to `models`, widening or removing `allowed_cidrs` and reactivating are **granting**: tenant-admin only with self-service. `kind = ctx-peer` (create), a lower `prompt_sensitivity`, `allow_plaintext = true`, a higher `fair_weight` and `admission_lane = urgent` stay **server-admin even with self-service**; on create they are measured against the defaults (`app`, `credentials`, `1`, `bulk`, no plaintext). **Peer row tier:** every granting change of a `ctx-peer` consumer — rotation, a granting update, reactivation — is server-admin only. `kind` is fixed at create; `tenant_id`, the peer binding and any key expiry cannot be updated — an unknown field is a `400`, `expires_at` included (a new expiry needs a new key: `model-key-rotate`). +**Field rule — revoking is always allowed, granting needs a release.** On `model-consumer-update` each field is compared with the consumer as it stands (under its row lock, so a concurrent write is what the comparison sees): narrowing `allowed_cidrs` (a list whose every prefix lies inside a current one, or a list where there was none), `tenant_scope` → null, `all_models` → false, `allow_plaintext` → false, a higher `prompt_sensitivity`, a lower `fair_weight`, `admission_lane` `urgent` → `bulk`, deactivating (`active` false), `label` and `description` — always open to a tenant-admin. Removing an id from `models` is revoking too. Setting or changing `tenant_scope`, `all_models` true, adding an id to `models`, widening or removing `allowed_cidrs` and reactivating are **granting**: tenant-admin only with self-service. `kind = ctx-peer` (create), a lower `prompt_sensitivity`, `allow_plaintext = true`, a higher `fair_weight`, `admission_lane = urgent` and `record_bodies = true` stay **server-admin even with self-service**; on create they are measured against the defaults (`app`, `credentials`, `1`, `bulk`, no plaintext, no recording). `record_bodies` → `false` is revoking, open to a tenant-admin. **Peer row tier:** every granting change of a `ctx-peer` consumer — rotation, a granting update, reactivation — is server-admin only. `kind` is fixed at create; `tenant_id`, the peer binding and any key expiry cannot be updated — an unknown field is a `400`, `expires_at` included (a new expiry needs a new key: `model-key-rotate`). + +**Recording** (`record_bodies`, migration 197, issue #571). With `record_bodies: true` every gateway row of the consumer keeps its request and answer **in full** — whatever `gateway.body_logging`, the alias, `prompt_sensitivity`, the body scan or `Ctx-Sensitivity` say, without the 64 KiB cut, credentials in a prompt included — and is marked `metadata.gw.recorded` ([telemetry](#telemetry--logging), [security](security.md#gateway-telemetry-v1-v2)). Switching it on (create, or update from `false`) needs `confirm_record_bodies: true`, else `400` with `record_bodies:true stores every request and answer of this consumer in full in the LLM log — credentials in a prompt included, in clear text, readable by server-admins — requires confirm_record_bodies:true`; the tier check comes first, so a tenant-admin gets the shared `403 admin key required` with or without the confirmation. Sending the value a consumer already has is no change (no tier, no confirmation); `confirm_record_bodies` alone changes nothing; `null` is a `400`. Every change is an audited `update` row (`record_bodies` in `old_value`/`new_value`). A switch applies from the consumer's next request (the door reads it with the key, migration 197's `ctx_model_auth` column); a request already running keeps what it was admitted with. **Model grants** (`models`, migration 164). `all_models: true` releases every model alias the consumer can see; otherwise only the aliases listed in `models` — by **id**, never by name: a deleted alias takes its grants with it, and an alias created later under the same name is granted to no one. `models` is a target set (duplicates and spellings are folded, the answer lists them sorted; on update `null` is a `400` and `[]` removes every grant; on create `null`, `[]` and an absent field all mean none); the server turns it into the grants to add and to remove, in the transaction of the update. Every id it **adds** must be one the consumer's own `tenant_scope` is offered — an enabled alias with a valid policy, `_global` or of that scope, and not a `_global` alias that a tenant alias of the same name (enabled or not) takes the place of; a consumer without `tenant_scope` is offered `_global` aliases only, and so is a `ctx-peer` consumer whatever its `tenant_scope` — a peer resolves model names against `_global` aliases only. The caller's own scope plays no part. Any other id — unknown, deleted, disabled, invalid, of another scope, shadowed — is `400` with `"param": "models"` and one text for all these reasons (a malformed id is a `400` at `models` as well); when the scope changes in the same update, the new scope decides. An id the consumer already holds is not judged again, so a grant stays when its alias is disabled later or a later `tenant_scope` change hides it — it then releases nothing (the request time checks visibility again). The list is judged against the server's in-memory alias catalog, which follows an alias write within moments; an alias created a moment ago may still be a `400`. Without the catalog (a wiring fault) a `models` write that adds an id is `503`; removing grants still works. Deleting an alias that an **active** consumer holds an explicit grant on is `409` with `"code": "model_granted"` and `"count"` — the number of such consumers, never who they are; `all_models` is no grant and does not count. Remove the alias from their `models`, or deactivate them, first; grants of inactive consumers go with the alias. A held grant that its consumer can no longer see — its alias was disabled, or a later `tenant_scope` change hid it — releases nothing but still counts for this `409` until it is removed from `models` (or the consumer is deactivated). The SPA's create dialog (`/gateway`, wave W05-06) is a client of exactly this rule: it offers the aliases of the chosen `tenant_scope` the way the server's offer does (enabled ones, a tenant alias in place of the `_global` one of the same name, shadowing by presence), sends the picked **ids** as `models` (or `all_models: true`), never sends `kind`, and shows a `400` at `models` in the dialog. @@ -281,7 +283,7 @@ A **model consumer** is an external caller of the models ctx serves (`/v1`, not **Reveal-once.** `api_key` — the plaintext — appears in the answer of `model-consumer-create` and `model-key-rotate` and nowhere else; no answer carries a key hash. `cancelled_inflight` is the number of requests on the revoked key (`model-key-revoke`) or on any key of the deactivated consumer (`model-consumer-delete`) that were running in **this** ctx process and are ended by the action (`0`: none ran here). Another ctx process on the same database ends its own through the database signal (migration 165) and is not counted. It is `null` only on a server without the model API's door (unknown — never a `0` that would claim no request ran). Only these two actions end running requests themselves and count them: `model-key-rotate` (the keys it revokes, and with `grace: 0` its predecessor) and `model-consumer-update` with `"active": false` end the requests of what they revoke through the database signal after their commit — within milliseconds while the server's listener is connected, at the latest at the next `gateway.inflight_sweep_interval` sweep while it is away — and answer no `cancelled_inflight`. -**Reading.** A consumer reads as `{id, tenant_id, tenant_slug, label, description, kind, tenant_scope, all_models, models, prompt_sensitivity, fair_weight, admission_lane, allowed_cidrs, allow_plaintext, active, status, last_used_at, created_at, created_by_label, keys, keys_total, peer}`; a key as `{id, hint, status, created_at, expires_at, revoked_at, rotated_from, last_used_at}`. `status` of a consumer: `inactive`; `no_key` (no live key); `rotating` (two live keys); `expiring` (one live key expiring within `gateway.key_expiry_warn`, 14 d); `active`. Of a key: `revoked` ≻ `expired` ≻ `superseded` (live, but a newer live key exists — its grace runs) ≻ `expiring` ≻ `active`. The server computes both; a client never judges expiry by its own clock. `peer` (`{instance_id, bound_at}`) is null without a binding and for every reader below server-admin; `created_by_label` reads `"server-admin"` to a tenant-admin unless the creating key is a non-server-admin key of its own tenant, and is null once the creating key is deleted. `last_used_at` has 60 s resolution. +**Reading.** A consumer reads as `{id, tenant_id, tenant_slug, label, description, kind, tenant_scope, all_models, models, prompt_sensitivity, fair_weight, admission_lane, allowed_cidrs, allow_plaintext, record_bodies, active, status, last_used_at, created_at, created_by_label, keys, keys_total, peer}` (`record_bodies` for every reader, tenant-admins included); a key as `{id, hint, status, created_at, expires_at, revoked_at, rotated_from, last_used_at}`. `status` of a consumer: `inactive`; `no_key` (no live key); `rotating` (two live keys); `expiring` (one live key expiring within `gateway.key_expiry_warn`, 14 d); `active`. Of a key: `revoked` ≻ `expired` ≻ `superseded` (live, but a newer live key exists — its grace runs) ≻ `expiring` ≻ `active`. The server computes both; a client never judges expiry by its own clock. `peer` (`{instance_id, bound_at}`) is null without a binding and for every reader below server-admin; `created_by_label` reads `"server-admin"` to a tenant-admin unless the creating key is a non-server-admin key of its own tenant, and is null once the creating key is deleted. `last_used_at` has 60 s resolution. - `model-consumer-list` lists newest first. `status` is a list of the five statuses or `["all"]`; absent = the four statuses of an active consumer. `q` is a label prefix (case-insensitive, `%` and `_` literal). `limit` defaults to and is capped at `gateway.consumer_list_max_limit` (100); `next_cursor` is the opaque token of the next page, `null` on the last; a malformed cursor is a `400` (it is opaque, not signed: a well-formed one only moves the keyset position within the caller's own reach). Every filter runs in SQL — a page of inactive consumers never hides the active ones behind it. The list carries the live keys only; `keys_total` counts the whole chain. The SPA's `/gateway` list ([multi-tenancy](multi-tenancy.md#admin-tiers)) is a client of exactly this form: it sends the status set explicitly (`["all"]` for all five), sends no `limit` (its page size is the server's cap), hands `next_cursor` through untouched and renders `status` as received. - `model-consumer-get` adds the chain (newest first, at most `gateway.consumer_chain_max` = 50; `keys_truncated` says more exist) and the **audit trail**: the newest `gateway.consumer_audit_trail_max` (20) rows of `model_consumer`, `model_key` and `gateway_limits` whose entity is the consumer or a key of the returned chain (older keys' rows need `GET /api/audit?entity=model_key&id=…`), each with its `entity_type`, redacted for a tenant-admin exactly as `GET /api/audit` redacts ([security](security.md#audit-trail)) — the cap applies before the redaction leaves out invisible updates, so a trail may hold fewer rows than the cap. @@ -846,7 +848,7 @@ The contract every gateway route writes against (`llmlog.GatewayEntry` / `llmlog - **One LLM-log row per request.** Chat, streamed chat, embeddings and rerank each write exactly one `context_llm_log` row, failover included: `attempt` is the number of physical attempts, `metadata.chain` lists them. Pipelines are `gateway-chat`, `gateway-embeddings` and `gateway-rerank`. - **Attribution.** The row names the consumer in `consumer_id`; `api_key_id` is always `NULL` (a row with both is refused by the database). `metadata.gw` (version 1) carries `v`, `op` (`chat`/`embed`/`rerank`), `alias`, `stream`, `hop` (0–16), `claimed_chain` (display only), `peer_pipeline` (ctx peers), `usage` (`backend`/`estimated`), `ttft_ms` (streams), `client_req_id` (`[A-Za-z0-9._:-]{1,128}`, else dropped), `finish` (`stop`, `length`, `tool_calls`, `content_filter`, `error`, `aborted`) and `model_key_id` — never an origin and never a second copy of the consumer. The hourly usage rollup counts such rows as `source = 'gateway'` with the alias. -- **Bodies.** `gateway.body_logging` (global-only, hot): `none` (default) stores no prompt and no answer (`''`, shown as `bodyless`), `errors` stores the serialized request and the answer only on rows with an error, `full` on every row (a streamed answer is not stored yet — its row carries the request only); each body is capped at 64 KiB with a visible truncation marker. A credentials-class row stays `sealed` under every policy — a tenant's `tenant.devmode` does not open it — and a row with an empty or unknown sensitivity stores no body either. +- **Bodies.** `gateway.body_logging` (global-only, hot): `none` (default) stores no prompt and no answer (`''`, shown as `bodyless`), `errors` stores the serialized request and the answer only on rows with an error, `full` on every row (a streamed answer is not stored — its row carries the request only); each body is capped at 64 KiB with a visible truncation marker. A credentials-class row stays `sealed` under every policy — a tenant's `tenant.devmode` does not open it — and a row with an empty or unknown sensitivity stores no body either. **A recording consumer's rows** (`record_bodies`, see [model consumer administration](#model-consumer-administration)) are the one exception: whatever the policy and the class, the row stores the request whole (chat: the message array; embeddings: the `input`; rerank: the query, a line break and the documents) and the answer whole (a non-streamed chat answer as the client received it; a stream: its `data:` lines as relayed, in order, without the closing `[DONE]` or error frame; embeddings and rerank: none — the vectors and scores are not kept), with `metadata.gw.recorded: true`. A text the process's recording account (128 MiB, [operations](operations.md#recording-a-consumer)) cannot take is left out and named: `metadata.gw.record_lost` (`["request"]`, `["response"]` or both) with `record_lost_cause` `memory`; the shutdown's forced row of a request still open names both with cause `shutdown`. - **Errors.** The `error` column of a gateway row is ` ` (for example `bad_request 400 upstream_rejected`) — never the upstream response body, which can echo the prompt. - **Access log.** One INFO line `gateway request` per successful request (`consumer_id`, `model_key_id`, `tenant_id`, `op`, `alias`, `status`, `stream`, token counts, `usage`, `duration_ms`, `queue_wait_ms`, `class`, `hop`, `request_id`), on while `gateway.access_log` is `true` (default); a client that left before the handler returned is logged with `status=499` and the handler's status in `handler_status` — `0` when it wrote nothing — (at WARN with `waited_for=admission` when it left while waiting for an admission slot) (see [operations](operations.md#requests-the-client-gave-up-on)). Refusals (status ≥ 400) are never logged per request: they are counted per consumer (empty before authentication) and reason — for a refusal the [refusal ledger](#refusal-ledger) counts its `reason`, with the window's details in `detail`; otherwise the error code of the gateway or the model-key door, else `http_` — and written as at most one WARN line `gateway rejections` with `count` and `window="1m"` per minute — the flag's `404` and the door's `401` included. The global `http request` line is not written for these requests: each gateway request is one line or one count. @@ -860,7 +862,7 @@ Read surfaces of the model API's usage, mounted with `/api/llmlog` behind **admi - **`null` is not `0`.** A bucket before the rollup's coverage (its first hour, or the hour migration 159 was applied) is `complete: false` with every counter `null`; a covered bucket without traffic is a real `0` with `complete: true`; the running bucket carries its partial values with `complete: false`. `rejected` is `null` for buckets before the refusal ledger existed (migration 167) and `[]` for a covered bucket without refusals. A percentile without samples is `null`, never `0`. - **Tenant-admin view.** Only the rows of the tenant's own model consumers: `?consumer=` is checked with a single-row membership query, and a foreign or unknown id answers `200` with no series — the same as a consumer without traffic, so the answer is no existence oracle. Internal rows (knowledge keys, background pipelines), refusals before the model-key door (`auth`, no consumer) and the refusal fields `target`/`dispatch_class` never appear; `group=instance` is `403`. - **`GET /api/usage/consumers`.** One entry per visible consumer and operation: `limits{server, tenant, defaults, effective}`, `day`/`month` `{used, limit, reset_at}` (UTC calendar windows), `cost_month{used_usd, limit_usd}`, `binding` (`consumer`, `tenant` or `instance` — the level with the least headroom), `live{reservations, inflight, rpm_remaining, tpm_remaining}` from the meter (no database read; `null` until the meter's boot seed has read the rollup — the meter is seeded at boot whether or not the gateway is enabled), `last_bucket` (newest hour with traffic in the last 30 days), `rejections_24h` and `usage_24h` (the 24 hourly buckets up to and including the running one). The rollup part is one batch per tenant, cached for 30 seconds — two polls within 30 seconds cost one statement. A tenant-admin sees the instance envelope only as `binding: "instance"`, without its values. -- **`GET /api/status` sections (model API).** While `gateway.enabled` is on, a server-admin's status carries `gateway` (`enabled`, `consumers`, `consumers_used_1h`, `consumers_expiring` — a live key expiring within `gateway.key_expiry_warn` —, `top_consumers_1h` from an in-memory ring of one-minute buckets, `auth` = the model-key door's counters, among them the in-flight registry's `inflight`, `inflight_keys`, `inflight_timers`, `inflight_cancelled`, `inflight_sweeps` and `inflight_sweep_errors` — every key of these sections is snake_case —, `events` = the usage-event recorder's counters, `generated_at`; `reservations_open` and `rejections_5m` are `null` until the meter and the in-memory ledger feed them), `usage_split_24h` (`[{target, source, class, calls, gpu_ms}]` over the last 24 hourly buckets) and `federation` (`header_ignored`, `peer_without_path`, `stamp_without_identity` since process start, `peer_bound` from the event recorder, and `loop_rejects`, `depth_rejects`, `header_invalid`, `peer_mismatch`, `busy` from the refusal ledger over the last 24 hourly buckets; `embed_space_rejects` has no ledger detail and stays `null`). A tenant-admin's status carries `gateway` with its own consumers only — no `auth`, `events`, `usage_split_24h` or `federation`. The counts come from one database read at most every 30 seconds, never from the raw log; the sections are per caller on `GET /api/status` and are not part of the `/api/events` stream. With the gateway off the sections are absent. +- **`GET /api/status` sections (model API).** While `gateway.enabled` is on, a server-admin's status carries `gateway` (`enabled`, `consumers`, `consumers_used_1h`, `consumers_expiring` — a live key expiring within `gateway.key_expiry_warn` —, `recording_consumers` — the ids of the active consumers with `record_bodies` on, sorted, `[]` when none —, `top_consumers_1h` from an in-memory ring of one-minute buckets, `auth` = the model-key door's counters, among them the in-flight registry's `inflight`, `inflight_keys`, `inflight_timers`, `inflight_cancelled`, `inflight_sweeps` and `inflight_sweep_errors` — every key of these sections is snake_case —, `events` = the usage-event recorder's counters, `generated_at`; `reservations_open` and `rejections_5m` are `null` until the meter and the in-memory ledger feed them), `usage_split_24h` (`[{target, source, class, calls, gpu_ms}]` over the last 24 hourly buckets) and `federation` (`header_ignored`, `peer_without_path`, `stamp_without_identity` since process start, `peer_bound` from the event recorder, and `loop_rejects`, `depth_rejects`, `header_invalid`, `peer_mismatch`, `busy` from the refusal ledger over the last 24 hourly buckets; `embed_space_rejects` has no ledger detail and stays `null`). A tenant-admin's status carries `gateway` with its own consumers only (`recording_consumers` included) — no `auth`, `events`, `usage_split_24h` or `federation`. The counts come from one database read at most every 30 seconds, never from the raw log; the sections are per caller on `GET /api/status` and are not part of the `/api/events` stream. With the gateway off the sections are absent. - **`GET /api/llmlog?consumer_id=`.** The list now carries `consumer_id` on every row (`null` for knowledge-key and background rows). A tenant-admin's list is the union of two bounded reads — its knowledge keys and its model consumers, each limited to the last 30 days — and `consumer_id=` narrows to one of its own consumers (a foreign id: no rows). A server-admin's list is unchanged and `consumer_id=` narrows it. The detail `GET /api/llmlog/{id}` of a consumer row answers a tenant-admin with the uniform `404`. ### Quota warnings and usage events diff --git a/docs/operations.md b/docs/operations.md index 5a8eaba5e..a358faf0f 100644 --- a/docs/operations.md +++ b/docs/operations.md @@ -542,7 +542,10 @@ chunk exclusion. The JSON summary on stderr (always printed, also on failure) carries `rows_total`, `rows_body`, `rows_bodyless_slim` (credentials-class rows whose bodies were slimmed to `''`), -`rows_bodyless_null` (bodies NULLed by retention), `count_gate`, `bytes` (what was actually +`rows_bodyless_null` (bodies NULLed by retention), `rows_recorded_sealed` (rows of a recording +consumer, and fail-closed every gateway row without a readable `metadata.gw` marker, written with +their bodies sealed — they count in `rows_bodyless_slim`/`rows_bodyless_null` too, see +[Recording a consumer](#recording-a-consumer)), `count_gate`, `bytes` (what was actually flushed — valid even after a cancel), `watermark` + `watermark_id` (the last row). A delta run continues **exactly** behind the previous run with `-since -since-id `; `-since` alone is inclusive and re-exports every row sharing the watermark's `created_at`. @@ -971,8 +974,39 @@ Every LLM call ctx makes writes one row to `context_llm_log` (the telemetry behi - **Throttle.** At most **4** inserts run at once; further rows wait in a queue of at most **4 096** rows. Both numbers are fixed in the code (`internal/llmlog`): they bound ctx's own bookkeeping, not a policy anyone tunes. Before this, every row got its own goroutine and connection, so a slow database let a burst take all 20 connections. - **Losses are counted, not silent.** A row the full queue cannot take is dropped; an insert the database refuses (or that runs past its 5 s deadline) is lost. Both are counted since process start and shown to a server-admin on `GET /api/status` as `"llmlog": {"insert_failures": N, "insert_dropped": M}` — present at `0/0` too, so a zero means "nothing lost", not "not measured". The section is absent on a tenant-admin's view: the counters cover every tenant and the background. In the log, the first loss raises one `WARN` (`llmlog: insert failed, row lost` or `llmlog: insert queue full, row dropped`, with `insert_failures_total`/`insert_dropped_total`), and at most one more per minute after that however many rows are lost; every failure still has its `DEBUG` line. A rising `insert_failures` usually means the database is unreachable or `context_llm_log` is broken (missing table, failing trigger); a rising `insert_dropped` means the queue stayed full — the database has been slow or unreachable for long enough to back up 4 096 rows. - **Shutdown settles the queue, twice.** On `SIGTERM` ctxd stops HTTP (up to 15 s), settles the model gateway's meter reservations still open after that drain with their estimate and queues their request's row (up to 1 s, in memory; `gateway: open meter reservations settled with their estimate at shutdown` with the count — so the next start's budget seed counts what those requests used), writes the refusal ledger's last counts ([Migration 167](#migration-167-the-refusal-ledger-of-the-model-api); up to 5 s, `gateway: refusal ledger flushed at shutdown` in the log), ends the model gateway's loops with their final flush (up to 5 s, alongside the next step; a model key whose row another transaction holds at that moment — a rotation, a deactivation, a prune — keeps its `last_used_at` stamp pending, and the flush retries it every 100 ms for up to 4 s; stamps still unwritten then are counted in `WARN gateway: last_used_at stamps of model keys left unwritten at shutdown` with `stamps=N` — after a failed attempt an upper bound; should the gateway's own 5 s run out first, the older `WARN gateway: final flush incomplete at shutdown` appears instead, without a count) and waits up to **5 s** for every queued and running llmlog insert (the [read record](#the-read-record-in-context_access_log)'s queue settles alongside, within the same 5 s); then it waits for the scheduler to finish its running work, and settles the queue once more (up to 5 s) before it closes the pool. The first settle exists because the scheduler wait has no limit: a dream cycle that is running when the signal arrives is not cancelled, it runs to its end or to `dream.cycle_timeout` (700 s by default). If that outlasts the stop grace period, Docker kills ctxd during the wait — the HTTP side's rows have had their settle by then, and only the rows still queued from the scheduler are lost. The log says which way each settle went: `llmlog: settled at shutdown` (with `after=http` or `after=scheduler`, the elapsed time and the loss totals) or `WARN llmlog: settle at shutdown incomplete, pending rows are lost`. +- **Recorded rows** ([Recording a consumer](#recording-a-consumer)) take the same queue and the same counters: a recorded row the full queue cannot take is dropped whole and counted in `insert_dropped` like any row — nothing in the counter or the `WARN` line says that it was a recorded one or whose; a recorded row the database refuses is in `insert_failures`. - **`stop_grace_period`.** Docker waits 10 s between `SIGTERM` and `SIGKILL` unless told otherwise — too short for the 15 s HTTP drain alone. The shipped `docker-compose.yml` sets `stop_grace_period: 36s` on the `ctx` service: 15 s HTTP drain + 1 s forced meter settle + 5 s refusal ledger flush + 2 × 5 s llmlog settle = 31 s, plus 5 s margin for the scheduler wait; the model gateway's final flush (the batched `last_used_at` stamps of model keys and the last `gateway rejections` lines, at most 5 s — of it at most 4 s of retries while a key row is locked —, measured in milliseconds; `gateway: usage stamps and rejection counts flushed at shutdown` in the log, or the `WARN` with the count of stamps left unwritten) runs alongside the first settle and adds nothing. A test pins it at 31 s or more (25 s before the refusal ledger, 30 s before the forced meter settle). Keep it at least that long in your own compose file, and raise it if you raise the shutdown budget or want a running dream cycle to finish rather than be killed. +### Recording a consumer + +A server-admin can make one model consumer's gateway rows keep their request and answer **in full** (migration 197, issue #571) — for example to rebuild what a client sent from the rows it leaves: + +```bash +ctx manage model-consumer-update '' '{"id":"","record_bodies":true,"confirm_record_bodies":true}' +``` + +(The consumer's `id` goes into `data`; `model-consumer-create` takes the same two fields.) From the consumer's next request on, every gateway row of its own stores the whole request and the whole answer, whatever `gateway.body_logging`, the alias, the consumer's `prompt_sensitivity`, the body scan or `Ctx-Sensitivity` say ([api — Telemetry & logging](api.md#telemetry--logging)); a request already running keeps what it was admitted with. The request path is the same with and without the switch, and no other consumer's rows change. Switching off is `"record_bodies": false` — a tenant-admin of the consumer's tenant may do that too. The consumer view (API, CLI `--json`, `/gateway` in the SPA) shows the switch to every reader; `GET /api/status` lists the recording consumers in `gateway.recording_consumers`. + +**What the rows can hold.** Everything the client sent: a password, a token or a private key in a prompt is stored in clear text. The row is marked `metadata.gw.recorded = true`; its bodies are for a server-admin only ([security](security.md#gateway-telemetry-v1-v2)) — `GET /api/llmlog/{id}` as server-admin, or psql. `ctx-llmlog-export` writes such rows with their bodies sealed (below). A database backup carries them like every other content of the database. + +**Reading a consumer's rows out** (psql, in order; `request_user` is the message array of a chat request, the `input` of an embeddings request, the query, a line break and the documents of a rerank request; `response_content` the answer of a chat request — a stream's `data:` lines): + +```sql +SELECT created_at, pipeline, metadata->'gw'->>'finish' AS finish, request_user, response_content, + metadata->'gw'->'record_lost' AS lost + FROM context_llm_log + WHERE consumer_id = '' AND metadata->'gw'->>'recorded' = 'true' + ORDER BY created_at, id; +``` + +The predicate rides `idx_llm_log_consumer` (migration 158). Rows of requests the gateway refused before the route (`401`, `429`, a limit) are not rows at all — they are only counted in `context_llm_rejections_hourly`. + +**Size and memory.** No cut: a request text is at most twice `gateway.max_request_bytes` (8 MiB; an invalid byte is stored as U+FFFD), a non-streamed chat answer is the answer the client received (its upstream read is capped by `gateway.max_response_bytes`, 4 MiB), a stream's answer grows with the stream. The texts are held against one process-wide account of **128 MiB** (fixed in the code, `internal/llmlog`, like the writer's queue bound) from the moment the route captures them until the row is inserted — never against `gateway.inflight_budget`, so recording books nothing on the request path; the container (1536 MiB) holds the default budget of 512 MiB, this account, the writer's copy of the rows being inserted (4 at a time) and the base. A text the account cannot take — many large recorded requests at once, or a slow database that keeps rows queued — is not captured: the row is written without it and says so (`metadata.gw.record_lost: ["request"]` or `["response"]`, `record_lost_cause: "memory"`), and `GET /api/status` counts such rows in `llmlog.recorded_bodies_lost`. Measured on the test image: a row of 16 MiB request text and 24 MiB answer is inserted in 256 ms (compressible text, stored in 161 KiB) and 360 ms (incompressible, 40 MiB), against the insert's 5 s deadline. Embedding vectors and rerank scores are not stored (the request is the record). A request still open when the shutdown's forced settle writes its row gets a row without bodies (`record_lost` both, cause `shutdown`). + +**Retention.** Recorded bodies are NULLed after `scheduler.llmlog_retention_days` (90 days) like every other body; the row and its marker stay. Export or read them out before that if they are needed longer. + +**Export.** `ctx-llmlog-export` leaves every recorded row's bodies sealed (`''`; a body retention already NULLed stays `null`) and counts the rows in `rows_recorded_sealed`; it does the same, fail-closed, for a gateway row whose `metadata.gw` is missing or does not read as an unrecorded call. The query above is the way to read them. + ### Upgrading to 5.33.1: the image's `GOMEMLIMIT` is 768MiB The image sets `GOMEMLIMIT=768MiB` (it was `200MiB`): the gateway's in-flight budget default of 512 MiB (5.33.0) plus the process's own base, measured idle at 21–32 MiB. The shipped `docker-compose.yml` gives the `ctx` service `memory: 1536M`, which holds that soft limit with room for the runtime's overshoot. **An own compose file (or an older copy of the shipped one) that still caps the container at 512M or 1G must raise the limit before this image runs** — a Go soft limit above the cgroup hard limit means the kernel kills the container under load while the collector still believes it has room. Either raise `memory:` to at least 1536M, or size the pair for the smaller container: set `GOMEMLIMIT` in the service's `environment:` (it beats the image's `ENV`) to about the container limit minus 128 MiB, and `CTX_GATEWAY_INFLIGHT_BUDGET` to at most that value minus the base — V39 refuses a budget under the floor (257 MiB at the default caps), so a 512M container cannot hold the default caps and needs `CTX_GATEWAY_MAX_REQUEST_BYTES` lowered as well. Check with `docker inspect ctx --format '{{.HostConfig.Memory}}'` against `docker inspect ctx --format '{{range .Config.Env}}{{println .}}{{end}}' | grep GOMEMLIMIT`. @@ -2331,6 +2365,14 @@ Issue #289. The Hermes plugin `ctx_checkpoint` stores, with `memory: true`, sess **The plugin's recall sends a second query.** With `memory: true`, once a server took a digest or fact write naming the type, the recall of plugin 0.19.0 follows each of its queries with a second retrieval-only query that sees only `session-digest` blocks (`prefetch_session_digest_results`, default 3, `0` turns it off): one more `/api/query` (over MCP one more `query` call) per recalled turn against the key's read rate limit and the tenant's query quota. The question's embedding is cached for it when the first embed backend is shareable (`_global` or no scope); a tenant's own embed backend embeds it again. Over REST the plugin reads `type-list` once per client for it. +### Migration 197: the recording switch of a model consumer + +Issue #571. `context_model_consumers.record_bodies BOOLEAN NOT NULL DEFAULT false` — every consumer reads `false` after the upgrade, nothing records until a server-admin switches it on ([Recording a consumer](#recording-a-consumer)). The audit projection `audit_state_model_consumer` and the trigger `trg_model_consumers_audit_upd` gain the column, so every switch is an `update` row of `model_consumer` and every later audit row of a consumer carries the key `record_bodies` (older rows stay as written). `ctx_model_auth` gains `record_bodies` as its last column; the result type changes, so the migration drops and creates the function in its transaction. + +**Locks.** `ADD COLUMN` with a constant default rewrites nothing: `ACCESS EXCLUSIVE` on `context_model_consumers` until the commit (the table holds at most `max_model_consumers`, 64 by default, rows per tenant) — milliseconds during which a `/v1` door check (`ctx_model_auth` reads the table) and every consumer write of another ctx process on the same database wait. `CREATE TRIGGER` takes `SHARE ROW EXCLUSIVE` on the same table inside that window; dropping and creating the function locks no table, a session calling it meanwhile uses the old definition until the commit. `lock_timeout 3s` fails the boot instead of queueing behind a long transaction; the next start retries. + +**Rolling deploy and way back.** The release before (v5.89.0) runs unchanged on a database with 197 (executed: its auth, model-key door, consumer administration and `/v1` chat-row tests over a schema with 197): its door selects `ctx_model_auth`'s columns by name and does not see the new one, its consumer writes leave the column at its default, and its rows of a recording consumer are written as before — sealed or capped by `gateway.body_logging`, without the marker. Its schema-contract check reports the unknown migration as for every release ahead of it (`schema_contract: attention`; mode `enforce` refuses to start). The way back, in this order: `DROP FUNCTION ctx_model_auth(TEXT, INET, BOOLEAN);` the `CREATE OR REPLACE FUNCTION ctx_model_auth` of migration 161 (section 8); the `CREATE OR REPLACE FUNCTION audit_state_model_consumer` of 161 (section 7); `DROP TRIGGER trg_model_consumers_audit_upd ON context_model_consumers;` and the `CREATE TRIGGER trg_model_consumers_audit_upd` of 161; `ALTER TABLE context_model_consumers DROP COLUMN record_bodies;` `DELETE FROM _migrations WHERE version = 197;` — `TestMigration197Idempotent` runs exactly these and compares the catalog with 196's. Recorded rows already written keep their bodies and marker until the retention. + ### `graph_overview.csr_loader`: the rebuild's input substrate `CTX_GRAPH_OVERVIEW_CSR_LOADER` (default `false`, hot) switches how the rebuild gets its graph into memory. It changes no result — the partition, the modularity and the intra-cluster degrees are byte-identical either way, and that identity is a gate, not a hope. diff --git a/docs/security.md b/docs/security.md index ca071b168..49fa998fe 100644 --- a/docs/security.md +++ b/docs/security.md @@ -8,7 +8,7 @@ How the system defends itself is below. How to **report** a vulnerability — pr **Rationale.** Before this gate, ANY valid key of any `home_scope` could mint keys for arbitrary scopes — read access to foreign tenants — and the settings/secrets API must not inherit that model. The per-tenant admin tier (owner/admin/member) that layers on top is documented in [multi-tenancy](multi-tenancy.md#admin-tiers). -**Self-service stage (`tierSelfService`, W01-5).** The model consumer actions that grant a new credential — `model-consumer-create` and `model-key-rotate` — carry a fourth stage in the dispatch table: server-admin, and a tenant-admin of its own tenant only while `gateway.enabled` **and** `gateway.tenant_self_service` are on (both default off; a missing config snapshot counts as off). The switch is a setting, so it cannot be a payload-shaped tier function; as a stage of its own the lock sits in the pinned table, and the handlers check the same switch a second time. With the gateway off nobody below server-admin grants anything, whatever the self-service switch says (dark launch). The refusal is the shared `403 admin key required` — no tier, switch or field oracle. Inside `model-consumer-update` the rule is **revoking is always allowed, granting needs a release** ([api](api.md#model-consumer-administration)): narrowing a consumer stays open to tenant-admins; widening it needs self-service; `kind = ctx-peer`, a lower `prompt_sensitivity` (egress of foreign prompts to less trusted backends), `allow_plaintext = true` (credential transport without TLS), a higher `fair_weight` and `admission_lane = urgent` (the GPU is a host-global good) stay server-admin with self-service on. **Peer row tier:** any granting change of a `ctx-peer` consumer is server-admin only. The comparison runs against the row under its lock, so a concurrent server-admin write cannot be undone by a tenant-admin re-submitting the old value. +**Self-service stage (`tierSelfService`, W01-5).** The model consumer actions that grant a new credential — `model-consumer-create` and `model-key-rotate` — carry a fourth stage in the dispatch table: server-admin, and a tenant-admin of its own tenant only while `gateway.enabled` **and** `gateway.tenant_self_service` are on (both default off; a missing config snapshot counts as off). The switch is a setting, so it cannot be a payload-shaped tier function; as a stage of its own the lock sits in the pinned table, and the handlers check the same switch a second time. With the gateway off nobody below server-admin grants anything, whatever the self-service switch says (dark launch). The refusal is the shared `403 admin key required` — no tier, switch or field oracle. Inside `model-consumer-update` the rule is **revoking is always allowed, granting needs a release** ([api](api.md#model-consumer-administration)): narrowing a consumer stays open to tenant-admins; widening it needs self-service; `kind = ctx-peer`, a lower `prompt_sensitivity` (egress of foreign prompts to less trusted backends), `allow_plaintext = true` (credential transport without TLS), a higher `fair_weight` and `admission_lane = urgent` (the GPU is a host-global good) and `record_bodies = true` (every request and answer of the consumer in clear text in the LLM log, [below](#gateway-telemetry-v1-v2); also needs `confirm_record_bodies: true`) stay server-admin with self-service on. **Peer row tier:** any granting change of a `ctx-peer` consumer is server-admin only. The comparison runs against the row under its lock, so a concurrent server-admin write cannot be undone by a tenant-admin re-submitting the old value. **Admin bootstrap** (one-time, host access required). Promote by `id`, never by label — `label` has no UNIQUE constraint and an UPDATE by label would escalate every same-named key, including inactive ones: @@ -160,13 +160,14 @@ Every refusal carries `x-should-retry: false`: the same request against the same - **Request identity.** ctx mints the answer id and a fresh upstream request id per attempt; the client's `X-Request-ID` is only recorded (`metadata.gw.client_req_id`), never sent to a backend — a client-chosen id would become the engine's request id (vLLM) or a correlation handle at a third party. - **Kill switch and revocation while running.** A watcher per request (streamed or not) ends a running request within 5 s when `gateway.enabled` goes `false` or the alias is disabled or removed; a non-streamed request checks the alias and the grant once more right before the answer is written. The lease is released with the aborted upstream call. - **Revocation of running requests.** Every request the door accepts runs on a context the door's in-flight registry can end (one registry per process, entries indexed by model key, consumer, tenant and tenant scope, gone when the request ends — a panic included). A key that stops authenticating — revoked, its expiry passed, its consumer deactivated, its tenant suspended, offboarded or pruned, its `tenant_scope` moved to another tenant or deleted (gates 1–4 of `ctx_model_auth`) — ends the requests running on it: `401 invalid_api_key` before anything is written, the error frame `invalid_api_key` in a committed stream; the upstream call is aborted, the lease and the consumer's concurrency slot are freed, and the key's hash leaves the door's known-good set (its next request pays the probe token). Four triggers: `model-key-revoke` and `model-consumer-delete` end them right after their commit and answer how many requests of this process they ended (`cancelled_inflight`); every write that can end a key's validity — psql and other ctx processes on the same database included — fires `NOTIFY ctx_model_access_write` (migration 165), and the registry checks the keys it touches with `ctx_model_auth_live` (one statement); a key's expiry ends its requests at that instant through one timer per key (a rotation's grace moves it through the same signal); and every `gateway.inflight_sweep_interval` (30 s) one `ctx_model_auth_live` statement over the keys of all running requests is the second line behind the signal — and the sweep right after the listener reconnects covers a signal lost while it was away. A failed sweep ends nothing (the next one, or the signal, does). **Boundary:** the registry checks liveness only (gates 1–4); the door's other checks run at a request's entry and are not repeated while it runs. A narrowed policy — `allowed_cidrs` narrowed so the request's client address is outside (gate 5), `allow_plaintext` set to `false` under a plaintext request (gate 6), a withdrawn `all_models`, a withdrawn alias grant (except as below), another `tenant_scope` that still belongs to the tenant, a lower `prompt_sensitivity`, another lane or weight — applies from the next request; none of these writes ends a request that is already running, and none fires the database signal. A running request keeps what it was admitted with (its egress has already happened, an abort would not take it back). A withdrawn grant of a consumer without `all_models` is read again right before a non-streamed answer is written (`404 model_not_found`) and by a stream's watcher when the alias registry changes during the stream; otherwise it too applies from the next request. A key's expiry is the one the request was authenticated with, moved by the database signal; a rotation's grace that lands while the listener is away ends the predecessor's requests at the first sweep after the grace (at most one `gateway.inflight_sweep_interval` late), and an expiry extended by hand in psql during such a gap still ends them at the old expiry (no admin action extends an expiry). The kill switch and a removed or disabled alias still end a running request through the watcher. Every grant read of a running request — and the one at its entry — has the door's 1-second deadline, and the kill switch and the alias registry are checked in memory before it: while the database hangs (an exhausted pool, a locked grants table) the kill switch and a removed or disabled alias still end a running request within one watcher tick (5 s) plus that second, and a new request whose grant read does not answer in time gets `503 internal_error`. With the database down, a revoked key's running requests end through the local action of the same process or at its expiry timer; the signal and the sweep need the database. -- **Telemetry.** The request's one LLM-log row stores only ` ` as its error, never the backend's body (which can echo the prompt), and bodies only as `gateway.body_logging` allows (see below). +- **Telemetry.** The request's one LLM-log row stores only ` ` as its error, never the backend's body (which can echo the prompt), and bodies only as `gateway.body_logging` allows — or whole for a consumer a server-admin set to record (see below). ## Gateway telemetry (`/v1`, `/v2`) What the gateway writes about a request, and what it never writes (design 06 §4.6): -- **One body policy.** `gateway.body_logging` is the only switch for prompt and answer bodies of gateway rows in `context_llm_log` — global-only, so no tenant can raise it for itself. `none` (default) stores none; `errors` stores the serialized request and the answer on rows with an error only; `full` on every row, each capped at 64 KiB. Every row is then slimmed as for a tenant without developer mode: a credentials-class row stays sealed under every policy, whatever the tenant's `tenant.devmode` says — and so does a row whose sensitivity is empty or unknown (fail-closed, logged as a wiring defect). Embedded NUL bytes and invalid UTF-8 are cleaned before the write, so a crafted body cannot make the row — and its attribution — vanish. +- **One body policy.** `gateway.body_logging` is the only switch for prompt and answer bodies of the gateway rows of every consumer that does not record (next point) in `context_llm_log` — global-only, so no tenant can raise it for itself. `none` (default) stores none; `errors` stores the serialized request and the answer on rows with an error only; `full` on every row, each capped at 64 KiB. Every row is then slimmed as for a tenant without developer mode: a credentials-class row stays sealed under every policy, whatever the tenant's `tenant.devmode` says — and so does a row whose sensitivity is empty or unknown (fail-closed, logged as a wiring defect). Embedded NUL bytes and invalid UTF-8 are cleaned before the write, so a crafted body cannot make the row — and its attribution — vanish. +- **The one exception: a recording consumer (migration 197, issue #571).** A model consumer with `record_bodies` on has every gateway row of its own — chat, a stream's relayed answer, embeddings, rerank, rows with an error — written with the request and the answer in full: whatever `gateway.body_logging`, the alias, the consumer's `prompt_sensitivity`, the body scan or `Ctx-Sensitivity` say, without the 64 KiB cut and without the credentials seal. **Such a row can carry credentials in clear text** — a password or key a client puts into a prompt is stored as sent. Only a server-admin can switch it on (also with self-service, and only with `confirm_record_bodies: true`); switching it off is open to the consumer's tenant-admin; both are audited. The row is marked `metadata.gw.recorded = true`, and its bodies reach a server-admin only: `GET /api/llmlog/{id}` answers every other caller with the uniform `404` (a gateway row has no knowledge key, so the tenant gate never matches it), the LLM log list, the usage and status surfaces carry no body, `ctx-llmlog-export` writes the row with its bodies sealed (also, fail-closed, every gateway row whose marker is missing or unreadable), and no pipeline (distill, dream, digest) reads the log's bodies (`TestBodyColumnReadersCensus` lists every reader of the body columns). **What the switch does not change:** the request path — the required sensitivity, the chain and its egress rule, the body scan and its `413`, the limits and the answer are the same with and without it (the captured texts are held against a fixed account of their own, never against the request's in-flight budget); every other consumer's rows, byte for byte under every `gateway.body_logging` value; the retention — recorded bodies are NULLed after `scheduler.llmlog_retention_days` (90) like every body; and a database backup (`backup.sh`), which carries them like every other content of the database. Embedding vectors and rerank scores are not stored (the request is the record); the shutdown's forced row of a request still open carries no body and names it (`metadata.gw.record_lost`). See [operations — Recording a consumer](operations.md#recording-a-consumer). - **Error redaction.** The `error` column of a gateway row holds only class, status and ctx code. The upstream response body (which can echo prompt fragments, and which tenant-admins would read in the LLM log list) never reaches it; class and code must have the shape of vocabulary words (lower snake case, at most 64 characters), anything else is stored as `[redacted]`; the writer takes the code from the gateway's own code vocabulary, never from the upstream answer. - **One identity.** A gateway row is attributed to the consumer (`consumer_id`); a knowledge key id that reached the row anyway is cleared with an ERROR line, and the database refuses any row carrying both. The model key id is kept in `metadata.gw.model_key_id` for key-leak forensics, never as a column. - **Access log.** A successful request is one `gateway request` line with ids, op, alias, status, token counts and timings (`gateway.access_log`, default on) — no consumer label, no content, never a key, its hint or a query string. Refusals are counted per (consumer, reason — a code of the gateway or door vocabulary, else `http_`) and logged as one `gateway rejections` WARN line per minute with the count, so a flood of `401`/`429` answers cannot rotate the error and security lines out of the 50 MB × 3 container log. The global request log stays silent for these requests. diff --git a/go/cmd/ctxd/v1_record_integration_test.go b/go/cmd/ctxd/v1_record_integration_test.go new file mode 100644 index 000000000..1c59ec98c --- /dev/null +++ b/go/cmd/ctxd/v1_record_integration_test.go @@ -0,0 +1,262 @@ +//go:build integration + +// Issue #571 over the PRODUCTION router (buildRouter, the v1ChatFixture of +// v1_chat_integration_test.go): a consumer whose recording switch a +// server-admin set through /api/manage has its /v1 chat row written by the +// production writer (llmlog.RecordGateway → the async insert) with the whole +// request and answer — a prompt past the 64 KiB cap that carries a +// credentials pattern included — marked metadata.gw.recorded; the same +// request of a consumer without the switch gets the same answer and the row +// it always got. Then every reader of the row (TestBodyColumnReadersCensus +// lists them) with that row: +// +// - GET /api/llmlog/{id}: a server-admin reads the bodies; the tenant-admin +// of the consumer's tenant gets the uniform 404; +// - GET /api/llmlog (list): metadata only, for both — the pattern is in +// neither answer; +// - GET /api/status: recording_consumers names the consumer — for the +// server-admin and for its tenant-admin — and no body; +// - ctx-llmlog-export (llmlogexport.Export): the row leaves sealed; +// - the retention janitor (llmlog.EvictBodies): the row's bodies go after +// the retention like every row's; +// - switching off (the tenant-admin may) applies from the next request. +// +// go test -tags=integration -p 1 -count=1 -run 'TestV1RecordedConsumer' -v ./cmd/ctxd/ +package main + +import ( + "bytes" + "context" + "encoding/json" + "net/http" + "net/http/httptest" + "regexp" + "strings" + "testing" + + "github.com/GottZ/ctx/internal/backends" + "github.com/GottZ/ctx/internal/llmlog" + "github.com/GottZ/ctx/internal/llmlogexport" + "github.com/GottZ/ctx/internal/store" +) + +// v1RecSecret is a credentials pattern (the sensitivity scan's assignment +// rule) — the kind of text a recorded row can carry in clear. +const v1RecSecret = "password=Tr0ub4dor-recorded-571" + +// v1RecAPI calls the router's /api surface with a knowledge key. +func v1RecAPI(t *testing.T, f *v1ChatFixture, method, path, key string, body any) (int, []byte, map[string]any) { + t.Helper() + var rd *bytes.Reader + if body != nil { + b, _ := json.Marshal(body) + rd = bytes.NewReader(b) + } else { + rd = bytes.NewReader(nil) + } + req := httptest.NewRequest(method, path, rd) + req.Header.Set("Authorization", "Bearer "+key) + if body != nil { + req.Header.Set("Content-Type", "application/json") + } + rec := httptest.NewRecorder() + f.router.ServeHTTP(rec, req) + var out map[string]any + _ = json.Unmarshal(rec.Body.Bytes(), &out) + return rec.Code, rec.Body.Bytes(), out +} + +// v1RecRow is the stored row of one consumer's newest gateway-chat call. +type v1RecRow struct { + id, user, resp, sens string + recorded *string + userNull bool +} + +func v1RecRead(t *testing.T, f *v1ChatFixture, consumerID string) v1RecRow { + t.Helper() + f.settle(t) + var r v1RecRow + var user, resp *string + if err := f.seed.QueryRow(context.Background(), ` + SELECT id::text, request_user, response_content, COALESCE(required_sensitivity, ''), metadata->'gw'->>'recorded' + FROM context_llm_log WHERE consumer_id = $1::uuid AND pipeline = $2 + ORDER BY created_at DESC, id DESC LIMIT 1`, consumerID, llmlog.PipelineGatewayChat). + Scan(&r.id, &user, &resp, &r.sens, &r.recorded); err != nil { + t.Fatalf("read the row of %s: %v", consumerID, err) + } + r.userNull = user == nil + if user != nil { + r.user = *user + } + if resp != nil { + r.resp = *resp + } + return r +} + +var v1RecIdentity = regexp.MustCompile(`"(id|created)":("[^"]*"|\d+)`) + +func TestV1RecordedConsumerRowAndItsReaders(t *testing.T) { + e := newV1ChatEngine(t, http.StatusOK) + f := newV1ChatFixture(t, []backends.Backend{e.row("eng", 10)}) + ctx := context.Background() + // The fixture minted the first key already, so the server-admin is a key + // promoted the way model_inflight_integration_test.go promotes one. + k, adminKey, err := store.CreateApiKey(ctx, f.seed, "v1-rec-admin", "private", nil, "") + if err != nil { + t.Fatalf("admin key: %v", err) + } + if _, err := f.seed.Exec(ctx, `UPDATE context_api_keys SET is_admin = true, tenant_role = 'owner' WHERE id = $1::uuid`, k.ID); err != nil { + t.Fatalf("promote admin key: %v", err) + } + v1RecAdminKey := adminKey + status, body, resp := v1RecAPI(t, f, http.MethodPost, "/api/manage", v1RecAdminKey, map[string]any{ + "action": "tenant-create", "data": map[string]any{"slug": "v1rec", "display_name": "v1 rec"}}) + tenantAdmin, _ := resp["owner_key"].(string) + tn, _ := resp["tenant"].(map[string]any) + tenantID, _ := tn["id"].(string) + if status != http.StatusOK || tenantAdmin == "" || tenantID == "" { + t.Fatalf("tenant-create: %d %s", status, body) + } + mkConsumer := func(label string, extra map[string]any) (id, key string) { + t.Helper() + data := map[string]any{"label": label, "tenant_id": tenantID, "all_models": true} + for k, v := range extra { + data[k] = v + } + status, body, resp := v1RecAPI(t, f, http.MethodPost, "/api/manage", v1RecAdminKey, map[string]any{"action": "model-consumer-create", "data": data}) + c, _ := resp["consumer"].(map[string]any) + id, _ = c["id"].(string) + key, _ = resp["api_key"].(string) + if status != http.StatusOK || id == "" || key == "" { + t.Fatalf("model-consumer-create %s: %d %s", label, status, body) + } + return id, key + } + recID, recKey := mkConsumer("v1-rec-on", map[string]any{"record_bodies": true, "confirm_record_bodies": true}) + plainID, plainKey := mkConsumer("v1-rec-off", nil) + + content := v1RecSecret + " " + strings.Repeat("0123456789abcdef", 5<<10) // 80 KiB + chat := `{"model":"` + v1ChatAlias + `","messages":[{"role":"user","content":"` + content + `"}]}` + messages := `[{"role":"user","content":"` + content + `"}]` + onA := f.post(t, recKey, chat) + offA := f.post(t, plainKey, chat) + if onA.status != http.StatusOK || offA.status != http.StatusOK { + t.Fatalf("status on %d off %d, want 200: %s / %s", onA.status, offA.status, onA.body, offA.body) + } + if v1RecIdentity.ReplaceAllString(string(onA.body), "") != v1RecIdentity.ReplaceAllString(string(offA.body), "") { + t.Errorf("the answer differs with the switch:\n on %s\n off %s", onA.body, offA.body) + } + e.mu.Lock() + sameUpstream := len(e.bodies) == 2 && bytes.Equal(e.bodies[0], e.bodies[1]) + e.mu.Unlock() + if !sameUpstream { + t.Errorf("the engine saw different bodies with and without the switch") + } + + rec := v1RecRead(t, f, recID) + plain := v1RecRead(t, f, plainID) + if rec.user != messages || rec.resp != strings.TrimSuffix(string(onA.body), "\n") || rec.recorded == nil || *rec.recorded != "true" { + t.Fatalf("recorded row: request %d bytes (want %d), answer %d bytes (want %d), recorded %v", + len(rec.user), len(messages), len(rec.resp), len(onA.body)-1, rec.recorded) + } + if rec.sens != string(backends.SensCredentials) || plain.sens != rec.sens { + t.Errorf("required_sensitivity recorded %q plain %q, want credentials both (the switch changes no class)", rec.sens, plain.sens) + } + if plain.user != "" || plain.resp != "" || plain.recorded != nil { + t.Errorf("the plain consumer's row: %d/%d body bytes, recorded %v — want the sealed row it always got", len(plain.user), len(plain.resp), plain.recorded) + } + + t.Run("detail", func(t *testing.T) { + st, b, out := v1RecAPI(t, f, http.MethodGet, "/api/llmlog/"+rec.id, v1RecAdminKey, nil) + d, _ := out["detail"].(map[string]any) + if st != http.StatusOK || d["recorded"] != true || !strings.Contains(string(b), "Tr0ub4dor-recorded-571") { + t.Errorf("server-admin detail: %d recorded %v, secret present %v — want 200, true, the whole bodies", st, d["recorded"], strings.Contains(string(b), "Tr0ub4dor")) + } + stT, bT, _ := v1RecAPI(t, f, http.MethodGet, "/api/llmlog/"+rec.id, tenantAdmin, nil) + stU, bU, _ := v1RecAPI(t, f, http.MethodGet, "/api/llmlog/0195a6f0-0000-7000-8000-000000000571", tenantAdmin, nil) + if stT != http.StatusNotFound || string(bT) != string(bU) || strings.Contains(string(bT), "Tr0ub4dor") { + t.Errorf("tenant-admin detail of the recorded row: %d %s — want the uniform 404 of an unknown id (%d %s)", stT, bT, stU, bU) + } + }) + t.Run("list", func(t *testing.T) { + for name, key := range map[string]string{"server_admin": v1RecAdminKey, "tenant_admin": tenantAdmin} { + st, b, out := v1RecAPI(t, f, http.MethodGet, "/api/llmlog?consumer_id="+recID, key, nil) + entries, _ := out["entries"].([]any) + if st != http.StatusOK || len(entries) == 0 || strings.Contains(string(b), "Tr0ub4dor") || strings.Contains(string(b), "0123456789abcdef0123") { + t.Errorf("%s list: %d, %d entries, a body in the answer %v — want 200, the row, metadata only", name, st, len(entries), strings.Contains(string(b), "Tr0ub4dor")) + } + } + }) + t.Run("status", func(t *testing.T) { + for name, key := range map[string]string{"server_admin": v1RecAdminKey, "tenant_admin": tenantAdmin} { + st, b, out := v1RecAPI(t, f, http.MethodGet, "/api/status", key, nil) + gw, _ := out["gateway"].(map[string]any) + ids, _ := gw["recording_consumers"].([]any) + if st != http.StatusOK || len(ids) != 1 || ids[0] != recID || strings.Contains(string(b), "Tr0ub4dor") { + t.Errorf("%s status: %d recording_consumers %v — want exactly [%s], no body", name, st, gw["recording_consumers"], recID) + } + } + }) + t.Run("export", func(t *testing.T) { + var buf bytes.Buffer + sum, err := llmlogexport.Export(ctx, f.seed, &buf, llmlogexport.ExportOptions{UntilMargin: 1}) + if err != nil { + t.Fatalf("export: %v", err) + } + // The summary by its wire (the CLI's stderr JSON), so the file + // compiles against the base. + var counts map[string]any + _ = json.Unmarshal(llmlogexport.MarshalSummary(sum), &counts) + if strings.Contains(buf.String(), "Tr0ub4dor") || counts["rows_recorded_sealed"] != float64(1) { + t.Errorf("export: secret present %v, rows_recorded_sealed %v — want the recorded row sealed", strings.Contains(buf.String(), "Tr0ub4dor"), counts["rows_recorded_sealed"]) + } + if !strings.Contains(buf.String(), rec.id) { + t.Errorf("the export left the recorded row out — it keeps the row, without its bodies") + } + }) + t.Run("switch_off_applies_from_the_next_request", func(t *testing.T) { + st, b, _ := v1RecAPI(t, f, http.MethodPost, "/api/manage", tenantAdmin, map[string]any{ + "action": "model-consumer-update", "data": map[string]any{"id": recID, "record_bodies": false}}) + if st != http.StatusOK { + t.Fatalf("tenant-admin switches off: %d %s", st, b) + } + if a := f.post(t, recKey, chat); a.status != http.StatusOK { + t.Fatalf("request after the switch: %d", a.status) + } + if r := v1RecRead(t, f, recID); r.id == rec.id || r.recorded != nil || r.user != "" { + t.Errorf("the next row after switching off: recorded %v, %d body bytes — want an unrecorded, sealed row", r.recorded, len(r.user)) + } + }) + t.Run("retention_janitor", func(t *testing.T) { + // A hypertable row cannot move to an older chunk, so the recorded row + // is copied 91 days back (its bodies and metadata as the writer + // stored them) and the janitor runs over both. + var old string + if err := f.seed.QueryRow(ctx, `INSERT INTO context_llm_log + SELECT (jsonb_populate_record(NULL::context_llm_log, to_jsonb(t) || + jsonb_build_object('id', gen_random_uuid(), 'created_at', now() - interval '91 days'))).* + FROM context_llm_log t WHERE t.id = $1::uuid + RETURNING id::text`, rec.id).Scan(&old); err != nil { + t.Fatalf("copy the row back: %v", err) + } + if _, err := llmlog.EvictBodies(ctx, f.seed, 90); err != nil { + t.Fatalf("evict: %v", err) + } + bodies := func(id string) (user, resp, recorded *string) { + t.Helper() + if err := f.seed.QueryRow(ctx, `SELECT request_user, response_content, metadata->'gw'->>'recorded' FROM context_llm_log WHERE id = $1::uuid`, id). + Scan(&user, &resp, &recorded); err != nil { + t.Fatalf("read: %v", err) + } + return user, resp, recorded + } + if u, r, m := bodies(old); u != nil || r != nil || m == nil || *m != "true" { + t.Errorf("past the retention: request %v answer %v recorded %v — want NULL bodies and the marker kept", u != nil, r != nil, m) + } + if u, _, _ := bodies(rec.id); u == nil || *u != messages { + t.Errorf("the janitor touched the recorded row inside the retention") + } + }) +} diff --git a/go/internal/auth/consumer.go b/go/internal/auth/consumer.go index 04813779a..14fae1800 100644 --- a/go/internal/auth/consumer.go +++ b/go/internal/auth/consumer.go @@ -50,6 +50,12 @@ type ConsumerAuth struct { IsValid bool AdmissionLane string // 'urgent' | 'bulk' — the external lane ceiling (design/03) PeerInstanceID string // a ctx-peer's bound instance id; "" = not bound + // RecordBodies is the consumer's recording switch (migration 197): every + // gateway row of the request keeps its request and answer in full + // (llmlog.GatewayRow.Recorded). It is read once at the door, like every + // other column: a switch applies from the next request on. It changes + // what the row carries and nothing on the request path. + RecordBodies bool } // consumerKind maps the kind column; anything but 'ctx-peer' is an app. @@ -92,15 +98,15 @@ func AuthenticateModelKey(ctx context.Context, q ModelAuthQuerier, keyHash strin var ( keyID, consumerID, tenantID, scope, peer *string kind, sens, lane string - all, valid bool + all, valid, record bool weight int16 expires *time.Time ) // Columns by name and in the function's order (K20: new columns go last). err := q.QueryRow(ctx, - `SELECT model_key_id, consumer_id, tenant_id, tenant_scope, kind, all_models, prompt_sensitivity, fair_weight, key_expires_at, is_valid, admission_lane, peer_instance_id FROM ctx_model_auth($1, $2, $3)`, + `SELECT model_key_id, consumer_id, tenant_id, tenant_scope, kind, all_models, prompt_sensitivity, fair_weight, key_expires_at, is_valid, admission_lane, peer_instance_id, record_bodies FROM ctx_model_auth($1, $2, $3)`, keyHash, addrArg(ip), secure, - ).Scan(&keyID, &consumerID, &tenantID, &scope, &kind, &all, &sens, &weight, &expires, &valid, &lane, &peer) + ).Scan(&keyID, &consumerID, &tenantID, &scope, &kind, &all, &sens, &weight, &expires, &valid, &lane, &peer, &record) if err != nil { return nil, fmt.Errorf("auth: query ctx_model_auth: %w", err) } @@ -123,6 +129,7 @@ func AuthenticateModelKey(ctx context.Context, q ModelAuthQuerier, keyHash strin KeyExpiresAt: expires, IsValid: true, AdmissionLane: lane, + RecordBodies: record, } if scope != nil { ca.TenantScope = *scope diff --git a/go/internal/cli/models.go b/go/internal/cli/models.go index 7b4f493f3..ae2e44665 100644 --- a/go/internal/cli/models.go +++ b/go/internal/cli/models.go @@ -97,6 +97,7 @@ type modelsConsumerView struct { AdmissionLane string `json:"admission_lane"` AllowedCIDRs []string `json:"allowed_cidrs"` AllowPlaintext bool `json:"allow_plaintext"` + RecordBodies bool `json:"record_bodies"` Active bool `json:"active"` Status string `json:"status"` LastUsedAt *string `json:"last_used_at"` diff --git a/go/internal/handler/llmlog.go b/go/internal/handler/llmlog.go index 4c5ee02e1..ddbf3a73e 100644 --- a/go/internal/handler/llmlog.go +++ b/go/internal/handler/llmlog.go @@ -229,6 +229,11 @@ type llmlogDetail struct { RequestSystem *string `json:"request_system"` RequestUser *string `json:"request_user"` ResponseContent *string `json:"response_content"` + // Recorded marks the row of a recording consumer (metadata.gw.recorded, + // issue #571): its bodies are whole and can carry credentials in clear + // text. Only a server-admin reaches such a row here — a gateway row has + // no api_key_id, so the tenant gate below never matches it. + Recorded bool `json:"recorded"` } // HandleLLMLogDetail serves GET /api/llmlog/{id} — the gated prompt/reply body @@ -282,13 +287,14 @@ func (h *LLMLogHandler) HandleLLMLogDetail(w http.ResponseWriter, r *http.Reques err := h.pool.QueryRow(r.Context(), ` SELECT id::text, created_at, pipeline, model, COALESCE(backend_name, host) AS backend, - required_sensitivity, request_system, request_user, response_content + required_sensitivity, request_system, request_user, response_content, + COALESCE(metadata->'gw'->'recorded' = 'true'::jsonb, false) FROM context_llm_log WHERE id = $1::uuid AND ($2::uuid[] IS NULL OR api_key_id = ANY($2))`, id, keyFilter, ).Scan(&d.ID, &d.CreatedAt, &d.Pipeline, &d.Model, &d.Backend, - &sensitivity, &reqSystem, &reqUser, &respContent) + &sensitivity, &reqSystem, &reqUser, &respContent, &d.Recorded) if err != nil { if errors.Is(err, pgx.ErrNoRows) { // Unknown id OR a row the caller may not see — one uniform answer. diff --git a/go/internal/handler/model_consumers.go b/go/internal/handler/model_consumers.go index 0d1f5bafb..aa041bdea 100644 --- a/go/internal/handler/model_consumers.go +++ b/go/internal/handler/model_consumers.go @@ -10,8 +10,9 @@ package handler // release" (consumerGrant): a tenant-admin may only narrow a consumer // unless gateway.enabled and gateway.tenant_self_service are both on, and // kind=ctx-peer, a lower prompt_sensitivity, allow_plaintext=true, a higher -// fair_weight and admission_lane=urgent stay server-admin even then (E3, -// V-01-a, design/03 §3.1); +// fair_weight, admission_lane=urgent and record_bodies=true stay +// server-admin even then (E3, V-01-a, design/03 §3.1; issue #571 — the +// recording switch also needs confirm_record_bodies); // - the peer row tier (V-01-b): every granting change of a ctx-peer // consumer is server-admin only; // - the tenant binding (N12 helpers resolveKeyMintTenant / @@ -295,6 +296,8 @@ func writeConsumerStoreError(w http.ResponseWriter, r *http.Request, err error, switch { case errors.Is(err, errFieldTier): writeAdminRequired(w) + case errors.Is(err, errRecordConfirm): + writeConsumerError(w, http.StatusBadRequest, recordConfirmRefusal) case errors.As(err, &mErr): writeModelsError(w, mErr) case errors.Is(err, errModelsNotWired): @@ -502,7 +505,11 @@ type consumerCreateRequest struct { AdmissionLane *string `json:"admission_lane"` AllowedCIDRs []string `json:"allowed_cidrs"` AllowPlaintext bool `json:"allow_plaintext"` - ExpiresAt *time.Time `json:"expires_at"` + // RecordBodies switches recording on (migration 197): server-admin + // only, and only with ConfirmRecordBodies (recordConfirmRefusal). + RecordBodies bool `json:"record_bodies"` + ConfirmRecordBodies bool `json:"confirm_record_bodies"` + ExpiresAt *time.Time `json:"expires_at"` // Limits are the consumer's starting limits per op (FOLGE-Z Z3): each // op's dimensions are written as the consumer's row of the CALLER's tier // in the create's transaction — validated like gateway-limits-set. @@ -553,20 +560,33 @@ func (d *consumerCreateRequest) validate() ([]netip.Prefix, error) { } // grant ranks a create against the fail-closed column defaults of migration -// 161 (app, credentials, fair_weight 1, bulk, no plaintext): creating is -// itself granting; a field above those defaults may be server-admin only. +// 161 (app, credentials, fair_weight 1, bulk, no plaintext) and 197 (no +// recording): creating is itself granting; a field above those defaults may +// be server-admin only. func (d *consumerCreateRequest) grant() consumerGrant { switch { case d.Kind == "ctx-peer", d.PromptSensitivity != nil && sensitivityLowered("credentials", *d.PromptSensitivity), d.AllowPlaintext, d.FairWeight != nil && *d.FairWeight > consumerFairWeightMin, - d.AdmissionLane != nil && *d.AdmissionLane == "urgent": + d.AdmissionLane != nil && *d.AdmissionLane == "urgent", + d.RecordBodies: return grantServerAdmin } return grantSelfService } +// recordConfirmRefusal is the 400 of switching recording on without +// confirm_record_bodies (the confirm_trust_elevation pattern): the switch +// stores what the consumer sends in clear text, credentials in a prompt +// included. +const recordConfirmRefusal = "record_bodies:true stores every request and answer of this consumer in full in the LLM log — " + + "credentials in a prompt included, in clear text, readable by server-admins — requires confirm_record_bodies:true" + +// errRecordConfirm is the refusal of recordConfirmRefusal under the consumer +// lock (store.UpdateConsumerChecked); it surfaces as that 400. +var errRecordConfirm = errors.New("record_bodies needs confirm_record_bodies") + func (h *ManageHandler) handleModelConsumerCreate(w http.ResponseWriter, r *http.Request, ar *auth.AuthResult, req manageRequest) { var d consumerCreateRequest if err := decodeConsumerPayload(req.Data, &d); err != nil { @@ -588,6 +608,10 @@ func (h *ManageHandler) handleModelConsumerCreate(w http.ResponseWriter, r *http writeAdminRequired(w) return } + if d.RecordBodies && !d.ConfirmRecordBodies { + writeConsumerError(w, http.StatusBadRequest, recordConfirmRefusal) + return + } if len(d.Models) > 0 && h.modelAliases == nil { writeModelsNotWired(w) return @@ -631,6 +655,7 @@ func (h *ManageHandler) handleModelConsumerCreate(w http.ResponseWriter, r *http spec := store.ModelConsumerSpec{Limits: limits, TenantID: tenant, Label: d.Label, Description: d.Description, Kind: d.Kind, TenantScope: d.TenantScope, AllModels: d.AllModels, Models: d.Models, AllowPlaintext: d.AllowPlaintext, + RecordBodies: d.RecordBodies, } if d.PromptSensitivity != nil { spec.PromptSensitivity = *d.PromptSensitivity @@ -668,6 +693,9 @@ func (h *ManageHandler) handleModelConsumerCreate(w http.ResponseWriter, r *http func (h *ManageHandler) freshConsumerView(r *http.Request, ar *auth.AuthResult, pol consumerPolicy, written store.ModelConsumer, keys []store.ModelKeyInfo) consumerView { now := time.Now() c, err := store.GetConsumer(r.Context(), h.pool, written.ID, accessOf(ar), now) + if err == nil { + err = h.readRecordBodies(r, []*store.ModelConsumer{&c}) + } if err != nil { slog.Warn("manage: consumer re-read after write failed", "error", err, "request_id", RequestIDFromContext(r.Context())) c = written @@ -678,6 +706,24 @@ func (h *ManageHandler) freshConsumerView(r *http.Request, ar *auth.AuthResult, return newConsumerView(c, c.Keys, ar, now, pol.expiryWarn) } +// readRecordBodies fills RecordBodies of consumers the caller has read +// (store.ConsumerRecordBodies — the switch is not part of the shared +// consumer read, migration 197). +func (h *ManageHandler) readRecordBodies(r *http.Request, cs []*store.ModelConsumer) error { + ids := make([]string, len(cs)) + for i, c := range cs { + ids[i] = c.ID + } + on, err := store.ConsumerRecordBodies(r.Context(), h.pool, ids) + if err != nil { + return err + } + for _, c := range cs { + c.RecordBodies = on[c.ID] + } + return nil +} + // consumerUpdateFields is the closed field set of model-consumer-update. // expires_at is deliberately absent (V-01-d: a new expiry needs a new key — // model-key-rotate), so are kind, tenant_id and the peer binding. models is @@ -687,14 +733,17 @@ var consumerUpdateFields = map[string]bool{ "models": true, "prompt_sensitivity": true, "fair_weight": true, "admission_lane": true, "allowed_cidrs": true, "allow_plaintext": true, "active": true, + "record_bodies": true, "confirm_record_bodies": true, } // consumerUpdate is a decoded update: the store patch plus what the field -// tiers compare (the parsed CIDR list). +// tiers compare (the parsed CIDR list) and the confirmation of switching +// recording on. type consumerUpdate struct { - id string - patch store.ModelConsumerPatch - cidrs []netip.Prefix + id string + patch store.ModelConsumerPatch + cidrs []netip.Prefix + confirmRecord bool } // decodeConsumerUpdate decodes model-consumer-update's payload. A field present @@ -722,6 +771,7 @@ func decodeConsumerUpdate(raw json.RawMessage) (consumerUpdate, error) { {"label", &p.Label}, {"description", &p.Description}, {"all_models", &p.AllModels}, {"prompt_sensitivity", &p.PromptSensitivity}, {"fair_weight", &p.FairWeight}, {"admission_lane", &p.AdmissionLane}, {"allow_plaintext", &p.AllowPlaintext}, {"active", &p.Active}, + {"record_bodies", &p.RecordBodies}, {"confirm_record_bodies", &u.confirmRecord}, } { raw, ok := fields[f.name] if !ok { @@ -849,10 +899,26 @@ func (u consumerUpdate) serverAdminOnly(cur store.ModelConsumer) bool { return true // above ctx's own background work (design/03 §3.1) case p.AllowPlaintext != nil && *p.AllowPlaintext && !cur.AllowPlaintext: return true // credential transport without TLS (B24) + case u.recordsOn(cur): + return true // every body of the consumer in clear text in the log (issue #571) } return false } +// recordsOn reports an update that switches recording on (off → on). +func (u consumerUpdate) recordsOn(cur store.ModelConsumer) bool { + return u.patch.RecordBodies != nil && *u.patch.RecordBodies && !cur.RecordBodies +} + +// recordConfirmed is the confirmation rule of switching recording on: an +// update that does needs confirm_record_bodies (errRecordConfirm). +func (u consumerUpdate) recordConfirmed(cur store.ModelConsumer) error { + if u.recordsOn(cur) && !u.confirmRecord { + return errRecordConfirm + } + return nil +} + // scopeAfter is the consumer's tenant_scope once the update has run: the // patch's value, NULL when it clears the scope, else the current one. func (u consumerUpdate) scopeAfter(cur store.ModelConsumer) *string { @@ -898,17 +964,24 @@ func (h *ManageHandler) handleModelConsumerUpdate(w http.ResponseWriter, r *http pol := h.consumerPolicy() access := accessOf(ar) cur, err := store.GetConsumer(r.Context(), h.pool, u.id, access, time.Now()) + if err == nil && u.patch.RecordBodies != nil { + err = h.readRecordBodies(r, []*store.ModelConsumer{&cur}) + } if err != nil { writeConsumerStoreError(w, r, err, "model-consumer-update") return } // First, unlocked: refuse early with the tier text before any scope // lookup can answer differently. The authoritative check repeats under - // the consumer lock below. + // the consumer lock below, the confirmation of recording with it. if !pol.allowed(ar, u.grant(cur), cur.Kind == "ctx-peer") { writeAdminRequired(w) return } + if err := u.recordConfirmed(cur); err != nil { + writeConsumerStoreError(w, r, err, "model-consumer-update") + return + } if u.patch.TenantScope != nil && h.rejectScopeOutsideTenant(w, r, []string{*u.patch.TenantScope}, cur.TenantID) { return } @@ -924,6 +997,9 @@ func (h *ManageHandler) handleModelConsumerUpdate(w http.ResponseWriter, r *http if !pol.allowed(ar, u.grant(locked), locked.Kind == "ctx-peer") { return errFieldTier } + if err := u.recordConfirmed(locked); err != nil { + return err + } return u.checkModels(snap, locked) } c, err := store.UpdateConsumerChecked(r.Context(), h.pool, u.id, access, u.patch, check, auditStamp(r, ar)) diff --git a/go/internal/handler/model_consumers_read.go b/go/internal/handler/model_consumers_read.go index 13097f910..cca8e52e4 100644 --- a/go/internal/handler/model_consumers_read.go +++ b/go/internal/handler/model_consumers_read.go @@ -41,8 +41,12 @@ type consumerView struct { AdmissionLane string `json:"admission_lane"` AllowedCIDRs []string `json:"allowed_cidrs"` AllowPlaintext bool `json:"allow_plaintext"` - Active bool `json:"active"` - Status string `json:"status"` + // RecordBodies: every gateway row of the consumer keeps its request and + // answer in full (migration 197) — shown to every reader of the + // consumer, its tenant-admins included. + RecordBodies bool `json:"record_bodies"` + Active bool `json:"active"` + Status string `json:"status"` LastUsedAt *time.Time `json:"last_used_at"` CreatedAt time.Time `json:"created_at"` CreatedByLabel *string `json:"created_by_label"` @@ -168,7 +172,7 @@ func newConsumerView(c store.ModelConsumer, keys []store.ModelKeyInfo, ar *auth. ID: c.ID, TenantID: c.TenantID, TenantSlug: c.TenantSlug, Label: c.Label, Description: c.Description, Kind: c.Kind, TenantScope: c.TenantScope, AllModels: c.AllModels, Models: models, PromptSensitivity: c.PromptSensitivity, FairWeight: c.FairWeight, AdmissionLane: c.AdmissionLane, - AllowedCIDRs: c.AllowedCIDRs, AllowPlaintext: c.AllowPlaintext, Active: c.Active, + AllowedCIDRs: c.AllowedCIDRs, AllowPlaintext: c.AllowPlaintext, RecordBodies: c.RecordBodies, Active: c.Active, Status: consumerStatus(c.Active, c.Keys, now, warn), LastUsedAt: c.LastUsedAt, CreatedAt: c.CreatedAt, CreatedByLabel: c.CreatedByLabel, Keys: kv, KeysTotal: c.KeysTotal, } @@ -308,6 +312,14 @@ func (h *ManageHandler) handleModelConsumerList(w http.ResponseWriter, r *http.R last := list[len(list)-1] next = encodeKeysetCursor(last.CreatedAt, last.ID) } + page := make([]*store.ModelConsumer, len(list)) + for i := range list { + page[i] = &list[i] + } + if err := h.readRecordBodies(r, page); err != nil { + writeConsumerStoreError(w, r, err, "model-consumer-list") + return + } views := make([]consumerView, 0, len(list)) for _, c := range list { views = append(views, newConsumerView(c, c.Keys, ar, now, pol.expiryWarn)) @@ -335,6 +347,9 @@ func (h *ManageHandler) handleModelConsumerGet(w http.ResponseWriter, r *http.Re access := accessOf(ar) now := time.Now() c, err := store.GetConsumer(r.Context(), h.pool, d.ID, access, now) + if err == nil { + err = h.readRecordBodies(r, []*store.ModelConsumer{&c}) + } if err != nil { writeConsumerStoreError(w, r, err, "model-consumer-get") return diff --git a/go/internal/handler/model_consumers_record_integration_test.go b/go/internal/handler/model_consumers_record_integration_test.go new file mode 100644 index 000000000..df7558756 --- /dev/null +++ b/go/internal/handler/model_consumers_record_integration_test.go @@ -0,0 +1,187 @@ +//go:build integration + +// The recording switch of a model consumer (issue #571, migration 197) +// through the real dispatch (HandleManage: table tier, then the field tiers): +// +// - switching on (create or update) is server-admin only, also with +// self-service — a tenant-admin gets the shared 403 of that tier — and +// needs confirm_record_bodies:true (400 without it, after the tier); +// - switching off is revoking: open to a tenant-admin of the consumer's +// tenant, without self-service; re-sending the value it has is no change; +// - the read form (create, update, get, list) names it, for every reader; +// - the switch is audited (model-consumer-get's trail); +// - the door reads it: AuthenticateModelKey after the update returns it — +// the next request records, nothing caches the old value. +// +// The file uses only the wire (action names, JSON payloads), so it compiles +// against the tree before the wave — where every create or update naming +// record_bodies answers 400 "unknown field" (the base red). +// +// go test -tags=integration -p 1 -run 'TestModelConsumerRecordSwitch' ./internal/handler/ -count=1 -v +package handler + +import ( + "context" + "net/http" + "strings" + "testing" + + "github.com/GottZ/ctx/internal/auth" + "github.com/GottZ/ctx/internal/modelkey" + "github.com/GottZ/ctx/internal/testdb" +) + +func TestModelConsumerRecordSwitch(t *testing.T) { + if testing.Short() { + t.Skip("integration test") + } + ctx := context.Background() + pool := testdb.SetupTestDB(t) + hOff := mcHandler(t, pool, false, false) // the defaults: server-admin only + hOn := mcHandler(t, pool, true, true) // gateway on + self-service + admin, _ := kaServerAdmin(ctx, t, pool) + a := auMakeTenant(ctx, t, pool, hOff, admin, "rec-a") + ta := a.ar + + const adminRequired = "admin key required" + // The wire text of the refusal (recordConfirmRefusal), spelled out so the + // file compiles against the base. + const confirm = "record_bodies:true stores every request and answer of this consumer in full in the LLM log — " + + "credentials in a prompt included, in clear text, readable by server-admins — requires confirm_record_bodies:true" + recordOf := func(resp map[string]any) any { + c, _ := resp["consumer"].(map[string]any) + return c["record_bodies"] + } + + // Create. + for _, row := range []mcRow{ + {"create/server_admin_without_confirm", hOff, admin, "model-consumer-create", + map[string]any{"label": "rec-c1", "tenant_id": a.id, "record_bodies": true}, http.StatusBadRequest, confirm}, + {"create/tenant_admin_with_self_service", hOn, ta, "model-consumer-create", + map[string]any{"label": "rec-c2", "record_bodies": true, "confirm_record_bodies": true}, http.StatusForbidden, adminRequired}, + {"create/tenant_admin_with_self_service_without_confirm", hOn, ta, "model-consumer-create", + map[string]any{"label": "rec-c3", "record_bodies": true}, http.StatusForbidden, adminRequired}, + } { + row.run(t) + } + status, body, resp := mcCall(t, hOff, admin, "model-consumer-create", + map[string]any{"label": "rec-on", "tenant_id": a.id, "record_bodies": true, "confirm_record_bodies": true}) + if status != http.StatusOK || recordOf(resp) != true { + t.Fatalf("server-admin create with confirmation: %d %s, want 200 with record_bodies true", status, body) + } + onID := resp["consumer"].(map[string]any)["id"].(string) + plain, _ := resp["api_key"].(string) + plainOff := mcCreate(t, hOn, ta, map[string]any{"label": "rec-off"}) // self-service create without the switch + if _, _, r := mcCall(t, hOff, ta, "model-consumer-get", map[string]any{"id": plainOff.id}); recordOf(r) != false { + t.Fatalf("a consumer created without the switch reads record_bodies %v, want false", recordOf(r)) + } + + // Update: switching on. + for _, row := range []mcRow{ + {"update_on/tenant_admin_with_self_service", hOn, ta, "model-consumer-update", + map[string]any{"id": plainOff.id, "record_bodies": true, "confirm_record_bodies": true}, http.StatusForbidden, adminRequired}, + {"update_on/tenant_admin_without_self_service", hOff, ta, "model-consumer-update", + map[string]any{"id": plainOff.id, "record_bodies": true, "confirm_record_bodies": true}, http.StatusForbidden, adminRequired}, + {"update_on/server_admin_without_confirm", hOff, admin, "model-consumer-update", + map[string]any{"id": plainOff.id, "record_bodies": true}, http.StatusBadRequest, confirm}, + {"update_on/server_admin_confirm_false", hOff, admin, "model-consumer-update", + map[string]any{"id": plainOff.id, "record_bodies": true, "confirm_record_bodies": false}, http.StatusBadRequest, confirm}, + {"update/record_bodies_null", hOff, admin, "model-consumer-update", + map[string]any{"id": plainOff.id, "record_bodies": nil}, http.StatusBadRequest, "record_bodies must not be null"}, + {"update/record_bodies_string", hOff, admin, "model-consumer-update", + map[string]any{"id": plainOff.id, "record_bodies": "yes"}, http.StatusBadRequest, "record_bodies has the wrong type"}, + // Re-sending the value a recording consumer has is no change. + {"update_on/tenant_admin_unchanged", hOff, ta, "model-consumer-update", + map[string]any{"id": onID, "record_bodies": true}, http.StatusOK, ""}, + // A confirmation alone switches nothing on. + {"update/confirm_alone", hOff, admin, "model-consumer-update", + map[string]any{"id": plainOff.id, "confirm_record_bodies": true}, http.StatusOK, ""}, + } { + row.run(t) + } + if _, _, r := mcCall(t, hOff, admin, "model-consumer-get", map[string]any{"id": plainOff.id}); recordOf(r) != false { + t.Fatalf("refused or confirmation-only updates switched recording on: %v", recordOf(r)) + } + + // The door reads the switch at the next check (ctx_model_auth by name, + // so the file compiles against the base; the Go side of the column is + // pinned through the router, cmd/ctxd TestV1RecordedConsumerRowAndItsReaders). + key, err := modelkey.Parse(plain) + if err != nil { + t.Fatalf("parse key: %v", err) + } + doorSays := func() bool { + t.Helper() + var valid, record bool + if err := pool.QueryRow(ctx, `SELECT is_valid, record_bodies FROM ctx_model_auth($1, '192.0.2.7'::inet, true)`, key.Hash()). + Scan(&valid, &record); err != nil || !valid { + t.Fatalf("authenticate: valid %v err %v", valid, err) + } + return record + } + if !doorSays() { + t.Fatal("the door reads record_bodies false for a recording consumer") + } + + // Switching off is revoking: a tenant-admin without self-service. + status, body, resp = mcCall(t, hOff, ta, "model-consumer-update", map[string]any{"id": onID, "record_bodies": false}) + if status != http.StatusOK || recordOf(resp) != false { + t.Fatalf("tenant-admin switches off: %d %s, want 200 with record_bodies false", status, body) + } + if doorSays() { + t.Fatal("after switching off the door still reads record_bodies true") + } + // And on again by the server-admin, with the confirmation. + status, body, resp = mcCall(t, hOff, admin, "model-consumer-update", + map[string]any{"id": onID, "record_bodies": true, "confirm_record_bodies": true}) + if status != http.StatusOK || recordOf(resp) != true || !doorSays() { + t.Fatalf("server-admin switches on: %d %s, want 200 with record_bodies true read by the door", status, body) + } + + // The read form names it for every reader; the list too. + for _, ar := range []*auth.AuthResult{admin, ta} { + _, body, r := mcCall(t, hOff, ar, "model-consumer-list", map[string]any{"status": []string{"all"}}) + cs, _ := r["consumers"].([]any) + seen := 0 + for _, c := range cs { + m := c.(map[string]any) + want := m["id"] == onID + if m["record_bodies"] != want { + t.Errorf("list (server-admin %v): consumer %v record_bodies %v, want %v", ar.IsServerAdmin(), m["label"], m["record_bodies"], want) + } + seen++ + } + if seen == 0 { + t.Fatalf("empty list: %s", body) + } + } + + // The trail: on (create), off, on — each an audited state. + _, body, r := mcCall(t, hOff, ta, "model-consumer-get", map[string]any{"id": onID}) + trail, _ := r["audit"].([]any) + var flips []string + for _, row := range trail { + m := row.(map[string]any) + if m["entity_type"] != "model_consumer" { + continue + } + nv, _ := m["new_value"].(map[string]any) + flips = append(flips, m["action"].(string)+":"+strings.ToLower(strings.TrimSpace(fmtAny(nv["record_bodies"])))) + } + if strings.Join(flips, ",") != "update:true,update:false,create:true" { + t.Errorf("audit trail of the switch %v (body %s), want update:true, update:false, create:true (newest first)", flips, body) + } +} + +func fmtAny(v any) string { + switch x := v.(type) { + case bool: + if x { + return "true" + } + return "false" + case nil: + return "" + } + return "?" +} diff --git a/go/internal/handler/status.go b/go/internal/handler/status.go index ab277a16d..ca3fcb133 100644 --- a/go/internal/handler/status.go +++ b/go/internal/handler/status.go @@ -307,11 +307,17 @@ type statusResponse struct { type llmlogWriteStatus struct { InsertFailures int64 `json:"insert_failures"` InsertDropped int64 `json:"insert_dropped"` + // RecordedBodiesLost counts the rows of recording consumers written + // without a body they should carry (llmlog.RecordedBodiesLost; the row + // names it in metadata.gw.record_lost) — monotone since start, like the + // two above. + RecordedBodiesLost int64 `json:"recorded_bodies_lost"` } // readLLMLogWriteStatus is the production llmlogStats source. func readLLMLogWriteStatus() llmlogWriteStatus { - return llmlogWriteStatus{InsertFailures: llmlog.InsertFailures(), InsertDropped: llmlog.InsertDropped()} + return llmlogWriteStatus{InsertFailures: llmlog.InsertFailures(), InsertDropped: llmlog.InsertDropped(), + RecordedBodiesLost: llmlog.RecordedBodiesLost()} } // advisoryRow is one named reason on the admin status surface (A02-W4): diff --git a/go/internal/handler/status_gateway.go b/go/internal/handler/status_gateway.go index 48db0eedf..790cf6d14 100644 --- a/go/internal/handler/status_gateway.go +++ b/go/internal/handler/status_gateway.go @@ -25,7 +25,8 @@ import ( // from the same generation keyed by AuthResult.TenantID (SnapshotForTenant // knows only the home scope; pattern GuardReviewByScope) and carries // only the tenant's own consumers' figures — -// consumers, consumers_used_1h, consumers_expiring, top_consumers_1h, +// consumers, consumers_used_1h, consumers_expiring, recording_consumers, +// top_consumers_1h, // reservations_open and rejections_5m of its consumers — and never // instance_envelope, auth or events (pointers left nil). // - usage_split_24h, federation: server-admin only (foreign-load @@ -59,7 +60,12 @@ type gatewayStatus struct { TopConsumers1h []TopConsumer `json:"top_consumers_1h"` ConsumersUsed1h int64 `json:"consumers_used_1h"` ConsumersExpiring int64 `json:"consumers_expiring"` - InstanceEnvelope *map[string]envelopeUse `json:"instance_envelope,omitempty"` + // RecordingConsumers are the ids of the active consumers whose gateway + // rows keep their request and answer in full (record_bodies, migration + // 197), sorted — every one for a server-admin, the tenant's own for a + // tenant-admin; [] when none records. + RecordingConsumers []string `json:"recording_consumers"` + InstanceEnvelope *map[string]envelopeUse `json:"instance_envelope,omitempty"` Auth *ModelAuthStats `json:"auth,omitempty"` Events *usageevents.Stats `json:"events,omitempty"` // GeneratedAt is when the 30-second generation behind the counts was @@ -177,8 +183,11 @@ func (g *gatewayGeneration) refusalCount(reason, detail string) *int64 { // gatewayCounts are the consumers of one tenant: active ones, those whose // keys were used in the last hour, those with a live key expiring within -// gateway.key_expiry_warn. -type gatewayCounts struct{ consumers, used1h, expiring int64 } +// gateway.key_expiry_warn, and the ids of those that record (sorted). +type gatewayCounts struct { + consumers, used1h, expiring int64 + recording []string +} // gatewayCountsSQL is the generation's one statement on the consumers and // their keys (idx_model_consumers_tenant_active; the key probes are per @@ -189,7 +198,8 @@ SELECT c.tenant_id::text, count(*)::bigint, WHERE k.consumer_id = c.id AND k.last_used_at > $1))::bigint, count(*) FILTER (WHERE EXISTS (SELECT 1 FROM context_model_keys k WHERE k.consumer_id = c.id AND k.revoked_at IS NULL - AND k.expires_at > $2 AND k.expires_at <= $3))::bigint + AND k.expires_at > $2 AND k.expires_at <= $3))::bigint, + COALESCE(array_agg(c.id::text ORDER BY c.id::text) FILTER (WHERE c.record_bodies), '{}') FROM context_model_consumers c WHERE c.active GROUP BY 1` @@ -213,7 +223,7 @@ func (c *StatusCollector) gatewayGenNow(ctx context.Context, f *GatewayFeed) *ga for rows.Next() { var tenant string var n gatewayCounts - if err = rows.Scan(&tenant, &n.consumers, &n.used1h, &n.expiring); err != nil { + if err = rows.Scan(&tenant, &n.consumers, &n.used1h, &n.expiring, &n.recording); err != nil { break } g.byTenant[tenant] = n @@ -256,16 +266,19 @@ func (c *StatusCollector) stampGateway(ctx context.Context, resp *statusResponse if g == nil { return } - gw := &gatewayStatus{Enabled: true, GeneratedAt: &g.at} + gw := &gatewayStatus{Enabled: true, GeneratedAt: &g.at, RecordingConsumers: []string{}} if admin { for _, n := range g.byTenant { gw.Consumers += n.consumers gw.ConsumersUsed1h += n.used1h gw.ConsumersExpiring += n.expiring + gw.RecordingConsumers = append(gw.RecordingConsumers, n.recording...) } + sort.Strings(gw.RecordingConsumers) } else { n := g.byTenant[tenant] gw.Consumers, gw.ConsumersUsed1h, gw.ConsumersExpiring = n.consumers, n.used1h, n.expiring + gw.RecordingConsumers = append(gw.RecordingConsumers, n.recording...) } gw.TopConsumers1h = []TopConsumer{} if f.Ring != nil { diff --git a/go/internal/llmlog/body_readers_census_test.go b/go/internal/llmlog/body_readers_census_test.go new file mode 100644 index 000000000..488ddbb58 --- /dev/null +++ b/go/internal/llmlog/body_readers_census_test.go @@ -0,0 +1,108 @@ +package llmlog + +import ( + "go/ast" + "go/token" + "regexp" + "sort" + "strconv" + "strings" + "testing" +) + +// The readers of the body columns (issue #571, promise 5). A recorded row's +// request_system/request_user/response_content can carry credentials in +// clear text; its bodies are for a server-admin only and for no pipeline. +// This census walks every non-test .go file of the module and lists each +// file whose STRING LITERALS name a body column (SQL, a JSON key) or read a +// row of context_llm_log whole — comments do not count. Every such file is +// classified below with what it does with a recorded row; a new reader of +// the columns turns this test red until it is classified here (and given its +// test). +// +// Not covered, stated rather than assumed: SQL assembled from fragments that +// never spell a column name (none today), the shell scripts of the +// repository (backup.sh and coverage.sh dump the whole database — a backup, +// not a reader of the log), and the web frontend, which reads the bodies +// only through GET /api/llmlog/{id}. +var bodyColumnReaders = map[string]string{ + // The writer: the insert and the retention janitor (EvictBodies NULLs the + // bodies of every row past scheduler.llmlog_retention_days, recorded rows + // included — TestRecordedRowsUnderTheRetentionJanitor). + "internal/llmlog/llmlog.go": "writer and retention janitor", + // GET /api/llmlog/{id}: a server-admin reads every row; anyone else only + // rows of its own knowledge keys (api_key_id) — a gateway row has none, so + // a recorded row is a uniform 404 below server-admin + // (TestRecordedRowReaders, detail). + "internal/handler/llmlog.go": "per-id detail, server-admin only for gateway rows", + // ctx-llmlog-export: the bodies of a recorded row (and fail-closed of a + // gateway row without a readable marker) leave sealed + // (SQLBodiesServerAdminOnly; TestRecordedRowReaders, export). + "internal/llmlogexport/export.go": "bulk export, recorded rows sealed", + // The status page's per-pipeline counts: SELECT * reads its own CTEs + // (edge, roll), the table only for counts and sums — no body. + "internal/llmusage/groups.go": "aggregates only (SELECT * over its CTEs)", +} + +// bodyColumnRE matches a body column name as a word inside a literal; +// wholeRowRE a literal that reads context_llm_log whole (SELECT *, alias.*, +// to_jsonb/row_to_json of a row), which carries the bodies without naming +// them. +var ( + bodyColumnRE = regexp.MustCompile(`\b(request_system|request_user|response_content)\b`) + wholeRowRE = regexp.MustCompile(`(?is)context_llm_log.*?(\bselect\s+\*|\w\.\*|to_jsonb\s*\(|row_to_json\s*\()|(\bselect\s+\*|\w\.\*|to_jsonb\s*\(|row_to_json\s*\().*?context_llm_log`) +) + +func TestBodyColumnReadersCensus(t *testing.T) { + root := gatewayCensusModuleRoot(t) + fset := token.NewFileSet() + files := productionFiles(t, fset, root) + found := map[string][]string{} + for _, cf := range files { + ast.Inspect(cf.file, func(n ast.Node) bool { + lit, ok := n.(*ast.BasicLit) + if !ok || lit.Kind != token.STRING { + return true + } + s, err := strconv.Unquote(lit.Value) + if err != nil { + s = lit.Value + } + if bodyColumnRE.MatchString(s) || wholeRowRE.MatchString(s) { + found[cf.rel] = append(found[cf.rel], fset.Position(lit.Pos()).String()) + } + return true + }) + } + var unclassified, gone []string + for rel, at := range found { + if _, ok := bodyColumnReaders[rel]; !ok { + unclassified = append(unclassified, rel+" ("+strings.Join(at, ", ")+")") + } + } + for rel := range bodyColumnReaders { + if _, ok := found[rel]; !ok { + gone = append(gone, rel) + } + } + sort.Strings(unclassified) + sort.Strings(gone) + t.Logf("census: %d production files, %d name a body column: %v", len(files), len(found), keys(found)) + if len(unclassified) > 0 { + t.Errorf("files whose literals name a context_llm_log body column without a classification in bodyColumnReaders "+ + "(a recorded row's bodies are for a server-admin only — classify the reader and give it its test):\n %s", + strings.Join(unclassified, "\n ")) + } + if len(gone) > 0 { + t.Errorf("classified readers that no longer name a body column (drop them from bodyColumnReaders): %v", gone) + } +} + +func keys(m map[string][]string) []string { + out := make([]string, 0, len(m)) + for k := range m { + out = append(out, k) + } + sort.Strings(out) + return out +} diff --git a/go/internal/llmlog/gateway.go b/go/internal/llmlog/gateway.go index 78b553870..0ce8df869 100644 --- a/go/internal/llmlog/gateway.go +++ b/go/internal/llmlog/gateway.go @@ -172,6 +172,12 @@ type Gateway struct { // forensics ("which requests ran over the leaked key?") through the // consumer index plus this field (§8 d01 (3)); never a column. ModelKeyID string + // Recorded, RecordLost and RecordLostCause are metadata.gw.recorded, + // record_lost and record_lost_cause (recorded.go). GatewayEntry sets + // them from the GatewayRow; a writer never sets them itself. + Recorded bool + RecordLost []string + RecordLostCause string } // gatewayWire is metadata.gw as stored: the keys the rollup trigger reads @@ -190,6 +196,11 @@ type gatewayWire struct { Finish string `json:"finish,omitempty"` ModelKeyID string `json:"model_key_id,omitempty"` PeerInstance string `json:"peer_instance,omitempty"` + // The recording marker (issue #571): absent on every row of a consumer + // without the switch, so those rows stay byte-identical. + Recorded bool `json:"recorded,omitempty"` + RecordLost []string `json:"record_lost,omitempty"` + RecordLostCause string `json:"record_lost_cause,omitempty"` } // StampGateway records WHO made a /v1 request and how it ran: the @@ -257,6 +268,12 @@ func (g Gateway) wire() gatewayWire { if u, err := uuid.Parse(g.PeerInstance); err == nil { w.PeerInstance = u.String() } + if g.Recorded { + w.Recorded = true + if w.RecordLost = cleanRecordLost(g.RecordLost); w.RecordLost != nil && recordLostCauses[g.RecordLostCause] { + w.RecordLostCause = g.RecordLostCause + } + } return w } @@ -349,13 +366,27 @@ type GatewayRow struct { Err *RedactedErr // Request and Response are the serialized client input (messages or // input) and the answer the client received. Stored only as the body - // policy says, capped at 64 KiB each. + // policy says, capped at 64 KiB each — on a Recorded row always and + // whole. Request, Response string // BodyLogging is gateway.body_logging of the request's settings // snapshot; anything but errors or full stores no body, and neither // does a row whose Telemetry.RequiredSensitivity is credentials, empty // or unknown. BodyLogging string + // Recorded is the consumer's recording switch as the door read it + // (auth.ConsumerAuth.RecordBodies, migration 197): the row stores + // Request and Response in full — no cap, no body policy, no seal — and + // carries metadata.gw.recorded (recorded.go). RecordLost and + // RecordLostCause name a body the route could not keep and why; they + // count only on a recorded row. + Recorded bool + RecordLost []string + RecordLostCause string + // RecordedHeld is what the route reserved for Request and Response + // (ReserveRecorded); the writer gives it back once the row is inserted + // or lost. 0 on every row that is not recorded. + RecordedHeld int64 } // GatewayEntry builds the ONE row of a /v1 request: pipeline, StampGateway, @@ -363,10 +394,47 @@ type GatewayRow struct { // Slimmed(false) — always false, never the tenant's devmode: tenant.devmode // is tenant-overridable, and a tenant must not open the seal of a // credentials-class /v1 row for itself (design/06 §4.6, design/04 R-06-1). +// It builds the row of an unrecorded call: Recorded, RecordLost and +// RecordedHeld of r are not its business (a recorded row is +// RecordedGatewayEntry's). // A row without a consumer or with a pipeline outside the vocabulary is a // wiring defect: logged at ERROR (throttled per defect) and still built, so // the defect is visible in the log and the row is not lost. func GatewayEntry(r GatewayRow) Entry { + e := gatewayRowBase(r, false) + store := false + switch strings.ToLower(strings.TrimSpace(r.BodyLogging)) { + case BodyLoggingFull: + store = true + case BodyLoggingErrors: + store = r.Err != nil + } + if store && bodiesAllowed(e.RequiredSensitivity, e.Pipeline) { + e.RequestUser, e.ResponseContent = capBody(r.Request), capBody(r.Response) + } + return e.Slimmed(false) +} + +// RecordedGatewayEntry builds the ONE row of a recorded request (issue #571, +// recorded.go): GatewayEntry's row with metadata.gw.recorded (and +// record_lost, record_lost_cause) and both bodies as the route captured them +// — no body policy, no cap, and no seal: Slimmed would drop them at +// credentials, and the switch is the server-admin's, not a tenant setting. +// Their readers are server-admins only (SQLBodiesServerAdminOnly). The row +// carries what the texts hold of the recording account (RecordedHeld); the +// writer gives it back. RecordGateway takes this builder for a Recorded row +// and GatewayEntry for every other. +func RecordedGatewayEntry(r GatewayRow) Entry { + e := gatewayRowBase(r, true) + e.RequestUser, e.ResponseContent = storable(r.Request), storable(r.Response) + e.recordedHeld = r.RecordedHeld + return e +} + +// gatewayRowBase is what both builders share: pipeline, StampGateway (with +// the recording marker only for a recorded row), the redacted error, the +// folded attempts, and no body yet. +func gatewayRowBase(r GatewayRow, recorded bool) Entry { e := r.Telemetry e.Pipeline = r.Pipeline g := r.Gateway @@ -378,6 +446,10 @@ func GatewayEntry(r GatewayRow) Entry { if r.ConsumerID == "" { wiringError(&lastConsumerWarn, "llmlog: a gateway row without a consumer — the request is unattributed", "pipeline", r.Pipeline) } + g.Recorded, g.RecordLost, g.RecordLostCause = recorded, nil, "" + if recorded { + g.RecordLost, g.RecordLostCause = r.RecordLost, r.RecordLostCause + } e.StampGateway(r.ConsumerID, g) e.Err = nil @@ -393,17 +465,7 @@ func GatewayEntry(r GatewayRow) Entry { } e.RequestSystem, e.RequestUser, e.ResponseContent = "", "", "" - store := false - switch strings.ToLower(strings.TrimSpace(r.BodyLogging)) { - case BodyLoggingFull: - store = true - case BodyLoggingErrors: - store = r.Err != nil - } - if store && bodiesAllowed(e.RequiredSensitivity, e.Pipeline) { - e.RequestUser, e.ResponseContent = capBody(r.Request), capBody(r.Response) - } - return e.Slimmed(false) + return e } // The wiring-defect ERRORs of the gateway row, one throttle per defect: a @@ -452,6 +514,13 @@ func bodiesAllowed(sensitivity, pipeline string) bool { // the gateway (census TestGatewayOAICensus: no llmlog.Record under // internal/oai). Asynchronous like Record. func RecordGateway(pool *pgxpool.Pool, r GatewayRow) { + if r.Recorded { + if len(cleanRecordLost(r.RecordLost)) > 0 { + recordedLost.Add(1) + } + Record(pool, RecordedGatewayEntry(r)) + return + } Record(pool, GatewayEntry(r)) } diff --git a/go/internal/llmlog/gateway_recorded_test.go b/go/internal/llmlog/gateway_recorded_test.go new file mode 100644 index 000000000..70eece129 --- /dev/null +++ b/go/internal/llmlog/gateway_recorded_test.go @@ -0,0 +1,214 @@ +package llmlog + +import ( + "encoding/json" + "strings" + "sync" + "sync/atomic" + "testing" + "time" + + "github.com/jackc/pgx/v5/pgxpool" +) + +// The recorded row (issue #571): a row of a consumer with record_bodies keeps +// its request and its answer whole — under every gateway.body_logging value +// and every required sensitivity (credentials, unset and unknown included), +// past the 64 KiB cap of the body policy — and says so in metadata.gw. + +// recordedRow is a chat row of a recording consumer with a request past the +// cap that carries a credentials pattern. +func recordedRow(pol, sens string) GatewayRow { + secret := "Authorization: Bearer sk-live-571-" + strings.Repeat("Z", 40) + return GatewayRow{ + Pipeline: PipelineGatewayChat, ConsumerID: "0195a6f0-0000-7000-8000-00000000c571", + Gateway: Gateway{Alias: "chat", Finish: FinishStop}, + Telemetry: Entry{RequiredSensitivity: sens, Metadata: map[string]any{}}, + Request: `[{"role":"user","content":"` + secret + strings.Repeat("x", 100<<10) + `"}]`, + Response: `{"choices":[{"message":{"content":"` + strings.Repeat("y", 90<<10) + `"}}]}`, + BodyLogging: pol, + Recorded: true, + } +} + +// gwWire reads metadata.gw back as JSON. +func gwWire(t *testing.T, e Entry) map[string]any { + t.Helper() + raw, err := json.Marshal(e.Metadata["gw"]) + if err != nil { + t.Fatalf("marshal gw: %v", err) + } + var m map[string]any + if err := json.Unmarshal(raw, &m); err != nil { + t.Fatalf("unmarshal gw: %v", err) + } + return m +} + +func TestRecordedRowKeepsWholeBodies(t *testing.T) { + for _, pol := range goldenPolicies { + for _, sens := range goldenSensitivities { + r := recordedRow(pol, sens) + e := RecordedGatewayEntry(r) + if e.RequestUser != r.Request || e.ResponseContent != r.Response || e.RequestSystem != "" { + t.Errorf("policy %q sensitivity %q: stored request %d / answer %d bytes, want the whole %d / %d", + pol, sens, len(e.RequestUser), len(e.ResponseContent), len(r.Request), len(r.Response)) + } + if !strings.Contains(e.RequestUser, "sk-live-571-") { + t.Errorf("policy %q sensitivity %q: the credentials pattern is not in the recorded row", pol, sens) + } + gw := gwWire(t, e) + if gw["recorded"] != true || gw["record_lost"] != nil { + t.Errorf("policy %q sensitivity %q: metadata.gw %v, want recorded true without record_lost", pol, sens, gw) + } + if e.ConsumerID != r.ConsumerID || e.Pipeline != PipelineGatewayChat || gw["op"] != GatewayOpChat { + t.Errorf("policy %q sensitivity %q: row %s/%s op %v — the attribution is GatewayEntry's", pol, sens, e.Pipeline, e.ConsumerID, gw["op"]) + } + } + } +} + +// TestGatewayEntryIgnoresTheRecordingFields: GatewayEntry builds the row of +// an unrecorded call; recording fields on its input change nothing (the +// marker and the whole bodies are RecordedGatewayEntry's), and a recorded row +// built by it would be sealed like any other. +func TestGatewayEntryIgnoresTheRecordingFields(t *testing.T) { + names, rows := unrecordedMatrix() + for _, n := range names { + r := rows[n] + base := goldenLine(n, GatewayEntry(r)) + r.RecordLost, r.RecordLostCause, r.RecordedHeld = []string{RecordLostRequest}, RecordLostMemory, 42 + if got := goldenLine(n, GatewayEntry(r)); got != base { + t.Fatalf("%s: recording fields on an unrecorded row changed it:\n got %s\n want %s", n, got, base) + } + } +} + +func TestRecordedRowNamesWhatItLost(t *testing.T) { + r := recordedRow(BodyLoggingNone, "credentials") + r.Request = "" + r.RecordLost = []string{"bogus", RecordLostResponse, RecordLostRequest, RecordLostRequest} + r.RecordLostCause = RecordLostMemory + gw := gwWire(t, RecordedGatewayEntry(r)) + lost, _ := json.Marshal(gw["record_lost"]) + if string(lost) != `["request","response"]` || gw["record_lost_cause"] != RecordLostMemory { + t.Errorf("record_lost %s cause %v, want [request response] (vocabulary order, once each, unknown dropped) and memory", lost, gw["record_lost_cause"]) + } + r.RecordLostCause = "made-up" + if gw := gwWire(t, RecordedGatewayEntry(r)); gw["record_lost_cause"] != nil { + t.Errorf("an unknown cause is stored: %v", gw["record_lost_cause"]) + } + r.RecordLost = []string{"bogus"} + if gw := gwWire(t, RecordedGatewayEntry(r)); gw["record_lost"] != nil || gw["record_lost_cause"] != nil { + t.Errorf("no known lost body, yet record_lost %v cause %v", gw["record_lost"], gw["record_lost_cause"]) + } +} + +// recordedAccount resets the recording account for a test and checks it is +// back at zero afterwards. +func recordedAccount(t *testing.T) { + t.Helper() + if n := recordedHeld.Load(); n != 0 { + t.Fatalf("the recording account holds %d bytes before the test", n) + } + t.Cleanup(func() { + if n := recordedHeld.Load(); n != 0 { + t.Errorf("the recording account holds %d bytes after the test, want 0", n) + recordedHeld.Store(0) + } + }) +} + +func TestRecordedAccountBound(t *testing.T) { + recordedAccount(t) + if !ReserveRecorded(maxRecordedHeld-10) || !ReserveRecorded(10) { + t.Fatal("the account refuses bytes within its bound") + } + if ReserveRecorded(1) { + t.Fatal("the account takes a byte past maxRecordedHeld") + } + if !ReserveRecorded(0) || !ReserveRecorded(-5) { + t.Fatal("a reservation of nothing is refused") + } + if RecordedHeld() != maxRecordedHeld { + t.Fatalf("held %d, want %d", RecordedHeld(), maxRecordedHeld) + } + ReleaseRecorded(maxRecordedHeld) + ReleaseRecorded(-3) + if RecordedHeld() != 0 { + t.Fatalf("held %d after the release, want 0", RecordedHeld()) + } + // Concurrent reservations never pass the bound together. + var wg sync.WaitGroup + var mu sync.Mutex + took := int64(0) + for range 64 { + wg.Add(1) + go func() { + defer wg.Done() + if ReserveRecorded(maxRecordedHeld / 8) { + mu.Lock() + took += maxRecordedHeld / 8 + mu.Unlock() + } + }() + } + wg.Wait() + if took != maxRecordedHeld || RecordedHeld() != maxRecordedHeld { + t.Fatalf("64 concurrent reservations of an eighth took %d (held %d), want exactly the bound %d", took, RecordedHeld(), int64(maxRecordedHeld)) + } + ReleaseRecorded(took) +} + +// TestWriterGivesTheRecordedTextsBack: a recorded row's texts go back to the +// account once the writer is done with them — inserted, failed, dropped at +// a full queue, or written to no pool at all. +func TestWriterGivesTheRecordedTextsBack(t *testing.T) { + recordedAccount(t) + pool := &pgxpool.Pool{} + block := make(chan struct{}) + var inserted atomic.Int64 + w := newWriter(pool, func(*pgxpool.Pool, Entry) error { + <-block + inserted.Add(1) + return nil + }) + row := recordedRow(BodyLoggingNone, "credentials") + if !ReserveRecorded(int64(len(row.Request) + len(row.Response))) { + t.Fatal("reserve") + } + row.RecordedHeld = int64(len(row.Request) + len(row.Response)) + w.enqueue(RecordedGatewayEntry(row)) + if RecordedHeld() != row.RecordedHeld { + t.Fatalf("held %d while the row is queued, want %d", RecordedHeld(), row.RecordedHeld) + } + close(block) + for deadline := time.Now().Add(10 * time.Second); w.pending.Load() > 0 && time.Now().Before(deadline); { + time.Sleep(time.Millisecond) + } + if RecordedHeld() != 0 || inserted.Load() != 1 { + t.Fatalf("after the insert held %d inserted %d, want 0 and 1", RecordedHeld(), inserted.Load()) + } + // A full queue drops the row and gives its texts back. + full := newWriter(pool, func(*pgxpool.Pool, Entry) error { return nil }) + full.queue = make([]Entry, maxQueuedInserts) + full.running = maxConcurrentInserts + if !ReserveRecorded(100) { + t.Fatal("reserve") + } + before := InsertDropped() + full.enqueue(Entry{Pipeline: PipelineGatewayChat, recordedHeld: 100}) + if RecordedHeld() != 0 || InsertDropped() != before+1 { + t.Fatalf("a dropped recorded row: held %d dropped +%d, want 0 and +1", RecordedHeld(), InsertDropped()-before) + } + // No pool: nothing is written, the texts go back. + if !ReserveRecorded(7) { + t.Fatal("reserve") + } + r := recordedRow(BodyLoggingNone, "public") + r.RecordedHeld = 7 + RecordGateway(nil, r) + if RecordedHeld() != 0 { + t.Fatalf("a row without a pool keeps %d bytes", RecordedHeld()) + } +} diff --git a/go/internal/llmlog/gateway_unrecorded_golden_test.go b/go/internal/llmlog/gateway_unrecorded_golden_test.go new file mode 100644 index 000000000..fec4f8724 --- /dev/null +++ b/go/internal/llmlog/gateway_unrecorded_golden_test.go @@ -0,0 +1,131 @@ +package llmlog + +import ( + "crypto/sha256" + "encoding/hex" + "encoding/json" + "fmt" + "os" + "strings" + "testing" +) + +// The rows of a consumer WITHOUT the recording switch (issue #571, promise 4) +// are byte-identical to the rows before it, under every gateway.body_logging +// value: testdata/gateway_unrecorded.golden was written by this test on the +// base commit 2cc39a21 (CTX_LLMLOG_GOLDEN_WRITE=) and is compared here +// row by row — bodies as sha256 and length, every other column and +// metadata.gw as JSON. A change to the row of an unrecorded call shows as +// the first line that differs. + +// goldenPolicies are the body_logging values a row can carry: the three +// policies, unset, and spellings the route never sends (GatewayEntry trims +// and lowers). +var goldenPolicies = []string{BodyLoggingNone, BodyLoggingErrors, BodyLoggingFull, "", " FULL ", "bogus"} + +// goldenSensitivities are the required sensitivities of a row: every class, +// unset and an unknown word. +var goldenSensitivities = []string{"credentials", "personal", "internal", "public", "", "bogus"} + +// goldenBodies are the request texts: short, a credentials pattern, past the +// 64 KiB cap, invalid UTF-8 and NUL. +func goldenBodies() map[string]string { + return map[string]string{ + "short": `[{"role":"user","content":"hi"}]`, + "secret": `[{"role":"user","content":"password=hunter2-correct-horse"}]`, + "70KiB": `[{"role":"user","content":"` + strings.Repeat("abcdefgh", 70<<7) + `"}]`, + "bytes": "a\xffb\x00c" + strings.Repeat("é", 40000), + } +} + +// unrecordedMatrix is every row the golden holds, keyed by a stable name. +func unrecordedMatrix() (names []string, rows map[string]GatewayRow) { + rows = map[string]GatewayRow{} + bodies := goldenBodies() + for _, pipe := range []string{PipelineGatewayChat, PipelineGatewayEmbeddings, PipelineGatewayRerank} { + for _, pol := range goldenPolicies { + for _, sens := range goldenSensitivities { + for _, withErr := range []bool{false, true} { + for _, bname := range []string{"short", "secret", "70KiB", "bytes"} { + r := GatewayRow{ + Pipeline: pipe, ConsumerID: "0195a6f0-0000-7000-8000-00000000c571", + Gateway: Gateway{Alias: "chat", Hop: 1, Usage: UsageBackend, Finish: FinishStop, + ModelKeyID: "0195a6f0-0000-7000-8000-00000000a571", ClientReqID: "req-571"}, + Telemetry: Entry{Model: "m", Host: "h", PromptTokens: 7, RequiredSensitivity: sens, + Metadata: map[string]any{"sub_batches": 1}}, + Attempts: []WireAttempt{{Backend: "spark", Class: "ok"}}, + Request: bodies[bname], + Response: `{"answer":"` + bname + `"}`, + BodyLogging: pol, + } + if withErr { + r.Err = &RedactedErr{Class: "server_fault", Status: 502, Code: "upstream_error"} + } + name := fmt.Sprintf("%s|%q|%q|err=%t|%s", pipe, pol, sens, withErr, bname) + names = append(names, name) + rows[name] = r + } + } + } + } + } + return names, rows +} + +// goldenLine renders the row GatewayEntry builds: bodies as sha256:len, the +// rest as JSON. +func goldenLine(name string, e Entry) string { + h := func(s string) string { + sum := sha256.Sum256([]byte(s)) + return fmt.Sprintf("%s:%d", hex.EncodeToString(sum[:8]), len(s)) + } + errText := "" + if e.Err != nil { + errText = e.Err.Error() + } + md, err := json.Marshal(e.Metadata) + if err != nil { + md = []byte("unmarshalable: " + err.Error()) + } + return fmt.Sprintf("%s\tsys=%s user=%s resp=%s err=%q pipe=%s consumer=%s key=%q attempt=%d sens=%q md=%s", + name, h(e.RequestSystem), h(e.RequestUser), h(e.ResponseContent), errText, e.Pipeline, e.ConsumerID, + e.APIKeyID, e.Attempt, e.RequiredSensitivity, md) +} + +func TestGatewayUnrecordedRowsMatchTheBase(t *testing.T) { + names, rows := unrecordedMatrix() + var b strings.Builder + for _, n := range names { + b.WriteString(goldenLine(n, GatewayEntry(rows[n]))) + b.WriteByte('\n') + } + if out := os.Getenv("CTX_LLMLOG_GOLDEN_WRITE"); out != "" { + if err := os.WriteFile(out, []byte(b.String()), 0o600); err != nil { + t.Fatalf("write golden: %v", err) + } + t.Logf("wrote %d rows to %s", len(names), out) + return + } + raw, err := os.ReadFile("testdata/gateway_unrecorded.golden") + if err != nil { + t.Fatalf("read golden: %v", err) + } + want := strings.Split(strings.TrimSuffix(string(raw), "\n"), "\n") + got := strings.Split(strings.TrimSuffix(b.String(), "\n"), "\n") + if len(got) != len(want) { + t.Fatalf("%d rows, the golden of the base holds %d", len(got), len(want)) + } + diffs := 0 + for i := range want { + if got[i] != want[i] { + diffs++ + if diffs <= 5 { + t.Errorf("row %d differs from the base:\n got %s\n want %s", i, got[i], want[i]) + } + } + } + if diffs > 0 { + t.Fatalf("%d of %d unrecorded rows differ from the base", diffs, len(want)) + } + t.Logf("%d unrecorded rows byte-identical to the base (2cc39a21)", len(want)) +} diff --git a/go/internal/llmlog/llmlog.go b/go/internal/llmlog/llmlog.go index 4a064290d..de37c0e41 100644 --- a/go/internal/llmlog/llmlog.go +++ b/go/internal/llmlog/llmlog.go @@ -133,6 +133,11 @@ type Entry struct { // persists as NULL instead of a fake 0 — Duration measures the wire // call, and there was none. NoWireCall bool + + // recordedHeld is what a recorded gateway row's texts hold of the + // recording account (recorded.go); the writer releases it when the row + // is inserted, fails or is dropped. Set by GatewayEntry only. + recordedHeld int64 } // StampPrompt records WHICH prompt body produced this row: metadata.prompt_id @@ -285,6 +290,7 @@ func InsertDropped() int64 { return insertDropped.Load() } // closed pool — is allowed: the row is then a counted failure. func Record(pool *pgxpool.Pool, e Entry) { if pool == nil || e.Pipeline == "" { + ReleaseRecorded(e.recordedHeld) return } writerFor(pool).enqueue(e) @@ -294,6 +300,7 @@ func (w *writer) enqueue(e Entry) { w.mu.Lock() if len(w.queue) >= maxQueuedInserts { w.mu.Unlock() + ReleaseRecorded(e.recordedHeld) insertDropped.Add(1) warnLoss("llmlog: insert queue full, row dropped", e.Pipeline, nil) return @@ -332,6 +339,7 @@ func (w *writer) drain() { slog.Debug("llmlog: insert failed", "pipeline", e.Pipeline, "error", err) warnLoss("llmlog: insert failed, row lost", e.Pipeline, err) } + ReleaseRecorded(e.recordedHeld) // the texts are no longer the writer's w.pending.Add(-1) } } diff --git a/go/internal/llmlog/recorded.go b/go/internal/llmlog/recorded.go new file mode 100644 index 000000000..482a62db5 --- /dev/null +++ b/go/internal/llmlog/recorded.go @@ -0,0 +1,121 @@ +package llmlog + +import ( + "fmt" + "slices" + "sync/atomic" +) + +// Recording (issue #571, migration 197). A model consumer with the switch +// record_bodies on has every gateway row of its own written with the request +// and the answer in full — whatever gateway.body_logging, the alias, the +// consumer's floor, the body scan or Ctx-Sensitivity say, and without +// gatewayBodyCap. Such a row is marked metadata.gw.recorded = true and can +// carry credentials in clear text: its bodies are for a server-admin only +// (SQLBodiesServerAdminOnly). +// +// The texts a recorded row keeps are held against ONE process-wide account, +// not against the request's in-flight budget: from the moment a route +// captures a text (ReserveRecorded) until the writer has inserted the row or +// lost it (queue full, failed insert). The request path books nothing for +// them, so its bookings, its 503s and its answer are the same with and +// without the switch; and the rows of recorded calls the writer has not +// inserted yet — a slow database, a burst of large requests — hold at most +// maxRecordedHeld bytes of text. A text the account cannot take is not +// captured: the row is still written, without it, and says so +// (metadata.gw.record_lost, record_lost_cause "memory"). + +// maxRecordedHeld bounds the bytes of recorded texts the process holds at +// once — captured by running requests, queued and in insertion. Hardcoded on +// purpose, like maxQueuedInserts: it bounds the process's own bookkeeping, +// not anybody's policy. 128 MiB beside the default gateway.inflight_budget +// of 512 MiB stay inside the container's 1536 MiB (docs/operations.md +// "Recording a consumer"); the largest non-streamed row — a request text of +// at most 2 × gateway.max_request_bytes (an invalid byte becomes U+FFFD) and +// the answer the client received — fits it at the defaults. +const maxRecordedHeld = 128 << 20 + +// metadata.gw.record_lost — the bodies a recorded row should carry and does +// not. +const ( + RecordLostRequest = "request" + RecordLostResponse = "response" +) + +// metadata.gw.record_lost_cause — why. +const ( + // RecordLostMemory: maxRecordedHeld could not take the text. + RecordLostMemory = "memory" + // RecordLostShutdown: the shutdown's forced settle wrote the row of a + // request still open (W06-13); that row carries no body. + RecordLostShutdown = "shutdown" +) + +var ( + recordedHeld atomic.Int64 // bytes of recorded texts held (ReserveRecorded − ReleaseRecorded) + recordedLost atomic.Int64 // recorded rows written without a body they should carry +) + +// ReserveRecorded takes n bytes of a recorded text from the account; false +// when they do not fit (nothing is taken then). n <= 0 always fits. +func ReserveRecorded(n int64) bool { + if n <= 0 { + return true + } + for { + cur := recordedHeld.Load() + if cur+n > maxRecordedHeld { + return false + } + if recordedHeld.CompareAndSwap(cur, cur+n) { + return true + } + } +} + +// ReleaseRecorded gives n bytes back (n <= 0: nothing). +func ReleaseRecorded(n int64) { + if n > 0 { + recordedHeld.Add(-n) + } +} + +// RecordedHeld is the bytes of recorded texts the process holds now. +func RecordedHeld() int64 { return recordedHeld.Load() } + +// RecordedBodiesLost counts, since the process started, the recorded rows +// the writer was handed without a body they should carry (record_lost). A +// recorded row the queue drops or the database refuses is in InsertDropped +// or InsertFailures, like every row. +func RecordedBodiesLost() int64 { return recordedLost.Load() } + +// recordLostKinds and recordLostCauses are the vocabularies of the two keys. +var ( + recordLostKinds = []string{RecordLostRequest, RecordLostResponse} + recordLostCauses = map[string]bool{RecordLostMemory: true, RecordLostShutdown: true} +) + +// cleanRecordLost keeps the known bodies of lost, each once, in vocabulary +// order; nil when none is left. +func cleanRecordLost(lost []string) []string { + var out []string + for _, k := range recordLostKinds { + if slices.Contains(lost, k) { + out = append(out, k) + } + } + return out +} + +// SQLBodiesServerAdminOnly is the SQL condition, over the context_llm_log +// alias t, of a row whose bodies only a server-admin may read: a gateway row +// (consumer_id set, or a gateway pipeline) unless its metadata.gw is an +// object that does not mark it recorded — recorded = true, and fail-closed a +// gateway row whose marker is missing or unreadable (metadata.gw absent or +// not an object, recorded anything but absent or false). Every other row +// (knowledge-key and background pipelines) is untouched. Never NULL. +func SQLBodiesServerAdminOnly(t string) string { + return fmt.Sprintf(`((%[1]s.consumer_id IS NOT NULL OR COALESCE(%[1]s.pipeline LIKE 'gateway-%%', false)) + AND NOT (COALESCE(jsonb_typeof(%[1]s.metadata->'gw') = 'object', false) + AND COALESCE(%[1]s.metadata->'gw'->'recorded', 'false'::jsonb) = 'false'::jsonb))`, t) +} diff --git a/go/internal/llmlog/recorded_integration_test.go b/go/internal/llmlog/recorded_integration_test.go new file mode 100644 index 000000000..fae76db5e --- /dev/null +++ b/go/internal/llmlog/recorded_integration_test.go @@ -0,0 +1,118 @@ +//go:build integration + +// The recorded row (issue #571) over real inserts: +// +// - TestRecordedRowLandsWhole: a recorded row with a credentials-class +// sensitivity, a request and an answer past 64 KiB lands with both +// bodies whole and metadata.gw.recorded, and gives its texts back to the +// recording account once written; +// - TestRecordedRowInsertCost (opt-in, CTX_RECORD_PROBE=1): the insert time +// and the stored size of recorded rows up to the largest non-streamed row +// at the default caps (a request text of 2 × gateway.max_request_bytes = +// 16 MiB and a 24 MiB answer), against insertTimeout (5 s). +// +// go test -tags=integration -p 1 -count=1 -run 'TestRecordedRow' -v ./internal/llmlog/ +// CTX_RECORD_PROBE=1 go test -tags=integration -p 1 -count=1 -run TestRecordedRowInsertCost -v ./internal/llmlog/ +package llmlog_test + +import ( + "context" + "os" + "strings" + "testing" + "time" + + "github.com/GottZ/ctx/internal/llmlog" + "github.com/GottZ/ctx/internal/testdb" +) + +func recordedGwiRow(request, response string) llmlog.GatewayRow { + r := gwiRow(llmlog.PipelineGatewayChat) + r.Telemetry.RequiredSensitivity = "credentials" + r.Request, r.Response, r.Recorded = request, response, true + return r +} + +func TestRecordedRowLandsWhole(t *testing.T) { + if testing.Short() { + t.Skip("integration test") + } + ctx := context.Background() + pool := testdb.SetupTestDB(t) + req := `[{"role":"user","content":"password=s3cr3t-571 ` + strings.Repeat("r", 100<<10) + `"}]` + resp := `{"choices":[{"message":{"content":"` + strings.Repeat("a", 90<<10) + `"}}]}` + held := int64(len(req) + len(resp)) + before := llmlog.RecordedHeld() + if !llmlog.ReserveRecorded(held) { + t.Fatal("reserve") + } + row := recordedGwiRow(req, resp) + row.RecordedHeld = held + llmlog.RecordGateway(pool, row) + if err := llmlog.Settle(ctx, pool); err != nil { + t.Fatalf("settle: %v", err) + } + if got := llmlog.RecordedHeld(); got != before { + t.Errorf("the recording account holds %d bytes after the insert, want %d", got, before) + } + var user, answer, sens, recorded string + if err := pool.QueryRow(ctx, `SELECT request_user, response_content, required_sensitivity, metadata->'gw'->>'recorded' + FROM context_llm_log WHERE consumer_id = $1::uuid`, gwiConsumer).Scan(&user, &answer, &sens, &recorded); err != nil { + t.Fatalf("read: %v", err) + } + if user != req || answer != resp || sens != "credentials" || recorded != "true" { + t.Errorf("stored request %d/%d bytes, answer %d/%d, sensitivity %s, recorded %s — want both whole, credentials, true", + len(user), len(req), len(answer), len(resp), sens, recorded) + } +} + +func TestRecordedRowInsertCost(t *testing.T) { + if os.Getenv("CTX_RECORD_PROBE") == "" { + t.Skip("opt-in probe: CTX_RECORD_PROBE=1") + } + ctx := context.Background() + pool := testdb.SetupTestDB(t) + // Text that compresses like a prompt (repeated words) and text that does + // not (pseudo-random letters) — TOAST compresses the first. + words := func(n int) string { + var b strings.Builder + for b.Len() < n { + b.WriteString("the quick brown fox jumps over the lazy dog ") + } + return b.String()[:n] + } + noise := func(n int, seed uint64) string { + b := make([]byte, n) + x := seed + for i := range b { + x ^= x << 13 + x ^= x >> 7 + x ^= x << 17 + b[i] = 'a' + byte(x%26) + } + return string(b) + } + for _, c := range []struct { + name string + request, resp string + }{ + {"1 MiB words", words(1 << 20), words(64 << 10)}, + {"8 MiB words + 4 MiB", words(8 << 20), words(4 << 20)}, + {"16 MiB + 24 MiB words", words(16 << 20), words(24 << 20)}, + {"16 MiB + 24 MiB noise", noise(16<<20, 571), noise(24<<20, 197)}, + } { + start := time.Now() + llmlog.RecordGateway(pool, recordedGwiRow(c.request, c.resp)) + if err := llmlog.Settle(ctx, pool); err != nil { + t.Fatalf("%s: settle: %v", c.name, err) + } + took := time.Since(start) + var size int64 + if err := pool.QueryRow(ctx, `SELECT pg_column_size(request_user) + pg_column_size(response_content) + FROM context_llm_log ORDER BY created_at DESC LIMIT 1`).Scan(&size); err != nil { + t.Fatalf("%s: size: %v", c.name, err) + } + t.Logf("%s: %d bytes of text → insert %v, stored %d bytes (failures so far %d)", + c.name, len(c.request)+len(c.resp), took.Round(time.Millisecond), size, llmlog.InsertFailures()) + } +} diff --git a/go/internal/llmlog/testdata/gateway_unrecorded.golden b/go/internal/llmlog/testdata/gateway_unrecorded.golden new file mode 100644 index 000000000..2ff2b0317 --- /dev/null +++ b/go/internal/llmlog/testdata/gateway_unrecorded.golden @@ -0,0 +1,864 @@ +gateway-chat|"none"|"credentials"|err=false|short sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="credentials" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|"none"|"credentials"|err=false|secret sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="credentials" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|"none"|"credentials"|err=false|70KiB sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="credentials" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|"none"|"credentials"|err=false|bytes sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="credentials" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|"none"|"credentials"|err=true|short sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="credentials" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|"none"|"credentials"|err=true|secret sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="credentials" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|"none"|"credentials"|err=true|70KiB sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="credentials" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|"none"|"credentials"|err=true|bytes sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="credentials" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|"none"|"personal"|err=false|short sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="personal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|"none"|"personal"|err=false|secret sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="personal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|"none"|"personal"|err=false|70KiB sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="personal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|"none"|"personal"|err=false|bytes sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="personal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|"none"|"personal"|err=true|short sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="personal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|"none"|"personal"|err=true|secret sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="personal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|"none"|"personal"|err=true|70KiB sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="personal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|"none"|"personal"|err=true|bytes sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="personal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|"none"|"internal"|err=false|short sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="internal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|"none"|"internal"|err=false|secret sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="internal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|"none"|"internal"|err=false|70KiB sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="internal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|"none"|"internal"|err=false|bytes sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="internal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|"none"|"internal"|err=true|short sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="internal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|"none"|"internal"|err=true|secret sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="internal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|"none"|"internal"|err=true|70KiB sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="internal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|"none"|"internal"|err=true|bytes sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="internal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|"none"|"public"|err=false|short sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="public" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|"none"|"public"|err=false|secret sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="public" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|"none"|"public"|err=false|70KiB sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="public" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|"none"|"public"|err=false|bytes sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="public" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|"none"|"public"|err=true|short sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="public" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|"none"|"public"|err=true|secret sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="public" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|"none"|"public"|err=true|70KiB sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="public" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|"none"|"public"|err=true|bytes sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="public" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|"none"|""|err=false|short sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|"none"|""|err=false|secret sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|"none"|""|err=false|70KiB sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|"none"|""|err=false|bytes sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|"none"|""|err=true|short sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|"none"|""|err=true|secret sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|"none"|""|err=true|70KiB sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|"none"|""|err=true|bytes sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|"none"|"bogus"|err=false|short sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="bogus" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|"none"|"bogus"|err=false|secret sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="bogus" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|"none"|"bogus"|err=false|70KiB sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="bogus" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|"none"|"bogus"|err=false|bytes sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="bogus" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|"none"|"bogus"|err=true|short sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="bogus" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|"none"|"bogus"|err=true|secret sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="bogus" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|"none"|"bogus"|err=true|70KiB sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="bogus" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|"none"|"bogus"|err=true|bytes sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="bogus" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|"errors"|"credentials"|err=false|short sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="credentials" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|"errors"|"credentials"|err=false|secret sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="credentials" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|"errors"|"credentials"|err=false|70KiB sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="credentials" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|"errors"|"credentials"|err=false|bytes sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="credentials" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|"errors"|"credentials"|err=true|short sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="credentials" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|"errors"|"credentials"|err=true|secret sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="credentials" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|"errors"|"credentials"|err=true|70KiB sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="credentials" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|"errors"|"credentials"|err=true|bytes sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="credentials" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|"errors"|"personal"|err=false|short sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="personal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|"errors"|"personal"|err=false|secret sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="personal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|"errors"|"personal"|err=false|70KiB sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="personal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|"errors"|"personal"|err=false|bytes sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="personal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|"errors"|"personal"|err=true|short sys=e3b0c44298fc1c14:0 user=b03d228fdf33e7c8:32 resp=d0a697f30bcc23be:18 err="server_fault 502 upstream_error" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="personal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|"errors"|"personal"|err=true|secret sys=e3b0c44298fc1c14:0 user=f671fb2c9b1dd57f:60 resp=7a60296900e9d441:19 err="server_fault 502 upstream_error" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="personal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|"errors"|"personal"|err=true|70KiB sys=e3b0c44298fc1c14:0 user=c83e6014ce9611f2:65536 resp=5b69fe1525f7898f:18 err="server_fault 502 upstream_error" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="personal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|"errors"|"personal"|err=true|bytes sys=e3b0c44298fc1c14:0 user=f6cbb609d68544f3:65535 resp=2de7bf232ff41013:18 err="server_fault 502 upstream_error" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="personal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|"errors"|"internal"|err=false|short sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="internal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|"errors"|"internal"|err=false|secret sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="internal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|"errors"|"internal"|err=false|70KiB sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="internal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|"errors"|"internal"|err=false|bytes sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="internal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|"errors"|"internal"|err=true|short sys=e3b0c44298fc1c14:0 user=b03d228fdf33e7c8:32 resp=d0a697f30bcc23be:18 err="server_fault 502 upstream_error" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="internal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|"errors"|"internal"|err=true|secret sys=e3b0c44298fc1c14:0 user=f671fb2c9b1dd57f:60 resp=7a60296900e9d441:19 err="server_fault 502 upstream_error" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="internal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|"errors"|"internal"|err=true|70KiB sys=e3b0c44298fc1c14:0 user=c83e6014ce9611f2:65536 resp=5b69fe1525f7898f:18 err="server_fault 502 upstream_error" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="internal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|"errors"|"internal"|err=true|bytes sys=e3b0c44298fc1c14:0 user=f6cbb609d68544f3:65535 resp=2de7bf232ff41013:18 err="server_fault 502 upstream_error" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="internal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|"errors"|"public"|err=false|short sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="public" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|"errors"|"public"|err=false|secret sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="public" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|"errors"|"public"|err=false|70KiB sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="public" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|"errors"|"public"|err=false|bytes sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="public" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|"errors"|"public"|err=true|short sys=e3b0c44298fc1c14:0 user=b03d228fdf33e7c8:32 resp=d0a697f30bcc23be:18 err="server_fault 502 upstream_error" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="public" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|"errors"|"public"|err=true|secret sys=e3b0c44298fc1c14:0 user=f671fb2c9b1dd57f:60 resp=7a60296900e9d441:19 err="server_fault 502 upstream_error" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="public" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|"errors"|"public"|err=true|70KiB sys=e3b0c44298fc1c14:0 user=c83e6014ce9611f2:65536 resp=5b69fe1525f7898f:18 err="server_fault 502 upstream_error" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="public" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|"errors"|"public"|err=true|bytes sys=e3b0c44298fc1c14:0 user=f6cbb609d68544f3:65535 resp=2de7bf232ff41013:18 err="server_fault 502 upstream_error" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="public" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|"errors"|""|err=false|short sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|"errors"|""|err=false|secret sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|"errors"|""|err=false|70KiB sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|"errors"|""|err=false|bytes sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|"errors"|""|err=true|short sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|"errors"|""|err=true|secret sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|"errors"|""|err=true|70KiB sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|"errors"|""|err=true|bytes sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|"errors"|"bogus"|err=false|short sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="bogus" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|"errors"|"bogus"|err=false|secret sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="bogus" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|"errors"|"bogus"|err=false|70KiB sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="bogus" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|"errors"|"bogus"|err=false|bytes sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="bogus" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|"errors"|"bogus"|err=true|short sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="bogus" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|"errors"|"bogus"|err=true|secret sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="bogus" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|"errors"|"bogus"|err=true|70KiB sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="bogus" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|"errors"|"bogus"|err=true|bytes sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="bogus" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|"full"|"credentials"|err=false|short sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="credentials" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|"full"|"credentials"|err=false|secret sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="credentials" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|"full"|"credentials"|err=false|70KiB sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="credentials" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|"full"|"credentials"|err=false|bytes sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="credentials" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|"full"|"credentials"|err=true|short sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="credentials" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|"full"|"credentials"|err=true|secret sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="credentials" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|"full"|"credentials"|err=true|70KiB sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="credentials" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|"full"|"credentials"|err=true|bytes sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="credentials" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|"full"|"personal"|err=false|short sys=e3b0c44298fc1c14:0 user=b03d228fdf33e7c8:32 resp=d0a697f30bcc23be:18 err="" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="personal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|"full"|"personal"|err=false|secret sys=e3b0c44298fc1c14:0 user=f671fb2c9b1dd57f:60 resp=7a60296900e9d441:19 err="" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="personal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|"full"|"personal"|err=false|70KiB sys=e3b0c44298fc1c14:0 user=c83e6014ce9611f2:65536 resp=5b69fe1525f7898f:18 err="" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="personal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|"full"|"personal"|err=false|bytes sys=e3b0c44298fc1c14:0 user=f6cbb609d68544f3:65535 resp=2de7bf232ff41013:18 err="" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="personal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|"full"|"personal"|err=true|short sys=e3b0c44298fc1c14:0 user=b03d228fdf33e7c8:32 resp=d0a697f30bcc23be:18 err="server_fault 502 upstream_error" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="personal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|"full"|"personal"|err=true|secret sys=e3b0c44298fc1c14:0 user=f671fb2c9b1dd57f:60 resp=7a60296900e9d441:19 err="server_fault 502 upstream_error" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="personal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|"full"|"personal"|err=true|70KiB sys=e3b0c44298fc1c14:0 user=c83e6014ce9611f2:65536 resp=5b69fe1525f7898f:18 err="server_fault 502 upstream_error" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="personal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|"full"|"personal"|err=true|bytes sys=e3b0c44298fc1c14:0 user=f6cbb609d68544f3:65535 resp=2de7bf232ff41013:18 err="server_fault 502 upstream_error" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="personal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|"full"|"internal"|err=false|short sys=e3b0c44298fc1c14:0 user=b03d228fdf33e7c8:32 resp=d0a697f30bcc23be:18 err="" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="internal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|"full"|"internal"|err=false|secret sys=e3b0c44298fc1c14:0 user=f671fb2c9b1dd57f:60 resp=7a60296900e9d441:19 err="" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="internal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|"full"|"internal"|err=false|70KiB sys=e3b0c44298fc1c14:0 user=c83e6014ce9611f2:65536 resp=5b69fe1525f7898f:18 err="" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="internal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|"full"|"internal"|err=false|bytes sys=e3b0c44298fc1c14:0 user=f6cbb609d68544f3:65535 resp=2de7bf232ff41013:18 err="" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="internal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|"full"|"internal"|err=true|short sys=e3b0c44298fc1c14:0 user=b03d228fdf33e7c8:32 resp=d0a697f30bcc23be:18 err="server_fault 502 upstream_error" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="internal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|"full"|"internal"|err=true|secret sys=e3b0c44298fc1c14:0 user=f671fb2c9b1dd57f:60 resp=7a60296900e9d441:19 err="server_fault 502 upstream_error" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="internal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|"full"|"internal"|err=true|70KiB sys=e3b0c44298fc1c14:0 user=c83e6014ce9611f2:65536 resp=5b69fe1525f7898f:18 err="server_fault 502 upstream_error" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="internal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|"full"|"internal"|err=true|bytes sys=e3b0c44298fc1c14:0 user=f6cbb609d68544f3:65535 resp=2de7bf232ff41013:18 err="server_fault 502 upstream_error" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="internal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|"full"|"public"|err=false|short sys=e3b0c44298fc1c14:0 user=b03d228fdf33e7c8:32 resp=d0a697f30bcc23be:18 err="" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="public" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|"full"|"public"|err=false|secret sys=e3b0c44298fc1c14:0 user=f671fb2c9b1dd57f:60 resp=7a60296900e9d441:19 err="" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="public" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|"full"|"public"|err=false|70KiB sys=e3b0c44298fc1c14:0 user=c83e6014ce9611f2:65536 resp=5b69fe1525f7898f:18 err="" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="public" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|"full"|"public"|err=false|bytes sys=e3b0c44298fc1c14:0 user=f6cbb609d68544f3:65535 resp=2de7bf232ff41013:18 err="" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="public" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|"full"|"public"|err=true|short sys=e3b0c44298fc1c14:0 user=b03d228fdf33e7c8:32 resp=d0a697f30bcc23be:18 err="server_fault 502 upstream_error" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="public" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|"full"|"public"|err=true|secret sys=e3b0c44298fc1c14:0 user=f671fb2c9b1dd57f:60 resp=7a60296900e9d441:19 err="server_fault 502 upstream_error" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="public" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|"full"|"public"|err=true|70KiB sys=e3b0c44298fc1c14:0 user=c83e6014ce9611f2:65536 resp=5b69fe1525f7898f:18 err="server_fault 502 upstream_error" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="public" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|"full"|"public"|err=true|bytes sys=e3b0c44298fc1c14:0 user=f6cbb609d68544f3:65535 resp=2de7bf232ff41013:18 err="server_fault 502 upstream_error" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="public" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|"full"|""|err=false|short sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|"full"|""|err=false|secret sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|"full"|""|err=false|70KiB sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|"full"|""|err=false|bytes sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|"full"|""|err=true|short sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|"full"|""|err=true|secret sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|"full"|""|err=true|70KiB sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|"full"|""|err=true|bytes sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|"full"|"bogus"|err=false|short sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="bogus" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|"full"|"bogus"|err=false|secret sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="bogus" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|"full"|"bogus"|err=false|70KiB sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="bogus" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|"full"|"bogus"|err=false|bytes sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="bogus" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|"full"|"bogus"|err=true|short sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="bogus" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|"full"|"bogus"|err=true|secret sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="bogus" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|"full"|"bogus"|err=true|70KiB sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="bogus" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|"full"|"bogus"|err=true|bytes sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="bogus" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|""|"credentials"|err=false|short sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="credentials" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|""|"credentials"|err=false|secret sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="credentials" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|""|"credentials"|err=false|70KiB sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="credentials" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|""|"credentials"|err=false|bytes sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="credentials" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|""|"credentials"|err=true|short sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="credentials" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|""|"credentials"|err=true|secret sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="credentials" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|""|"credentials"|err=true|70KiB sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="credentials" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|""|"credentials"|err=true|bytes sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="credentials" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|""|"personal"|err=false|short sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="personal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|""|"personal"|err=false|secret sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="personal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|""|"personal"|err=false|70KiB sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="personal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|""|"personal"|err=false|bytes sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="personal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|""|"personal"|err=true|short sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="personal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|""|"personal"|err=true|secret sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="personal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|""|"personal"|err=true|70KiB sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="personal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|""|"personal"|err=true|bytes sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="personal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|""|"internal"|err=false|short sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="internal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|""|"internal"|err=false|secret sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="internal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|""|"internal"|err=false|70KiB sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="internal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|""|"internal"|err=false|bytes sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="internal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|""|"internal"|err=true|short sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="internal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|""|"internal"|err=true|secret sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="internal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|""|"internal"|err=true|70KiB sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="internal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|""|"internal"|err=true|bytes sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="internal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|""|"public"|err=false|short sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="public" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|""|"public"|err=false|secret sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="public" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|""|"public"|err=false|70KiB sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="public" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|""|"public"|err=false|bytes sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="public" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|""|"public"|err=true|short sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="public" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|""|"public"|err=true|secret sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="public" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|""|"public"|err=true|70KiB sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="public" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|""|"public"|err=true|bytes sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="public" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|""|""|err=false|short sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|""|""|err=false|secret sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|""|""|err=false|70KiB sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|""|""|err=false|bytes sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|""|""|err=true|short sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|""|""|err=true|secret sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|""|""|err=true|70KiB sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|""|""|err=true|bytes sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|""|"bogus"|err=false|short sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="bogus" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|""|"bogus"|err=false|secret sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="bogus" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|""|"bogus"|err=false|70KiB sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="bogus" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|""|"bogus"|err=false|bytes sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="bogus" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|""|"bogus"|err=true|short sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="bogus" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|""|"bogus"|err=true|secret sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="bogus" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|""|"bogus"|err=true|70KiB sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="bogus" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|""|"bogus"|err=true|bytes sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="bogus" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|" FULL "|"credentials"|err=false|short sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="credentials" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|" FULL "|"credentials"|err=false|secret sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="credentials" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|" FULL "|"credentials"|err=false|70KiB sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="credentials" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|" FULL "|"credentials"|err=false|bytes sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="credentials" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|" FULL "|"credentials"|err=true|short sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="credentials" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|" FULL "|"credentials"|err=true|secret sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="credentials" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|" FULL "|"credentials"|err=true|70KiB sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="credentials" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|" FULL "|"credentials"|err=true|bytes sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="credentials" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|" FULL "|"personal"|err=false|short sys=e3b0c44298fc1c14:0 user=b03d228fdf33e7c8:32 resp=d0a697f30bcc23be:18 err="" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="personal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|" FULL "|"personal"|err=false|secret sys=e3b0c44298fc1c14:0 user=f671fb2c9b1dd57f:60 resp=7a60296900e9d441:19 err="" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="personal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|" FULL "|"personal"|err=false|70KiB sys=e3b0c44298fc1c14:0 user=c83e6014ce9611f2:65536 resp=5b69fe1525f7898f:18 err="" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="personal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|" FULL "|"personal"|err=false|bytes sys=e3b0c44298fc1c14:0 user=f6cbb609d68544f3:65535 resp=2de7bf232ff41013:18 err="" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="personal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|" FULL "|"personal"|err=true|short sys=e3b0c44298fc1c14:0 user=b03d228fdf33e7c8:32 resp=d0a697f30bcc23be:18 err="server_fault 502 upstream_error" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="personal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|" FULL "|"personal"|err=true|secret sys=e3b0c44298fc1c14:0 user=f671fb2c9b1dd57f:60 resp=7a60296900e9d441:19 err="server_fault 502 upstream_error" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="personal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|" FULL "|"personal"|err=true|70KiB sys=e3b0c44298fc1c14:0 user=c83e6014ce9611f2:65536 resp=5b69fe1525f7898f:18 err="server_fault 502 upstream_error" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="personal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|" FULL "|"personal"|err=true|bytes sys=e3b0c44298fc1c14:0 user=f6cbb609d68544f3:65535 resp=2de7bf232ff41013:18 err="server_fault 502 upstream_error" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="personal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|" FULL "|"internal"|err=false|short sys=e3b0c44298fc1c14:0 user=b03d228fdf33e7c8:32 resp=d0a697f30bcc23be:18 err="" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="internal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|" FULL "|"internal"|err=false|secret sys=e3b0c44298fc1c14:0 user=f671fb2c9b1dd57f:60 resp=7a60296900e9d441:19 err="" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="internal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|" FULL "|"internal"|err=false|70KiB sys=e3b0c44298fc1c14:0 user=c83e6014ce9611f2:65536 resp=5b69fe1525f7898f:18 err="" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="internal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|" FULL "|"internal"|err=false|bytes sys=e3b0c44298fc1c14:0 user=f6cbb609d68544f3:65535 resp=2de7bf232ff41013:18 err="" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="internal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|" FULL "|"internal"|err=true|short sys=e3b0c44298fc1c14:0 user=b03d228fdf33e7c8:32 resp=d0a697f30bcc23be:18 err="server_fault 502 upstream_error" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="internal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|" FULL "|"internal"|err=true|secret sys=e3b0c44298fc1c14:0 user=f671fb2c9b1dd57f:60 resp=7a60296900e9d441:19 err="server_fault 502 upstream_error" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="internal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|" FULL "|"internal"|err=true|70KiB sys=e3b0c44298fc1c14:0 user=c83e6014ce9611f2:65536 resp=5b69fe1525f7898f:18 err="server_fault 502 upstream_error" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="internal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|" FULL "|"internal"|err=true|bytes sys=e3b0c44298fc1c14:0 user=f6cbb609d68544f3:65535 resp=2de7bf232ff41013:18 err="server_fault 502 upstream_error" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="internal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|" FULL "|"public"|err=false|short sys=e3b0c44298fc1c14:0 user=b03d228fdf33e7c8:32 resp=d0a697f30bcc23be:18 err="" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="public" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|" FULL "|"public"|err=false|secret sys=e3b0c44298fc1c14:0 user=f671fb2c9b1dd57f:60 resp=7a60296900e9d441:19 err="" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="public" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|" FULL "|"public"|err=false|70KiB sys=e3b0c44298fc1c14:0 user=c83e6014ce9611f2:65536 resp=5b69fe1525f7898f:18 err="" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="public" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|" FULL "|"public"|err=false|bytes sys=e3b0c44298fc1c14:0 user=f6cbb609d68544f3:65535 resp=2de7bf232ff41013:18 err="" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="public" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|" FULL "|"public"|err=true|short sys=e3b0c44298fc1c14:0 user=b03d228fdf33e7c8:32 resp=d0a697f30bcc23be:18 err="server_fault 502 upstream_error" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="public" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|" FULL "|"public"|err=true|secret sys=e3b0c44298fc1c14:0 user=f671fb2c9b1dd57f:60 resp=7a60296900e9d441:19 err="server_fault 502 upstream_error" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="public" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|" FULL "|"public"|err=true|70KiB sys=e3b0c44298fc1c14:0 user=c83e6014ce9611f2:65536 resp=5b69fe1525f7898f:18 err="server_fault 502 upstream_error" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="public" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|" FULL "|"public"|err=true|bytes sys=e3b0c44298fc1c14:0 user=f6cbb609d68544f3:65535 resp=2de7bf232ff41013:18 err="server_fault 502 upstream_error" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="public" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|" FULL "|""|err=false|short sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|" FULL "|""|err=false|secret sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|" FULL "|""|err=false|70KiB sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|" FULL "|""|err=false|bytes sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|" FULL "|""|err=true|short sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|" FULL "|""|err=true|secret sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|" FULL "|""|err=true|70KiB sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|" FULL "|""|err=true|bytes sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|" FULL "|"bogus"|err=false|short sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="bogus" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|" FULL "|"bogus"|err=false|secret sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="bogus" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|" FULL "|"bogus"|err=false|70KiB sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="bogus" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|" FULL "|"bogus"|err=false|bytes sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="bogus" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|" FULL "|"bogus"|err=true|short sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="bogus" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|" FULL "|"bogus"|err=true|secret sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="bogus" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|" FULL "|"bogus"|err=true|70KiB sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="bogus" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|" FULL "|"bogus"|err=true|bytes sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="bogus" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|"bogus"|"credentials"|err=false|short sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="credentials" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|"bogus"|"credentials"|err=false|secret sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="credentials" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|"bogus"|"credentials"|err=false|70KiB sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="credentials" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|"bogus"|"credentials"|err=false|bytes sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="credentials" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|"bogus"|"credentials"|err=true|short sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="credentials" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|"bogus"|"credentials"|err=true|secret sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="credentials" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|"bogus"|"credentials"|err=true|70KiB sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="credentials" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|"bogus"|"credentials"|err=true|bytes sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="credentials" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|"bogus"|"personal"|err=false|short sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="personal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|"bogus"|"personal"|err=false|secret sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="personal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|"bogus"|"personal"|err=false|70KiB sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="personal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|"bogus"|"personal"|err=false|bytes sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="personal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|"bogus"|"personal"|err=true|short sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="personal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|"bogus"|"personal"|err=true|secret sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="personal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|"bogus"|"personal"|err=true|70KiB sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="personal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|"bogus"|"personal"|err=true|bytes sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="personal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|"bogus"|"internal"|err=false|short sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="internal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|"bogus"|"internal"|err=false|secret sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="internal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|"bogus"|"internal"|err=false|70KiB sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="internal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|"bogus"|"internal"|err=false|bytes sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="internal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|"bogus"|"internal"|err=true|short sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="internal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|"bogus"|"internal"|err=true|secret sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="internal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|"bogus"|"internal"|err=true|70KiB sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="internal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|"bogus"|"internal"|err=true|bytes sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="internal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|"bogus"|"public"|err=false|short sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="public" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|"bogus"|"public"|err=false|secret sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="public" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|"bogus"|"public"|err=false|70KiB sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="public" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|"bogus"|"public"|err=false|bytes sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="public" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|"bogus"|"public"|err=true|short sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="public" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|"bogus"|"public"|err=true|secret sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="public" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|"bogus"|"public"|err=true|70KiB sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="public" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|"bogus"|"public"|err=true|bytes sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="public" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|"bogus"|""|err=false|short sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|"bogus"|""|err=false|secret sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|"bogus"|""|err=false|70KiB sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|"bogus"|""|err=false|bytes sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|"bogus"|""|err=true|short sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|"bogus"|""|err=true|secret sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|"bogus"|""|err=true|70KiB sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|"bogus"|""|err=true|bytes sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|"bogus"|"bogus"|err=false|short sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="bogus" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|"bogus"|"bogus"|err=false|secret sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="bogus" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|"bogus"|"bogus"|err=false|70KiB sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="bogus" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|"bogus"|"bogus"|err=false|bytes sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="bogus" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|"bogus"|"bogus"|err=true|short sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="bogus" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|"bogus"|"bogus"|err=true|secret sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="bogus" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|"bogus"|"bogus"|err=true|70KiB sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="bogus" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-chat|"bogus"|"bogus"|err=true|bytes sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-chat consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="bogus" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"chat","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|"none"|"credentials"|err=false|short sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="credentials" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|"none"|"credentials"|err=false|secret sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="credentials" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|"none"|"credentials"|err=false|70KiB sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="credentials" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|"none"|"credentials"|err=false|bytes sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="credentials" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|"none"|"credentials"|err=true|short sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="credentials" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|"none"|"credentials"|err=true|secret sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="credentials" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|"none"|"credentials"|err=true|70KiB sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="credentials" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|"none"|"credentials"|err=true|bytes sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="credentials" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|"none"|"personal"|err=false|short sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="personal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|"none"|"personal"|err=false|secret sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="personal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|"none"|"personal"|err=false|70KiB sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="personal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|"none"|"personal"|err=false|bytes sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="personal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|"none"|"personal"|err=true|short sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="personal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|"none"|"personal"|err=true|secret sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="personal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|"none"|"personal"|err=true|70KiB sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="personal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|"none"|"personal"|err=true|bytes sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="personal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|"none"|"internal"|err=false|short sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="internal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|"none"|"internal"|err=false|secret sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="internal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|"none"|"internal"|err=false|70KiB sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="internal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|"none"|"internal"|err=false|bytes sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="internal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|"none"|"internal"|err=true|short sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="internal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|"none"|"internal"|err=true|secret sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="internal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|"none"|"internal"|err=true|70KiB sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="internal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|"none"|"internal"|err=true|bytes sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="internal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|"none"|"public"|err=false|short sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="public" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|"none"|"public"|err=false|secret sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="public" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|"none"|"public"|err=false|70KiB sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="public" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|"none"|"public"|err=false|bytes sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="public" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|"none"|"public"|err=true|short sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="public" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|"none"|"public"|err=true|secret sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="public" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|"none"|"public"|err=true|70KiB sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="public" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|"none"|"public"|err=true|bytes sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="public" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|"none"|""|err=false|short sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|"none"|""|err=false|secret sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|"none"|""|err=false|70KiB sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|"none"|""|err=false|bytes sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|"none"|""|err=true|short sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|"none"|""|err=true|secret sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|"none"|""|err=true|70KiB sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|"none"|""|err=true|bytes sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|"none"|"bogus"|err=false|short sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="bogus" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|"none"|"bogus"|err=false|secret sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="bogus" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|"none"|"bogus"|err=false|70KiB sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="bogus" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|"none"|"bogus"|err=false|bytes sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="bogus" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|"none"|"bogus"|err=true|short sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="bogus" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|"none"|"bogus"|err=true|secret sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="bogus" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|"none"|"bogus"|err=true|70KiB sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="bogus" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|"none"|"bogus"|err=true|bytes sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="bogus" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|"errors"|"credentials"|err=false|short sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="credentials" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|"errors"|"credentials"|err=false|secret sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="credentials" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|"errors"|"credentials"|err=false|70KiB sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="credentials" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|"errors"|"credentials"|err=false|bytes sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="credentials" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|"errors"|"credentials"|err=true|short sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="credentials" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|"errors"|"credentials"|err=true|secret sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="credentials" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|"errors"|"credentials"|err=true|70KiB sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="credentials" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|"errors"|"credentials"|err=true|bytes sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="credentials" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|"errors"|"personal"|err=false|short sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="personal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|"errors"|"personal"|err=false|secret sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="personal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|"errors"|"personal"|err=false|70KiB sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="personal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|"errors"|"personal"|err=false|bytes sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="personal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|"errors"|"personal"|err=true|short sys=e3b0c44298fc1c14:0 user=b03d228fdf33e7c8:32 resp=d0a697f30bcc23be:18 err="server_fault 502 upstream_error" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="personal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|"errors"|"personal"|err=true|secret sys=e3b0c44298fc1c14:0 user=f671fb2c9b1dd57f:60 resp=7a60296900e9d441:19 err="server_fault 502 upstream_error" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="personal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|"errors"|"personal"|err=true|70KiB sys=e3b0c44298fc1c14:0 user=c83e6014ce9611f2:65536 resp=5b69fe1525f7898f:18 err="server_fault 502 upstream_error" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="personal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|"errors"|"personal"|err=true|bytes sys=e3b0c44298fc1c14:0 user=f6cbb609d68544f3:65535 resp=2de7bf232ff41013:18 err="server_fault 502 upstream_error" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="personal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|"errors"|"internal"|err=false|short sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="internal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|"errors"|"internal"|err=false|secret sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="internal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|"errors"|"internal"|err=false|70KiB sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="internal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|"errors"|"internal"|err=false|bytes sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="internal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|"errors"|"internal"|err=true|short sys=e3b0c44298fc1c14:0 user=b03d228fdf33e7c8:32 resp=d0a697f30bcc23be:18 err="server_fault 502 upstream_error" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="internal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|"errors"|"internal"|err=true|secret sys=e3b0c44298fc1c14:0 user=f671fb2c9b1dd57f:60 resp=7a60296900e9d441:19 err="server_fault 502 upstream_error" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="internal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|"errors"|"internal"|err=true|70KiB sys=e3b0c44298fc1c14:0 user=c83e6014ce9611f2:65536 resp=5b69fe1525f7898f:18 err="server_fault 502 upstream_error" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="internal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|"errors"|"internal"|err=true|bytes sys=e3b0c44298fc1c14:0 user=f6cbb609d68544f3:65535 resp=2de7bf232ff41013:18 err="server_fault 502 upstream_error" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="internal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|"errors"|"public"|err=false|short sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="public" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|"errors"|"public"|err=false|secret sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="public" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|"errors"|"public"|err=false|70KiB sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="public" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|"errors"|"public"|err=false|bytes sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="public" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|"errors"|"public"|err=true|short sys=e3b0c44298fc1c14:0 user=b03d228fdf33e7c8:32 resp=d0a697f30bcc23be:18 err="server_fault 502 upstream_error" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="public" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|"errors"|"public"|err=true|secret sys=e3b0c44298fc1c14:0 user=f671fb2c9b1dd57f:60 resp=7a60296900e9d441:19 err="server_fault 502 upstream_error" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="public" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|"errors"|"public"|err=true|70KiB sys=e3b0c44298fc1c14:0 user=c83e6014ce9611f2:65536 resp=5b69fe1525f7898f:18 err="server_fault 502 upstream_error" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="public" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|"errors"|"public"|err=true|bytes sys=e3b0c44298fc1c14:0 user=f6cbb609d68544f3:65535 resp=2de7bf232ff41013:18 err="server_fault 502 upstream_error" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="public" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|"errors"|""|err=false|short sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|"errors"|""|err=false|secret sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|"errors"|""|err=false|70KiB sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|"errors"|""|err=false|bytes sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|"errors"|""|err=true|short sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|"errors"|""|err=true|secret sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|"errors"|""|err=true|70KiB sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|"errors"|""|err=true|bytes sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|"errors"|"bogus"|err=false|short sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="bogus" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|"errors"|"bogus"|err=false|secret sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="bogus" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|"errors"|"bogus"|err=false|70KiB sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="bogus" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|"errors"|"bogus"|err=false|bytes sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="bogus" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|"errors"|"bogus"|err=true|short sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="bogus" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|"errors"|"bogus"|err=true|secret sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="bogus" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|"errors"|"bogus"|err=true|70KiB sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="bogus" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|"errors"|"bogus"|err=true|bytes sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="bogus" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|"full"|"credentials"|err=false|short sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="credentials" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|"full"|"credentials"|err=false|secret sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="credentials" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|"full"|"credentials"|err=false|70KiB sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="credentials" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|"full"|"credentials"|err=false|bytes sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="credentials" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|"full"|"credentials"|err=true|short sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="credentials" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|"full"|"credentials"|err=true|secret sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="credentials" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|"full"|"credentials"|err=true|70KiB sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="credentials" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|"full"|"credentials"|err=true|bytes sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="credentials" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|"full"|"personal"|err=false|short sys=e3b0c44298fc1c14:0 user=b03d228fdf33e7c8:32 resp=d0a697f30bcc23be:18 err="" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="personal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|"full"|"personal"|err=false|secret sys=e3b0c44298fc1c14:0 user=f671fb2c9b1dd57f:60 resp=7a60296900e9d441:19 err="" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="personal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|"full"|"personal"|err=false|70KiB sys=e3b0c44298fc1c14:0 user=c83e6014ce9611f2:65536 resp=5b69fe1525f7898f:18 err="" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="personal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|"full"|"personal"|err=false|bytes sys=e3b0c44298fc1c14:0 user=f6cbb609d68544f3:65535 resp=2de7bf232ff41013:18 err="" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="personal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|"full"|"personal"|err=true|short sys=e3b0c44298fc1c14:0 user=b03d228fdf33e7c8:32 resp=d0a697f30bcc23be:18 err="server_fault 502 upstream_error" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="personal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|"full"|"personal"|err=true|secret sys=e3b0c44298fc1c14:0 user=f671fb2c9b1dd57f:60 resp=7a60296900e9d441:19 err="server_fault 502 upstream_error" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="personal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|"full"|"personal"|err=true|70KiB sys=e3b0c44298fc1c14:0 user=c83e6014ce9611f2:65536 resp=5b69fe1525f7898f:18 err="server_fault 502 upstream_error" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="personal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|"full"|"personal"|err=true|bytes sys=e3b0c44298fc1c14:0 user=f6cbb609d68544f3:65535 resp=2de7bf232ff41013:18 err="server_fault 502 upstream_error" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="personal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|"full"|"internal"|err=false|short sys=e3b0c44298fc1c14:0 user=b03d228fdf33e7c8:32 resp=d0a697f30bcc23be:18 err="" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="internal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|"full"|"internal"|err=false|secret sys=e3b0c44298fc1c14:0 user=f671fb2c9b1dd57f:60 resp=7a60296900e9d441:19 err="" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="internal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|"full"|"internal"|err=false|70KiB sys=e3b0c44298fc1c14:0 user=c83e6014ce9611f2:65536 resp=5b69fe1525f7898f:18 err="" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="internal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|"full"|"internal"|err=false|bytes sys=e3b0c44298fc1c14:0 user=f6cbb609d68544f3:65535 resp=2de7bf232ff41013:18 err="" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="internal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|"full"|"internal"|err=true|short sys=e3b0c44298fc1c14:0 user=b03d228fdf33e7c8:32 resp=d0a697f30bcc23be:18 err="server_fault 502 upstream_error" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="internal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|"full"|"internal"|err=true|secret sys=e3b0c44298fc1c14:0 user=f671fb2c9b1dd57f:60 resp=7a60296900e9d441:19 err="server_fault 502 upstream_error" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="internal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|"full"|"internal"|err=true|70KiB sys=e3b0c44298fc1c14:0 user=c83e6014ce9611f2:65536 resp=5b69fe1525f7898f:18 err="server_fault 502 upstream_error" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="internal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|"full"|"internal"|err=true|bytes sys=e3b0c44298fc1c14:0 user=f6cbb609d68544f3:65535 resp=2de7bf232ff41013:18 err="server_fault 502 upstream_error" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="internal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|"full"|"public"|err=false|short sys=e3b0c44298fc1c14:0 user=b03d228fdf33e7c8:32 resp=d0a697f30bcc23be:18 err="" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="public" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|"full"|"public"|err=false|secret sys=e3b0c44298fc1c14:0 user=f671fb2c9b1dd57f:60 resp=7a60296900e9d441:19 err="" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="public" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|"full"|"public"|err=false|70KiB sys=e3b0c44298fc1c14:0 user=c83e6014ce9611f2:65536 resp=5b69fe1525f7898f:18 err="" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="public" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|"full"|"public"|err=false|bytes sys=e3b0c44298fc1c14:0 user=f6cbb609d68544f3:65535 resp=2de7bf232ff41013:18 err="" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="public" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|"full"|"public"|err=true|short sys=e3b0c44298fc1c14:0 user=b03d228fdf33e7c8:32 resp=d0a697f30bcc23be:18 err="server_fault 502 upstream_error" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="public" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|"full"|"public"|err=true|secret sys=e3b0c44298fc1c14:0 user=f671fb2c9b1dd57f:60 resp=7a60296900e9d441:19 err="server_fault 502 upstream_error" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="public" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|"full"|"public"|err=true|70KiB sys=e3b0c44298fc1c14:0 user=c83e6014ce9611f2:65536 resp=5b69fe1525f7898f:18 err="server_fault 502 upstream_error" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="public" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|"full"|"public"|err=true|bytes sys=e3b0c44298fc1c14:0 user=f6cbb609d68544f3:65535 resp=2de7bf232ff41013:18 err="server_fault 502 upstream_error" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="public" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|"full"|""|err=false|short sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|"full"|""|err=false|secret sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|"full"|""|err=false|70KiB sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|"full"|""|err=false|bytes sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|"full"|""|err=true|short sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|"full"|""|err=true|secret sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|"full"|""|err=true|70KiB sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|"full"|""|err=true|bytes sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|"full"|"bogus"|err=false|short sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="bogus" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|"full"|"bogus"|err=false|secret sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="bogus" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|"full"|"bogus"|err=false|70KiB sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="bogus" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|"full"|"bogus"|err=false|bytes sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="bogus" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|"full"|"bogus"|err=true|short sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="bogus" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|"full"|"bogus"|err=true|secret sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="bogus" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|"full"|"bogus"|err=true|70KiB sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="bogus" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|"full"|"bogus"|err=true|bytes sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="bogus" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|""|"credentials"|err=false|short sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="credentials" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|""|"credentials"|err=false|secret sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="credentials" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|""|"credentials"|err=false|70KiB sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="credentials" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|""|"credentials"|err=false|bytes sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="credentials" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|""|"credentials"|err=true|short sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="credentials" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|""|"credentials"|err=true|secret sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="credentials" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|""|"credentials"|err=true|70KiB sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="credentials" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|""|"credentials"|err=true|bytes sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="credentials" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|""|"personal"|err=false|short sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="personal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|""|"personal"|err=false|secret sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="personal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|""|"personal"|err=false|70KiB sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="personal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|""|"personal"|err=false|bytes sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="personal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|""|"personal"|err=true|short sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="personal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|""|"personal"|err=true|secret sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="personal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|""|"personal"|err=true|70KiB sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="personal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|""|"personal"|err=true|bytes sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="personal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|""|"internal"|err=false|short sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="internal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|""|"internal"|err=false|secret sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="internal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|""|"internal"|err=false|70KiB sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="internal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|""|"internal"|err=false|bytes sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="internal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|""|"internal"|err=true|short sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="internal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|""|"internal"|err=true|secret sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="internal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|""|"internal"|err=true|70KiB sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="internal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|""|"internal"|err=true|bytes sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="internal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|""|"public"|err=false|short sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="public" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|""|"public"|err=false|secret sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="public" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|""|"public"|err=false|70KiB sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="public" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|""|"public"|err=false|bytes sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="public" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|""|"public"|err=true|short sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="public" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|""|"public"|err=true|secret sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="public" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|""|"public"|err=true|70KiB sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="public" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|""|"public"|err=true|bytes sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="public" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|""|""|err=false|short sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|""|""|err=false|secret sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|""|""|err=false|70KiB sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|""|""|err=false|bytes sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|""|""|err=true|short sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|""|""|err=true|secret sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|""|""|err=true|70KiB sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|""|""|err=true|bytes sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|""|"bogus"|err=false|short sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="bogus" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|""|"bogus"|err=false|secret sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="bogus" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|""|"bogus"|err=false|70KiB sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="bogus" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|""|"bogus"|err=false|bytes sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="bogus" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|""|"bogus"|err=true|short sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="bogus" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|""|"bogus"|err=true|secret sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="bogus" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|""|"bogus"|err=true|70KiB sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="bogus" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|""|"bogus"|err=true|bytes sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="bogus" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|" FULL "|"credentials"|err=false|short sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="credentials" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|" FULL "|"credentials"|err=false|secret sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="credentials" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|" FULL "|"credentials"|err=false|70KiB sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="credentials" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|" FULL "|"credentials"|err=false|bytes sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="credentials" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|" FULL "|"credentials"|err=true|short sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="credentials" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|" FULL "|"credentials"|err=true|secret sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="credentials" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|" FULL "|"credentials"|err=true|70KiB sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="credentials" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|" FULL "|"credentials"|err=true|bytes sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="credentials" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|" FULL "|"personal"|err=false|short sys=e3b0c44298fc1c14:0 user=b03d228fdf33e7c8:32 resp=d0a697f30bcc23be:18 err="" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="personal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|" FULL "|"personal"|err=false|secret sys=e3b0c44298fc1c14:0 user=f671fb2c9b1dd57f:60 resp=7a60296900e9d441:19 err="" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="personal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|" FULL "|"personal"|err=false|70KiB sys=e3b0c44298fc1c14:0 user=c83e6014ce9611f2:65536 resp=5b69fe1525f7898f:18 err="" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="personal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|" FULL "|"personal"|err=false|bytes sys=e3b0c44298fc1c14:0 user=f6cbb609d68544f3:65535 resp=2de7bf232ff41013:18 err="" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="personal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|" FULL "|"personal"|err=true|short sys=e3b0c44298fc1c14:0 user=b03d228fdf33e7c8:32 resp=d0a697f30bcc23be:18 err="server_fault 502 upstream_error" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="personal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|" FULL "|"personal"|err=true|secret sys=e3b0c44298fc1c14:0 user=f671fb2c9b1dd57f:60 resp=7a60296900e9d441:19 err="server_fault 502 upstream_error" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="personal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|" FULL "|"personal"|err=true|70KiB sys=e3b0c44298fc1c14:0 user=c83e6014ce9611f2:65536 resp=5b69fe1525f7898f:18 err="server_fault 502 upstream_error" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="personal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|" FULL "|"personal"|err=true|bytes sys=e3b0c44298fc1c14:0 user=f6cbb609d68544f3:65535 resp=2de7bf232ff41013:18 err="server_fault 502 upstream_error" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="personal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|" FULL "|"internal"|err=false|short sys=e3b0c44298fc1c14:0 user=b03d228fdf33e7c8:32 resp=d0a697f30bcc23be:18 err="" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="internal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|" FULL "|"internal"|err=false|secret sys=e3b0c44298fc1c14:0 user=f671fb2c9b1dd57f:60 resp=7a60296900e9d441:19 err="" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="internal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|" FULL "|"internal"|err=false|70KiB sys=e3b0c44298fc1c14:0 user=c83e6014ce9611f2:65536 resp=5b69fe1525f7898f:18 err="" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="internal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|" FULL "|"internal"|err=false|bytes sys=e3b0c44298fc1c14:0 user=f6cbb609d68544f3:65535 resp=2de7bf232ff41013:18 err="" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="internal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|" FULL "|"internal"|err=true|short sys=e3b0c44298fc1c14:0 user=b03d228fdf33e7c8:32 resp=d0a697f30bcc23be:18 err="server_fault 502 upstream_error" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="internal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|" FULL "|"internal"|err=true|secret sys=e3b0c44298fc1c14:0 user=f671fb2c9b1dd57f:60 resp=7a60296900e9d441:19 err="server_fault 502 upstream_error" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="internal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|" FULL "|"internal"|err=true|70KiB sys=e3b0c44298fc1c14:0 user=c83e6014ce9611f2:65536 resp=5b69fe1525f7898f:18 err="server_fault 502 upstream_error" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="internal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|" FULL "|"internal"|err=true|bytes sys=e3b0c44298fc1c14:0 user=f6cbb609d68544f3:65535 resp=2de7bf232ff41013:18 err="server_fault 502 upstream_error" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="internal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|" FULL "|"public"|err=false|short sys=e3b0c44298fc1c14:0 user=b03d228fdf33e7c8:32 resp=d0a697f30bcc23be:18 err="" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="public" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|" FULL "|"public"|err=false|secret sys=e3b0c44298fc1c14:0 user=f671fb2c9b1dd57f:60 resp=7a60296900e9d441:19 err="" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="public" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|" FULL "|"public"|err=false|70KiB sys=e3b0c44298fc1c14:0 user=c83e6014ce9611f2:65536 resp=5b69fe1525f7898f:18 err="" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="public" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|" FULL "|"public"|err=false|bytes sys=e3b0c44298fc1c14:0 user=f6cbb609d68544f3:65535 resp=2de7bf232ff41013:18 err="" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="public" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|" FULL "|"public"|err=true|short sys=e3b0c44298fc1c14:0 user=b03d228fdf33e7c8:32 resp=d0a697f30bcc23be:18 err="server_fault 502 upstream_error" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="public" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|" FULL "|"public"|err=true|secret sys=e3b0c44298fc1c14:0 user=f671fb2c9b1dd57f:60 resp=7a60296900e9d441:19 err="server_fault 502 upstream_error" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="public" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|" FULL "|"public"|err=true|70KiB sys=e3b0c44298fc1c14:0 user=c83e6014ce9611f2:65536 resp=5b69fe1525f7898f:18 err="server_fault 502 upstream_error" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="public" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|" FULL "|"public"|err=true|bytes sys=e3b0c44298fc1c14:0 user=f6cbb609d68544f3:65535 resp=2de7bf232ff41013:18 err="server_fault 502 upstream_error" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="public" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|" FULL "|""|err=false|short sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|" FULL "|""|err=false|secret sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|" FULL "|""|err=false|70KiB sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|" FULL "|""|err=false|bytes sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|" FULL "|""|err=true|short sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|" FULL "|""|err=true|secret sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|" FULL "|""|err=true|70KiB sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|" FULL "|""|err=true|bytes sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|" FULL "|"bogus"|err=false|short sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="bogus" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|" FULL "|"bogus"|err=false|secret sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="bogus" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|" FULL "|"bogus"|err=false|70KiB sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="bogus" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|" FULL "|"bogus"|err=false|bytes sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="bogus" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|" FULL "|"bogus"|err=true|short sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="bogus" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|" FULL "|"bogus"|err=true|secret sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="bogus" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|" FULL "|"bogus"|err=true|70KiB sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="bogus" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|" FULL "|"bogus"|err=true|bytes sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="bogus" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|"bogus"|"credentials"|err=false|short sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="credentials" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|"bogus"|"credentials"|err=false|secret sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="credentials" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|"bogus"|"credentials"|err=false|70KiB sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="credentials" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|"bogus"|"credentials"|err=false|bytes sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="credentials" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|"bogus"|"credentials"|err=true|short sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="credentials" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|"bogus"|"credentials"|err=true|secret sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="credentials" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|"bogus"|"credentials"|err=true|70KiB sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="credentials" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|"bogus"|"credentials"|err=true|bytes sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="credentials" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|"bogus"|"personal"|err=false|short sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="personal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|"bogus"|"personal"|err=false|secret sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="personal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|"bogus"|"personal"|err=false|70KiB sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="personal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|"bogus"|"personal"|err=false|bytes sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="personal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|"bogus"|"personal"|err=true|short sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="personal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|"bogus"|"personal"|err=true|secret sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="personal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|"bogus"|"personal"|err=true|70KiB sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="personal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|"bogus"|"personal"|err=true|bytes sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="personal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|"bogus"|"internal"|err=false|short sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="internal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|"bogus"|"internal"|err=false|secret sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="internal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|"bogus"|"internal"|err=false|70KiB sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="internal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|"bogus"|"internal"|err=false|bytes sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="internal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|"bogus"|"internal"|err=true|short sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="internal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|"bogus"|"internal"|err=true|secret sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="internal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|"bogus"|"internal"|err=true|70KiB sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="internal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|"bogus"|"internal"|err=true|bytes sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="internal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|"bogus"|"public"|err=false|short sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="public" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|"bogus"|"public"|err=false|secret sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="public" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|"bogus"|"public"|err=false|70KiB sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="public" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|"bogus"|"public"|err=false|bytes sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="public" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|"bogus"|"public"|err=true|short sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="public" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|"bogus"|"public"|err=true|secret sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="public" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|"bogus"|"public"|err=true|70KiB sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="public" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|"bogus"|"public"|err=true|bytes sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="public" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|"bogus"|""|err=false|short sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|"bogus"|""|err=false|secret sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|"bogus"|""|err=false|70KiB sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|"bogus"|""|err=false|bytes sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|"bogus"|""|err=true|short sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|"bogus"|""|err=true|secret sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|"bogus"|""|err=true|70KiB sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|"bogus"|""|err=true|bytes sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|"bogus"|"bogus"|err=false|short sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="bogus" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|"bogus"|"bogus"|err=false|secret sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="bogus" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|"bogus"|"bogus"|err=false|70KiB sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="bogus" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|"bogus"|"bogus"|err=false|bytes sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="bogus" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|"bogus"|"bogus"|err=true|short sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="bogus" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|"bogus"|"bogus"|err=true|secret sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="bogus" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|"bogus"|"bogus"|err=true|70KiB sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="bogus" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-embeddings|"bogus"|"bogus"|err=true|bytes sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-embeddings consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="bogus" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"embed","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|"none"|"credentials"|err=false|short sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="credentials" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|"none"|"credentials"|err=false|secret sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="credentials" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|"none"|"credentials"|err=false|70KiB sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="credentials" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|"none"|"credentials"|err=false|bytes sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="credentials" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|"none"|"credentials"|err=true|short sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="credentials" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|"none"|"credentials"|err=true|secret sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="credentials" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|"none"|"credentials"|err=true|70KiB sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="credentials" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|"none"|"credentials"|err=true|bytes sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="credentials" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|"none"|"personal"|err=false|short sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="personal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|"none"|"personal"|err=false|secret sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="personal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|"none"|"personal"|err=false|70KiB sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="personal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|"none"|"personal"|err=false|bytes sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="personal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|"none"|"personal"|err=true|short sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="personal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|"none"|"personal"|err=true|secret sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="personal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|"none"|"personal"|err=true|70KiB sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="personal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|"none"|"personal"|err=true|bytes sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="personal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|"none"|"internal"|err=false|short sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="internal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|"none"|"internal"|err=false|secret sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="internal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|"none"|"internal"|err=false|70KiB sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="internal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|"none"|"internal"|err=false|bytes sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="internal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|"none"|"internal"|err=true|short sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="internal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|"none"|"internal"|err=true|secret sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="internal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|"none"|"internal"|err=true|70KiB sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="internal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|"none"|"internal"|err=true|bytes sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="internal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|"none"|"public"|err=false|short sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="public" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|"none"|"public"|err=false|secret sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="public" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|"none"|"public"|err=false|70KiB sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="public" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|"none"|"public"|err=false|bytes sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="public" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|"none"|"public"|err=true|short sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="public" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|"none"|"public"|err=true|secret sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="public" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|"none"|"public"|err=true|70KiB sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="public" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|"none"|"public"|err=true|bytes sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="public" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|"none"|""|err=false|short sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|"none"|""|err=false|secret sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|"none"|""|err=false|70KiB sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|"none"|""|err=false|bytes sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|"none"|""|err=true|short sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|"none"|""|err=true|secret sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|"none"|""|err=true|70KiB sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|"none"|""|err=true|bytes sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|"none"|"bogus"|err=false|short sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="bogus" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|"none"|"bogus"|err=false|secret sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="bogus" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|"none"|"bogus"|err=false|70KiB sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="bogus" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|"none"|"bogus"|err=false|bytes sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="bogus" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|"none"|"bogus"|err=true|short sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="bogus" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|"none"|"bogus"|err=true|secret sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="bogus" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|"none"|"bogus"|err=true|70KiB sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="bogus" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|"none"|"bogus"|err=true|bytes sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="bogus" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|"errors"|"credentials"|err=false|short sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="credentials" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|"errors"|"credentials"|err=false|secret sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="credentials" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|"errors"|"credentials"|err=false|70KiB sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="credentials" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|"errors"|"credentials"|err=false|bytes sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="credentials" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|"errors"|"credentials"|err=true|short sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="credentials" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|"errors"|"credentials"|err=true|secret sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="credentials" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|"errors"|"credentials"|err=true|70KiB sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="credentials" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|"errors"|"credentials"|err=true|bytes sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="credentials" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|"errors"|"personal"|err=false|short sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="personal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|"errors"|"personal"|err=false|secret sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="personal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|"errors"|"personal"|err=false|70KiB sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="personal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|"errors"|"personal"|err=false|bytes sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="personal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|"errors"|"personal"|err=true|short sys=e3b0c44298fc1c14:0 user=b03d228fdf33e7c8:32 resp=d0a697f30bcc23be:18 err="server_fault 502 upstream_error" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="personal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|"errors"|"personal"|err=true|secret sys=e3b0c44298fc1c14:0 user=f671fb2c9b1dd57f:60 resp=7a60296900e9d441:19 err="server_fault 502 upstream_error" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="personal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|"errors"|"personal"|err=true|70KiB sys=e3b0c44298fc1c14:0 user=c83e6014ce9611f2:65536 resp=5b69fe1525f7898f:18 err="server_fault 502 upstream_error" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="personal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|"errors"|"personal"|err=true|bytes sys=e3b0c44298fc1c14:0 user=f6cbb609d68544f3:65535 resp=2de7bf232ff41013:18 err="server_fault 502 upstream_error" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="personal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|"errors"|"internal"|err=false|short sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="internal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|"errors"|"internal"|err=false|secret sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="internal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|"errors"|"internal"|err=false|70KiB sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="internal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|"errors"|"internal"|err=false|bytes sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="internal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|"errors"|"internal"|err=true|short sys=e3b0c44298fc1c14:0 user=b03d228fdf33e7c8:32 resp=d0a697f30bcc23be:18 err="server_fault 502 upstream_error" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="internal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|"errors"|"internal"|err=true|secret sys=e3b0c44298fc1c14:0 user=f671fb2c9b1dd57f:60 resp=7a60296900e9d441:19 err="server_fault 502 upstream_error" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="internal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|"errors"|"internal"|err=true|70KiB sys=e3b0c44298fc1c14:0 user=c83e6014ce9611f2:65536 resp=5b69fe1525f7898f:18 err="server_fault 502 upstream_error" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="internal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|"errors"|"internal"|err=true|bytes sys=e3b0c44298fc1c14:0 user=f6cbb609d68544f3:65535 resp=2de7bf232ff41013:18 err="server_fault 502 upstream_error" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="internal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|"errors"|"public"|err=false|short sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="public" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|"errors"|"public"|err=false|secret sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="public" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|"errors"|"public"|err=false|70KiB sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="public" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|"errors"|"public"|err=false|bytes sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="public" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|"errors"|"public"|err=true|short sys=e3b0c44298fc1c14:0 user=b03d228fdf33e7c8:32 resp=d0a697f30bcc23be:18 err="server_fault 502 upstream_error" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="public" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|"errors"|"public"|err=true|secret sys=e3b0c44298fc1c14:0 user=f671fb2c9b1dd57f:60 resp=7a60296900e9d441:19 err="server_fault 502 upstream_error" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="public" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|"errors"|"public"|err=true|70KiB sys=e3b0c44298fc1c14:0 user=c83e6014ce9611f2:65536 resp=5b69fe1525f7898f:18 err="server_fault 502 upstream_error" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="public" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|"errors"|"public"|err=true|bytes sys=e3b0c44298fc1c14:0 user=f6cbb609d68544f3:65535 resp=2de7bf232ff41013:18 err="server_fault 502 upstream_error" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="public" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|"errors"|""|err=false|short sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|"errors"|""|err=false|secret sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|"errors"|""|err=false|70KiB sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|"errors"|""|err=false|bytes sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|"errors"|""|err=true|short sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|"errors"|""|err=true|secret sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|"errors"|""|err=true|70KiB sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|"errors"|""|err=true|bytes sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|"errors"|"bogus"|err=false|short sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="bogus" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|"errors"|"bogus"|err=false|secret sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="bogus" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|"errors"|"bogus"|err=false|70KiB sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="bogus" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|"errors"|"bogus"|err=false|bytes sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="bogus" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|"errors"|"bogus"|err=true|short sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="bogus" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|"errors"|"bogus"|err=true|secret sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="bogus" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|"errors"|"bogus"|err=true|70KiB sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="bogus" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|"errors"|"bogus"|err=true|bytes sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="bogus" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|"full"|"credentials"|err=false|short sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="credentials" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|"full"|"credentials"|err=false|secret sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="credentials" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|"full"|"credentials"|err=false|70KiB sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="credentials" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|"full"|"credentials"|err=false|bytes sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="credentials" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|"full"|"credentials"|err=true|short sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="credentials" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|"full"|"credentials"|err=true|secret sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="credentials" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|"full"|"credentials"|err=true|70KiB sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="credentials" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|"full"|"credentials"|err=true|bytes sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="credentials" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|"full"|"personal"|err=false|short sys=e3b0c44298fc1c14:0 user=b03d228fdf33e7c8:32 resp=d0a697f30bcc23be:18 err="" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="personal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|"full"|"personal"|err=false|secret sys=e3b0c44298fc1c14:0 user=f671fb2c9b1dd57f:60 resp=7a60296900e9d441:19 err="" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="personal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|"full"|"personal"|err=false|70KiB sys=e3b0c44298fc1c14:0 user=c83e6014ce9611f2:65536 resp=5b69fe1525f7898f:18 err="" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="personal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|"full"|"personal"|err=false|bytes sys=e3b0c44298fc1c14:0 user=f6cbb609d68544f3:65535 resp=2de7bf232ff41013:18 err="" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="personal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|"full"|"personal"|err=true|short sys=e3b0c44298fc1c14:0 user=b03d228fdf33e7c8:32 resp=d0a697f30bcc23be:18 err="server_fault 502 upstream_error" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="personal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|"full"|"personal"|err=true|secret sys=e3b0c44298fc1c14:0 user=f671fb2c9b1dd57f:60 resp=7a60296900e9d441:19 err="server_fault 502 upstream_error" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="personal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|"full"|"personal"|err=true|70KiB sys=e3b0c44298fc1c14:0 user=c83e6014ce9611f2:65536 resp=5b69fe1525f7898f:18 err="server_fault 502 upstream_error" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="personal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|"full"|"personal"|err=true|bytes sys=e3b0c44298fc1c14:0 user=f6cbb609d68544f3:65535 resp=2de7bf232ff41013:18 err="server_fault 502 upstream_error" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="personal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|"full"|"internal"|err=false|short sys=e3b0c44298fc1c14:0 user=b03d228fdf33e7c8:32 resp=d0a697f30bcc23be:18 err="" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="internal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|"full"|"internal"|err=false|secret sys=e3b0c44298fc1c14:0 user=f671fb2c9b1dd57f:60 resp=7a60296900e9d441:19 err="" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="internal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|"full"|"internal"|err=false|70KiB sys=e3b0c44298fc1c14:0 user=c83e6014ce9611f2:65536 resp=5b69fe1525f7898f:18 err="" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="internal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|"full"|"internal"|err=false|bytes sys=e3b0c44298fc1c14:0 user=f6cbb609d68544f3:65535 resp=2de7bf232ff41013:18 err="" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="internal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|"full"|"internal"|err=true|short sys=e3b0c44298fc1c14:0 user=b03d228fdf33e7c8:32 resp=d0a697f30bcc23be:18 err="server_fault 502 upstream_error" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="internal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|"full"|"internal"|err=true|secret sys=e3b0c44298fc1c14:0 user=f671fb2c9b1dd57f:60 resp=7a60296900e9d441:19 err="server_fault 502 upstream_error" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="internal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|"full"|"internal"|err=true|70KiB sys=e3b0c44298fc1c14:0 user=c83e6014ce9611f2:65536 resp=5b69fe1525f7898f:18 err="server_fault 502 upstream_error" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="internal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|"full"|"internal"|err=true|bytes sys=e3b0c44298fc1c14:0 user=f6cbb609d68544f3:65535 resp=2de7bf232ff41013:18 err="server_fault 502 upstream_error" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="internal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|"full"|"public"|err=false|short sys=e3b0c44298fc1c14:0 user=b03d228fdf33e7c8:32 resp=d0a697f30bcc23be:18 err="" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="public" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|"full"|"public"|err=false|secret sys=e3b0c44298fc1c14:0 user=f671fb2c9b1dd57f:60 resp=7a60296900e9d441:19 err="" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="public" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|"full"|"public"|err=false|70KiB sys=e3b0c44298fc1c14:0 user=c83e6014ce9611f2:65536 resp=5b69fe1525f7898f:18 err="" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="public" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|"full"|"public"|err=false|bytes sys=e3b0c44298fc1c14:0 user=f6cbb609d68544f3:65535 resp=2de7bf232ff41013:18 err="" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="public" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|"full"|"public"|err=true|short sys=e3b0c44298fc1c14:0 user=b03d228fdf33e7c8:32 resp=d0a697f30bcc23be:18 err="server_fault 502 upstream_error" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="public" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|"full"|"public"|err=true|secret sys=e3b0c44298fc1c14:0 user=f671fb2c9b1dd57f:60 resp=7a60296900e9d441:19 err="server_fault 502 upstream_error" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="public" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|"full"|"public"|err=true|70KiB sys=e3b0c44298fc1c14:0 user=c83e6014ce9611f2:65536 resp=5b69fe1525f7898f:18 err="server_fault 502 upstream_error" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="public" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|"full"|"public"|err=true|bytes sys=e3b0c44298fc1c14:0 user=f6cbb609d68544f3:65535 resp=2de7bf232ff41013:18 err="server_fault 502 upstream_error" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="public" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|"full"|""|err=false|short sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|"full"|""|err=false|secret sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|"full"|""|err=false|70KiB sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|"full"|""|err=false|bytes sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|"full"|""|err=true|short sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|"full"|""|err=true|secret sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|"full"|""|err=true|70KiB sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|"full"|""|err=true|bytes sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|"full"|"bogus"|err=false|short sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="bogus" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|"full"|"bogus"|err=false|secret sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="bogus" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|"full"|"bogus"|err=false|70KiB sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="bogus" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|"full"|"bogus"|err=false|bytes sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="bogus" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|"full"|"bogus"|err=true|short sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="bogus" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|"full"|"bogus"|err=true|secret sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="bogus" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|"full"|"bogus"|err=true|70KiB sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="bogus" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|"full"|"bogus"|err=true|bytes sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="bogus" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|""|"credentials"|err=false|short sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="credentials" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|""|"credentials"|err=false|secret sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="credentials" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|""|"credentials"|err=false|70KiB sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="credentials" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|""|"credentials"|err=false|bytes sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="credentials" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|""|"credentials"|err=true|short sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="credentials" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|""|"credentials"|err=true|secret sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="credentials" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|""|"credentials"|err=true|70KiB sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="credentials" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|""|"credentials"|err=true|bytes sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="credentials" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|""|"personal"|err=false|short sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="personal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|""|"personal"|err=false|secret sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="personal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|""|"personal"|err=false|70KiB sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="personal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|""|"personal"|err=false|bytes sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="personal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|""|"personal"|err=true|short sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="personal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|""|"personal"|err=true|secret sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="personal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|""|"personal"|err=true|70KiB sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="personal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|""|"personal"|err=true|bytes sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="personal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|""|"internal"|err=false|short sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="internal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|""|"internal"|err=false|secret sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="internal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|""|"internal"|err=false|70KiB sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="internal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|""|"internal"|err=false|bytes sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="internal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|""|"internal"|err=true|short sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="internal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|""|"internal"|err=true|secret sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="internal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|""|"internal"|err=true|70KiB sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="internal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|""|"internal"|err=true|bytes sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="internal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|""|"public"|err=false|short sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="public" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|""|"public"|err=false|secret sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="public" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|""|"public"|err=false|70KiB sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="public" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|""|"public"|err=false|bytes sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="public" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|""|"public"|err=true|short sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="public" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|""|"public"|err=true|secret sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="public" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|""|"public"|err=true|70KiB sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="public" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|""|"public"|err=true|bytes sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="public" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|""|""|err=false|short sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|""|""|err=false|secret sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|""|""|err=false|70KiB sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|""|""|err=false|bytes sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|""|""|err=true|short sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|""|""|err=true|secret sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|""|""|err=true|70KiB sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|""|""|err=true|bytes sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|""|"bogus"|err=false|short sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="bogus" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|""|"bogus"|err=false|secret sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="bogus" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|""|"bogus"|err=false|70KiB sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="bogus" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|""|"bogus"|err=false|bytes sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="bogus" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|""|"bogus"|err=true|short sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="bogus" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|""|"bogus"|err=true|secret sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="bogus" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|""|"bogus"|err=true|70KiB sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="bogus" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|""|"bogus"|err=true|bytes sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="bogus" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|" FULL "|"credentials"|err=false|short sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="credentials" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|" FULL "|"credentials"|err=false|secret sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="credentials" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|" FULL "|"credentials"|err=false|70KiB sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="credentials" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|" FULL "|"credentials"|err=false|bytes sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="credentials" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|" FULL "|"credentials"|err=true|short sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="credentials" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|" FULL "|"credentials"|err=true|secret sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="credentials" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|" FULL "|"credentials"|err=true|70KiB sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="credentials" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|" FULL "|"credentials"|err=true|bytes sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="credentials" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|" FULL "|"personal"|err=false|short sys=e3b0c44298fc1c14:0 user=b03d228fdf33e7c8:32 resp=d0a697f30bcc23be:18 err="" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="personal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|" FULL "|"personal"|err=false|secret sys=e3b0c44298fc1c14:0 user=f671fb2c9b1dd57f:60 resp=7a60296900e9d441:19 err="" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="personal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|" FULL "|"personal"|err=false|70KiB sys=e3b0c44298fc1c14:0 user=c83e6014ce9611f2:65536 resp=5b69fe1525f7898f:18 err="" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="personal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|" FULL "|"personal"|err=false|bytes sys=e3b0c44298fc1c14:0 user=f6cbb609d68544f3:65535 resp=2de7bf232ff41013:18 err="" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="personal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|" FULL "|"personal"|err=true|short sys=e3b0c44298fc1c14:0 user=b03d228fdf33e7c8:32 resp=d0a697f30bcc23be:18 err="server_fault 502 upstream_error" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="personal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|" FULL "|"personal"|err=true|secret sys=e3b0c44298fc1c14:0 user=f671fb2c9b1dd57f:60 resp=7a60296900e9d441:19 err="server_fault 502 upstream_error" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="personal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|" FULL "|"personal"|err=true|70KiB sys=e3b0c44298fc1c14:0 user=c83e6014ce9611f2:65536 resp=5b69fe1525f7898f:18 err="server_fault 502 upstream_error" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="personal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|" FULL "|"personal"|err=true|bytes sys=e3b0c44298fc1c14:0 user=f6cbb609d68544f3:65535 resp=2de7bf232ff41013:18 err="server_fault 502 upstream_error" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="personal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|" FULL "|"internal"|err=false|short sys=e3b0c44298fc1c14:0 user=b03d228fdf33e7c8:32 resp=d0a697f30bcc23be:18 err="" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="internal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|" FULL "|"internal"|err=false|secret sys=e3b0c44298fc1c14:0 user=f671fb2c9b1dd57f:60 resp=7a60296900e9d441:19 err="" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="internal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|" FULL "|"internal"|err=false|70KiB sys=e3b0c44298fc1c14:0 user=c83e6014ce9611f2:65536 resp=5b69fe1525f7898f:18 err="" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="internal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|" FULL "|"internal"|err=false|bytes sys=e3b0c44298fc1c14:0 user=f6cbb609d68544f3:65535 resp=2de7bf232ff41013:18 err="" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="internal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|" FULL "|"internal"|err=true|short sys=e3b0c44298fc1c14:0 user=b03d228fdf33e7c8:32 resp=d0a697f30bcc23be:18 err="server_fault 502 upstream_error" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="internal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|" FULL "|"internal"|err=true|secret sys=e3b0c44298fc1c14:0 user=f671fb2c9b1dd57f:60 resp=7a60296900e9d441:19 err="server_fault 502 upstream_error" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="internal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|" FULL "|"internal"|err=true|70KiB sys=e3b0c44298fc1c14:0 user=c83e6014ce9611f2:65536 resp=5b69fe1525f7898f:18 err="server_fault 502 upstream_error" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="internal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|" FULL "|"internal"|err=true|bytes sys=e3b0c44298fc1c14:0 user=f6cbb609d68544f3:65535 resp=2de7bf232ff41013:18 err="server_fault 502 upstream_error" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="internal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|" FULL "|"public"|err=false|short sys=e3b0c44298fc1c14:0 user=b03d228fdf33e7c8:32 resp=d0a697f30bcc23be:18 err="" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="public" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|" FULL "|"public"|err=false|secret sys=e3b0c44298fc1c14:0 user=f671fb2c9b1dd57f:60 resp=7a60296900e9d441:19 err="" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="public" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|" FULL "|"public"|err=false|70KiB sys=e3b0c44298fc1c14:0 user=c83e6014ce9611f2:65536 resp=5b69fe1525f7898f:18 err="" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="public" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|" FULL "|"public"|err=false|bytes sys=e3b0c44298fc1c14:0 user=f6cbb609d68544f3:65535 resp=2de7bf232ff41013:18 err="" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="public" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|" FULL "|"public"|err=true|short sys=e3b0c44298fc1c14:0 user=b03d228fdf33e7c8:32 resp=d0a697f30bcc23be:18 err="server_fault 502 upstream_error" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="public" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|" FULL "|"public"|err=true|secret sys=e3b0c44298fc1c14:0 user=f671fb2c9b1dd57f:60 resp=7a60296900e9d441:19 err="server_fault 502 upstream_error" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="public" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|" FULL "|"public"|err=true|70KiB sys=e3b0c44298fc1c14:0 user=c83e6014ce9611f2:65536 resp=5b69fe1525f7898f:18 err="server_fault 502 upstream_error" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="public" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|" FULL "|"public"|err=true|bytes sys=e3b0c44298fc1c14:0 user=f6cbb609d68544f3:65535 resp=2de7bf232ff41013:18 err="server_fault 502 upstream_error" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="public" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|" FULL "|""|err=false|short sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|" FULL "|""|err=false|secret sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|" FULL "|""|err=false|70KiB sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|" FULL "|""|err=false|bytes sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|" FULL "|""|err=true|short sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|" FULL "|""|err=true|secret sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|" FULL "|""|err=true|70KiB sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|" FULL "|""|err=true|bytes sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|" FULL "|"bogus"|err=false|short sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="bogus" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|" FULL "|"bogus"|err=false|secret sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="bogus" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|" FULL "|"bogus"|err=false|70KiB sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="bogus" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|" FULL "|"bogus"|err=false|bytes sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="bogus" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|" FULL "|"bogus"|err=true|short sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="bogus" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|" FULL "|"bogus"|err=true|secret sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="bogus" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|" FULL "|"bogus"|err=true|70KiB sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="bogus" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|" FULL "|"bogus"|err=true|bytes sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="bogus" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|"bogus"|"credentials"|err=false|short sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="credentials" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|"bogus"|"credentials"|err=false|secret sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="credentials" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|"bogus"|"credentials"|err=false|70KiB sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="credentials" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|"bogus"|"credentials"|err=false|bytes sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="credentials" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|"bogus"|"credentials"|err=true|short sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="credentials" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|"bogus"|"credentials"|err=true|secret sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="credentials" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|"bogus"|"credentials"|err=true|70KiB sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="credentials" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|"bogus"|"credentials"|err=true|bytes sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="credentials" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|"bogus"|"personal"|err=false|short sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="personal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|"bogus"|"personal"|err=false|secret sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="personal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|"bogus"|"personal"|err=false|70KiB sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="personal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|"bogus"|"personal"|err=false|bytes sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="personal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|"bogus"|"personal"|err=true|short sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="personal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|"bogus"|"personal"|err=true|secret sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="personal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|"bogus"|"personal"|err=true|70KiB sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="personal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|"bogus"|"personal"|err=true|bytes sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="personal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|"bogus"|"internal"|err=false|short sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="internal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|"bogus"|"internal"|err=false|secret sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="internal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|"bogus"|"internal"|err=false|70KiB sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="internal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|"bogus"|"internal"|err=false|bytes sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="internal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|"bogus"|"internal"|err=true|short sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="internal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|"bogus"|"internal"|err=true|secret sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="internal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|"bogus"|"internal"|err=true|70KiB sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="internal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|"bogus"|"internal"|err=true|bytes sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="internal" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|"bogus"|"public"|err=false|short sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="public" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|"bogus"|"public"|err=false|secret sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="public" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|"bogus"|"public"|err=false|70KiB sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="public" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|"bogus"|"public"|err=false|bytes sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="public" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|"bogus"|"public"|err=true|short sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="public" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|"bogus"|"public"|err=true|secret sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="public" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|"bogus"|"public"|err=true|70KiB sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="public" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|"bogus"|"public"|err=true|bytes sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="public" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|"bogus"|""|err=false|short sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|"bogus"|""|err=false|secret sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|"bogus"|""|err=false|70KiB sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|"bogus"|""|err=false|bytes sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|"bogus"|""|err=true|short sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|"bogus"|""|err=true|secret sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|"bogus"|""|err=true|70KiB sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|"bogus"|""|err=true|bytes sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|"bogus"|"bogus"|err=false|short sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="bogus" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|"bogus"|"bogus"|err=false|secret sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="bogus" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|"bogus"|"bogus"|err=false|70KiB sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="bogus" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|"bogus"|"bogus"|err=false|bytes sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="bogus" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|"bogus"|"bogus"|err=true|short sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="bogus" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|"bogus"|"bogus"|err=true|secret sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="bogus" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|"bogus"|"bogus"|err=true|70KiB sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="bogus" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} +gateway-rerank|"bogus"|"bogus"|err=true|bytes sys=e3b0c44298fc1c14:0 user=e3b0c44298fc1c14:0 resp=e3b0c44298fc1c14:0 err="server_fault 502 upstream_error" pipe=gateway-rerank consumer=0195a6f0-0000-7000-8000-00000000c571 key="" attempt=1 sens="bogus" md={"chain":[{"backend":"spark","err_class":"ok","ms":0,"wait_ms":0}],"gw":{"v":1,"op":"rerank","alias":"chat","stream":false,"hop":1,"usage":"backend","client_req_id":"req-571","finish":"stop","model_key_id":"0195a6f0-0000-7000-8000-00000000a571"},"sub_batches":1} diff --git a/go/internal/llmlogexport/export.go b/go/internal/llmlogexport/export.go index c4ff5093e..3ddb00b58 100644 --- a/go/internal/llmlogexport/export.go +++ b/go/internal/llmlogexport/export.go @@ -24,6 +24,7 @@ import ( "github.com/jackc/pgx/v5" "github.com/jackc/pgx/v5/pgxpool" + "github.com/GottZ/ctx/internal/llmlog" "github.com/GottZ/ctx/internal/pgxdb" ) @@ -64,6 +65,10 @@ type ExportSummary struct { RowsBody int64 `json:"rows_body"` RowsBodylessSlim int64 `json:"rows_bodyless_slim"` RowsBodylessNull int64 `json:"rows_bodyless_null"` + // RowsRecordedSealed zählt die aufgezeichneten Gateway-Zeilen (issue + // #571), deren Bodies der Export versiegelt ausgibt (exportSelect); sie + // stehen zugleich in rows_bodyless_slim bzw. rows_bodyless_null. + RowsRecordedSealed int64 `json:"rows_recorded_sealed"` // CountGate ist count(*) mit demselben Fenster im selben Snapshot — // muss RowsTotal gleichen (Live-Gate KW1). CountGate int64 `json:"count_gate"` @@ -153,6 +158,7 @@ type exportRow struct { body []byte hasBody bool anyNull bool + sealed bool } // exportWindow baut das Fenster-Prädikat als Klausel-Liste + Argumente — @@ -183,13 +189,31 @@ func exportWindow(opts ExportOptions, until time.Time) (string, []any) { // Slim schreibt den Leerstring (Slimmed), EvictBodies schreibt NULL. Ein naiver // IS NOT NULL-Filter ließe Leer-Prompts als Replay-Kandidaten durch // (design/02 §5.2 — genau dieser Fehler steckte in der Erst-Inventur). -const exportSelect = ` - SELECT created_at, id::text, to_jsonb(t), - (coalesce(request_system, '') <> '' OR coalesce(request_user, '') <> '') AS has_body, - (request_system IS NULL OR request_user IS NULL OR response_content IS NULL) AS any_null +// +// Aufgezeichnete Gateway-Zeilen (issue #571, llmlog.SQLBodiesServerAdminOnly: +// metadata.gw.recorded, und fail-closed jede Gateway-Zeile ohne lesbare +// Markierung) verlassen den Export versiegelt: ihre Bodies stehen als +// Leerstring in der Zeile (NULL bleibt NULL — die Retention-Klassifikation +// bleibt gleich), has_body ist false, und sealed zählt sie. Ihre Bodies +// können Zugangsdaten im Klartext tragen; sie gehören in keinen Export und in +// keine Trainings-Pipeline — gelesen werden sie nur von einem Server-Admin +// (GET /api/llmlog/{id}, docs/operations.md „Recording a consumer"). +var exportSelect = ` + SELECT created_at, id::text, + CASE WHEN ` + exportSealed + ` THEN to_jsonb(t) || jsonb_build_object( + 'request_system', CASE WHEN t.request_system IS NULL THEN NULL ELSE '' END, + 'request_user', CASE WHEN t.request_user IS NULL THEN NULL ELSE '' END, + 'response_content', CASE WHEN t.response_content IS NULL THEN NULL ELSE '' END) + ELSE to_jsonb(t) END, + (NOT ` + exportSealed + ` AND (coalesce(request_system, '') <> '' OR coalesce(request_user, '') <> '')) AS has_body, + (request_system IS NULL OR request_user IS NULL OR response_content IS NULL) AS any_null, + ` + exportSealed + ` AS sealed FROM context_llm_log t WHERE ` +// exportSealed ist die Versiegelungs-Bedingung über dem Alias t. +var exportSealed = llmlog.SQLBodiesServerAdminOnly("t") + // pageSQL liefert die Seiten-Query. Der Cursor trägt neben der Rowcompare das // redundante `created_at >= $k`: logisch impliziert, aber die einzige Form, // die der Planner als Startbedingung auf dem created_at-Index UND für die @@ -317,11 +341,14 @@ func exportPage(ctx context.Context, pool *pgxpool.Pool, cw io.Writer, q string, defer rows.Close() for rows.Next() { var r exportRow - if err := rows.Scan(&r.createdAt, &r.id, &r.body, &r.hasBody, &r.anyNull); err != nil { + if err := rows.Scan(&r.createdAt, &r.id, &r.body, &r.hasBody, &r.anyNull, &r.sealed); err != nil { return fmt.Errorf("llmlog export: scan: %w", err) } n++ sum.RowsTotal++ + if r.sealed { + sum.RowsRecordedSealed++ + } switch { case r.anyNull: sum.RowsBodylessNull++ diff --git a/go/internal/oai/chat.go b/go/internal/oai/chat.go index 0d3fd04c6..1456af64e 100644 --- a/go/internal/oai/chat.go +++ b/go/internal/oai/chat.go @@ -154,11 +154,16 @@ type chatCall struct { // requestReserveFactor × body, grown by cover), spent what the request // has allocated against it (cover). held, spent int64 + + // recording is the capture of a recording consumer's request (record.go; + // off for every other consumer). + recording recording } func newChatCall(d Deps, w http.ResponseWriter, r *http.Request, ca *auth.ConsumerAuth, entry time.Time) *chatCall { s := d.Settings() c := &chatCall{d: d, w: w, s: s, ca: ca, entry: entry, client: r.Context(), rec: AccessRecordFrom(r.Context())} + c.recording.on = ca != nil && ca.RecordBodies if c.rec == nil { c.rec = &AccessRecord{} // outside a model group: filled, never read } @@ -220,6 +225,7 @@ func (c *chatCall) close() { for _, stop := range c.stops { stop() } + c.recording.release() // what no row of this request took } // refuse answers code and names it as the access record's reason. @@ -757,7 +763,7 @@ func (c *chatCall) admitLimiter(maxTokens int) bool { // The row the shutdown's forced settle writes should the request still // be open after the HTTP drain (W06-13 (e)). registerForcedRow(res, c.d.Record, func() llmlog.GatewayRow { - return llmlog.GatewayRow{Pipeline: chatPipeline, ConsumerID: c.ca.ConsumerID, + return llmlog.GatewayRow{Pipeline: chatPipeline, ConsumerID: c.ca.ConsumerID, Recorded: c.recording.on, Gateway: withFederation(c.r.Context(), llmlog.Gateway{Alias: c.alias.Name, Hop: c.rec.Hop, ClientReqID: clientRequestID(c.r), ModelKeyID: c.ca.ModelKeyID, Stream: c.sse != nil})} }, string(c.required)) return true @@ -1319,7 +1325,18 @@ func (c *chatCall) record(plan Plan, served *backends.Backend, attempts []llm.Ch } } request, response := "", "" - if c.s.BodyLogging == llmlog.BodyLoggingFull || (c.s.BodyLogging == llmlog.BodyLoggingErrors && out.redacted != nil) { + switch { + case c.recording.on: + // A recording consumer's row (issue #571): the whole text of the + // array and the whole answer — a stream's relayed lines — reserved + // against the recording account, not booked in the ledger (record.go). + request = c.recording.text(c.req.messages, llmlog.RecordLostRequest) + if c.sse != nil { + response = c.recording.streamText() + } else if len(out.response) > 0 { + response = c.recording.bytes(out.response, llmlog.RecordLostResponse) + } + case c.s.BodyLogging == llmlog.BodyLoggingFull || (c.s.BodyLogging == llmlog.BodyLoggingErrors && out.redacted != nil): // The row's text of the array is sized, then booked, then written // (hardening 6): under an exhausted budget the row goes without it. if n := bodyLogSize(c.req.messages); c.cover(int64(n)) { @@ -1331,7 +1348,7 @@ func (c *chatCall) record(plan Plan, served *backends.Backend, attempts []llm.Ch response = string(out.response[:n]) } } - c.d.Record(llmlog.GatewayRow{ + row := llmlog.GatewayRow{ Pipeline: chatPipeline, ConsumerID: c.ca.ConsumerID, Gateway: withFederation(c.r.Context(), llmlog.Gateway{ @@ -1344,7 +1361,9 @@ func (c *chatCall) record(plan Plan, served *backends.Backend, attempts []llm.Ch Request: request, Response: response, BodyLogging: c.s.BodyLogging, - }) + } + c.recording.mark(&row) + c.d.Record(row) } // bodyLogTextMax is how much of the message array's text the route hands to @@ -1353,17 +1372,18 @@ func (c *chatCall) record(plan Plan, served *backends.Backend, attempts []llm.Ch // stores the same. Pinned by TestBodyLogTextStoresWhatTheArrayStored. const bodyLogTextMax = 64<<10 + utf8.UTFMax -// bodyLogWalk yields the text of the message array raw for the log row as +// bodyLogWalkN yields the text of the message array raw for the log row as // the row stores it before its cut — valid UTF-8 with each run of invalid // bytes one U+FFFD and no NUL (llmlog's storable) — piece by piece to put, -// up to bodyLogTextMax bytes (hardening 6, the class gate: string(raw) -// copied the whole array outside the reservation, and the row's cleaning -// grew a text of invalid bytes between ASCII ones to 8 × its size before -// cutting it). -func bodyLogWalk(raw []byte, put func(p []byte)) { +// up to limit bytes: bodyLogTextMax for the body policy (hardening 6, the +// class gate: string(raw) copied the whole array outside the reservation, +// and the row's cleaning grew a text of invalid bytes between ASCII ones to +// 8 × its size before cutting it), noLogLimit for a recorded row's whole +// text (record.go). +func bodyLogWalkN(raw []byte, limit int, put func(p []byte)) { n := 0 invalid := false // the byte before was part of an invalid sequence - for i := 0; i < len(raw) && n < bodyLogTextMax; { + for i := 0; i < len(raw) && n < limit; { c := raw[i] size := 1 switch { @@ -1394,18 +1414,24 @@ func bodyLogWalk(raw []byte, put func(p []byte)) { var replacementChar = []byte(string(utf8.RuneError)) // bodyLogSize is the length of bodyLogText(raw). -func bodyLogSize(raw []byte) int { +func bodyLogSize(raw []byte) int { return bodyLogSizeN(raw, bodyLogTextMax) } + +// bodyLogSizeN is the length of bodyLogTextN(raw, …, limit). +func bodyLogSizeN(raw []byte, limit int) int { n := 0 - bodyLogWalk(raw, func(p []byte) { n += len(p) }) + bodyLogWalkN(raw, limit, func(p []byte) { n += len(p) }) return n } // bodyLogText is the log row's text of raw, written once into size bytes // (bodyLogSize). -func bodyLogText(raw []byte, size int) string { +func bodyLogText(raw []byte, size int) string { return bodyLogTextN(raw, size, bodyLogTextMax) } + +// bodyLogTextN is bodyLogText up to limit bytes (bodyLogSizeN). +func bodyLogTextN(raw []byte, size, limit int) string { var b strings.Builder b.Grow(size) - bodyLogWalk(raw, func(p []byte) { b.Write(p) }) + bodyLogWalkN(raw, limit, func(p []byte) { b.Write(p) }) return b.String() } diff --git a/go/internal/oai/chat_stream.go b/go/internal/oai/chat_stream.go index ecfdf6ffe..60c0599ff 100644 --- a/go/internal/oai/chat_stream.go +++ b/go/internal/oai/chat_stream.go @@ -146,6 +146,9 @@ func (c *chatCall) streamAttempt(st *walkState, spec llm.UpstreamSpec, lane stri } return werr } + // A recording consumer's row keeps every relayed line (record.go): + // after the relay took it, so the stream's own path is unchanged. + c.recording.addStream(chunk.out) st.relayed++ return nil }) diff --git a/go/internal/oai/embeddings.go b/go/internal/oai/embeddings.go index cc704ef4e..0fbba2318 100644 --- a/go/internal/oai/embeddings.go +++ b/go/internal/oai/embeddings.go @@ -649,7 +649,7 @@ func (c *embedCall) admitLimiter() bool { // The row the shutdown's forced settle writes should the request still // be open after the HTTP drain (W06-13 (e)). registerForcedRow(res, c.d.Record, func() llmlog.GatewayRow { - return llmlog.GatewayRow{Pipeline: embedPipeline, ConsumerID: c.ca.ConsumerID, + return llmlog.GatewayRow{Pipeline: embedPipeline, ConsumerID: c.ca.ConsumerID, Recorded: c.ca.RecordBodies, Gateway: withFederation(c.r.Context(), llmlog.Gateway{Alias: c.alias.Name, Hop: c.rec.Hop, ClientReqID: clientRequestID(c.r), ModelKeyID: c.ca.ModelKeyID})} }, string(c.required)) return true @@ -1548,7 +1548,14 @@ func (c *embedCall) record(plan Plan, served *backends.Backend, attempts []llm.C usage = llmlog.UsageBackend } request := "" - if c.s.BodyLogging == llmlog.BodyLoggingFull || (c.s.BodyLogging == llmlog.BodyLoggingErrors && out.redacted != nil) { + rc := recording{on: c.ca.RecordBodies} + switch { + case rc.on: + // A recording consumer's row (issue #571): the whole text of the + // input, reserved against the recording account (record.go). The + // answer — the vectors — is not kept: the input is what was sent. + request = rc.text(c.req.input, llmlog.RecordLostRequest) + case c.s.BodyLogging == llmlog.BodyLoggingFull || (c.s.BodyLogging == llmlog.BodyLoggingErrors && out.redacted != nil): // The row's text of the input is sized, then booked, then written // (FOLGE-E, as the chat route since FOLGE-P hardening 6): // string(input) copied the whole value outside the reservation, and @@ -1558,7 +1565,7 @@ func (c *embedCall) record(plan Plan, served *backends.Backend, attempts []llm.C request = bodyLogText(c.req.input, n) } } - c.d.Record(llmlog.GatewayRow{ + row := llmlog.GatewayRow{ Pipeline: embedPipeline, ConsumerID: c.ca.ConsumerID, Gateway: withFederation(c.r.Context(), llmlog.Gateway{ @@ -1570,5 +1577,7 @@ func (c *embedCall) record(plan Plan, served *backends.Backend, attempts []llm.C Err: out.redacted, Request: request, BodyLogging: c.s.BodyLogging, - }) + } + rc.mark(&row) + c.d.Record(row) } diff --git a/go/internal/oai/forced.go b/go/internal/oai/forced.go index 6096f9a2f..be40f4279 100644 --- a/go/internal/oai/forced.go +++ b/go/internal/oai/forced.go @@ -50,6 +50,7 @@ func registerForcedRow(l LimitReservation, record func(llmlog.GatewayRow), build row.Gateway.Finish = llmlog.FinishAborted row.Err = &llmlog.RedactedErr{Class: "shutdown", Code: CodeServiceUnavailable} row.BodyLogging = llmlog.BodyLoggingNone + markForced(&row, row.Recorded) // a recording consumer's row says what it lacks fs.OnForcedSettle(func(u dispatch.Usage) { r := row r.Telemetry = llmlog.Entry{RequiredSensitivity: required, Metadata: map[string]any{}, diff --git a/go/internal/oai/record.go b/go/internal/oai/record.go new file mode 100644 index 000000000..e19c5d9f3 --- /dev/null +++ b/go/internal/oai/record.go @@ -0,0 +1,156 @@ +package oai + +import ( + "math" + "strings" + + "github.com/GottZ/ctx/internal/llmlog" +) + +// recording is the capture of one request of a recording consumer (issue +// #571, auth.ConsumerAuth.RecordBodies): the texts its row keeps whole — the +// request as the body policy's text but without its cut, the answer the +// client received (a non-streamed chat answer as written, a stream's data +// lines as relayed). Every text is reserved against llmlog's recording +// account (llmlog.ReserveRecorded) before it is made — never against the +// request's in-flight budget, so the switch changes no booking, no refusal +// and no answer of the request. A text the account cannot take is not made: +// the row goes without it and names it (record_lost, cause "memory"). The +// zero value records nothing; on is set once, from the door's ConsumerAuth. +type recording struct { + on bool + // held is what this request reserved and has not handed to its row. + held int64 + // lost names the texts the account refused. + lost []string + // stream is a stream's relayed data lines; streamLost once the account + // refused one of them (the lines after it are not kept either: a stream + // with a hole is not the answer the client received). + stream strings.Builder + streamHeld int64 // the part of held the stream's buffer takes: its capacity + streamLost bool +} + +// noLogLimit is the text limit of a recorded row: none (bodyLogWalkN). +const noLogLimit = math.MaxInt + +// reserve takes n bytes from the account for this request. +func (r *recording) reserve(n int64) bool { + if !llmlog.ReserveRecorded(n) { + return false + } + r.held += n + return true +} + +// loseBody records that body (llmlog.RecordLostRequest/Response) was not +// kept. +func (r *recording) loseBody(body string) { + r.lost = append(r.lost, body) +} + +// text is the whole log text of raw (bodyLogWalkN without a limit), reserved +// first; "" and the body named lost when the account refuses it. +func (r *recording) text(raw []byte, body string) string { + n := bodyLogSizeN(raw, noLogLimit) + if !r.reserve(int64(n)) { + r.loseBody(body) + return "" + } + return bodyLogTextN(raw, n, noLogLimit) +} + +// bytes is a copy of b, reserved first; "" and the body named lost when the +// account refuses it. +func (r *recording) bytes(b []byte, body string) string { + if !r.reserve(int64(len(b))) { + r.loseBody(body) + return "" + } + return string(b) +} + +// addStream appends one relayed data line of a stream. The buffer grows as +// strings.Builder.Grow grows it (to 2 × its capacity + the line, then the +// allocator's size class); the new capacity is reserved before the growth +// and the allocator's rounding right after it — the account holds the +// current buffer, the replaced one is garbage from then on. A refusal drops +// what the stream kept so far and every later line. +func (r *recording) addStream(line []byte) { + if !r.on || r.streamLost || len(line) == 0 { + return + } + if r.stream.Cap()-r.stream.Len() < len(line) { + grown := int64(2*r.stream.Cap() + len(line)) + if !r.reserve(grown - r.streamHeld) { + r.dropStream() + return + } + r.streamHeld = grown + r.stream.Grow(len(line)) + if c := int64(r.stream.Cap()); c > r.streamHeld { + if !r.reserve(c - r.streamHeld) { + r.dropStream() + return + } + r.streamHeld = c + } + } + r.stream.Write(line) +} + +// dropStream gives the stream's buffer back and names the answer lost. +func (r *recording) dropStream() { + r.held -= r.streamHeld + llmlog.ReleaseRecorded(r.streamHeld) + r.streamHeld = 0 + r.stream = strings.Builder{} + r.streamLost = true + r.loseBody(llmlog.RecordLostResponse) +} + +// streamText is the stream's kept answer ("" after a refusal). +func (r *recording) streamText() string { + if r.streamLost { + return "" + } + return r.stream.String() +} + +// mark puts the recording on the row: Recorded, the lost bodies and what the +// texts hold of the account, which from now on is the writer's to give back. +// Not recording: the row stays as it is. +func (r *recording) mark(row *llmlog.GatewayRow) { + if !r.on { + return + } + row.Recorded = true + if len(r.lost) > 0 { + row.RecordLost, row.RecordLostCause = r.lost, llmlog.RecordLostMemory + } + row.RecordedHeld, r.held = r.held, 0 +} + +// release gives back what no row took (a request that wrote no row of its +// own: no wire attempt, the shutdown's forced settle). Runs at the request's +// end (close). +func (r *recording) release() { + llmlog.ReleaseRecorded(r.held) + r.held = 0 +} + +// markForced puts the recording on the row the shutdown's forced settle +// writes: recorded, without a body (it is built at the admission, before +// there is an answer) — the request's text is named lost, and for chat the +// answer too. +func markForced(row *llmlog.GatewayRow, on bool) { + if !on { + return + } + row.Recorded = true + row.RecordLost = []string{llmlog.RecordLostRequest} + if row.Pipeline == chatPipeline { + row.RecordLost = append(row.RecordLost, llmlog.RecordLostResponse) + } + row.RecordLostCause = llmlog.RecordLostShutdown +} diff --git a/go/internal/oai/record_test.go b/go/internal/oai/record_test.go new file mode 100644 index 000000000..fab1d4f56 --- /dev/null +++ b/go/internal/oai/record_test.go @@ -0,0 +1,195 @@ +package oai_test + +import ( + "context" + "encoding/json" + "regexp" + "strings" + "testing" + + "github.com/GottZ/ctx/internal/auth" + "github.com/GottZ/ctx/internal/backends" + "github.com/GottZ/ctx/internal/llmlog" + "github.com/GottZ/ctx/internal/oai" +) + +// The recording switch on the routes (issue #571): a consumer with +// RecordBodies has its row carry the whole request and the whole answer the +// client received — a non-streamed chat answer as written, a stream's relayed +// data lines, the inputs of embeddings and the query and documents of rerank +// — under every gateway.body_logging value and every alias class; and the +// request path is the same with and without the switch: the same upstream +// body (so the same chain, scan and limits), the same status, the same answer +// up to the request's own id and clock. + +// recSecret is a credentials pattern in a prompt: the sensitivity scan raises +// a request carrying it to credentials, where the body policy stores nothing. +const recSecret = "password=hunter2-recorded-571" + +// recordingConsumer is the rig's consumer with the switch set to on. +func recordingConsumer(on bool) *auth.ConsumerAuth { + ca := urgentApp() + ca.RecordBodies = on + return ca +} + +// releaseRows gives the rows' reservations back (the rig's sink is no writer). +func releaseRows(rows []llmlog.GatewayRow) { + for _, r := range rows { + llmlog.ReleaseRecorded(r.RecordedHeld) + } +} + +// answerIdentity drops what differs between two requests by construction: +// the answer's id and created stamp. +var answerIdentity = regexp.MustCompile(`"(id|created)":("[^"]*"|\d+)`) + +func sameAnswer(a, b []byte) bool { + return answerIdentity.ReplaceAllString(string(a), "") == answerIdentity.ReplaceAllString(string(b), "") +} + +func TestRecordedChatKeepsWholeBodiesAndChangesNoAnswer(t *testing.T) { + long := strings.Repeat("abcdefgh", 12<<10) // 96 KiB, past the 64 KiB cap + answer := `{"id":"gen-1","object":"chat.completion","created":1700000000,"model":"M",` + + `"choices":[{"index":0,"finish_reason":"stop","message":{"role":"assistant","content":"` + strings.Repeat("y", 80<<10) + `"}}],` + + `"usage":{"prompt_tokens":11,"completion_tokens":3,"total_tokens":14}}` + body := `{"model":"pub","messages":[{"role":"user","content":"` + recSecret + " " + long + `"}]}` + messages := `[{"role":"user","content":"` + recSecret + " " + long + `"}]` + for _, pol := range []string{llmlog.BodyLoggingNone, llmlog.BodyLoggingErrors, llmlog.BodyLoggingFull} { + t.Run(pol, func(t *testing.T) { + u := newUpstream(t, answer) + rig := newChatRig(t, []backends.Backend{u.row("spark", backends.TrustFull, 10)}, 4, 1) + rig.setSettings(func(s *oai.Settings) { s.BodyLogging = pol }) + rig.ca.Store(recordingConsumer(false)) + off := rig.post(t, body) + rig.ca.Store(recordingConsumer(true)) + on := rig.post(t, body) + rows := rig.rows.all() + defer releaseRows(rows) + if off.status != 200 || on.status != 200 { + t.Fatalf("status off %d on %d, want 200 both: %.200s / %.200s", off.status, on.status, off.body, on.body) + } + if !sameAnswer(off.body, on.body) { + t.Errorf("the answer differs with the switch on") + } + if len(u.raws) != 2 || string(u.raws[0]) != string(u.raws[1]) { + t.Errorf("the upstream bodies differ with the switch on (%d calls)", len(u.raws)) + } + if len(rows) != 2 { + t.Fatalf("%d rows, want 2", len(rows)) + } + ro, rn := rows[0], rows[1] + // The scan raised both to credentials: the switch changes no class. + if ro.Telemetry.RequiredSensitivity != string(backends.SensCredentials) || rn.Telemetry.RequiredSensitivity != ro.Telemetry.RequiredSensitivity { + t.Errorf("required sensitivity off %q on %q, want credentials both", ro.Telemetry.RequiredSensitivity, rn.Telemetry.RequiredSensitivity) + } + if ro.Recorded || ro.RecordedHeld != 0 { + t.Errorf("the row of the consumer without the switch is marked recorded") + } + if stored := llmlog.GatewayEntry(ro); stored.RequestUser != "" || stored.ResponseContent != "" { + t.Errorf("the unrecorded credentials row stores %d/%d bytes, want 0/0 (sealed)", len(stored.RequestUser), len(stored.ResponseContent)) + } + if !rn.Recorded || rn.RecordLost != nil { + t.Fatalf("the recording consumer's row: recorded %v lost %v, want recorded without a loss", rn.Recorded, rn.RecordLost) + } + stored := llmlog.RecordedGatewayEntry(rn) + if stored.RequestUser != messages { + t.Errorf("recorded request %d bytes, want the whole message array (%d bytes)", len(stored.RequestUser), len(messages)) + } + if !strings.HasSuffix(string(on.body), "\n") || stored.ResponseContent != strings.TrimSuffix(string(on.body), "\n") { + t.Errorf("recorded answer %d bytes, want the whole answer the client received (%d bytes)", len(stored.ResponseContent), len(on.body)) + } + if want := int64(len(stored.RequestUser) + len(stored.ResponseContent)); rn.RecordedHeld != want { + t.Errorf("the row holds %d bytes of the recording account, want %d", rn.RecordedHeld, want) + } + }) + } +} + +// TestRecordedStreamKeepsTheRelayedLines: a stream's recorded answer is the +// data lines the relay handed to the client, in order — the client's body is +// exactly those lines and the closing [DONE] — and the client gets the same +// stream with and without the switch. +func TestRecordedStreamKeepsTheRelayedLines(t *testing.T) { + sh := streamShapes[0] + u := newUpstream(t, "") + u.setRespond(sseRespond(sh.steps(), nil, nil)) + rig := newChatRig(t, []backends.Backend{u.row("spark", backends.TrustFull, 10)}, 4, 1, withStreamSettings) + srv := serveHTTP(t, rig.router) + rig.ca.Store(recordingConsumer(false)) + off := postStream(context.Background(), t, srv, streamBody("chat")) + rig.ca.Store(recordingConsumer(true)) + on := postStream(context.Background(), t, srv, streamBody("chat")) + rows := rig.rows.all() + defer releaseRows(rows) + checkRelay(t, on) + if !sameAnswer([]byte(off.raw), []byte(on.raw)) { + t.Errorf("the stream differs with the switch on:\n off %q\n on %q", off.raw, on.raw) + } + if len(rows) != 2 || rows[0].Recorded || rows[0].Response != "" || !rows[1].Recorded { + t.Fatalf("rows %d: off recorded %v response %d bytes, on recorded %v", len(rows), rows[0].Recorded, len(rows[0].Response), rows[1].Recorded) + } + got := llmlog.RecordedGatewayEntry(rows[1]).ResponseContent + if got == "" || got+"data: [DONE]\n\n" != on.raw { + t.Errorf("recorded stream answer %q, want the client's body without its closing [DONE]: %q", got, on.raw) + } + if !strings.Contains(llmlog.RecordedGatewayEntry(rows[1]).RequestUser, `"content":"hi"`) { + t.Errorf("recorded stream request %q, want the message array", rows[1].Request) + } +} + +func TestRecordedEmbeddingsKeepTheWholeInput(t *testing.T) { + inputs := []string{recSecret + " " + strings.Repeat("e", 70<<10), "second " + strings.Repeat("f", 1000)} + body := embedBody("emb1", inputs) + for _, pol := range []string{llmlog.BodyLoggingNone, llmlog.BodyLoggingFull} { + t.Run(pol, func(t *testing.T) { + e := newEmbedEngine(t, 8) + rig := newEmbedRig(t, []backends.Backend{e.row("spark-embed", backends.ProtocolOpenAI, 10)}, 4, 1) + rig.setSettings(func(s *oai.Settings) { s.BodyLogging = pol }) + rig.ca.Store(recordingConsumer(false)) + off := rig.postEmbed(t, body) + rig.ca.Store(recordingConsumer(true)) + on := rig.postEmbed(t, body) + rows := rig.rows.all() + defer releaseRows(rows) + if off.status != 200 || on.status != 200 || !sameAnswer(off.body, on.body) { + t.Fatalf("status off %d on %d (answers equal %v): %.300s", off.status, on.status, sameAnswer(off.body, on.body), on.body) + } + if len(rows) != 2 || rows[0].Recorded || !rows[1].Recorded { + t.Fatalf("rows %d, recorded off/on want false/true", len(rows)) + } + in, _ := json.Marshal(inputs) + stored := llmlog.RecordedGatewayEntry(rows[1]) + if stored.RequestUser != string(in) || stored.ResponseContent != "" { + t.Errorf("recorded embeddings row: request %d bytes (want the whole input, %d), answer %d bytes (want none — the vectors are not kept)", + len(stored.RequestUser), len(in), len(stored.ResponseContent)) + } + }) + } +} + +func TestRecordedRerankKeepsQueryAndDocuments(t *testing.T) { + docs := []string{recSecret + " " + strings.Repeat("d", 70<<10), "other"} + query := "which document? " + strings.Repeat("q", 100) + body := rerankBody("rrpub", query, docs) + e := newRerankEngine(t) + rig := newRerankRig(t, []backends.Backend{e.row("spark-rerank", 10)}, 4, 1) + rig.ca.Store(recordingConsumer(false)) + off := rig.postRerank(t, "/v1/rerank", body) + rig.ca.Store(recordingConsumer(true)) + on := rig.postRerank(t, "/v1/rerank", body) + rows := rig.rows.all() + defer releaseRows(rows) + if off.status != 200 || on.status != 200 || !sameAnswer(off.body, on.body) { + t.Fatalf("status off %d on %d (answers equal %v): %.300s", off.status, on.status, sameAnswer(off.body, on.body), on.body) + } + if len(rows) != 2 || rows[0].Recorded || !rows[1].Recorded { + t.Fatalf("rows %d, recorded off/on want false/true", len(rows)) + } + q, _ := json.Marshal(query) + d, _ := json.Marshal(docs) + stored := llmlog.RecordedGatewayEntry(rows[1]) + if want := string(q) + "\n" + string(d); stored.RequestUser != want { + t.Errorf("recorded rerank request %d bytes, want query, line break and documents (%d bytes)", len(stored.RequestUser), len(want)) + } +} diff --git a/go/internal/oai/rerank.go b/go/internal/oai/rerank.go index 2cb73ca8e..b8029c620 100644 --- a/go/internal/oai/rerank.go +++ b/go/internal/oai/rerank.go @@ -489,7 +489,7 @@ func (c *rerankCall) admitLimiter() bool { // The row the shutdown's forced settle writes should the request still // be open after the HTTP drain (W06-13 (e)). registerForcedRow(res, c.d.Record, func() llmlog.GatewayRow { - return llmlog.GatewayRow{Pipeline: rerankPipeline, ConsumerID: c.ca.ConsumerID, + return llmlog.GatewayRow{Pipeline: rerankPipeline, ConsumerID: c.ca.ConsumerID, Recorded: c.ca.RecordBodies, Gateway: withFederation(c.r.Context(), llmlog.Gateway{Alias: c.alias.Name, Hop: c.rec.Hop, ClientReqID: clientRequestID(c.r), ModelKeyID: c.ca.ModelKeyID})} }, string(c.required)) return true @@ -1115,14 +1115,26 @@ func (c *rerankCall) record(plan Plan, served *backends.Backend, attempts []llm. usage = llmlog.UsageBackend } request := "" - if c.s.BodyLogging == llmlog.BodyLoggingFull || (c.s.BodyLogging == llmlog.BodyLoggingErrors && out.redacted != nil) { + rc := recording{on: c.ca.RecordBodies} + switch { + case rc.on: + // A recording consumer's row (issue #571): the whole text of the + // query and the documents, reserved against the recording account + // (record.go). The answer — indexes and scores, the echo repeats the + // documents — is not kept. + if n := rerankLogSize(c.req, noLogLimit); rc.reserve(int64(n)) { + request = rerankLogText(c.req, n, noLogLimit) + } else { + rc.loseBody(llmlog.RecordLostRequest) + } + case c.s.BodyLogging == llmlog.BodyLoggingFull || (c.s.BodyLogging == llmlog.BodyLoggingErrors && out.redacted != nil): // The row's text of the query and the documents is sized, then // booked, then written (the embeddings route's rule). - if n := rerankLogSize(c.req); c.ledger.cover(int64(n)) { - request = rerankLogText(c.req, n) + if n := rerankLogSize(c.req, bodyLogTextMax); c.ledger.cover(int64(n)) { + request = rerankLogText(c.req, n, bodyLogTextMax) } } - c.d.Record(llmlog.GatewayRow{ + row := llmlog.GatewayRow{ Pipeline: rerankPipeline, ConsumerID: c.ca.ConsumerID, Gateway: withFederation(c.r.Context(), llmlog.Gateway{ @@ -1134,22 +1146,25 @@ func (c *rerankCall) record(plan Plan, served *backends.Backend, attempts []llm. Err: out.redacted, Request: request, BodyLogging: c.s.BodyLogging, - }) + } + rc.mark(&row) + c.d.Record(row) } // rerankLogSize is the length of rerankLogText: the query's text, a line -// break and the documents' text (bodyLogSize of each raw value). -func rerankLogSize(req *rerankRequest) int { - return bodyLogSize(req.queryRaw) + 1 + bodyLogSize(req.docsRaw) +// break and the documents' text (bodyLogSizeN of each raw value, each up to +// limit — bodyLogTextMax, or noLogLimit for a recorded row). +func rerankLogSize(req *rerankRequest, limit int) int { + return bodyLogSizeN(req.queryRaw, limit) + 1 + bodyLogSizeN(req.docsRaw, limit) } // rerankLogText is the log row's text of the request, written once into // size bytes (bodyLogText's form over two values). -func rerankLogText(req *rerankRequest, size int) string { +func rerankLogText(req *rerankRequest, size, limit int) string { var b strings.Builder b.Grow(size) - bodyLogWalk(req.queryRaw, func(p []byte) { b.Write(p) }) + bodyLogWalkN(req.queryRaw, limit, func(p []byte) { b.Write(p) }) b.WriteByte('\n') - bodyLogWalk(req.docsRaw, func(p []byte) { b.Write(p) }) + bodyLogWalkN(req.docsRaw, limit, func(p []byte) { b.Write(p) }) return b.String() } diff --git a/go/internal/schemacontract/manifest.json b/go/internal/schemacontract/manifest.json index 20e81aa69..85799e2f8 100644 --- a/go/internal/schemacontract/manifest.json +++ b/go/internal/schemacontract/manifest.json @@ -1,9 +1,9 @@ { "manifest_version": 1, "generated_against": { - "migration_max": 196, - "migration_count": 84, - "migration_chain_sha256": "df392ea0f70eb16d7cf0c60d46a0ad16b92a152c89321fcd0b592914cdcb4e27", + "migration_max": 197, + "migration_count": 85, + "migration_chain_sha256": "0af84720c017d6df9610f248d304edcb869f9ff57ef76a59da7ef17f22b71eb5", "pg_major": 18, "image": "pgvector-timescaledb:pg18" }, @@ -2592,6 +2592,12 @@ "type": "uuid", "not_null": false, "storage": "p" + }, + { + "name": "record_bodies", + "type": "boolean", + "not_null": true, + "storage": "p" } ], "row_security": false @@ -6120,7 +6126,7 @@ "src_hash": "51cec9a296a124f88b899b8c3bdf85605f85761389159b9c481199588b1ebcbc" }, "audit_state_model_consumer(c context_model_consumers)": { - "src_hash": "c31dfffa79233dbc075925f1fe69000cc1032ff1d48f4fccbafcb1735fe636d7" + "src_hash": "abc2776a43ffa046759bdb1e7e4048bb30fc0109e3f9b61c1cfb78c3f4504dd3" }, "audit_state_model_grant(g context_model_consumer_grants)": { "src_hash": "26acfa1913e6f6c346db99053b88d1c1dc730088dddfbb7778cbdabcbdf16bf2" @@ -6186,7 +6192,7 @@ "src_hash": "4029c6b45395dcdc3f8fd2886d8feff0a5b51d82b4a78358278a34f397c1add0" }, "ctx_model_auth(p_key_hash text, p_client_ip inet, p_secure boolean)": { - "src_hash": "4a53d01644bbb648173d964f2ffb2670e3cde0c9b81a1e98b9391edde7a20b45" + "src_hash": "f5015d876eac3fe552c75ce0e59e53b3f780c64de4d2b0d47fa8b5ec845e19ad" }, "ctx_model_auth_live(p_key_ids uuid[])": { "src_hash": "77d45df5527e257664bbb72a5ed5fd698b04c4718185b07da76be131964dd737" @@ -6377,7 +6383,7 @@ "def_hash": "bda1f75b177103c18e9499e9a1881991628cdd55aaf8ab405d9e88d6a0eadc2c" }, "context_model_consumers.trg_model_consumers_audit_upd": { - "def_hash": "eb7cf9da3704b9f60e84094cc4af53e35b50455dbfad04a5dad85205647401bf" + "def_hash": "80ac3ec855ea70d6a0e542d9cb93c8a615e57a9786c491300de511a6eb2591c5" }, "context_model_consumers.trg_model_consumers_deactivate": { "def_hash": "39098f2eeabd387754c4dd669f02c37f10a9c923f210392de606f17b9a10671f" diff --git a/go/internal/store/audit_classification_test.go b/go/internal/store/audit_classification_test.go index d601cbaa1..ddeeca7d0 100644 --- a/go/internal/store/audit_classification_test.go +++ b/go/internal/store/audit_classification_test.go @@ -60,6 +60,7 @@ import ( "github.com/GottZ/ctx/internal/store" "github.com/GottZ/ctx/internal/testdb" + "github.com/GottZ/ctx/migrations" ) // auditedTable is the classification of one audited table. @@ -110,6 +111,7 @@ var auditClassification = []auditedTable{ "tenant_id", "label", "description", "kind", "tenant_scope", "all_models", "prompt_sensitivity", "fair_weight", "admission_lane", "allowed_cidrs", "allow_plaintext", "active", "peer_instance_id", "peer_bound_at", + "record_bodies", }, excluded: map[string]string{ "id": "identity of the row, written as entity_key and metadata.consumer_id", @@ -495,6 +497,7 @@ var auditColumnProbes = map[string]auditProbeSet{ "active": "NOT active", "peer_instance_id": "gen_random_uuid()", "peer_bound_at": "peer_bound_at - interval '1 minute'", + "record_bodies": "NOT record_bodies", }, excluded: map[string]string{ "created_at": "created_at - interval '1 minute'", @@ -650,6 +653,13 @@ func TestAuditClassificationPerColumn(t *testing.T) { m163Apply(ctx, t, pool) m164Apply(ctx, t, pool) m168ApplyRest(ctx, t, pool) + // 197 (issue #571) adds record_bodies to the consumer and its audit; it + // needs only 161's objects, so its body goes onto the 168 schema here. + m197Body, err := migrations.FS.ReadFile("197_model_consumer_record_bodies.sql") + if err != nil { + t.Fatalf("read 197: %v", err) + } + kaExecInTx(ctx, t, pool, string(m197Body)) otherTenant := freshTenant(t, ctx, pool, "ka-pin-other") var otherPrincipal string diff --git a/go/internal/store/model_consumer_record_bodies_migration_integration_test.go b/go/internal/store/model_consumer_record_bodies_migration_integration_test.go new file mode 100644 index 000000000..d602e8bc7 --- /dev/null +++ b/go/internal/store/model_consumer_record_bodies_migration_integration_test.go @@ -0,0 +1,258 @@ +//go:build integration + +// Migration 197 gates (issue #571): the recording switch of a model consumer. +// +// go test -tags=integration -p 1 -count=1 -run 'TestMigration197' -v ./internal/store/ +// +// - schema: record_bodies BOOLEAN NOT NULL DEFAULT false; a consumer that +// existed before 197 reads false; +// - ctx_model_auth carries it as its LAST column, valid rows with the +// consumer's value, the sentinel with false; +// - the audit: switching writes one 'update' row whose old/new state carry +// record_bodies; an UPDATE that leaves it as it is writes none; +// - the way back of the header, in a rolled-back transaction, leaves the +// catalog of 196; a second run of 197 leaves its own catalog unchanged. +package store_test + +import ( + "context" + "regexp" + "strings" + "testing" + + "github.com/GottZ/ctx/internal/store" + "github.com/GottZ/ctx/internal/testdb" + "github.com/GottZ/ctx/migrations" +) + +const ( + m197File = "197_model_consumer_record_bodies.sql" + m197Version = 197 +) + +// m197Catalog is what 197 touches: the two functions, the consumer +// triggers, the consumer columns and the version row. +func m197Catalog(ctx context.Context, t *testing.T, q func(context.Context, string) ([]string, error)) string { + t.Helper() + var parts []string + for _, sql := range []string{ + `SELECT p.proname || ': ' || pg_get_functiondef(p.oid) FROM pg_proc p + WHERE p.proname IN ('ctx_model_auth', 'audit_state_model_consumer') ORDER BY p.proname`, + `SELECT 'trigger: ' || pg_get_triggerdef(oid) FROM pg_trigger + WHERE NOT tgisinternal AND tgrelid = 'context_model_consumers'::regclass ORDER BY tgname`, + `SELECT 'column: ' || column_name || ' ' || data_type || ' ' || is_nullable || ' ' || COALESCE(column_default, '') + FROM information_schema.columns + WHERE table_schema = current_schema() AND table_name = 'context_model_consumers' ORDER BY ordinal_position`, + `SELECT 'migration: ' || version FROM _migrations WHERE version = 197`, + } { + lines, err := q(ctx, sql) + if err != nil { + t.Fatalf("catalog: %v", err) + } + parts = append(parts, lines...) + } + return strings.Join(parts, "\n") +} + +// m197WayBack is the way back of the header: the definitions of 161 come +// from 161's own file, so the statements are exactly what an operator runs. +func m197WayBack(t *testing.T) string { + t.Helper() + raw, err := migrations.FS.ReadFile("161_model_consumers.sql") + if err != nil { + t.Fatalf("read 161: %v", err) + } + src := string(raw) + pick := func(re string) string { + m := regexp.MustCompile(re).FindString(src) + if m == "" { + t.Fatalf("161 has no match for %s", re) + } + return m + } + auth := pick(`(?s)CREATE OR REPLACE FUNCTION ctx_model_auth\(.*?\n\$\$;`) + state := pick(`(?s)CREATE OR REPLACE FUNCTION audit_state_model_consumer\(.*?\$\$ LANGUAGE sql STABLE;`) + trig := pick(`(?s)CREATE TRIGGER trg_model_consumers_audit_upd\s.*?EXECUTE FUNCTION audit_model_consumers_write\(\);`) + return strings.Join([]string{ + `DROP FUNCTION ctx_model_auth(TEXT, INET, BOOLEAN);`, + auth, + state, + `DROP TRIGGER trg_model_consumers_audit_upd ON context_model_consumers;`, + trig, + `ALTER TABLE context_model_consumers DROP COLUMN record_bodies;`, + `DELETE FROM _migrations WHERE version = 197;`, + }, "\n") +} + +func TestMigration197Idempotent(t *testing.T) { + if testing.Short() { + t.Skip("integration test") + } + ctx := context.Background() + pool := testdb.SetupTestDBUpTo(t, m197Version-1) + onPool := func(ctx context.Context, sql string) ([]string, error) { return stringList(ctx, pool, sql) } + at196 := m197Catalog(ctx, t, onPool) + tenant, _ := mcTenant(ctx, t, pool, "m197", "active") + before := mcConsumer(ctx, t, pool, tenant, "m197-before", nil) + _, hash := mcKey(ctx, t, pool, before, "m197-before", nil) + if err := store.RunMigrationsUpTo(ctx, pool, m197Version); err != nil { + t.Fatalf("migrate to 197: %v", err) + } + + t.Run("column_off_by_default", func(t *testing.T) { + var dtype, nullable, def string + if err := pool.QueryRow(ctx, `SELECT data_type, is_nullable, column_default FROM information_schema.columns + WHERE table_schema = current_schema() AND table_name = 'context_model_consumers' AND column_name = 'record_bodies'`). + Scan(&dtype, &nullable, &def); err != nil { + t.Fatalf("record_bodies column: %v", err) + } + if dtype != "boolean" || nullable != "NO" || def != "false" { + t.Errorf("record_bodies %s nullable %s default %s, want boolean NOT NULL DEFAULT false", dtype, nullable, def) + } + if n := mkCount(ctx, t, pool, `SELECT count(*) FROM context_model_consumers WHERE id = $1::uuid AND NOT record_bodies`, before); n != 1 { + t.Errorf("the consumer of 196 reads record_bodies on") + } + }) + t.Run("ctx_model_auth_carries_it_last", func(t *testing.T) { + var result string + if err := pool.QueryRow(ctx, `SELECT pg_get_function_result(p.oid) FROM pg_proc p WHERE p.proname = 'ctx_model_auth'`).Scan(&result); err != nil { + t.Fatalf("result type: %v", err) + } + if !strings.HasSuffix(result, "peer_instance_id uuid, record_bodies boolean)") { + t.Errorf("ctx_model_auth returns %s, want record_bodies boolean as the last column", result) + } + auth := func() (valid, record bool) { + t.Helper() + if err := pool.QueryRow(ctx, `SELECT is_valid, record_bodies FROM ctx_model_auth($1, NULL, true)`, hash).Scan(&valid, &record); err != nil { + t.Fatalf("ctx_model_auth: %v", err) + } + return valid, record + } + if v, r := auth(); !v || r { + t.Errorf("off: valid %v record %v, want true/false", v, r) + } + kaExec(ctx, t, pool, `UPDATE context_model_consumers SET record_bodies = true WHERE id = $1::uuid`, before) + if v, r := auth(); !v || !r { + t.Errorf("on: valid %v record %v, want true/true — the next check reads the switch", v, r) + } + var valid, record bool + if err := pool.QueryRow(ctx, `SELECT is_valid, record_bodies FROM ctx_model_auth($1, NULL, true)`, mcHash("nobody")).Scan(&valid, &record); err != nil || valid || record { + t.Errorf("sentinel valid %v record %v (err %v), want false/false", valid, record, err) + } + kaExec(ctx, t, pool, `UPDATE context_model_consumers SET record_bodies = false WHERE id = $1::uuid`, before) + }) + t.Run("switching_is_audited", func(t *testing.T) { + rows := func() int { + return kaCount(ctx, t, pool, `entity_type = 'model_consumer' AND entity_key = $1 AND action = 'update'`, before) + } + n0 := rows() + kaExec(ctx, t, pool, `UPDATE context_model_consumers SET record_bodies = true WHERE id = $1::uuid`, before) + if rows() != n0+1 { + t.Fatalf("switching on wrote %d update row(s), want 1", rows()-n0) + } + var oldV, newV string + if err := pool.QueryRow(ctx, `SELECT old_value->>'record_bodies', new_value->>'record_bodies' FROM context_settings_audit + WHERE entity_type = 'model_consumer' AND entity_key = $1 ORDER BY created_at DESC, id DESC LIMIT 1`, before).Scan(&oldV, &newV); err != nil { + t.Fatalf("audit row: %v", err) + } + if oldV != "false" || newV != "true" { + t.Errorf("audit old/new record_bodies %s/%s, want false/true", oldV, newV) + } + kaExec(ctx, t, pool, `UPDATE context_model_consumers SET record_bodies = true WHERE id = $1::uuid`, before) + if rows() != n0+1 { + t.Errorf("an UPDATE that leaves record_bodies as it is wrote an audit row") + } + kaExec(ctx, t, pool, `UPDATE context_model_consumers SET record_bodies = false WHERE id = $1::uuid`, before) + if rows() != n0+2 { + t.Errorf("switching off wrote %d update row(s), want 1", rows()-n0-1) + } + }) + t.Run("way_back_is_clean", func(t *testing.T) { + tx, err := pool.Begin(ctx) + if err != nil { + t.Fatalf("begin: %v", err) + } + defer func() { _ = tx.Rollback(ctx) }() + if _, err := tx.Exec(ctx, m197WayBack(t)); err != nil { + t.Fatalf("way back: %v (SQLSTATE %s)", err, mcSQLState(err)) + } + after := m197Catalog(ctx, t, func(ctx context.Context, sql string) ([]string, error) { return stringListTx(ctx, tx, sql) }) + if after != at196 { + t.Errorf("catalog after the way back differs from 196:\n--- 196\n%s\n--- way back\n%s", at196, after) + } + }) + t.Run("second_run_keeps_the_catalog", func(t *testing.T) { + body, err := migrations.FS.ReadFile(m197File) + if err != nil { + t.Fatalf("read %s: %v", m197File, err) + } + before := m197Catalog(ctx, t, onPool) + kaExecInTx(ctx, t, pool, string(body)) + if after := m197Catalog(ctx, t, onPool); after != before { + t.Fatalf("catalog changed on the second run:\n--- before\n%s\n--- after\n%s", before, after) + } + }) +} + +// TestConsumerRecordBodiesStore: the switch through the store's write paths +// — create, the patch, the locked read the check sees — and the on-demand +// read (ConsumerRecordBodies), with a patch that does not name it leaving it +// as it is. +func TestConsumerRecordBodiesStore(t *testing.T) { + if testing.Short() { + t.Skip("integration test") + } + ctx := context.Background() + pool := testdb.SetupTestDB(t) + admin, _, err := store.CreateApiKey(ctx, pool, "m197-store", "private", nil, "") + if err != nil { + t.Fatalf("admin key: %v", err) + } + stamp := store.APIStamp(admin.ID, "m197-store") + tenant, _ := mcTenant(ctx, t, pool, "m197s", "active") + on, _, _, err := store.CreateConsumerWithKey(ctx, pool, store.ModelConsumerSpec{TenantID: tenant, Label: "rec-on", RecordBodies: true}, nil, stamp) + if err != nil || !on.RecordBodies { + t.Fatalf("create with recording: %+v %v", on.RecordBodies, err) + } + off, _, _, err := store.CreateConsumerWithKey(ctx, pool, store.ModelConsumerSpec{TenantID: tenant, Label: "rec-off"}, nil, stamp) + if err != nil || off.RecordBodies { + t.Fatalf("create without recording: %+v %v", off.RecordBodies, err) + } + read := func() map[string]bool { + t.Helper() + m, err := store.ConsumerRecordBodies(ctx, pool, []string{on.ID, off.ID, "0195a6f0-0000-7000-8000-000000000197"}) + if err != nil { + t.Fatalf("ConsumerRecordBodies: %v", err) + } + return m + } + if m := read(); !m[on.ID] || m[off.ID] || len(m) != 1 { + t.Fatalf("on-demand read %v, want only %s", m, on.ID) + } + // A patch without the field leaves it; the check sees the locked value + // only when the patch names it. + label := "rec-on-renamed" + var seen *bool + if _, err := store.UpdateConsumerChecked(ctx, pool, on.ID, store.ModelAccess{ServerAdmin: true}, + store.ModelConsumerPatch{Label: &label}, func(cur store.ModelConsumer) error { v := cur.RecordBodies; seen = &v; return nil }, stamp); err != nil { + t.Fatalf("rename: %v", err) + } + if seen == nil || *seen { + t.Errorf("a patch without record_bodies showed the check %v, want false (not read)", seen) + } + if m := read(); !m[on.ID] { + t.Fatalf("a rename switched recording off") + } + offV := false + up, err := store.UpdateConsumerChecked(ctx, pool, on.ID, store.ModelAccess{ServerAdmin: true}, + store.ModelConsumerPatch{RecordBodies: &offV}, func(cur store.ModelConsumer) error { v := cur.RecordBodies; seen = &v; return nil }, stamp) + if err != nil || up.RecordBodies { + t.Fatalf("switch off: %+v %v", up.RecordBodies, err) + } + if seen == nil || !*seen { + t.Errorf("the check of a patch naming record_bodies saw %v, want the locked true", seen) + } + if m := read(); len(m) != 0 { + t.Fatalf("after switching off the read says %v", m) + } +} diff --git a/go/internal/store/model_keys.go b/go/internal/store/model_keys.go index c4d4c210e..3840e133a 100644 --- a/go/internal/store/model_keys.go +++ b/go/internal/store/model_keys.go @@ -161,6 +161,13 @@ type ModelConsumer struct { CreatedByLabel *string CreatedByTenantID *string CreatedByServerAdmin bool + // RecordBodies is the recording switch (migration 197). NOT part of + // sqlConsumerCols: the consumer read path is shared with migration tests + // that run the store against a schema before 197 (TestModelGrantStore at + // 164), so the column is read on demand — ConsumerRecordBodies, and the + // locked read of UpdateConsumerChecked when a patch names it — and is + // false wherever nothing read it. + RecordBodies bool } // ModelKeyInfo is a key as the store reads it: id, hint and lifecycle. There @@ -197,6 +204,9 @@ type ModelConsumerSpec struct { AdmissionLane string AllowedCIDRs []string AllowPlaintext bool + // RecordBodies switches recording on at create (migration 197); false + // leaves the column to its default and the insert does not name it. + RecordBodies bool // Limits are the consumer's starting limits (FOLGE-Z Z3): each one is // written as the new consumer's context_gateway_limits row of its tier // and op in the create's transaction — the row exists before the key @@ -235,6 +245,11 @@ type ModelConsumerPatch struct { ClearAllowedCIDRs bool AllowPlaintext *bool Active *bool + // RecordBodies switches recording on or off (migration 197). A patch + // that names it has the check of UpdateConsumerChecked see the locked + // value (current.RecordBodies); a patch without it never reads or writes + // the column. + RecordBodies *bool } // KeyCursor is the keyset position of KeyHistory: the (created_at, id) of the @@ -415,6 +430,7 @@ func insertConsumerTx(ctx context.Context, tx pgx.Tx, spec ModelConsumerSpec) (M {"prompt_sensitivity", "", spec.PromptSensitivity != "", spec.PromptSensitivity}, {"fair_weight", "::smallint", spec.FairWeight != 0, spec.FairWeight}, {"admission_lane", "", spec.AdmissionLane != "", spec.AdmissionLane}, + {"record_bodies", "", spec.RecordBodies, spec.RecordBodies}, } { if o.set { args = append(args, o.val) @@ -432,6 +448,7 @@ func insertConsumerTx(ctx context.Context, tx pgx.Tx, spec ModelConsumerSpec) (M } return ModelConsumer{}, fmt.Errorf("model_consumers: insert: %w", err) } + c.RecordBodies = spec.RecordBodies // what the insert wrote (false = the column default) return c, nil } @@ -679,13 +696,10 @@ func UpdateConsumerChecked(ctx context.Context, pool *pgxpool.Pool, consumerID s return err } if check != nil { - cur, err := readConsumerTx(ctx, tx, consumerID) + cur, err := readLockedConsumerTx(ctx, tx, consumerID, patch) if err != nil { return err } - if cur.Models, err = ConsumerGrantIDs(ctx, tx, consumerID); err != nil { - return err - } if err := check(cur); err != nil { return err } @@ -704,6 +718,9 @@ func UpdateConsumerChecked(ctx context.Context, pool *pgxpool.Pool, consumerID s if c, err = writeConsumerTx(ctx, tx, consumerID, set, args); err != nil { return err } + if patch.RecordBodies != nil { + c.RecordBodies = *patch.RecordBodies // what the UPDATE wrote + } if patch.Models != nil { // The transaction is stamped above. if err := SetConsumerGrants(ctx, tx, consumerID, *patch.Models, AuditStamp{}); err != nil { @@ -846,9 +863,70 @@ func (p ModelConsumerPatch) assignments() ([]string, []any, error) { if p.Active != nil { add("active", "", *p.Active) } + if p.RecordBodies != nil { + add("record_bodies", "", *p.RecordBodies) + } return set, args, nil } +// readLockedConsumerTx is the consumer UpdateConsumerChecked's check sees: +// the locked row, its grants, and — only when the patch names it — its +// recording switch (the column is read on demand, ModelConsumer.RecordBodies). +func readLockedConsumerTx(ctx context.Context, tx pgx.Tx, consumerID string, patch ModelConsumerPatch) (ModelConsumer, error) { + cur, err := readConsumerTx(ctx, tx, consumerID) + if err != nil { + return ModelConsumer{}, err + } + if cur.Models, err = ConsumerGrantIDs(ctx, tx, consumerID); err != nil { + return ModelConsumer{}, err + } + if patch.RecordBodies != nil { + if cur.RecordBodies, err = consumerRecordBodiesTx(ctx, tx, consumerID); err != nil { + return ModelConsumer{}, err + } + } + return cur, nil +} + +// consumerRecordBodiesTx reads the recording switch of a consumer the +// transaction has locked (UpdateConsumerChecked's check sees it). +func consumerRecordBodiesTx(ctx context.Context, tx pgx.Tx, consumerID string) (bool, error) { + var on bool + if err := tx.QueryRow(ctx, `SELECT record_bodies FROM context_model_consumers WHERE id = $1::uuid`, + consumerID).Scan(&on); err != nil { + return false, fmt.Errorf("model_consumers: read record_bodies: %w", err) + } + return on, nil +} + +// ConsumerRecordBodies returns the ids among ids whose consumer records its +// gateway rows in full (record_bodies, migration 197) — the on-demand read of +// the column beside the shared consumer read (ModelConsumer.RecordBodies). +// One statement on the primary key for any number of ids; an unknown id or a +// consumer with the switch off is absent from the map. ids are consumer ids +// the caller has read in its reach (ListConsumers, GetConsumer). +func ConsumerRecordBodies(ctx context.Context, q interface { + Query(context.Context, string, ...any) (pgx.Rows, error) +}, ids []string) (map[string]bool, error) { + out := map[string]bool{} + if len(ids) == 0 { + return out, nil + } + rows, err := q.Query(ctx, `SELECT id::text FROM context_model_consumers + WHERE id = ANY($1::text[]::uuid[]) AND record_bodies`, ids) + if err != nil { + return nil, fmt.Errorf("model_consumers: read record_bodies: %w", err) + } + on, err := pgx.CollectRows(rows, pgx.RowTo[string]) + if err != nil { + return nil, fmt.Errorf("model_consumers: read record_bodies: %w", err) + } + for _, id := range on { + out[id] = true + } + return out, nil +} + // KeyHistory pages through a consumer's keys, newest first, by the keyset // (created_at, id) — revoked and expired ones included. before is the last // key of the previous page (nil: the first page); limit is at least 1 — the diff --git a/go/migrations/197_model_consumer_record_bodies.sql b/go/migrations/197_model_consumer_record_bodies.sql new file mode 100644 index 000000000..6b977f7f3 --- /dev/null +++ b/go/migrations/197_model_consumer_record_bodies.sql @@ -0,0 +1,194 @@ +-- ============================================================================= +-- 197_model_consumer_record_bodies.sql — the recording switch of a model +-- consumer: record_bodies, off by default, set by a server-admin only; its +-- audit, and ctx_model_auth carrying it to the /v1 door (issue #571) +-- Part of ctx by GottZ (https://github.com/GottZ/ctx) +-- ============================================================================= +-- What. A consumer with record_bodies = true has every gateway row of its own +-- (chat, a stream included, embeddings, rerank, rows with an error) written to +-- context_llm_log with the request and the answer in full — whatever +-- gateway.body_logging, the alias, the consumer's prompt_sensitivity, the +-- body scan or Ctx-Sensitivity say, without the 64 KiB cut of the body +-- policy, and marked metadata.gw.recorded = true. Such a row can carry +-- credentials in clear text: its bodies are read by a server-admin only, every +-- other reader gets it as a sealed row (internal/llmlog/recorded.go). The +-- switch changes nothing on the request path (required sensitivity, chain, +-- scan, limits, answer) and nothing for any other consumer. Who may set it is +-- the handler's rule (model-consumer-create/-update: switching on is +-- server-admin only, also with self-service, and needs +-- confirm_record_bodies; switching off is open to a tenant-admin); the column +-- is the state. +-- +-- (1) context_model_consumers.record_bodies BOOLEAN NOT NULL DEFAULT false. +-- A constant default: no table rewrite, every existing consumer reads +-- false. NOT part of the store's shared consumer columns +-- (store.sqlConsumerCols): repair and migration tests run the store +-- against schemas before 197; the column is read on demand +-- (store.ConsumerRecordBodies) and written only when a write names it. +-- (2) The audit (161 section 7): audit_state_model_consumer gains the key +-- record_bodies, trg_model_consumers_audit_upd fires on it — switching +-- recording on or off is an audited 'update' row like every policy change +-- (internal/store/audit_classification_test.go pins the column audited). +-- From this migration on every model_consumer audit row carries the key; +-- older rows stay as written. +-- (3) ctx_model_auth gains the column record_bodies, LAST (161: callers scan +-- by name, a new column goes last; the sentinel row reads false). The +-- result type changes, so the function is dropped and created in this +-- transaction: an older binary on the same database selects its named +-- columns and does not see the new one; its rows stay unrecorded. Every +-- /v1 request runs ctx_model_auth once at the door and nothing caches a +-- positive answer (165: design/01 E-01-9), so a switch applies from the +-- next request on; a request already running keeps the value it was +-- admitted with — a narrowed policy fires nothing (165). +-- +-- Cost and locks. ADD COLUMN with a constant default is a catalog change: +-- ACCESS EXCLUSIVE on context_model_consumers until the commit — milliseconds; +-- during them a /v1 door check (ctx_model_auth reads the table) and every +-- consumer write of another ctx process on the same database wait. CREATE +-- TRIGGER takes SHARE ROW EXCLUSIVE on the same table, inside the same +-- window. DROP/CREATE FUNCTION locks no table; a session that calls +-- ctx_model_auth meanwhile uses the old definition until the commit. +-- lock_timeout 3s fails the boot instead of queueing behind a long +-- transaction; the next start retries. The table holds at most +-- max_model_consumers (64 by default) rows per tenant. +-- +-- Idempotent: ADD COLUMN IF NOT EXISTS, CREATE OR REPLACE FUNCTION, DROP +-- TRIGGER IF EXISTS + CREATE, DROP FUNCTION IF EXISTS + CREATE. +-- +-- Way back, in this order, one statement each: DROP FUNCTION ctx_model_auth( +-- TEXT, INET, BOOLEAN); the CREATE FUNCTION ctx_model_auth of 161 section 8; +-- the CREATE OR REPLACE FUNCTION audit_state_model_consumer of 161 section 7; +-- DROP TRIGGER trg_model_consumers_audit_upd ON context_model_consumers and +-- the CREATE TRIGGER of 161 section 7; ALTER TABLE context_model_consumers +-- DROP COLUMN record_bodies; DELETE FROM _migrations WHERE version = 197 (so +-- a later upgrade applies it again). The audit rows stay (append-only +-- history). TestMigration197Idempotent runs exactly these statements. +-- ============================================================================= + +SET LOCAL lock_timeout = '3s'; + +-- 1. The switch. +ALTER TABLE context_model_consumers + ADD COLUMN IF NOT EXISTS record_bodies BOOLEAN NOT NULL DEFAULT false; + +-- 2. The audit: the projection and the update trigger of 161 section 7, with +-- record_bodies. +CREATE OR REPLACE FUNCTION audit_state_model_consumer(c context_model_consumers) + RETURNS JSONB AS $$ + SELECT jsonb_build_object( + 'tenant_id', c.tenant_id, 'label', c.label, 'description', c.description, + 'kind', c.kind, 'tenant_scope', c.tenant_scope, 'all_models', c.all_models, + 'prompt_sensitivity', c.prompt_sensitivity, 'fair_weight', c.fair_weight, + 'admission_lane', c.admission_lane, 'allowed_cidrs', to_jsonb(c.allowed_cidrs), + 'allow_plaintext', c.allow_plaintext, 'active', c.active, + 'peer_instance_id', c.peer_instance_id, 'peer_bound_at', c.peer_bound_at, + 'record_bodies', c.record_bodies) +$$ LANGUAGE sql STABLE; + +DROP TRIGGER IF EXISTS trg_model_consumers_audit_upd ON context_model_consumers; +CREATE TRIGGER trg_model_consumers_audit_upd + AFTER UPDATE OF tenant_id, label, description, kind, tenant_scope, all_models, + prompt_sensitivity, fair_weight, admission_lane, allowed_cidrs, + allow_plaintext, active, peer_instance_id, peer_bound_at, + record_bodies + ON context_model_consumers FOR EACH ROW + WHEN ((OLD.tenant_id, OLD.label, OLD.description, OLD.kind, OLD.tenant_scope, + OLD.all_models, OLD.prompt_sensitivity, OLD.fair_weight, OLD.admission_lane, + OLD.allowed_cidrs, OLD.allow_plaintext, OLD.active, OLD.peer_instance_id, + OLD.peer_bound_at, OLD.record_bodies) + IS DISTINCT FROM + (NEW.tenant_id, NEW.label, NEW.description, NEW.kind, NEW.tenant_scope, + NEW.all_models, NEW.prompt_sensitivity, NEW.fair_weight, NEW.admission_lane, + NEW.allowed_cidrs, NEW.allow_plaintext, NEW.active, NEW.peer_instance_id, + NEW.peer_bound_at, NEW.record_bodies)) + EXECUTE FUNCTION audit_model_consumers_write(); + +-- 3. ctx_model_auth of 161 section 8 with record_bodies as the last column. +DROP FUNCTION IF EXISTS ctx_model_auth(TEXT, INET, BOOLEAN); +CREATE FUNCTION ctx_model_auth(p_key_hash TEXT, p_client_ip INET, p_secure BOOLEAN) +RETURNS TABLE ( + model_key_id UUID, + consumer_id UUID, + tenant_id UUID, + tenant_scope VARCHAR(50), + kind TEXT, + all_models BOOLEAN, + prompt_sensitivity TEXT, + fair_weight SMALLINT, + key_expires_at TIMESTAMPTZ, + is_valid BOOLEAN, + admission_lane TEXT, + peer_instance_id UUID, + record_bodies BOOLEAN + -- New columns go LAST: callers scan by position. +) LANGUAGE plpgsql STABLE AS $$ +DECLARE + v_key UUID; + v_cons UUID; + v_exp TIMESTAMPTZ; + v_tenant UUID; + v_scope VARCHAR(50); + v_kind TEXT; + v_all BOOLEAN; + v_sens TEXT; + v_weight SMALLINT; + v_lane TEXT; + v_peer UUID; + v_cidrs CIDR[]; + v_plain BOOLEAN; + v_status TEXT; + v_record BOOLEAN; +BEGIN + <> + BEGIN + -- Gate 1: the key exists and lives. + SELECT k.id, k.consumer_id, k.expires_at INTO v_key, v_cons, v_exp + FROM context_model_keys k + WHERE k.key_hash = p_key_hash + AND k.revoked_at IS NULL AND (k.expires_at IS NULL OR k.expires_at > now()); + IF v_key IS NULL THEN EXIT gates; END IF; + + -- Gate 2: the consumer is active. + SELECT c.tenant_id, c.tenant_scope, c.kind, c.all_models, c.prompt_sensitivity, + c.fair_weight, c.admission_lane, c.peer_instance_id, c.allowed_cidrs, + c.allow_plaintext, c.record_bodies + INTO v_tenant, v_scope, v_kind, v_all, v_sens, v_weight, v_lane, v_peer, + v_cidrs, v_plain, v_record + FROM context_model_consumers c + WHERE c.id = v_cons AND c.active; + IF NOT FOUND THEN EXIT gates; END IF; + + -- Gate 3: the tenant is active. + SELECT t.status INTO v_status FROM context_tenants t WHERE t.id = v_tenant; + IF v_status IS NULL OR v_status <> 'active' THEN EXIT gates; END IF; + + -- Gate 4: the tenant still owns the consumer's tenant_scope. + IF v_scope IS NOT NULL AND NOT EXISTS ( + SELECT 1 FROM context_tenant_scopes s + WHERE s.scope = v_scope AND s.tenant_id = v_tenant) THEN + EXIT gates; + END IF; + + -- Gate 5: network allowlist. An unknown client address (NULL) passes + -- only when there is none. + IF v_cidrs IS NOT NULL AND NOT COALESCE(p_client_ip <<= ANY (v_cidrs), false) THEN + EXIT gates; + END IF; + + -- Gate 6: transport. Without TLS only with allow_plaintext, which the + -- CHECK binds to private networks. + IF NOT COALESCE(p_secure, false) AND NOT v_plain THEN + EXIT gates; + END IF; + + RETURN QUERY SELECT v_key, v_cons, v_tenant, v_scope, v_kind, v_all, v_sens, + v_weight, v_exp, true, v_lane, v_peer, v_record; + RETURN; + END gates; + + -- The sentinel: one row, the same whichever gate refused (no oracle). + RETURN QUERY SELECT NULL::uuid, NULL::uuid, NULL::uuid, NULL::varchar, ''::text, false, + 'credentials'::text, 1::smallint, NULL::timestamptz, false, + 'bulk'::text, NULL::uuid, false; +END; +$$; From 77c1921a7a41e2c2ac39e42d57af655bc2f99307 Mon Sep 17 00:00:00 2001 From: Jan-Stefan Janetzky Date: Fri, 27 Nov 2026 02:51:12 +0100 Subject: [PATCH 02/27] feat(web): the consumer list and detail show a recording consumer ConsumerView carries record_bodies; the /gateway list row shows a "recording" badge and the consumer detail's policy card a recording line that says what the rows hold and who reads them. The SPA renders the server's flag and does not switch it (model-consumer-update does). Co-Authored-By: Claude Opus 5.5 --- docs/api.md | 2 +- go/web/e2e/fixtures.ts | 1 + go/web/e2e/gateway-panels-fixtures.ts | 1 + go/web/src/lib/api/types.ts | 2 + .../src/routes/gateway/ConsumerDetail.svelte | 6 ++- go/web/src/routes/gateway/ConsumerRow.svelte | 11 ++++- .../routes/gateway/ConsumerRow.svelte.test.ts | 48 +++++++++++++++++++ .../routes/gateway/consumer.svelte.test.ts | 1 + .../routes/gateway/consumers.svelte.test.ts | 1 + go/web/src/routes/gateway/format.ts | 7 +++ go/web/src/routes/gateway/forms.fixtures.ts | 1 + go/web/src/routes/gateway/mint.test.ts | 1 + 12 files changed, 78 insertions(+), 4 deletions(-) create mode 100644 go/web/src/routes/gateway/ConsumerRow.svelte.test.ts diff --git a/docs/api.md b/docs/api.md index b4adfcee7..82b89a867 100644 --- a/docs/api.md +++ b/docs/api.md @@ -285,7 +285,7 @@ A **model consumer** is an external caller of the models ctx serves (`/v1`, not **Reading.** A consumer reads as `{id, tenant_id, tenant_slug, label, description, kind, tenant_scope, all_models, models, prompt_sensitivity, fair_weight, admission_lane, allowed_cidrs, allow_plaintext, record_bodies, active, status, last_used_at, created_at, created_by_label, keys, keys_total, peer}` (`record_bodies` for every reader, tenant-admins included); a key as `{id, hint, status, created_at, expires_at, revoked_at, rotated_from, last_used_at}`. `status` of a consumer: `inactive`; `no_key` (no live key); `rotating` (two live keys); `expiring` (one live key expiring within `gateway.key_expiry_warn`, 14 d); `active`. Of a key: `revoked` ≻ `expired` ≻ `superseded` (live, but a newer live key exists — its grace runs) ≻ `expiring` ≻ `active`. The server computes both; a client never judges expiry by its own clock. `peer` (`{instance_id, bound_at}`) is null without a binding and for every reader below server-admin; `created_by_label` reads `"server-admin"` to a tenant-admin unless the creating key is a non-server-admin key of its own tenant, and is null once the creating key is deleted. `last_used_at` has 60 s resolution. -- `model-consumer-list` lists newest first. `status` is a list of the five statuses or `["all"]`; absent = the four statuses of an active consumer. `q` is a label prefix (case-insensitive, `%` and `_` literal). `limit` defaults to and is capped at `gateway.consumer_list_max_limit` (100); `next_cursor` is the opaque token of the next page, `null` on the last; a malformed cursor is a `400` (it is opaque, not signed: a well-formed one only moves the keyset position within the caller's own reach). Every filter runs in SQL — a page of inactive consumers never hides the active ones behind it. The list carries the live keys only; `keys_total` counts the whole chain. The SPA's `/gateway` list ([multi-tenancy](multi-tenancy.md#admin-tiers)) is a client of exactly this form: it sends the status set explicitly (`["all"]` for all five), sends no `limit` (its page size is the server's cap), hands `next_cursor` through untouched and renders `status` as received. +- `model-consumer-list` lists newest first. `status` is a list of the five statuses or `["all"]`; absent = the four statuses of an active consumer. `q` is a label prefix (case-insensitive, `%` and `_` literal). `limit` defaults to and is capped at `gateway.consumer_list_max_limit` (100); `next_cursor` is the opaque token of the next page, `null` on the last; a malformed cursor is a `400` (it is opaque, not signed: a well-formed one only moves the keyset position within the caller's own reach). Every filter runs in SQL — a page of inactive consumers never hides the active ones behind it. The list carries the live keys only; `keys_total` counts the whole chain. The SPA's `/gateway` list ([multi-tenancy](multi-tenancy.md#admin-tiers)) is a client of exactly this form: it sends the status set explicitly (`["all"]` for all five), sends no `limit` (its page size is the server's cap), hands `next_cursor` through untouched and renders `status` as received — and `record_bodies` as a `recording` badge on the row and a `recording` line in the consumer detail's policy card (the SPA does not switch it; that is `model-consumer-update`). - `model-consumer-get` adds the chain (newest first, at most `gateway.consumer_chain_max` = 50; `keys_truncated` says more exist) and the **audit trail**: the newest `gateway.consumer_audit_trail_max` (20) rows of `model_consumer`, `model_key` and `gateway_limits` whose entity is the consumer or a key of the returned chain (older keys' rows need `GET /api/audit?entity=model_key&id=…`), each with its `entity_type`, redacted for a tenant-admin exactly as `GET /api/audit` redacts ([security](security.md#audit-trail)) — the cap applies before the redaction leaves out invisible updates, so a trail may hold fewer rows than the cap. - `model-key-history` pages through all keys of a consumer, revoked and expired ones included, with the same `cursor`/`limit`/`next_cursor` as the list. diff --git a/go/web/e2e/fixtures.ts b/go/web/e2e/fixtures.ts index ddf9295e3..1e399cc21 100644 --- a/go/web/e2e/fixtures.ts +++ b/go/web/e2e/fixtures.ts @@ -791,6 +791,7 @@ function consumerView(c: MockConsumer, serverAdmin: boolean): Record{c.admission_lane}
network
{c.allowed_cidrs === null ? 'any source' : c.allowed_cidrs.join(', ')}
+
recording
+
+ {recordingText(c.record_bodies)} +
last used
{c.last_used_at === null ? 'never' : fmtMinute(c.last_used_at)}
diff --git a/go/web/src/routes/gateway/ConsumerRow.svelte b/go/web/src/routes/gateway/ConsumerRow.svelte index 24858eb21..223dbf4b9 100644 --- a/go/web/src/routes/gateway/ConsumerRow.svelte +++ b/go/web/src/routes/gateway/ConsumerRow.svelte @@ -20,7 +20,7 @@ // policy.canEditPolicy allows — never on a ctx-peer row below server-admin // (data-testid consumer-edit). import type { ConsumerView, KeyView } from '../../lib/api/types' - import { STATUS_LABEL, consumerTone, fmtDay, fmtMinute } from './format' + import { STATUS_LABEL, consumerTone, fmtDay, fmtMinute, recordingText } from './format' import KeyChain from './KeyChain.svelte' let { @@ -63,7 +63,10 @@ {c.label} {#if c.description}{c.description}{/if} - {c.kind} + + {c.kind} + {#if c.record_bodies}recording{/if} + {STATUS_LABEL[c.status] ?? c.status} @@ -163,6 +166,10 @@ color: var(--accent); border-color: var(--accent); } + .badge.rec { + color: var(--warn); + border-color: var(--warn); + } .dim { color: var(--text-faint); } diff --git a/go/web/src/routes/gateway/ConsumerRow.svelte.test.ts b/go/web/src/routes/gateway/ConsumerRow.svelte.test.ts new file mode 100644 index 000000000..b4d786f9e --- /dev/null +++ b/go/web/src/routes/gateway/ConsumerRow.svelte.test.ts @@ -0,0 +1,48 @@ +// The recording switch in the consumer views (issue #571): a consumer with +// record_bodies shows a "recording" badge in its list row and says so in the +// detail's policy card (recordingText); one without shows no badge. The flag +// is the server's — the views only render it. Server-rendered and asserted on +// the markup (BlockDetail test pattern: mount() is unavailable in the +// node-only vitest env). + +import { describe, expect, it } from 'vitest' +import { render } from 'svelte/server' +import ConsumerRow from './ConsumerRow.svelte' +import { consumerOf } from './forms.fixtures' +import { recordingText } from './format' + +function row(recordBodies: boolean): string { + const c = consumerOf('rec', { record_bodies: recordBodies }) + return render(ConsumerRow, { + props: { + consumer: c, + crossTenant: false, + reactivatable: false, + busy: false, + onrevoke: () => {}, + ondeactivate: () => {}, + onreactivate: () => {}, + }, + }).body +} + +describe('consumer recording', () => { + it('a recording consumer carries the badge in its list row', () => { + const markup = row(true) + expect(markup).toContain('data-consumer-recording') + expect(markup).toMatch(/>recording { + const markup = row(false) + expect(markup).not.toContain('data-consumer-recording') + expect(markup).not.toMatch(/>recording { + expect(recordingText(true)).toMatch(/in full/) + expect(recordingText(true)).toMatch(/credentials/) + expect(recordingText(true)).toMatch(/server-admins/) + expect(recordingText(false)).toBe('off') + }) +}) diff --git a/go/web/src/routes/gateway/consumer.svelte.test.ts b/go/web/src/routes/gateway/consumer.svelte.test.ts index 3f69f109b..991237045 100644 --- a/go/web/src/routes/gateway/consumer.svelte.test.ts +++ b/go/web/src/routes/gateway/consumer.svelte.test.ts @@ -24,6 +24,7 @@ function consumer(id: string, label: string): ConsumerView { admission_lane: 'bulk', allowed_cidrs: null, allow_plaintext: false, + record_bodies: false, active: true, status: 'active', last_used_at: null, diff --git a/go/web/src/routes/gateway/consumers.svelte.test.ts b/go/web/src/routes/gateway/consumers.svelte.test.ts index 242f68943..b205f7486 100644 --- a/go/web/src/routes/gateway/consumers.svelte.test.ts +++ b/go/web/src/routes/gateway/consumers.svelte.test.ts @@ -38,6 +38,7 @@ function consumer(label: string, p: Partial = {}): ConsumerView { admission_lane: 'bulk', allowed_cidrs: null, allow_plaintext: false, + record_bodies: false, active: true, status: 'active', last_used_at: null, diff --git a/go/web/src/routes/gateway/format.ts b/go/web/src/routes/gateway/format.ts index 1052d1ac8..8237fd315 100644 --- a/go/web/src/routes/gateway/format.ts +++ b/go/web/src/routes/gateway/format.ts @@ -22,6 +22,13 @@ export function consumerTone(status: string): 'ok' | 'warn' | 'off' { return 'off' } +/** What the consumer view says about recording (record_bodies, issue #571) — the server's flag, shown to every reader. */ +export function recordingText(on: boolean): string { + return on + ? 'on — every request and answer of this consumer is kept in full in the LLM log, credentials in a prompt included; server-admins read it' + : 'off' +} + /** Badge tone of a key status: active ok, expiring/superseded (grace running) warn, dead off. */ export function keyTone(status: ModelKeyStatus | string): 'ok' | 'warn' | 'off' { if (status === 'active') return 'ok' diff --git a/go/web/src/routes/gateway/forms.fixtures.ts b/go/web/src/routes/gateway/forms.fixtures.ts index 7a54a0517..a21ad4d24 100644 --- a/go/web/src/routes/gateway/forms.fixtures.ts +++ b/go/web/src/routes/gateway/forms.fixtures.ts @@ -33,6 +33,7 @@ export function consumerOf(label: string, p: Partial = {}): Consum admission_lane: 'bulk', allowed_cidrs: null, allow_plaintext: false, + record_bodies: false, active: true, status: 'active', last_used_at: null, diff --git a/go/web/src/routes/gateway/mint.test.ts b/go/web/src/routes/gateway/mint.test.ts index 4c48f90d8..746c3e8ca 100644 --- a/go/web/src/routes/gateway/mint.test.ts +++ b/go/web/src/routes/gateway/mint.test.ts @@ -280,6 +280,7 @@ function cv(p: Partial = {}): ConsumerView { admission_lane: 'bulk', allowed_cidrs: null, allow_plaintext: false, + record_bodies: false, active: true, status: 'active', last_used_at: null, From 5b39461f95aebe08dd49ccb5645e3a2c6e41d8de Mon Sep 17 00:00:00 2001 From: Jan-Stefan Janetzky Date: Fri, 27 Nov 2026 02:57:11 +0100 Subject: [PATCH 03/27] test(gateway): the recording switch's locked re-check, its stream capture account and forced row, and an unchanged chain preview A tenant-admin re-submitting record_bodies over a concurrent switch-off is refused by the check under the consumer lock (second connection, red with the unlocked value); the stream capture holds exactly its buffer in the recording account and gives it back on a refusal or without a row; the shutdown's forced row of a recording consumer names what it lacks; and model-alias-preview answers the same with and without the switch. Co-Authored-By: Claude Opus 5.5 --- go/cmd/ctxd/v1_record_integration_test.go | 16 ++- ...model_consumers_record_integration_test.go | 51 +++++++++ go/internal/oai/record_internal_test.go | 106 ++++++++++++++++++ 3 files changed, 172 insertions(+), 1 deletion(-) create mode 100644 go/internal/oai/record_internal_test.go diff --git a/go/cmd/ctxd/v1_record_integration_test.go b/go/cmd/ctxd/v1_record_integration_test.go index 1c59ec98c..5c66e2686 100644 --- a/go/cmd/ctxd/v1_record_integration_test.go +++ b/go/cmd/ctxd/v1_record_integration_test.go @@ -19,7 +19,8 @@ // - ctx-llmlog-export (llmlogexport.Export): the row leaves sealed; // - the retention janitor (llmlog.EvictBodies): the row's bodies go after // the retention like every row's; -// - switching off (the tenant-admin may) applies from the next request. +// - switching off (the tenant-admin may) applies from the next request, and +// model-alias-preview answers the same with and without the switch. // // go test -tags=integration -p 1 -count=1 -run 'TestV1RecordedConsumer' -v ./cmd/ctxd/ package main @@ -216,12 +217,25 @@ func TestV1RecordedConsumerRowAndItsReaders(t *testing.T) { t.Errorf("the export left the recorded row out — it keeps the row, without its bodies") } }) + preview := func() string { + t.Helper() + st, b, _ := v1RecAPI(t, f, http.MethodPost, "/api/manage", v1RecAdminKey, map[string]any{ + "action": "model-alias-preview", "data": map[string]any{"consumer_id": recID, "alias": v1ChatAlias}}) + if st != http.StatusOK { + t.Fatalf("model-alias-preview: %d %s", st, b) + } + return string(b) + } + previewOn := preview() t.Run("switch_off_applies_from_the_next_request", func(t *testing.T) { st, b, _ := v1RecAPI(t, f, http.MethodPost, "/api/manage", tenantAdmin, map[string]any{ "action": "model-consumer-update", "data": map[string]any{"id": recID, "record_bodies": false}}) if st != http.StatusOK { t.Fatalf("tenant-admin switches off: %d %s", st, b) } + if previewOff := preview(); previewOff != previewOn { + t.Errorf("model-alias-preview differs with the switch:\n on %s\n off %s", previewOn, previewOff) + } if a := f.post(t, recKey, chat); a.status != http.StatusOK { t.Fatalf("request after the switch: %d", a.status) } diff --git a/go/internal/handler/model_consumers_record_integration_test.go b/go/internal/handler/model_consumers_record_integration_test.go index df7558756..628eb497c 100644 --- a/go/internal/handler/model_consumers_record_integration_test.go +++ b/go/internal/handler/model_consumers_record_integration_test.go @@ -24,6 +24,7 @@ import ( "context" "net/http" "strings" + "sync" "testing" "github.com/GottZ/ctx/internal/auth" @@ -173,6 +174,56 @@ func TestModelConsumerRecordSwitch(t *testing.T) { } } +// TestModelConsumerRecordSwitchUnderLock: a server-admin transaction switches +// recording off and holds the consumer row while a tenant-admin re-submits +// record_bodies:true. The unlocked pre-check reads "on" (no change, no tier); +// the check under the lock reads "off" — switching on, server-admin only — +// and refuses: the switch stays off. Red against a handler whose locked +// check judges the value read before the lock (the TestModelConsumerUpdate +// TierUnderLock pattern of review F5). +func TestModelConsumerRecordSwitchUnderLock(t *testing.T) { + if testing.Short() { + t.Skip("integration test") + } + ctx := context.Background() + pool := testdb.SetupTestDB(t) + hOff := mcHandler(t, pool, false, false) + hOn := mcHandler(t, pool, true, true) + admin, _ := kaServerAdmin(ctx, t, pool) + a := auMakeTenant(ctx, t, pool, hOff, admin, "recl-a") + c := mcCreate(t, hOff, admin, map[string]any{"label": "recl", "tenant_id": a.id, "record_bodies": true, "confirm_record_bodies": true}) + tx, err := pool.Begin(ctx) + if err != nil { + t.Fatal(err) + } + defer func() { _ = tx.Rollback(ctx) }() + if _, err := tx.Exec(ctx, `UPDATE context_model_consumers SET record_bodies = false WHERE id = $1::uuid`, c.id); err != nil { + t.Fatal(err) + } + var ( + wg sync.WaitGroup + status int + body []byte + ) + wg.Add(1) + go func() { + defer wg.Done() + status, body, _ = mcCall(t, hOn, a.ar, "model-consumer-update", map[string]any{"id": c.id, "record_bodies": true}) + }() + mcAwaitLockWaiter(ctx, t, pool) + if err := tx.Commit(ctx); err != nil { + t.Fatal(err) + } + wg.Wait() + var on bool + if err := pool.QueryRow(ctx, `SELECT record_bodies FROM context_model_consumers WHERE id = $1::uuid`, c.id).Scan(&on); err != nil { + t.Fatal(err) + } + if status != http.StatusForbidden || on { + t.Fatalf("tenant-admin re-submitted record_bodies true over a concurrent switch-off: status %d body %s, stored %v — want 403 and false", status, body, on) + } +} + func fmtAny(v any) string { switch x := v.(type) { case bool: diff --git a/go/internal/oai/record_internal_test.go b/go/internal/oai/record_internal_test.go new file mode 100644 index 000000000..fd74a8ddf --- /dev/null +++ b/go/internal/oai/record_internal_test.go @@ -0,0 +1,106 @@ +package oai + +import ( + "strings" + "testing" + + "github.com/GottZ/ctx/internal/llmlog" +) + +// The capture of a recorded request (record.go): the recording account holds +// exactly the stream buffer's capacity while the stream grows, hands it to +// the row, and gives everything back on a refusal or when no row takes it; +// the shutdown's forced row of a recording consumer names what it lacks. + +func TestRecordingStreamHoldsItsCapacity(t *testing.T) { + base := llmlog.RecordedHeld() + r := recording{on: true} + line := []byte("data: " + strings.Repeat("x", 300) + "\n\n") + for range 1000 { + r.addStream(line) + if got := llmlog.RecordedHeld() - base; got != int64(r.stream.Cap()) || r.held != got || r.streamHeld != got { + t.Fatalf("held %d (request %d, stream %d), buffer capacity %d — the account must hold exactly the buffer", got, r.held, r.streamHeld, r.stream.Cap()) + } + } + if got := r.streamText(); got != strings.Repeat(string(line), 1000) || r.lost != nil { + t.Fatalf("stream text %d bytes, lost %v — want the 1000 lines whole", len(got), r.lost) + } + var row llmlog.GatewayRow + r.mark(&row) + if !row.Recorded || row.RecordedHeld != int64(r.stream.Cap()) || r.held != 0 || row.RecordLost != nil { + t.Fatalf("row recorded %v holds %d (request keeps %d), lost %v — want the buffer handed to the row", row.Recorded, row.RecordedHeld, r.held, row.RecordLost) + } + llmlog.ReleaseRecorded(row.RecordedHeld) + if llmlog.RecordedHeld() != base { + t.Fatalf("the account holds %d bytes after the row gave its texts back", llmlog.RecordedHeld()-base) + } +} + +func TestRecordingRefusalDropsTheStreamAndGivesBack(t *testing.T) { + base := llmlog.RecordedHeld() + r := recording{on: true} + r.addStream([]byte("data: first\n\n")) + // Fill the account to its last byte, so the next growth is refused. + rest := int64(0) + for step := int64(1 << 26); step > 0; step /= 2 { + for llmlog.ReserveRecorded(step) { + rest += step + } + } + defer llmlog.ReleaseRecorded(rest) + r.addStream([]byte(strings.Repeat("y", 4096))) + if r.streamText() != "" || !r.streamLost || len(r.lost) != 1 || r.lost[0] != llmlog.RecordLostResponse { + t.Fatalf("after a refused growth: text %q lost %v %v — want the stream dropped and the answer named lost", r.streamText(), r.streamLost, r.lost) + } + r.addStream([]byte("data: later\n\n")) + if r.streamText() != "" || r.held != 0 || llmlog.RecordedHeld()-base != rest { + t.Fatalf("after the refusal the request holds %d, the account %d beyond the filler — want 0 and 0", r.held, llmlog.RecordedHeld()-base-rest) + } + if got := r.text([]byte(`[{"role":"user","content":"z"}]`), llmlog.RecordLostRequest); got != "" || len(r.lost) != 2 { + t.Fatalf("a request text the full account cannot take: %q, lost %v", got, r.lost) + } + var row llmlog.GatewayRow + r.mark(&row) + if row.RecordLostCause != llmlog.RecordLostMemory || len(row.RecordLost) != 2 { + t.Fatalf("row lost %v cause %q, want both bodies, memory", row.RecordLost, row.RecordLostCause) + } +} + +func TestRecordingReleaseWithoutARow(t *testing.T) { + base := llmlog.RecordedHeld() + r := recording{on: true} + r.addStream([]byte("data: a\n\n")) + r.release() + if r.held != 0 || llmlog.RecordedHeld() != base { + t.Fatalf("release left %d held (account +%d)", r.held, llmlog.RecordedHeld()-base) + } + off := recording{} + off.addStream([]byte("data: b\n\n")) + var row llmlog.GatewayRow + off.mark(&row) + if off.stream.Len() != 0 || row.Recorded || llmlog.RecordedHeld() != base { + t.Fatalf("a consumer without the switch captured %d bytes, row recorded %v", off.stream.Len(), row.Recorded) + } +} + +func TestForcedRowOfARecordingConsumerNamesWhatItLacks(t *testing.T) { + for _, c := range []struct { + pipeline string + want []string + }{ + {chatPipeline, []string{llmlog.RecordLostRequest, llmlog.RecordLostResponse}}, + {embedPipeline, []string{llmlog.RecordLostRequest}}, + {rerankPipeline, []string{llmlog.RecordLostRequest}}, + } { + row := llmlog.GatewayRow{Pipeline: c.pipeline} + markForced(&row, true) + if !row.Recorded || strings.Join(row.RecordLost, ",") != strings.Join(c.want, ",") || row.RecordLostCause != llmlog.RecordLostShutdown { + t.Errorf("%s: forced row recorded %v lost %v cause %q, want %v shutdown", c.pipeline, row.Recorded, row.RecordLost, row.RecordLostCause, c.want) + } + plain := llmlog.GatewayRow{Pipeline: c.pipeline} + markForced(&plain, false) + if plain.Recorded || plain.RecordLost != nil { + t.Errorf("%s: the forced row of a consumer without the switch is marked", c.pipeline) + } + } +} From c3019d2ea7e56dafd0ccbd28ac6f473ecbd92353 Mon Sep 17 00:00:00 2001 From: Jan-Stefan Janetzky Date: Fri, 27 Nov 2026 02:59:25 +0100 Subject: [PATCH 04/27] feat(gateway): the status frame shows what recorded texts hold of their account MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit GET /api/status (server-admin) carries llmlog.recorded_held_bytes beside recorded_bodies_lost: the fill of the 128 MiB account of recorded texts (captured, queued, being inserted) — near the bound the next large texts are left out. The pin of the llmlog section follows the additive wire. Co-Authored-By: Claude Opus 5.5 --- docs/api.md | 2 +- docs/operations.md | 2 +- go/internal/handler/status.go | 7 ++++++- go/internal/handler/status_llmlog_test.go | 15 +++++++++------ 4 files changed, 17 insertions(+), 9 deletions(-) diff --git a/docs/api.md b/docs/api.md index 82b89a867..e0c8b39c8 100644 --- a/docs/api.md +++ b/docs/api.md @@ -35,7 +35,7 @@ hit it. Not a settings key: changing it is a rebuild, deliberately. | `POST /webhooks/github/{project_id}` | **Unauthenticated** GitHub inbound (workflow W13) — HMAC-SHA256 over the raw body against the per-project sealed secret replaces the api key. Bad/absent signature or unknown project ⇒ uniform **401** with ZERO DB write; valid ⇒ **202** and one redelivery-idempotent inbox row; per-project rate limit ⇒ **429**. The inbox is a debounced sync **trigger**, never an authority (see [Webhooks (inbound)](#webhooks-inbound-workflow-w13)). | | `GET\|PUT\|DELETE /api/settings[/{key}]` | Runtime config overrides, **admin-gated incl. reads** (see [Settings API](#settings-api)). | | `GET\|PUT\|DELETE /api/secrets[/{name}]` | Write-only sealed credentials, **admin-gated**: PUT creates/rotates (value never returned), GET lists metadata + `referenced_by`, DELETE 409s while referenced — by a `secret_ref` setting or a backend pool row's `api_key_ref` (entries prefixed `backend:`, remediation text per reference type) (see [security](security.md#sealed-secrets--break-glass)). | -| `GET /api/status` | **Admin dashboard** aggregate from the process-wide status collector: health, backend pool (`pool.Status()` shape), dream queue + mode, 24h LLM telemetry (with an `llm_24h_complete` attribution flag), and the disable-profile registry line (`profiles`: slim `{name, scope, label, active, member_count}` rows, U01-W7 — replaced the retired `gaming:{active}` field; member names load on-demand via `disable-profile-list`). A server-admin additionally sees `advisories` (`[{subject, state}]`, omitted when empty): named reasons for states the frame can only show as an absence — today exactly `backend_pool: empty` (fresh install, nobody seeded yet; deliberately NOT in the public `/health` body), and `llmlog` (`{insert_failures, insert_dropped, recorded_bodies_lost}`, present even at 0): the process-wide count of `context_llm_log` rows that never landed — inserts the database refused or that timed out, and rows dropped by the bounded insert queue ([operations](operations.md#shutdown-and-the-llm-log-write-path)) — and of the rows of recording consumers written without a body they should carry (`metadata.gw.record_lost`, [operations](operations.md#recording-a-consumer)), and `foreign_load` (present only while an enabled, not profile-parked `_global` backend row carries `metadata.foreign_load_probe`): one row per probed engine origin, `{target, probe, backends, running, active, held, delta, suspected, since, suspected_hourly, hourly{hour, engine_requests, ctx_requests}, probe_error, probed_at}` — the requests the engine holds (read from its own `GET /metrics` every `status.foreign_load_interval` and on each hour boundary, whether or not anyone reads the status) against the dispatcher's held leases, and hourly its finished responses against ctx's logged calls; evidence that ctx is the only load source of the GPU ([operations](operations.md#foreign-load-detector)), and `query_synthesize` (`{p95_ms, avg_ms, samples, since}`, present with no sample too): the latency of query synthesis from an in-memory ring of the last 512 syntheses since process start — per synthesis the wait-free wire duration of the backend that answered (or failed last) — the calls with a wire time among those `llm_24h` averages for pipeline `query-synthesize` (a call that reached no backend is not timed), the dispatcher's queue wait not included; `p95_ms` (nearest rank) is `null` below 20 samples, `avg_ms` without a sample; `since` (RFC3339, UTC, whole seconds) is where the window starts — the process start, or the oldest retained sample once more than 512 were seen. Read from process memory, never from the database. Never on the tenant view. The server-admin `dispatch` section carries per target `held` (ALL slot-holding leases, internal and external — the number the foreign-load detector compares) split into `held_internal` / `held_external`, `inflight_internal`, the external offer (`internal_reserved`, `external_offered`, `external_capacity`), the external class's wait view `external` and its refusals `external_rejects {cap, not_offered}`, the same two for the external bulk class (`external_bulk`, `external_bulk_rejects {cap, not_offered}`; `held_external` counts the leases of both external classes), and buckets with `tenant_id` and `class` (`interactive` \| `external` \| `external_bulk`; an external consumer's bucket key is `_consumer:` in either external class). The tenant-admin `dispatch_tenant` view never shows external load: `busy` and `depth` read only the internal leases and queues, and no external bucket appears. Served from a cache (N pollers cost one collection). Carries hostnames, so it is admin-gated where `/health` stays anonymous. Opens to a tenant-admin with a reduced own-tenant view (see [multi-tenancy](multi-tenancy.md#telemetry-per-tenant-views)). | +| `GET /api/status` | **Admin dashboard** aggregate from the process-wide status collector: health, backend pool (`pool.Status()` shape), dream queue + mode, 24h LLM telemetry (with an `llm_24h_complete` attribution flag), and the disable-profile registry line (`profiles`: slim `{name, scope, label, active, member_count}` rows, U01-W7 — replaced the retired `gaming:{active}` field; member names load on-demand via `disable-profile-list`). A server-admin additionally sees `advisories` (`[{subject, state}]`, omitted when empty): named reasons for states the frame can only show as an absence — today exactly `backend_pool: empty` (fresh install, nobody seeded yet; deliberately NOT in the public `/health` body), and `llmlog` (`{insert_failures, insert_dropped, recorded_bodies_lost, recorded_held_bytes}`, present even at 0): the process-wide count of `context_llm_log` rows that never landed — inserts the database refused or that timed out, and rows dropped by the bounded insert queue ([operations](operations.md#shutdown-and-the-llm-log-write-path)) — and of the rows of recording consumers written without a body they should carry (`metadata.gw.record_lost`, [operations](operations.md#recording-a-consumer)); `recorded_held_bytes` is what recorded texts hold of their 128 MiB account right now, and `foreign_load` (present only while an enabled, not profile-parked `_global` backend row carries `metadata.foreign_load_probe`): one row per probed engine origin, `{target, probe, backends, running, active, held, delta, suspected, since, suspected_hourly, hourly{hour, engine_requests, ctx_requests}, probe_error, probed_at}` — the requests the engine holds (read from its own `GET /metrics` every `status.foreign_load_interval` and on each hour boundary, whether or not anyone reads the status) against the dispatcher's held leases, and hourly its finished responses against ctx's logged calls; evidence that ctx is the only load source of the GPU ([operations](operations.md#foreign-load-detector)), and `query_synthesize` (`{p95_ms, avg_ms, samples, since}`, present with no sample too): the latency of query synthesis from an in-memory ring of the last 512 syntheses since process start — per synthesis the wait-free wire duration of the backend that answered (or failed last) — the calls with a wire time among those `llm_24h` averages for pipeline `query-synthesize` (a call that reached no backend is not timed), the dispatcher's queue wait not included; `p95_ms` (nearest rank) is `null` below 20 samples, `avg_ms` without a sample; `since` (RFC3339, UTC, whole seconds) is where the window starts — the process start, or the oldest retained sample once more than 512 were seen. Read from process memory, never from the database. Never on the tenant view. The server-admin `dispatch` section carries per target `held` (ALL slot-holding leases, internal and external — the number the foreign-load detector compares) split into `held_internal` / `held_external`, `inflight_internal`, the external offer (`internal_reserved`, `external_offered`, `external_capacity`), the external class's wait view `external` and its refusals `external_rejects {cap, not_offered}`, the same two for the external bulk class (`external_bulk`, `external_bulk_rejects {cap, not_offered}`; `held_external` counts the leases of both external classes), and buckets with `tenant_id` and `class` (`interactive` \| `external` \| `external_bulk`; an external consumer's bucket key is `_consumer:` in either external class). The tenant-admin `dispatch_tenant` view never shows external load: `busy` and `depth` read only the internal leases and queues, and no external bucket appears. Served from a cache (N pollers cost one collection). Carries hostnames, so it is admin-gated where `/health` stays anonymous. Opens to a tenant-admin with a reduced own-tenant view (see [multi-tenancy](multi-tenancy.md#telemetry-per-tenant-views)). | | `POST /api/manage` (`eject-mode`, alias `gaming-mode`) | Canonical shim for the reserved disable-profile `eject` (092): read = legacy gaming shape, mutation = server-admin toggle with implicit blackout confirm. Since U01-W5 a profile-only write (the legacy `gaming.active` settings dual-write was retired); the eject profile is the single source of truth. A toggle whose backend-pool or settings reload fails after the write answers `500` `{"success": false, "persisted": true, "error": "persisted but reload failed — …"}`: the toggle is written. | | `POST /api/manage` (`disable-profile-list/create/update/delete/toggle`) | Disable-profile registry (tenant-admin; tenant profiles may only contain own-scope backends, `_global` profiles are operator-owned). Toggle returns `{profile, impact, as_of}`; blacking out a whole role requires `confirm_role_blackout` (else 422; `dry_run` supported); the reserved `eject` profile is not deletable. | | `POST /api/manage` (`backend-create`/`backend-update`, field `disable_profiles`) | Profile membership as a backend property: list of profile NAMES (key absent = unchanged, `[]` = detach all); joins sync in the same transaction as the backend write. A tenant-admin may attach its OWN backend to `_global` profiles (self-disable) or its own tenant profiles; a scoped profile never contains foreign-scope backends. `backend-list` echoes `disable_profiles` including inactive membership. | diff --git a/docs/operations.md b/docs/operations.md index a358faf0f..90277a742 100644 --- a/docs/operations.md +++ b/docs/operations.md @@ -1001,7 +1001,7 @@ SELECT created_at, pipeline, metadata->'gw'->>'finish' AS finish, request_user, The predicate rides `idx_llm_log_consumer` (migration 158). Rows of requests the gateway refused before the route (`401`, `429`, a limit) are not rows at all — they are only counted in `context_llm_rejections_hourly`. -**Size and memory.** No cut: a request text is at most twice `gateway.max_request_bytes` (8 MiB; an invalid byte is stored as U+FFFD), a non-streamed chat answer is the answer the client received (its upstream read is capped by `gateway.max_response_bytes`, 4 MiB), a stream's answer grows with the stream. The texts are held against one process-wide account of **128 MiB** (fixed in the code, `internal/llmlog`, like the writer's queue bound) from the moment the route captures them until the row is inserted — never against `gateway.inflight_budget`, so recording books nothing on the request path; the container (1536 MiB) holds the default budget of 512 MiB, this account, the writer's copy of the rows being inserted (4 at a time) and the base. A text the account cannot take — many large recorded requests at once, or a slow database that keeps rows queued — is not captured: the row is written without it and says so (`metadata.gw.record_lost: ["request"]` or `["response"]`, `record_lost_cause: "memory"`), and `GET /api/status` counts such rows in `llmlog.recorded_bodies_lost`. Measured on the test image: a row of 16 MiB request text and 24 MiB answer is inserted in 256 ms (compressible text, stored in 161 KiB) and 360 ms (incompressible, 40 MiB), against the insert's 5 s deadline. Embedding vectors and rerank scores are not stored (the request is the record). A request still open when the shutdown's forced settle writes its row gets a row without bodies (`record_lost` both, cause `shutdown`). +**Size and memory.** No cut: a request text is at most twice `gateway.max_request_bytes` (8 MiB; an invalid byte is stored as U+FFFD), a non-streamed chat answer is the answer the client received (its upstream read is capped by `gateway.max_response_bytes`, 4 MiB), a stream's answer grows with the stream. The texts are held against one process-wide account of **128 MiB** (fixed in the code, `internal/llmlog`, like the writer's queue bound) from the moment the route captures them until the row is inserted — never against `gateway.inflight_budget`, so recording books nothing on the request path; the container (1536 MiB) holds the default budget of 512 MiB, this account, the writer's copy of the rows being inserted (4 at a time) and the base. A text the account cannot take — many large recorded requests at once, or a slow database that keeps rows queued — is not captured: the row is written without it and says so (`metadata.gw.record_lost: ["request"]` or `["response"]`, `record_lost_cause: "memory"`), and `GET /api/status` counts such rows in `llmlog.recorded_bodies_lost` and shows the account's fill in `llmlog.recorded_held_bytes`. Measured on the test image: a row of 16 MiB request text and 24 MiB answer is inserted in 256 ms (compressible text, stored in 161 KiB) and 360 ms (incompressible, 40 MiB), against the insert's 5 s deadline. Embedding vectors and rerank scores are not stored (the request is the record). A request still open when the shutdown's forced settle writes its row gets a row without bodies (`record_lost` both, cause `shutdown`). **Retention.** Recorded bodies are NULLed after `scheduler.llmlog_retention_days` (90 days) like every other body; the row and its marker stay. Export or read them out before that if they are needed longer. diff --git a/go/internal/handler/status.go b/go/internal/handler/status.go index ca3fcb133..4854da395 100644 --- a/go/internal/handler/status.go +++ b/go/internal/handler/status.go @@ -312,12 +312,17 @@ type llmlogWriteStatus struct { // names it in metadata.gw.record_lost) — monotone since start, like the // two above. RecordedBodiesLost int64 `json:"recorded_bodies_lost"` + // RecordedHeldBytes is what the texts of recorded rows hold of their + // account now (llmlog.RecordedHeld, bounded at 128 MiB): captured by + // running requests, queued or being inserted — near the bound, the next + // large texts are left out. + RecordedHeldBytes int64 `json:"recorded_held_bytes"` } // readLLMLogWriteStatus is the production llmlogStats source. func readLLMLogWriteStatus() llmlogWriteStatus { return llmlogWriteStatus{InsertFailures: llmlog.InsertFailures(), InsertDropped: llmlog.InsertDropped(), - RecordedBodiesLost: llmlog.RecordedBodiesLost()} + RecordedBodiesLost: llmlog.RecordedBodiesLost(), RecordedHeldBytes: llmlog.RecordedHeld()} } // advisoryRow is one named reason on the admin status surface (A02-W4): diff --git a/go/internal/handler/status_llmlog_test.go b/go/internal/handler/status_llmlog_test.go index 5df62b61a..7f8304570 100644 --- a/go/internal/handler/status_llmlog_test.go +++ b/go/internal/handler/status_llmlog_test.go @@ -11,7 +11,8 @@ import ( // TestStatusLLMLogSection is the status half of W06-1 gate (a): the server- // admin frame carries the llmlog write-path loss counters as a section that is -// PRESENT even when both are 0 — a zero must read as "nothing lost", never as +// PRESENT even when they are 0 (the two recording keys of issue #571 beside +// them) — a zero must read as "nothing lost", never as // "not measured" — and shows exactly what the counters hold. func TestStatusLLMLogSection(t *testing.T) { for _, tc := range []struct { @@ -19,9 +20,9 @@ func TestStatusLLMLogSection(t *testing.T) { failures, dropped int64 wire string }{ - {"zero_is_present", 0, 0, `"llmlog":{"insert_failures":0,"insert_dropped":0}`}, - {"one_failure", 1, 0, `"llmlog":{"insert_failures":1,"insert_dropped":0}`}, - {"drops", 3, 9, `"llmlog":{"insert_failures":3,"insert_dropped":9}`}, + {"zero_is_present", 0, 0, `"llmlog":{"insert_failures":0,"insert_dropped":0,"recorded_bodies_lost":0,"recorded_held_bytes":0}`}, + {"one_failure", 1, 0, `"llmlog":{"insert_failures":1,"insert_dropped":0,"recorded_bodies_lost":0,"recorded_held_bytes":0}`}, + {"drops", 3, 9, `"llmlog":{"insert_failures":3,"insert_dropped":9,"recorded_bodies_lost":0,"recorded_held_bytes":0}`}, } { t.Run(tc.name, func(t *testing.T) { c := &StatusCollector{llmlogStats: func() llmlogWriteStatus { @@ -50,7 +51,9 @@ func TestStatusCollectorWiresLLMLogCounters(t *testing.T) { t.Fatal("NewStatusCollector left the llmlog counter source unwired — the section would vanish in production") } got := c.llmlogStats() - if got.InsertFailures != llmlog.InsertFailures() || got.InsertDropped != llmlog.InsertDropped() { - t.Errorf("collector reads %+v, llmlog holds failures=%d dropped=%d", got, llmlog.InsertFailures(), llmlog.InsertDropped()) + if got.InsertFailures != llmlog.InsertFailures() || got.InsertDropped != llmlog.InsertDropped() || + got.RecordedBodiesLost != llmlog.RecordedBodiesLost() || got.RecordedHeldBytes != llmlog.RecordedHeld() { + t.Errorf("collector reads %+v, llmlog holds failures=%d dropped=%d recorded lost=%d held=%d", got, + llmlog.InsertFailures(), llmlog.InsertDropped(), llmlog.RecordedBodiesLost(), llmlog.RecordedHeld()) } } From 0a20dbb69a0a126e9730cfe87902328fbac55eb3 Mon Sep 17 00:00:00 2001 From: Jan-Stefan Janetzky Date: Fri, 27 Nov 2026 03:29:02 +0100 Subject: [PATCH 05/27] feat(gateway): a recorded rerank row keeps its answer; the export's fail-closed seal, the readers' census and the recording counters are pinned After the fresh review: a recording consumer's rerank row now stores the answer as written to the client (a tee after the client write; the forced row names it lost). The census lists every production literal that reads or writes context_llm_log, with its count per file, so a whole-row reader or a new statement in a listed file is red until classified. New tests pin the export's fail-closed seal over unreadable markers, an exhausted account on the real route (same answer, both bodies named lost), the tenant scope of recording_consumers and the loss counter. A recorded row without a defined sensitivity still logs the wiring defect. The wire-key goldens and the TS types follow the additive fields; the docs say what error rows and streams keep and what the account counts. Co-Authored-By: Claude Opus 5.5 --- docs/api.md | 2 +- docs/operations.md | 4 +- docs/security.md | 2 +- go/cmd/ctxd/v1_record_integration_test.go | 33 ++++- go/internal/handler/llmlog_test.go | 2 +- go/internal/handler/model_consumers_test.go | 2 +- go/internal/handler/status_test.go | 5 +- .../llmlog/body_readers_census_test.go | 108 --------------- go/internal/llmlog/gateway.go | 6 + go/internal/llmlog/gateway_recorded_test.go | 22 ++++ .../llmlog/llmlog_readers_census_test.go | 124 ++++++++++++++++++ go/internal/llmlog/recorded.go | 7 +- .../export_recorded_integration_test.go | 76 +++++++++++ go/internal/oai/record.go | 30 ++++- go/internal/oai/record_account_full_test.go | 53 ++++++++ go/internal/oai/record_internal_test.go | 2 +- go/internal/oai/record_test.go | 4 + go/internal/oai/rerank.go | 30 +++-- go/web/src/lib/api/types.ts | 4 + 19 files changed, 376 insertions(+), 140 deletions(-) delete mode 100644 go/internal/llmlog/body_readers_census_test.go create mode 100644 go/internal/llmlog/llmlog_readers_census_test.go create mode 100644 go/internal/llmlogexport/export_recorded_integration_test.go create mode 100644 go/internal/oai/record_account_full_test.go diff --git a/docs/api.md b/docs/api.md index e0c8b39c8..95ac7f7a2 100644 --- a/docs/api.md +++ b/docs/api.md @@ -848,7 +848,7 @@ The contract every gateway route writes against (`llmlog.GatewayEntry` / `llmlog - **One LLM-log row per request.** Chat, streamed chat, embeddings and rerank each write exactly one `context_llm_log` row, failover included: `attempt` is the number of physical attempts, `metadata.chain` lists them. Pipelines are `gateway-chat`, `gateway-embeddings` and `gateway-rerank`. - **Attribution.** The row names the consumer in `consumer_id`; `api_key_id` is always `NULL` (a row with both is refused by the database). `metadata.gw` (version 1) carries `v`, `op` (`chat`/`embed`/`rerank`), `alias`, `stream`, `hop` (0–16), `claimed_chain` (display only), `peer_pipeline` (ctx peers), `usage` (`backend`/`estimated`), `ttft_ms` (streams), `client_req_id` (`[A-Za-z0-9._:-]{1,128}`, else dropped), `finish` (`stop`, `length`, `tool_calls`, `content_filter`, `error`, `aborted`) and `model_key_id` — never an origin and never a second copy of the consumer. The hourly usage rollup counts such rows as `source = 'gateway'` with the alias. -- **Bodies.** `gateway.body_logging` (global-only, hot): `none` (default) stores no prompt and no answer (`''`, shown as `bodyless`), `errors` stores the serialized request and the answer only on rows with an error, `full` on every row (a streamed answer is not stored — its row carries the request only); each body is capped at 64 KiB with a visible truncation marker. A credentials-class row stays `sealed` under every policy — a tenant's `tenant.devmode` does not open it — and a row with an empty or unknown sensitivity stores no body either. **A recording consumer's rows** (`record_bodies`, see [model consumer administration](#model-consumer-administration)) are the one exception: whatever the policy and the class, the row stores the request whole (chat: the message array; embeddings: the `input`; rerank: the query, a line break and the documents) and the answer whole (a non-streamed chat answer as the client received it; a stream: its `data:` lines as relayed, in order, without the closing `[DONE]` or error frame; embeddings and rerank: none — the vectors and scores are not kept), with `metadata.gw.recorded: true`. A text the process's recording account (128 MiB, [operations](operations.md#recording-a-consumer)) cannot take is left out and named: `metadata.gw.record_lost` (`["request"]`, `["response"]` or both) with `record_lost_cause` `memory`; the shutdown's forced row of a request still open names both with cause `shutdown`. +- **Bodies.** `gateway.body_logging` (global-only, hot): `none` (default) stores no prompt and no answer (`''`, shown as `bodyless`), `errors` stores the serialized request and the answer only on rows with an error, `full` on every row (a streamed answer is not stored — its row carries the request only); each body is capped at 64 KiB with a visible truncation marker. A credentials-class row stays `sealed` under every policy — a tenant's `tenant.devmode` does not open it — and a row with an empty or unknown sensitivity stores no body either. **A recording consumer's rows** (`record_bodies`, see [model consumer administration](#model-consumer-administration)) are the one exception: whatever the policy and the class, the row stores the request whole (chat: the message array; embeddings: the `input`; rerank: the query, a line break and the documents) and the answer whole (a non-streamed chat answer as the client received it; a stream: its `data:` lines as relayed, in order, without the closing `[DONE]` or error frame; rerank: the answer as written to the client; embeddings: none — the vectors are not kept, the input is the record), with `metadata.gw.recorded: true`. A text the process's recording account (128 MiB, [operations](operations.md#recording-a-consumer)) cannot take is left out and named: `metadata.gw.record_lost` (`["request"]`, `["response"]` or both) with `record_lost_cause` `memory`; the shutdown's forced row of a request still open names both with cause `shutdown`. - **Errors.** The `error` column of a gateway row is ` ` (for example `bad_request 400 upstream_rejected`) — never the upstream response body, which can echo the prompt. - **Access log.** One INFO line `gateway request` per successful request (`consumer_id`, `model_key_id`, `tenant_id`, `op`, `alias`, `status`, `stream`, token counts, `usage`, `duration_ms`, `queue_wait_ms`, `class`, `hop`, `request_id`), on while `gateway.access_log` is `true` (default); a client that left before the handler returned is logged with `status=499` and the handler's status in `handler_status` — `0` when it wrote nothing — (at WARN with `waited_for=admission` when it left while waiting for an admission slot) (see [operations](operations.md#requests-the-client-gave-up-on)). Refusals (status ≥ 400) are never logged per request: they are counted per consumer (empty before authentication) and reason — for a refusal the [refusal ledger](#refusal-ledger) counts its `reason`, with the window's details in `detail`; otherwise the error code of the gateway or the model-key door, else `http_` — and written as at most one WARN line `gateway rejections` with `count` and `window="1m"` per minute — the flag's `404` and the door's `401` included. The global `http request` line is not written for these requests: each gateway request is one line or one count. diff --git a/docs/operations.md b/docs/operations.md index 90277a742..24bbb58ae 100644 --- a/docs/operations.md +++ b/docs/operations.md @@ -989,7 +989,7 @@ ctx manage model-consumer-update '' '{"id":"","record_bodies":true, **What the rows can hold.** Everything the client sent: a password, a token or a private key in a prompt is stored in clear text. The row is marked `metadata.gw.recorded = true`; its bodies are for a server-admin only ([security](security.md#gateway-telemetry-v1-v2)) — `GET /api/llmlog/{id}` as server-admin, or psql. `ctx-llmlog-export` writes such rows with their bodies sealed (below). A database backup carries them like every other content of the database. -**Reading a consumer's rows out** (psql, in order; `request_user` is the message array of a chat request, the `input` of an embeddings request, the query, a line break and the documents of a rerank request; `response_content` the answer of a chat request — a stream's `data:` lines): +**Reading a consumer's rows out** (psql, in order; `request_user` is the message array of a chat request, the `input` of an embeddings request, the query, a line break and the documents of a rerank request; `response_content` the answer of a chat or rerank request — a stream's `data:` lines; none for embeddings): ```sql SELECT created_at, pipeline, metadata->'gw'->>'finish' AS finish, request_user, response_content, @@ -1001,7 +1001,7 @@ SELECT created_at, pipeline, metadata->'gw'->>'finish' AS finish, request_user, The predicate rides `idx_llm_log_consumer` (migration 158). Rows of requests the gateway refused before the route (`401`, `429`, a limit) are not rows at all — they are only counted in `context_llm_rejections_hourly`. -**Size and memory.** No cut: a request text is at most twice `gateway.max_request_bytes` (8 MiB; an invalid byte is stored as U+FFFD), a non-streamed chat answer is the answer the client received (its upstream read is capped by `gateway.max_response_bytes`, 4 MiB), a stream's answer grows with the stream. The texts are held against one process-wide account of **128 MiB** (fixed in the code, `internal/llmlog`, like the writer's queue bound) from the moment the route captures them until the row is inserted — never against `gateway.inflight_budget`, so recording books nothing on the request path; the container (1536 MiB) holds the default budget of 512 MiB, this account, the writer's copy of the rows being inserted (4 at a time) and the base. A text the account cannot take — many large recorded requests at once, or a slow database that keeps rows queued — is not captured: the row is written without it and says so (`metadata.gw.record_lost: ["request"]` or `["response"]`, `record_lost_cause: "memory"`), and `GET /api/status` counts such rows in `llmlog.recorded_bodies_lost` and shows the account's fill in `llmlog.recorded_held_bytes`. Measured on the test image: a row of 16 MiB request text and 24 MiB answer is inserted in 256 ms (compressible text, stored in 161 KiB) and 360 ms (incompressible, 40 MiB), against the insert's 5 s deadline. Embedding vectors and rerank scores are not stored (the request is the record). A request still open when the shutdown's forced settle writes its row gets a row without bodies (`record_lost` both, cause `shutdown`). +**Size and memory.** No cut: a request text is at most twice `gateway.max_request_bytes` (8 MiB; an invalid byte is stored as U+FFFD), a non-streamed chat answer is the answer the client received (its upstream read is capped by `gateway.max_response_bytes`, 4 MiB), a stream's answer grows with the stream. A row with an error carries the request; the error ctx answered is the row's `error` column. A stream's answer is its relayed `data:` lines, without the closing `[DONE]` or error frame. The texts are held against one process-wide account of **128 MiB** (fixed in the code, `internal/llmlog`, like the writer's queue bound) from the moment the route captures them until the row is inserted — never against `gateway.inflight_budget`, so recording books nothing on the request path; the container (1536 MiB) holds the default budget of 512 MiB, this account, the writer's copy of the rows being inserted (4 at a time) and the base. A text the account cannot take — many large recorded requests at once, or a slow database that keeps rows queued — is not captured: the row is written without it and says so (`metadata.gw.record_lost: ["request"]` or `["response"]`, `record_lost_cause: "memory"`), and `GET /api/status` counts such rows in `llmlog.recorded_bodies_lost` and shows the account's fill in `llmlog.recorded_held_bytes`. Measured on the test image: a row of 16 MiB request text and 24 MiB answer is inserted in 256 ms (compressible text, stored in 161 KiB) and 360 ms (incompressible, 40 MiB), against the insert's 5 s deadline. Embedding vectors are not stored (the input is the record); a rerank answer is stored as written to the client. **What the account counts:** a stream holds the capacity of its growing buffer — up to about twice the text so far (measured: 6.8 MB of text held 12.6 MB) — so streams reach the bound sooner than their text alone; the writer's copies of a row while it is inserted (pgx encodes the arguments, up to two transient copies per row, 4 inserts at a time) are not counted. `gateway.max_request_bytes` above 64 MiB can make a request text (up to twice the body) larger than the whole account: such a text is never captured. Deactivating and reactivating a recording consumer leaves the switch as it was. A request still open when the shutdown's forced settle writes its row gets a row without bodies (`record_lost` both, cause `shutdown`). **Retention.** Recorded bodies are NULLed after `scheduler.llmlog_retention_days` (90 days) like every other body; the row and its marker stay. Export or read them out before that if they are needed longer. diff --git a/docs/security.md b/docs/security.md index 49fa998fe..99d0583d6 100644 --- a/docs/security.md +++ b/docs/security.md @@ -167,7 +167,7 @@ Every refusal carries `x-should-retry: false`: the same request against the same What the gateway writes about a request, and what it never writes (design 06 §4.6): - **One body policy.** `gateway.body_logging` is the only switch for prompt and answer bodies of the gateway rows of every consumer that does not record (next point) in `context_llm_log` — global-only, so no tenant can raise it for itself. `none` (default) stores none; `errors` stores the serialized request and the answer on rows with an error only; `full` on every row, each capped at 64 KiB. Every row is then slimmed as for a tenant without developer mode: a credentials-class row stays sealed under every policy, whatever the tenant's `tenant.devmode` says — and so does a row whose sensitivity is empty or unknown (fail-closed, logged as a wiring defect). Embedded NUL bytes and invalid UTF-8 are cleaned before the write, so a crafted body cannot make the row — and its attribution — vanish. -- **The one exception: a recording consumer (migration 197, issue #571).** A model consumer with `record_bodies` on has every gateway row of its own — chat, a stream's relayed answer, embeddings, rerank, rows with an error — written with the request and the answer in full: whatever `gateway.body_logging`, the alias, the consumer's `prompt_sensitivity`, the body scan or `Ctx-Sensitivity` say, without the 64 KiB cut and without the credentials seal. **Such a row can carry credentials in clear text** — a password or key a client puts into a prompt is stored as sent. Only a server-admin can switch it on (also with self-service, and only with `confirm_record_bodies: true`); switching it off is open to the consumer's tenant-admin; both are audited. The row is marked `metadata.gw.recorded = true`, and its bodies reach a server-admin only: `GET /api/llmlog/{id}` answers every other caller with the uniform `404` (a gateway row has no knowledge key, so the tenant gate never matches it), the LLM log list, the usage and status surfaces carry no body, `ctx-llmlog-export` writes the row with its bodies sealed (also, fail-closed, every gateway row whose marker is missing or unreadable), and no pipeline (distill, dream, digest) reads the log's bodies (`TestBodyColumnReadersCensus` lists every reader of the body columns). **What the switch does not change:** the request path — the required sensitivity, the chain and its egress rule, the body scan and its `413`, the limits and the answer are the same with and without it (the captured texts are held against a fixed account of their own, never against the request's in-flight budget); every other consumer's rows, byte for byte under every `gateway.body_logging` value; the retention — recorded bodies are NULLed after `scheduler.llmlog_retention_days` (90) like every body; and a database backup (`backup.sh`), which carries them like every other content of the database. Embedding vectors and rerank scores are not stored (the request is the record); the shutdown's forced row of a request still open carries no body and names it (`metadata.gw.record_lost`). See [operations — Recording a consumer](operations.md#recording-a-consumer). +- **The one exception: a recording consumer (migration 197, issue #571).** A model consumer with `record_bodies` on has every gateway row of its own — chat, a stream's relayed answer, embeddings, rerank, rows with an error (they carry the request; the error ctx answered is the row's `error` column, ` `) — written with the request and the answer in full: whatever `gateway.body_logging`, the alias, the consumer's `prompt_sensitivity`, the body scan or `Ctx-Sensitivity` say, without the 64 KiB cut and without the credentials seal. **Such a row can carry credentials in clear text** — a password or key a client puts into a prompt is stored as sent. Only a server-admin can switch it on (also with self-service, and only with `confirm_record_bodies: true`); switching it off is open to the consumer's tenant-admin; both are audited. The row is marked `metadata.gw.recorded = true`, and its bodies reach a server-admin only: `GET /api/llmlog/{id}` answers every other caller with the uniform `404` (a gateway row has no knowledge key, so the tenant gate never matches it), the LLM log list, the usage and status surfaces carry no body, `ctx-llmlog-export` writes the row with its bodies sealed (also, fail-closed, every gateway row whose marker is missing or unreadable), and no pipeline (distill, dream, digest) reads the log's bodies (`TestBodyColumnReadersCensus` lists every reader of the body columns). **What the switch does not change:** the request path — the required sensitivity, the chain and its egress rule, the body scan and its `413`, the limits and the answer are the same with and without it (the captured texts are held against a fixed account of their own, never against the request's in-flight budget; the one booking that differs is the body policy's own log text of at most 64 KiB, booked at the end of a request under `gateway.body_logging` `errors`/`full`, which a recorded row does not take); deactivating and reactivating the consumer (the switch stays as it was); every other consumer's rows, byte for byte under every `gateway.body_logging` value; the retention — recorded bodies are NULLed after `scheduler.llmlog_retention_days` (90) like every body; and a database backup (`backup.sh`), which carries them like every other content of the database. Embedding vectors are not stored (the input is the record); the shutdown's forced row of a request still open carries no body and names it (`metadata.gw.record_lost`). See [operations — Recording a consumer](operations.md#recording-a-consumer). - **Error redaction.** The `error` column of a gateway row holds only class, status and ctx code. The upstream response body (which can echo prompt fragments, and which tenant-admins would read in the LLM log list) never reaches it; class and code must have the shape of vocabulary words (lower snake case, at most 64 characters), anything else is stored as `[redacted]`; the writer takes the code from the gateway's own code vocabulary, never from the upstream answer. - **One identity.** A gateway row is attributed to the consumer (`consumer_id`); a knowledge key id that reached the row anyway is cleared with an ERROR line, and the database refuses any row carrying both. The model key id is kept in `metadata.gw.model_key_id` for key-leak forensics, never as a column. - **Access log.** A successful request is one `gateway request` line with ids, op, alias, status, token counts and timings (`gateway.access_log`, default on) — no consumer label, no content, never a key, its hint or a query string. Refusals are counted per (consumer, reason — a code of the gateway or door vocabulary, else `http_`) and logged as one `gateway rejections` WARN line per minute with the count, so a flood of `401`/`429` answers cannot rotate the error and security lines out of the 50 MB × 3 container log. The global request log stays silent for these requests. diff --git a/go/cmd/ctxd/v1_record_integration_test.go b/go/cmd/ctxd/v1_record_integration_test.go index 5c66e2686..c9e5b1452 100644 --- a/go/cmd/ctxd/v1_record_integration_test.go +++ b/go/cmd/ctxd/v1_record_integration_test.go @@ -32,6 +32,7 @@ import ( "net/http" "net/http/httptest" "regexp" + "sort" "strings" "testing" @@ -137,6 +138,22 @@ func TestV1RecordedConsumerRowAndItsReaders(t *testing.T) { } recID, recKey := mkConsumer("v1-rec-on", map[string]any{"record_bodies": true, "confirm_record_bodies": true}) plainID, plainKey := mkConsumer("v1-rec-off", nil) + // A recording consumer of another tenant: the tenant-admin's status must + // not name it, the server-admin's must. + status, body, resp = v1RecAPI(t, f, http.MethodPost, "/api/manage", v1RecAdminKey, map[string]any{ + "action": "tenant-create", "data": map[string]any{"slug": "v1rec-other", "display_name": "v1 rec other"}}) + otherTn, _ := resp["tenant"].(map[string]any) + otherTenant, _ := otherTn["id"].(string) + if status != http.StatusOK || otherTenant == "" { + t.Fatalf("tenant-create other: %d %s", status, body) + } + status, body, resp = v1RecAPI(t, f, http.MethodPost, "/api/manage", v1RecAdminKey, map[string]any{"action": "model-consumer-create", + "data": map[string]any{"label": "v1-rec-foreign", "tenant_id": otherTenant, "record_bodies": true, "confirm_record_bodies": true}}) + foreign, _ := resp["consumer"].(map[string]any) + foreignID, _ := foreign["id"].(string) + if status != http.StatusOK || foreignID == "" { + t.Fatalf("foreign recording consumer: %d %s", status, body) + } content := v1RecSecret + " " + strings.Repeat("0123456789abcdef", 5<<10) // 80 KiB chat := `{"model":"` + v1ChatAlias + `","messages":[{"role":"user","content":"` + content + `"}]}` @@ -191,12 +208,18 @@ func TestV1RecordedConsumerRowAndItsReaders(t *testing.T) { } }) t.Run("status", func(t *testing.T) { - for name, key := range map[string]string{"server_admin": v1RecAdminKey, "tenant_admin": tenantAdmin} { - st, b, out := v1RecAPI(t, f, http.MethodGet, "/api/status", key, nil) + both := []string{recID, foreignID} + sort.Strings(both) + for name, c := range map[string]struct { + key string + want []string + }{"server_admin": {v1RecAdminKey, both}, "tenant_admin": {tenantAdmin, []string{recID}}} { + st, b, out := v1RecAPI(t, f, http.MethodGet, "/api/status", c.key, nil) gw, _ := out["gateway"].(map[string]any) - ids, _ := gw["recording_consumers"].([]any) - if st != http.StatusOK || len(ids) != 1 || ids[0] != recID || strings.Contains(string(b), "Tr0ub4dor") { - t.Errorf("%s status: %d recording_consumers %v — want exactly [%s], no body", name, st, gw["recording_consumers"], recID) + raw, _ := json.Marshal(gw["recording_consumers"]) + want, _ := json.Marshal(c.want) + if st != http.StatusOK || string(raw) != string(want) || strings.Contains(string(b), "Tr0ub4dor") { + t.Errorf("%s status: %d recording_consumers %s — want exactly %s, no body", name, st, raw, want) } } }) diff --git a/go/internal/handler/llmlog_test.go b/go/internal/handler/llmlog_test.go index f2edad99c..65f8af561 100644 --- a/go/internal/handler/llmlog_test.go +++ b/go/internal/handler/llmlog_test.go @@ -129,7 +129,7 @@ func TestLLMLogDetailGoldenKeys(t *testing.T) { assertKeys(t, "detail", top["detail"], []string{ "id", "created_at", "pipeline", "model", "backend", "required_sensitivity", "body_state", - "request_system", "request_user", "response_content", + "request_system", "request_user", "response_content", "recorded", }) } diff --git a/go/internal/handler/model_consumers_test.go b/go/internal/handler/model_consumers_test.go index 14b888c85..84522dd97 100644 --- a/go/internal/handler/model_consumers_test.go +++ b/go/internal/handler/model_consumers_test.go @@ -87,7 +87,7 @@ func TestConsumerViewGoldenKeys(t *testing.T) { want := map[string][]string{ "consumer": {"active", "admission_lane", "all_models", "allow_plaintext", "allowed_cidrs", "created_at", "created_by_label", "description", "fair_weight", "id", "keys", "keys_total", "kind", "label", - "last_used_at", "models", "peer", "prompt_sensitivity", "status", "tenant_id", "tenant_scope", "tenant_slug"}, + "last_used_at", "models", "peer", "prompt_sensitivity", "record_bodies", "status", "tenant_id", "tenant_scope", "tenant_slug"}, "key": {"created_at", "expires_at", "hint", "id", "last_used_at", "revoked_at", "rotated_from", "status"}, "peer": {"bound_at", "instance_id"}, } diff --git a/go/internal/handler/status_test.go b/go/internal/handler/status_test.go index 99335b6ff..160fa910f 100644 --- a/go/internal/handler/status_test.go +++ b/go/internal/handler/status_test.go @@ -296,8 +296,9 @@ func TestStatusGoldenKeys(t *testing.T) { assertKeys(t, "advisories.row", advs[0], []string{"subject", "state"}) // W06-1: the llmlog write-path section — two process-wide loss counters, - // nothing else (no pipeline names, no error text: those are log material). - assertKeys(t, "llmlog", top["llmlog"], []string{"insert_failures", "insert_dropped"}) + // nothing else (no pipeline names, no error text: those are log material); + // issue #571 adds the recording account's loss counter and fill. + assertKeys(t, "llmlog", top["llmlog"], []string{"insert_failures", "insert_dropped", "recorded_bodies_lost", "recorded_held_bytes"}) // FOLGE-Y: the query-synthesis latency block — exactly the four names // the bench contract reads (p95_ms only when samples >= 20). diff --git a/go/internal/llmlog/body_readers_census_test.go b/go/internal/llmlog/body_readers_census_test.go deleted file mode 100644 index 488ddbb58..000000000 --- a/go/internal/llmlog/body_readers_census_test.go +++ /dev/null @@ -1,108 +0,0 @@ -package llmlog - -import ( - "go/ast" - "go/token" - "regexp" - "sort" - "strconv" - "strings" - "testing" -) - -// The readers of the body columns (issue #571, promise 5). A recorded row's -// request_system/request_user/response_content can carry credentials in -// clear text; its bodies are for a server-admin only and for no pipeline. -// This census walks every non-test .go file of the module and lists each -// file whose STRING LITERALS name a body column (SQL, a JSON key) or read a -// row of context_llm_log whole — comments do not count. Every such file is -// classified below with what it does with a recorded row; a new reader of -// the columns turns this test red until it is classified here (and given its -// test). -// -// Not covered, stated rather than assumed: SQL assembled from fragments that -// never spell a column name (none today), the shell scripts of the -// repository (backup.sh and coverage.sh dump the whole database — a backup, -// not a reader of the log), and the web frontend, which reads the bodies -// only through GET /api/llmlog/{id}. -var bodyColumnReaders = map[string]string{ - // The writer: the insert and the retention janitor (EvictBodies NULLs the - // bodies of every row past scheduler.llmlog_retention_days, recorded rows - // included — TestRecordedRowsUnderTheRetentionJanitor). - "internal/llmlog/llmlog.go": "writer and retention janitor", - // GET /api/llmlog/{id}: a server-admin reads every row; anyone else only - // rows of its own knowledge keys (api_key_id) — a gateway row has none, so - // a recorded row is a uniform 404 below server-admin - // (TestRecordedRowReaders, detail). - "internal/handler/llmlog.go": "per-id detail, server-admin only for gateway rows", - // ctx-llmlog-export: the bodies of a recorded row (and fail-closed of a - // gateway row without a readable marker) leave sealed - // (SQLBodiesServerAdminOnly; TestRecordedRowReaders, export). - "internal/llmlogexport/export.go": "bulk export, recorded rows sealed", - // The status page's per-pipeline counts: SELECT * reads its own CTEs - // (edge, roll), the table only for counts and sums — no body. - "internal/llmusage/groups.go": "aggregates only (SELECT * over its CTEs)", -} - -// bodyColumnRE matches a body column name as a word inside a literal; -// wholeRowRE a literal that reads context_llm_log whole (SELECT *, alias.*, -// to_jsonb/row_to_json of a row), which carries the bodies without naming -// them. -var ( - bodyColumnRE = regexp.MustCompile(`\b(request_system|request_user|response_content)\b`) - wholeRowRE = regexp.MustCompile(`(?is)context_llm_log.*?(\bselect\s+\*|\w\.\*|to_jsonb\s*\(|row_to_json\s*\()|(\bselect\s+\*|\w\.\*|to_jsonb\s*\(|row_to_json\s*\().*?context_llm_log`) -) - -func TestBodyColumnReadersCensus(t *testing.T) { - root := gatewayCensusModuleRoot(t) - fset := token.NewFileSet() - files := productionFiles(t, fset, root) - found := map[string][]string{} - for _, cf := range files { - ast.Inspect(cf.file, func(n ast.Node) bool { - lit, ok := n.(*ast.BasicLit) - if !ok || lit.Kind != token.STRING { - return true - } - s, err := strconv.Unquote(lit.Value) - if err != nil { - s = lit.Value - } - if bodyColumnRE.MatchString(s) || wholeRowRE.MatchString(s) { - found[cf.rel] = append(found[cf.rel], fset.Position(lit.Pos()).String()) - } - return true - }) - } - var unclassified, gone []string - for rel, at := range found { - if _, ok := bodyColumnReaders[rel]; !ok { - unclassified = append(unclassified, rel+" ("+strings.Join(at, ", ")+")") - } - } - for rel := range bodyColumnReaders { - if _, ok := found[rel]; !ok { - gone = append(gone, rel) - } - } - sort.Strings(unclassified) - sort.Strings(gone) - t.Logf("census: %d production files, %d name a body column: %v", len(files), len(found), keys(found)) - if len(unclassified) > 0 { - t.Errorf("files whose literals name a context_llm_log body column without a classification in bodyColumnReaders "+ - "(a recorded row's bodies are for a server-admin only — classify the reader and give it its test):\n %s", - strings.Join(unclassified, "\n ")) - } - if len(gone) > 0 { - t.Errorf("classified readers that no longer name a body column (drop them from bodyColumnReaders): %v", gone) - } -} - -func keys(m map[string][]string) []string { - out := make([]string, 0, len(m)) - for k := range m { - out = append(out, k) - } - sort.Strings(out) - return out -} diff --git a/go/internal/llmlog/gateway.go b/go/internal/llmlog/gateway.go index 0ce8df869..cea6f3043 100644 --- a/go/internal/llmlog/gateway.go +++ b/go/internal/llmlog/gateway.go @@ -426,6 +426,12 @@ func GatewayEntry(r GatewayRow) Entry { // and GatewayEntry for every other. func RecordedGatewayEntry(r GatewayRow) Entry { e := gatewayRowBase(r, true) + if !backends.ValidSensitivity(backends.Sensitivity(e.RequiredSensitivity)) { + // The bodies are kept whatever the class; the defect is still logged + // as bodiesAllowed logs it for every other row. + wiringError(&lastSensWarn, "llmlog: a gateway row without a defined required_sensitivity — recorded whole (recording consumer)", + "pipeline", e.Pipeline, "required_sensitivity", cleanText(e.RequiredSensitivity, gatewayTokenMax)) + } e.RequestUser, e.ResponseContent = storable(r.Request), storable(r.Response) e.recordedHeld = r.RecordedHeld return e diff --git a/go/internal/llmlog/gateway_recorded_test.go b/go/internal/llmlog/gateway_recorded_test.go index 70eece129..dd5107445 100644 --- a/go/internal/llmlog/gateway_recorded_test.go +++ b/go/internal/llmlog/gateway_recorded_test.go @@ -104,6 +104,28 @@ func TestRecordedRowNamesWhatItLost(t *testing.T) { } } +// TestRecordedBodiesLostCounts: RecordGateway counts a recorded row written +// without a body it should carry (llmlog.recorded_bodies_lost on the status +// frame) — and nothing else: a whole recorded row, or an unrecorded row that +// names a loss it cannot have, leaves the counter. +func TestRecordedBodiesLostCounts(t *testing.T) { + before := RecordedBodiesLost() + whole := recordedRow(BodyLoggingNone, "public") + RecordGateway(nil, whole) + plain := recordedRow(BodyLoggingNone, "public") + plain.Recorded, plain.RecordLost = false, []string{RecordLostRequest} + RecordGateway(nil, plain) + if got := RecordedBodiesLost() - before; got != 0 { + t.Fatalf("a whole recorded row and an unrecorded one counted %d losses", got) + } + lost := recordedRow(BodyLoggingNone, "public") + lost.RecordLost, lost.RecordLostCause = []string{RecordLostResponse}, RecordLostMemory + RecordGateway(nil, lost) + if got := RecordedBodiesLost() - before; got != 1 { + t.Fatalf("a recorded row without its answer counted %d losses, want 1", got) + } +} + // recordedAccount resets the recording account for a test and checks it is // back at zero afterwards. func recordedAccount(t *testing.T) { diff --git a/go/internal/llmlog/llmlog_readers_census_test.go b/go/internal/llmlog/llmlog_readers_census_test.go new file mode 100644 index 000000000..389eb9288 --- /dev/null +++ b/go/internal/llmlog/llmlog_readers_census_test.go @@ -0,0 +1,124 @@ +package llmlog + +import ( + "fmt" + "go/ast" + "go/token" + "regexp" + "sort" + "strconv" + "strings" + "testing" +) + +// The readers of context_llm_log (issue #571, promise 5). A recorded row's +// request_system/request_user/response_content can carry credentials in +// clear text; its bodies are for a server-admin only and for no pipeline. +// This census walks every non-test .go file of the module and lists each file +// whose STRING LITERALS read or write the table (FROM, JOIN, TABLE, INTO, +// UPDATE context_llm_log) or name a body column — comments do not count. +// Every such file is classified below with what it reads and how many such +// literals it holds; a new reader of the table — a whole-row one included +// (SELECT l FROM context_llm_log l, to_jsonb, json_agg), and a new statement +// in a file already listed — turns this test red until it is classified here +// (and, if it reads bodies, given its test). +// +// Not covered, stated rather than assumed: SQL assembled from fragments that +// never spell the table's name, the shell scripts of the repository +// (backup.sh and coverage.sh dump the whole database — a backup, not a +// reader of the log), and the web frontend, which reads the bodies only +// through GET /api/llmlog/{id}. +// llmlogReader is one classified file: the number of its literals that +// read the table or name a body column (struct tags included), and what they +// read. +type llmlogReader struct { + n int + what string +} + +var llmlogReaders = map[string]llmlogReader{ + // Bodies: the writer's insert and the retention janitor (EvictBodies NULLs + // the bodies of every row past scheduler.llmlog_retention_days, recorded + // rows included — TestV1RecordedConsumerRowAndItsReaders/retention_janitor). + "internal/llmlog/llmlog.go": {2, "bodies: writer and retention janitor"}, + // Bodies: GET /api/llmlog/{id} — a server-admin reads every row, anyone + // else only rows of its own knowledge keys (api_key_id); a gateway row has + // none, so a recorded row is a uniform 404 below server-admin + // (TestV1RecordedConsumerRowAndItsReaders/detail). + "internal/handler/llmlog.go": {4, "bodies: per-id detail, server-admin only for gateway rows"}, + // Bodies: ctx-llmlog-export — the bodies of a recorded row, and fail-closed + // of a gateway row without a readable marker, leave sealed + // (SQLBodiesServerAdminOnly; TestExportSealsRecordedRows, + // TestV1RecordedConsumerRowAndItsReaders/export). + "internal/llmlogexport/export.go": {4, "bodies: bulk export, recorded rows sealed"}, + // Metadata only (the projections name no body column): + "internal/handler/llmlog_consumer.go": {2, "metadata: GET /api/llmlog list (llmlogListColumns)"}, + "internal/handler/events.go": {1, "metadata: the llmcalls SSE feed, server-admin"}, + "internal/handler/status.go": {1, "metadata: max(created_at) of the 24 h window"}, + "internal/llmusage/groups.go": {2, "metadata: per-pipeline counts and sums (SELECT * over its own CTEs)"}, + "internal/llmusage/window.go": {1, "metadata: usage windows of the tenant quota"}, + "internal/events/distill_spend.go": {1, "metadata: count and duration of the distill pipeline's own rows"}, + "cmd/ctx-armcost/report.go": {3, "metadata: an operator tool's cost report"}, + "cmd/ctx-armcost/pertopic.go": {2, "metadata: an operator tool's per-topic cost"}, +} + +// tableRE matches a literal that reads or writes the table; bodyColumnRE one +// that names a body column. +var ( + tableRE = regexp.MustCompile(`(?i)\b(from|join|table|into|update)\s+context_llm_log\b`) + bodyColumnRE = regexp.MustCompile(`\b(request_system|request_user|response_content)\b`) +) + +func TestLLMLogReadersCensus(t *testing.T) { + root := gatewayCensusModuleRoot(t) + fset := token.NewFileSet() + files := productionFiles(t, fset, root) + found := map[string][]string{} + for _, cf := range files { + ast.Inspect(cf.file, func(n ast.Node) bool { + lit, ok := n.(*ast.BasicLit) + if !ok || lit.Kind != token.STRING { + return true + } + s, err := strconv.Unquote(lit.Value) + if err != nil { + s = lit.Value + } + if tableRE.MatchString(s) || bodyColumnRE.MatchString(s) { + found[cf.rel] = append(found[cf.rel], fset.Position(lit.Pos()).String()) + } + return true + }) + } + var unclassified, gone []string + for rel, at := range found { + if r, ok := llmlogReaders[rel]; !ok || r.n != len(at) { + unclassified = append(unclassified, fmt.Sprintf("%s: %d literal(s), classified %d (%s)", rel, len(at), r.n, strings.Join(at, ", "))) + } + } + for rel := range llmlogReaders { + if _, ok := found[rel]; !ok { + gone = append(gone, rel) + } + } + sort.Strings(unclassified) + sort.Strings(gone) + t.Logf("census: %d production files, %d read or write context_llm_log: %v", len(files), len(found), keys(found)) + if len(unclassified) > 0 { + t.Errorf("files whose literals read context_llm_log without a classification in llmlogReaders "+ + "(a recorded row's bodies are for a server-admin only — classify the reader and give it its test):\n %s", + strings.Join(unclassified, "\n ")) + } + if len(gone) > 0 { + t.Errorf("classified readers that no longer read context_llm_log (drop them from llmlogReaders): %v", gone) + } +} + +func keys(m map[string][]string) []string { + out := make([]string, 0, len(m)) + for k := range m { + out = append(out, k) + } + sort.Strings(out) + return out +} diff --git a/go/internal/llmlog/recorded.go b/go/internal/llmlog/recorded.go index 482a62db5..ec1fd1bc0 100644 --- a/go/internal/llmlog/recorded.go +++ b/go/internal/llmlog/recorded.go @@ -18,8 +18,11 @@ import ( // not against the request's in-flight budget: from the moment a route // captures a text (ReserveRecorded) until the writer has inserted the row or // lost it (queue full, failed insert). The request path books nothing for -// them, so its bookings, its 503s and its answer are the same with and -// without the switch; and the rows of recorded calls the writer has not +// them, so its chain, its refusals and its answer are the same with and +// without the switch — the one booking that differs is the body policy's own +// log text (at most 64 KiB, booked at the request's end under +// gateway.body_logging errors/full), which a recorded row does not take; and +// the rows of recorded calls the writer has not // inserted yet — a slow database, a burst of large requests — hold at most // maxRecordedHeld bytes of text. A text the account cannot take is not // captured: the row is still written, without it, and says so diff --git a/go/internal/llmlogexport/export_recorded_integration_test.go b/go/internal/llmlogexport/export_recorded_integration_test.go new file mode 100644 index 000000000..06d761dbd --- /dev/null +++ b/go/internal/llmlogexport/export_recorded_integration_test.go @@ -0,0 +1,76 @@ +//go:build integration + +// The export's seal of recorded rows (issue #571), fail-closed: a gateway row +// leaves ctx-llmlog-export with its bodies sealed unless its metadata.gw is an +// object that does not mark it recorded. The production writer always stamps +// metadata.gw on a gateway row, so the rows without a readable marker are +// written by hand here — they are the states the predicate must not trust +// (llmlog.SQLBodiesServerAdminOnly). +// +// go test -tags=integration -p 1 -count=1 -run TestExportSealsRecordedRows -v ./internal/llmlogexport/ +package llmlogexport_test + +import ( + "bytes" + "context" + "fmt" + "strings" + "testing" + + "github.com/GottZ/ctx/internal/llmlogexport" + "github.com/GottZ/ctx/internal/testdb" +) + +func TestExportSealsRecordedRows(t *testing.T) { + if testing.Short() { + t.Skip("integration test") + } + ctx := context.Background() + pool := testdb.SetupTestDB(t) + const consumer = "0195a6f0-0000-7000-8000-00000000e571" + rows := []struct { + name, pipeline string + consumer bool + metadata string // JSON (the column is NOT NULL) + sealed bool + }{ + {"recorded", "gateway-chat", true, `{"gw":{"v":1,"recorded":true}}`, true}, + {"recorded as a string", "gateway-chat", true, `{"gw":{"v":1,"recorded":"true"}}`, true}, + {"recorded false", "gateway-chat", true, `{"gw":{"v":1,"recorded":false}}`, false}, + {"unrecorded", "gateway-embeddings", true, `{"gw":{"v":1,"op":"embed"}}`, false}, + {"marker missing", "gateway-chat", true, `{"chain":[]}`, true}, + {"gw JSON null", "gateway-rerank", true, `{"gw":null}`, true}, + {"gw not an object", "gateway-chat", true, `{"gw":[1]}`, true}, + {"gateway pipeline without consumer", "gateway-chat", false, `{}`, true}, + {"background pipeline", "query-synthesize", false, `{}`, false}, + } + for i, r := range rows { + var cons any + if r.consumer { + cons = consumer + } + if _, err := pool.Exec(ctx, `INSERT INTO context_llm_log (pipeline, model, host, request_user, response_content, request_system, metadata, consumer_id) + VALUES ($1, 'm', 'h', $2, $3, '', $4::jsonb, $5::uuid)`, + r.pipeline, fmt.Sprintf("SECRET-%d-%s", i, r.name), fmt.Sprintf("ANSWER-%d-%s", i, r.name), r.metadata, cons); err != nil { + t.Fatalf("row %d (%s): %v", i, r.name, err) + } + } + var buf bytes.Buffer + sum, err := llmlogexport.Export(ctx, pool, &buf, llmlogexport.ExportOptions{UntilMargin: 1}) + if err != nil { + t.Fatalf("export: %v", err) + } + want := 0 + for i, r := range rows { + inExport := strings.Contains(buf.String(), fmt.Sprintf("SECRET-%d-", i)) || strings.Contains(buf.String(), fmt.Sprintf("ANSWER-%d-", i)) + if r.sealed { + want++ + } + if inExport == r.sealed { + t.Errorf("%s: bodies in the export %v, want sealed %v", r.name, inExport, r.sealed) + } + } + if sum.RowsRecordedSealed != int64(want) || sum.RowsTotal != int64(len(rows)) { + t.Errorf("rows_recorded_sealed %d of %d, want %d of %d", sum.RowsRecordedSealed, sum.RowsTotal, want, len(rows)) + } +} diff --git a/go/internal/oai/record.go b/go/internal/oai/record.go index e19c5d9f3..e717fdcad 100644 --- a/go/internal/oai/record.go +++ b/go/internal/oai/record.go @@ -1,6 +1,7 @@ package oai import ( + "io" "math" "strings" @@ -13,8 +14,9 @@ import ( // client received (a non-streamed chat answer as written, a stream's data // lines as relayed). Every text is reserved against llmlog's recording // account (llmlog.ReserveRecorded) before it is made — never against the -// request's in-flight budget, so the switch changes no booking, no refusal -// and no answer of the request. A text the account cannot take is not made: +// request's in-flight budget, so the switch changes no refusal and no answer +// of the request (the one booking it drops is the body policy's own 64 KiB +// log text at the request's end, which a recorded row does not take). A text the account cannot take is not made: // the row goes without it and names it (record_lost, cause "memory"). The // zero value records nothing; on is set once, from the door's ConsumerAuth. type recording struct { @@ -70,7 +72,23 @@ func (r *recording) bytes(b []byte, body string) string { return string(b) } -// addStream appends one relayed data line of a stream. The buffer grows as +// recordWriter hands the bytes written to the client to the capture of a +// recording consumer's request — after the client write, so the answer the +// client gets is the one it gets without the switch (the rerank answer, +// which writeRerank writes piece by piece and never holds whole). +type recordWriter struct { + w io.Writer + r *recording +} + +func (t recordWriter) Write(p []byte) (int, error) { + n, err := t.w.Write(p) + t.r.addStream(p[:n]) + return n, err +} + +// addStream appends one piece of an answer written piece by piece — a +// stream's relayed data line, a part of a rerank answer. The buffer grows as // strings.Builder.Grow grows it (to 2 × its capacity + the line, then the // allocator's size class); the new capacity is reserved before the growth // and the allocator's rounding right after it — the account holds the @@ -141,15 +159,15 @@ func (r *recording) release() { // markForced puts the recording on the row the shutdown's forced settle // writes: recorded, without a body (it is built at the admission, before -// there is an answer) — the request's text is named lost, and for chat the -// answer too. +// there is an answer) — the request's text is named lost, and for chat and +// rerank the answer too (embeddings keep none). func markForced(row *llmlog.GatewayRow, on bool) { if !on { return } row.Recorded = true row.RecordLost = []string{llmlog.RecordLostRequest} - if row.Pipeline == chatPipeline { + if row.Pipeline != embedPipeline { row.RecordLost = append(row.RecordLost, llmlog.RecordLostResponse) } row.RecordLostCause = llmlog.RecordLostShutdown diff --git a/go/internal/oai/record_account_full_test.go b/go/internal/oai/record_account_full_test.go new file mode 100644 index 000000000..72dd59ed9 --- /dev/null +++ b/go/internal/oai/record_account_full_test.go @@ -0,0 +1,53 @@ +package oai_test + +import ( + "strings" + "testing" + + "github.com/GottZ/ctx/internal/backends" + "github.com/GottZ/ctx/internal/llmlog" +) + +// TestRecordedChatWithAFullAccount (issue #571, promise 3 under memory +// pressure): when the recording account cannot take a recorded request's +// texts, the request is answered exactly as without the switch and its row +// is written without them, naming both (record_lost, cause memory) — the +// account is never the request's budget. +func TestRecordedChatWithAFullAccount(t *testing.T) { + answer := `{"id":"gen-1","object":"chat.completion","created":1700000000,"model":"M",` + + `"choices":[{"index":0,"finish_reason":"stop","message":{"role":"assistant","content":"hello"}}],` + + `"usage":{"prompt_tokens":11,"completion_tokens":3,"total_tokens":14}}` + body := `{"model":"pub","messages":[{"role":"user","content":"` + strings.Repeat("w", 4096) + `"}]}` + u := newUpstream(t, answer) + rig := newChatRig(t, []backends.Backend{u.row("spark", backends.TrustFull, 10)}, 4, 1) + rig.ca.Store(recordingConsumer(false)) + off := rig.post(t, body) + // Fill the account to its last byte. + filled := int64(0) + for step := int64(1 << 26); step > 0; step /= 2 { + for llmlog.ReserveRecorded(step) { + filled += step + } + } + defer llmlog.ReleaseRecorded(filled) + rig.ca.Store(recordingConsumer(true)) + on := rig.post(t, body) + rows := rig.rows.all() + defer releaseRows(rows) + if off.status != 200 || on.status != 200 || !sameAnswer(off.body, on.body) { + t.Fatalf("status off %d on %d, answers equal %v — a full account must not change the answer", off.status, on.status, sameAnswer(off.body, on.body)) + } + if len(u.raws) != 2 || string(u.raws[0]) != string(u.raws[1]) { + t.Errorf("the upstream bodies differ with a full account") + } + if len(rows) != 2 { + t.Fatalf("%d rows, want 2", len(rows)) + } + r := rows[1] + stored := llmlog.RecordedGatewayEntry(r) + if !r.Recorded || stored.RequestUser != "" || stored.ResponseContent != "" || r.RecordedHeld != 0 || + strings.Join(r.RecordLost, ",") != "request,response" || r.RecordLostCause != llmlog.RecordLostMemory { + t.Errorf("row with a full account: recorded %v, %d/%d body bytes, holds %d, lost %v cause %q — want recorded, no bodies, nothing held, both lost, memory", + r.Recorded, len(stored.RequestUser), len(stored.ResponseContent), r.RecordedHeld, r.RecordLost, r.RecordLostCause) + } +} diff --git a/go/internal/oai/record_internal_test.go b/go/internal/oai/record_internal_test.go index fd74a8ddf..ebab4b484 100644 --- a/go/internal/oai/record_internal_test.go +++ b/go/internal/oai/record_internal_test.go @@ -90,7 +90,7 @@ func TestForcedRowOfARecordingConsumerNamesWhatItLacks(t *testing.T) { }{ {chatPipeline, []string{llmlog.RecordLostRequest, llmlog.RecordLostResponse}}, {embedPipeline, []string{llmlog.RecordLostRequest}}, - {rerankPipeline, []string{llmlog.RecordLostRequest}}, + {rerankPipeline, []string{llmlog.RecordLostRequest, llmlog.RecordLostResponse}}, } { row := llmlog.GatewayRow{Pipeline: c.pipeline} markForced(&row, true) diff --git a/go/internal/oai/record_test.go b/go/internal/oai/record_test.go index fab1d4f56..906d2e6f0 100644 --- a/go/internal/oai/record_test.go +++ b/go/internal/oai/record_test.go @@ -192,4 +192,8 @@ func TestRecordedRerankKeepsQueryAndDocuments(t *testing.T) { if want := string(q) + "\n" + string(d); stored.RequestUser != want { t.Errorf("recorded rerank request %d bytes, want query, line break and documents (%d bytes)", len(stored.RequestUser), len(want)) } + if stored.ResponseContent != string(on.body) || rows[0].Response != "" { + t.Errorf("recorded rerank answer %q, want the answer the client received %q (the unrecorded row keeps none: %q)", + stored.ResponseContent, on.body, rows[0].Response) + } } diff --git a/go/internal/oai/rerank.go b/go/internal/oai/rerank.go index b8029c620..f657cb982 100644 --- a/go/internal/oai/rerank.go +++ b/go/internal/oai/rerank.go @@ -176,11 +176,16 @@ type rerankCall struct { // scores (sigmoid, in place) — one slice of the answer reserve, made // once per request. logits []float64 + // recording is the capture of a recording consumer's request (record.go; + // off for every other consumer): the query and documents, and the answer + // as written to the client. + recording recording } func newRerankCall(d Deps, w http.ResponseWriter, r *http.Request, ca *auth.ConsumerAuth, entry time.Time, dialect RerankDialect) *rerankCall { s := d.Settings() c := &rerankCall{d: d, w: w, s: s, ca: ca, entry: entry, client: r.Context(), rec: AccessRecordFrom(r.Context()), dialect: dialect} + c.recording.on = ca != nil && ca.RecordBodies if c.rec == nil { c.rec = &AccessRecord{} // outside a model group: filled, never read } @@ -222,6 +227,7 @@ func (c *rerankCall) close() { for _, stop := range c.stops { stop() } + c.recording.release() // what no row of this request took } func (c *rerankCall) refuse(code, message string, shouldRetry bool) { @@ -942,7 +948,11 @@ func (c *rerankCall) success(st *rerankState) embedOutcome { if returnDocs { a.docs = c.req.docs } - if err := writeRerank(c.w, a); err != nil { + var out io.Writer = c.w + if c.recording.on { + out = recordWriter{w: c.w, r: &c.recording} // the bytes the client was written, for its row + } + if err := writeRerank(out, a); err != nil { slog.Warn("gateway: failed to write the answer", "error", err, "request_id", c.w.Header().Get("X-Request-ID")) return embedOutcome{finish: llmlog.FinishAborted} } @@ -1114,19 +1124,18 @@ func (c *rerankCall) record(plan Plan, served *backends.Backend, attempts []llm. if st.usage.PromptTokens > 0 { usage = llmlog.UsageBackend } - request := "" - rc := recording{on: c.ca.RecordBodies} + request, response := "", "" switch { - case rc.on: + case c.recording.on: // A recording consumer's row (issue #571): the whole text of the - // query and the documents, reserved against the recording account - // (record.go). The answer — indexes and scores, the echo repeats the - // documents — is not kept. - if n := rerankLogSize(c.req, noLogLimit); rc.reserve(int64(n)) { + // query and the documents and the answer as the client was written + // it (success), reserved against the recording account (record.go). + if n := rerankLogSize(c.req, noLogLimit); c.recording.reserve(int64(n)) { request = rerankLogText(c.req, n, noLogLimit) } else { - rc.loseBody(llmlog.RecordLostRequest) + c.recording.loseBody(llmlog.RecordLostRequest) } + response = c.recording.streamText() case c.s.BodyLogging == llmlog.BodyLoggingFull || (c.s.BodyLogging == llmlog.BodyLoggingErrors && out.redacted != nil): // The row's text of the query and the documents is sized, then // booked, then written (the embeddings route's rule). @@ -1145,9 +1154,10 @@ func (c *rerankCall) record(plan Plan, served *backends.Backend, attempts []llm. Attempts: attempts, Err: out.redacted, Request: request, + Response: response, BodyLogging: c.s.BodyLogging, } - rc.mark(&row) + c.recording.mark(&row) c.d.Record(row) } diff --git a/go/web/src/lib/api/types.ts b/go/web/src/lib/api/types.ts index afd48f1e9..661df7272 100644 --- a/go/web/src/lib/api/types.ts +++ b/go/web/src/lib/api/types.ts @@ -694,6 +694,8 @@ export interface LLMLogDetail { request_system: string | null request_user: string | null response_content: string | null + /** The row of a recording consumer (metadata.gw.recorded, issue #571): its bodies are whole and can hold credentials in clear text. */ + recorded: boolean } // Source: go/internal/handler/llmlog.go (HandleLLMLogDetail happy path). An @@ -2106,6 +2108,8 @@ export interface GatewayStatus { top_consumers_1h: GatewayTopConsumer[] | null consumers_used_1h: number consumers_expiring: number + /** Ids of the active consumers with record_bodies on, sorted (the tenant's own on the tenant path); [] when none. */ + recording_consumers: string[] /** Server-admin only; not assigned by stampGateway yet (S3) — absent today. */ instance_envelope?: Record /** From 86cd6614bebb17ce4e4f31ac4ab6327453157b64 Mon Sep 17 00:00:00 2001 From: Jan-Stefan Janetzky Date: Fri, 27 Nov 2026 03:30:42 +0100 Subject: [PATCH 06/27] test(web): the status fixtures carry the recording fields GatewayStatus.recording_consumers and LLMLogDetail.recorded are required in the TS types; the status page fixtures name them. Co-Authored-By: Claude Opus 5.5 --- go/web/src/routes/status/gateway.test.ts | 2 ++ go/web/src/routes/status/llmlog-detail.svelte.test.ts | 1 + 2 files changed, 3 insertions(+) diff --git a/go/web/src/routes/status/gateway.test.ts b/go/web/src/routes/status/gateway.test.ts index a90087bc5..b6e988135 100644 --- a/go/web/src/routes/status/gateway.test.ts +++ b/go/web/src/routes/status/gateway.test.ts @@ -22,6 +22,7 @@ const ADMIN: GatewayStatus = { top_consumers_1h: [], consumers_used_1h: 3, consumers_expiring: 2, + recording_consumers: [], auth: { invalid_key: 5 }, } @@ -34,6 +35,7 @@ const TENANT_GATEWAY: GatewayStatus = { top_consumers_1h: [], consumers_used_1h: 1, consumers_expiring: 0, + recording_consumers: [], } function tt(origin: string, depth: string): DispatchTenantTarget { diff --git a/go/web/src/routes/status/llmlog-detail.svelte.test.ts b/go/web/src/routes/status/llmlog-detail.svelte.test.ts index 4f847cf0a..edafe281f 100644 --- a/go/web/src/routes/status/llmlog-detail.svelte.test.ts +++ b/go/web/src/routes/status/llmlog-detail.svelte.test.ts @@ -22,6 +22,7 @@ function detail(over: Partial = {}): LLMLogDetail { request_system: 'you are ctx', request_user: 'hello', response_content: 'hi', + recorded: false, ...over, } } From b78ddfec9c07050aa1cbdaa423526584476bb2f6 Mon Sep 17 00:00:00 2001 From: Jan-Stefan Janetzky Date: Fri, 27 Nov 2026 05:15:02 +0100 Subject: [PATCH 07/27] feat(gateway): a recording consumer's request is held in context_llm_recordings before it is served, and refused when it cannot be (migration 197) The first round recorded on a best-effort basis: the whole bodies rode the asynchronous llmlog row after the answer, a full 128 MiB account left them out, a full writer queue or a failed insert lost the row, and a refused request left none. Now a recording consumer's request passes a recording stage behind the door (oai.RecordingStage) and is committed to the new table context_llm_recordings (body as read, bytea) before the first backend attempt; a request that cannot be held is 503 recording_unavailable and reaches no backend. A non-streamed answer is committed before it is written (else the same 503 instead of the answer); a stream's relayed lines are kept before the relay takes them and committed when it ends; every request refused after the door leaves its row. Memory beyond the request's own in-flight bookings is held against one account with backpressure (wait, then refuse), never dropped. GET /api/status counts admitted, recorded, unrecordable and unfinished requests per recording consumer and process. The llmlog row is the row of every consumer plus metadata.gw.recorded and recording_id; the first round's whole-body llmlog rows, their account, record_lost and the export seal are gone. The consumer detail shows the recording line only while it is on. Co-Authored-By: Claude Opus 5.5 --- docs/api.md | 16 +- docs/operations.md | 58 +- docs/security.md | 8 +- go/cmd/ctxd/gateway.go | 8 +- go/cmd/ctxd/model_group.go | 12 +- go/cmd/ctxd/v1_record_integration_test.go | 459 +++++++---- .../v1_record_latency_integration_test.go | 92 +++ go/internal/backends/classify.go | 2 + go/internal/handler/llmlog.go | 10 +- go/internal/handler/llmlog_test.go | 2 +- go/internal/handler/model_consumers.go | 4 +- ...model_consumers_record_integration_test.go | 4 +- go/internal/handler/status.go | 13 +- go/internal/handler/status_gateway.go | 35 +- go/internal/handler/status_llmlog_test.go | 15 +- go/internal/handler/status_test.go | 5 +- go/internal/llmlog/gateway.go | 110 +-- go/internal/llmlog/gateway_recorded_test.go | 236 ------ go/internal/llmlog/llmlog.go | 18 +- .../llmlog/llmlog_readers_census_test.go | 124 --- go/internal/llmlog/recorded.go | 124 --- .../llmlog/recorded_integration_test.go | 118 --- go/internal/llmlog/recordings.go | 204 +++++ .../llmlog/recordings_integration_test.go | 203 +++++ .../llmlog/recordings_readers_census_test.go | 105 +++ go/internal/llmlogexport/export.go | 37 +- .../export_recorded_integration_test.go | 76 -- go/internal/oai/chat.go | 118 ++- go/internal/oai/chat_harness_test.go | 6 + go/internal/oai/chat_stream.go | 12 +- go/internal/oai/embed_harness_test.go | 3 + go/internal/oai/embeddings.go | 52 +- go/internal/oai/errors.go | 4 + go/internal/oai/errors_test.go | 1 + go/internal/oai/export_test.go | 15 + go/internal/oai/forced.go | 1 - go/internal/oai/record.go | 745 +++++++++++++++--- go/internal/oai/record_account_full_test.go | 53 -- go/internal/oai/record_internal_test.go | 106 --- go/internal/oai/record_route_test.go | 579 ++++++++++++++ go/internal/oai/record_test.go | 199 ----- go/internal/oai/rerank.go | 103 ++- go/internal/oai/rerank_harness_test.go | 3 + go/internal/schemacontract/manifest.json | 136 +++- ...ecord_bodies_migration_integration_test.go | 34 +- .../197_model_consumer_record_bodies.sql | 99 ++- go/web/src/lib/api/types.ts | 25 +- .../src/routes/gateway/ConsumerDetail.svelte | 8 +- go/web/src/routes/gateway/ConsumerRow.svelte | 5 +- .../routes/gateway/ConsumerRow.svelte.test.ts | 20 +- go/web/src/routes/gateway/format.ts | 9 +- .../status/llmlog-detail.svelte.test.ts | 1 - test.sh | 7 +- 53 files changed, 2768 insertions(+), 1674 deletions(-) create mode 100644 go/cmd/ctxd/v1_record_latency_integration_test.go delete mode 100644 go/internal/llmlog/gateway_recorded_test.go delete mode 100644 go/internal/llmlog/llmlog_readers_census_test.go delete mode 100644 go/internal/llmlog/recorded.go delete mode 100644 go/internal/llmlog/recorded_integration_test.go create mode 100644 go/internal/llmlog/recordings.go create mode 100644 go/internal/llmlog/recordings_integration_test.go create mode 100644 go/internal/llmlog/recordings_readers_census_test.go delete mode 100644 go/internal/llmlogexport/export_recorded_integration_test.go delete mode 100644 go/internal/oai/record_account_full_test.go delete mode 100644 go/internal/oai/record_internal_test.go create mode 100644 go/internal/oai/record_route_test.go delete mode 100644 go/internal/oai/record_test.go diff --git a/docs/api.md b/docs/api.md index 95ac7f7a2..a7995be66 100644 --- a/docs/api.md +++ b/docs/api.md @@ -35,12 +35,12 @@ hit it. Not a settings key: changing it is a rebuild, deliberately. | `POST /webhooks/github/{project_id}` | **Unauthenticated** GitHub inbound (workflow W13) — HMAC-SHA256 over the raw body against the per-project sealed secret replaces the api key. Bad/absent signature or unknown project ⇒ uniform **401** with ZERO DB write; valid ⇒ **202** and one redelivery-idempotent inbox row; per-project rate limit ⇒ **429**. The inbox is a debounced sync **trigger**, never an authority (see [Webhooks (inbound)](#webhooks-inbound-workflow-w13)). | | `GET\|PUT\|DELETE /api/settings[/{key}]` | Runtime config overrides, **admin-gated incl. reads** (see [Settings API](#settings-api)). | | `GET\|PUT\|DELETE /api/secrets[/{name}]` | Write-only sealed credentials, **admin-gated**: PUT creates/rotates (value never returned), GET lists metadata + `referenced_by`, DELETE 409s while referenced — by a `secret_ref` setting or a backend pool row's `api_key_ref` (entries prefixed `backend:`, remediation text per reference type) (see [security](security.md#sealed-secrets--break-glass)). | -| `GET /api/status` | **Admin dashboard** aggregate from the process-wide status collector: health, backend pool (`pool.Status()` shape), dream queue + mode, 24h LLM telemetry (with an `llm_24h_complete` attribution flag), and the disable-profile registry line (`profiles`: slim `{name, scope, label, active, member_count}` rows, U01-W7 — replaced the retired `gaming:{active}` field; member names load on-demand via `disable-profile-list`). A server-admin additionally sees `advisories` (`[{subject, state}]`, omitted when empty): named reasons for states the frame can only show as an absence — today exactly `backend_pool: empty` (fresh install, nobody seeded yet; deliberately NOT in the public `/health` body), and `llmlog` (`{insert_failures, insert_dropped, recorded_bodies_lost, recorded_held_bytes}`, present even at 0): the process-wide count of `context_llm_log` rows that never landed — inserts the database refused or that timed out, and rows dropped by the bounded insert queue ([operations](operations.md#shutdown-and-the-llm-log-write-path)) — and of the rows of recording consumers written without a body they should carry (`metadata.gw.record_lost`, [operations](operations.md#recording-a-consumer)); `recorded_held_bytes` is what recorded texts hold of their 128 MiB account right now, and `foreign_load` (present only while an enabled, not profile-parked `_global` backend row carries `metadata.foreign_load_probe`): one row per probed engine origin, `{target, probe, backends, running, active, held, delta, suspected, since, suspected_hourly, hourly{hour, engine_requests, ctx_requests}, probe_error, probed_at}` — the requests the engine holds (read from its own `GET /metrics` every `status.foreign_load_interval` and on each hour boundary, whether or not anyone reads the status) against the dispatcher's held leases, and hourly its finished responses against ctx's logged calls; evidence that ctx is the only load source of the GPU ([operations](operations.md#foreign-load-detector)), and `query_synthesize` (`{p95_ms, avg_ms, samples, since}`, present with no sample too): the latency of query synthesis from an in-memory ring of the last 512 syntheses since process start — per synthesis the wait-free wire duration of the backend that answered (or failed last) — the calls with a wire time among those `llm_24h` averages for pipeline `query-synthesize` (a call that reached no backend is not timed), the dispatcher's queue wait not included; `p95_ms` (nearest rank) is `null` below 20 samples, `avg_ms` without a sample; `since` (RFC3339, UTC, whole seconds) is where the window starts — the process start, or the oldest retained sample once more than 512 were seen. Read from process memory, never from the database. Never on the tenant view. The server-admin `dispatch` section carries per target `held` (ALL slot-holding leases, internal and external — the number the foreign-load detector compares) split into `held_internal` / `held_external`, `inflight_internal`, the external offer (`internal_reserved`, `external_offered`, `external_capacity`), the external class's wait view `external` and its refusals `external_rejects {cap, not_offered}`, the same two for the external bulk class (`external_bulk`, `external_bulk_rejects {cap, not_offered}`; `held_external` counts the leases of both external classes), and buckets with `tenant_id` and `class` (`interactive` \| `external` \| `external_bulk`; an external consumer's bucket key is `_consumer:` in either external class). The tenant-admin `dispatch_tenant` view never shows external load: `busy` and `depth` read only the internal leases and queues, and no external bucket appears. Served from a cache (N pollers cost one collection). Carries hostnames, so it is admin-gated where `/health` stays anonymous. Opens to a tenant-admin with a reduced own-tenant view (see [multi-tenancy](multi-tenancy.md#telemetry-per-tenant-views)). | +| `GET /api/status` | **Admin dashboard** aggregate from the process-wide status collector: health, backend pool (`pool.Status()` shape), dream queue + mode, 24h LLM telemetry (with an `llm_24h_complete` attribution flag), and the disable-profile registry line (`profiles`: slim `{name, scope, label, active, member_count}` rows, U01-W7 — replaced the retired `gaming:{active}` field; member names load on-demand via `disable-profile-list`). A server-admin additionally sees `advisories` (`[{subject, state}]`, omitted when empty): named reasons for states the frame can only show as an absence — today exactly `backend_pool: empty` (fresh install, nobody seeded yet; deliberately NOT in the public `/health` body), and `llmlog` (`{insert_failures, insert_dropped}`, present even at 0): the process-wide count of `context_llm_log` rows that never landed — inserts the database refused or that timed out, and rows dropped by the bounded insert queue ([operations](operations.md#shutdown-and-the-llm-log-write-path)), and `foreign_load` (present only while an enabled, not profile-parked `_global` backend row carries `metadata.foreign_load_probe`): one row per probed engine origin, `{target, probe, backends, running, active, held, delta, suspected, since, suspected_hourly, hourly{hour, engine_requests, ctx_requests}, probe_error, probed_at}` — the requests the engine holds (read from its own `GET /metrics` every `status.foreign_load_interval` and on each hour boundary, whether or not anyone reads the status) against the dispatcher's held leases, and hourly its finished responses against ctx's logged calls; evidence that ctx is the only load source of the GPU ([operations](operations.md#foreign-load-detector)), and `query_synthesize` (`{p95_ms, avg_ms, samples, since}`, present with no sample too): the latency of query synthesis from an in-memory ring of the last 512 syntheses since process start — per synthesis the wait-free wire duration of the backend that answered (or failed last) — the calls with a wire time among those `llm_24h` averages for pipeline `query-synthesize` (a call that reached no backend is not timed), the dispatcher's queue wait not included; `p95_ms` (nearest rank) is `null` below 20 samples, `avg_ms` without a sample; `since` (RFC3339, UTC, whole seconds) is where the window starts — the process start, or the oldest retained sample once more than 512 were seen. Read from process memory, never from the database. Never on the tenant view. The server-admin `dispatch` section carries per target `held` (ALL slot-holding leases, internal and external — the number the foreign-load detector compares) split into `held_internal` / `held_external`, `inflight_internal`, the external offer (`internal_reserved`, `external_offered`, `external_capacity`), the external class's wait view `external` and its refusals `external_rejects {cap, not_offered}`, the same two for the external bulk class (`external_bulk`, `external_bulk_rejects {cap, not_offered}`; `held_external` counts the leases of both external classes), and buckets with `tenant_id` and `class` (`interactive` \| `external` \| `external_bulk`; an external consumer's bucket key is `_consumer:` in either external class). The tenant-admin `dispatch_tenant` view never shows external load: `busy` and `depth` read only the internal leases and queues, and no external bucket appears. Served from a cache (N pollers cost one collection). Carries hostnames, so it is admin-gated where `/health` stays anonymous. Opens to a tenant-admin with a reduced own-tenant view (see [multi-tenancy](multi-tenancy.md#telemetry-per-tenant-views)). | | `POST /api/manage` (`eject-mode`, alias `gaming-mode`) | Canonical shim for the reserved disable-profile `eject` (092): read = legacy gaming shape, mutation = server-admin toggle with implicit blackout confirm. Since U01-W5 a profile-only write (the legacy `gaming.active` settings dual-write was retired); the eject profile is the single source of truth. A toggle whose backend-pool or settings reload fails after the write answers `500` `{"success": false, "persisted": true, "error": "persisted but reload failed — …"}`: the toggle is written. | | `POST /api/manage` (`disable-profile-list/create/update/delete/toggle`) | Disable-profile registry (tenant-admin; tenant profiles may only contain own-scope backends, `_global` profiles are operator-owned). Toggle returns `{profile, impact, as_of}`; blacking out a whole role requires `confirm_role_blackout` (else 422; `dry_run` supported); the reserved `eject` profile is not deletable. | | `POST /api/manage` (`backend-create`/`backend-update`, field `disable_profiles`) | Profile membership as a backend property: list of profile NAMES (key absent = unchanged, `[]` = detach all); joins sync in the same transaction as the backend write. A tenant-admin may attach its OWN backend to `_global` profiles (self-disable) or its own tenant profiles; a scoped profile never contains foreign-scope backends. `backend-list` echoes `disable_profiles` including inactive membership. | | `GET\|PUT\|DELETE /api/graph/category-hues[/{category}]` | Per-category graph HUE overrides (093, AM-2): GET (**any valid key** — the graph is a member surface) returns the resolved sparse map `{category: hue}` for the caller's `{_global, tenant}` view, tenant beating `_global` per category; PUT `{"hue":0–359}`/DELETE (**tenant-admin**) write the caller's own scope (operator → `_global`), never a client-supplied one. Only the hue is overridden — sat/lum stay theme tokens, so every choice sits inside the G1a contrast sweep. Absent override = seeded hash colour. UI: the hue wheel at `/settings/hues` (U02-W6) — markers sit at perceptual OKLCH angles for distance judgement, the stored value is always the HSL degree. | -| `GET /api/llmlog` | **Admin** LLM telemetry table (`?limit=`/`pipeline=`/`errors_only=`). NEVER returns the `request_system`/`request_user`/`response_content` body columns (the prompt shadow corpus); the `error` is normalized to a class + 256-char-capped detail. Tenant-admin sees only its own tenant's rows. `?consumer_id=` narrows the list to one model consumer (a malformed id answers `400 invalid consumer_id`); every entry carries `consumer_id` (`null` for knowledge-key and background rows). A tenant-admin sees the last 30 days of its own knowledge keys’ and model consumers’ rows; a foreign or unknown `consumer_id` answers the same empty list. The detail `GET /api/llmlog/{id}` of a consumer row stays server-admin-only (uniform 404) — see [usage API](#usage-api-get-apiusage-get-apiusageconsumers); its `detail` carries `recorded` (`true` for the row of a recording consumer, whose bodies are whole and can hold credentials in clear text). | +| `GET /api/llmlog` | **Admin** LLM telemetry table (`?limit=`/`pipeline=`/`errors_only=`). NEVER returns the `request_system`/`request_user`/`response_content` body columns (the prompt shadow corpus); the `error` is normalized to a class + 256-char-capped detail. Tenant-admin sees only its own tenant's rows. `?consumer_id=` narrows the list to one model consumer (a malformed id answers `400 invalid consumer_id`); every entry carries `consumer_id` (`null` for knowledge-key and background rows). A tenant-admin sees the last 30 days of its own knowledge keys’ and model consumers’ rows; a foreign or unknown `consumer_id` answers the same empty list. The detail `GET /api/llmlog/{id}` of a consumer row stays server-admin-only (uniform 404) — see [usage API](#usage-api-get-apiusage-get-apiusageconsumers). | | `GET /api/audit` | **Admin or tenant-admin** history of the access-deciding tables ([security](security.md#audit-trail)): `?entity=` (required) one of `api_key`, `tenant_quota`, `gateway_limits`, `model_alias`, `model_consumer`, `model_key`, `model_grant`, `consumer_usage`, `scope_purge`, `forge_sync`, `instance`; `id=` an exact `entity_key` (a key id, a quota scope); `since=` RFC 3339, rows strictly newer; `limit=` a positive integer, clamped to `audit.max_limit` (default `200`, also the page size without `limit`; a configured `0` falls back to the default). Newest first (`created_at`, then `id`). `400` for a missing or unknown `entity`, for `setting`/`secret`/`backend` (their history stays on their own surfaces, e.g. `GET /api/settings/{key}`), for an `id` that is not valid UTF-8 or carries NUL, for a malformed `since` and a non-positive or non-numeric `limit`. Response `{success, entity, rows:[{id, entity_key, scope, action, old_value, new_value, api_key_id, actor_label, metadata, created_at}]}`. `model_consumer` and `model_key` rows are written by the triggers of migration 161, `model_alias` rows by those of migration 162 (a `_global` alias carries no tenant, so its rows are server-admin-only), `instance` rows by those of migration 163 (`entity_key` `self`; a rotation is a `rotate` row with the old and the new `instance_id`, never the secret); `model_grant` rows by the trigger of migration 164 (`entity_key` `:`, actions `grant`/`ungrant`, `scope` the consumer's `tenant_scope`); `scope_purge` rows are written by `manage purge`, one per run (`entity_key` the scope, action `purge`); `forge_sync` rows by `forge-conflict-resolve` and `forge-stamp-reset` (`entity_key` the block, or the project for a reset of all its mappings; actions `resolve-local`, `resolve-remote`, `stamp-reset`; `metadata.tenant_id` the project's tenant, [forge sync](#forge-sync-manage-actions-workflow-i-f)); `gateway_limits` and `consumer_usage` answer `rows: []` until their writers ship. A server-admin reads every row unredacted. A tenant-admin reads only rows whose `metadata.tenant_id` is its own tenant (filtered in SQL): another tenant's id answers the same `200` with `rows: []` as an id that does not exist, rows of a scope no tenant owns are server-admin-only, and so is `instance` (`rows: []` for a tenant-admin). For a tenant-admin the actor is **redacted** unless it provably is a non-server-admin key of the reader's own tenant: `actor_label` becomes `"server-admin"`, `api_key_id` `null`, `metadata.actor_principal` is dropped; `metadata.actor_tenant_id`/`actor_server_admin` (the inputs of that decision) and every other `actor_*` key (any letter case) are never sent to a tenant-admin, and neither are `is_admin` and `principal_id` inside the `old_value`/`new_value` of `api_key` rows (dropped on every key row — `api-key-list` shows neither). An `api_key` `update` whose only change lies in those two fields is left out of a tenant-admin's answer; the rows are filtered after `limit`, so such a page can hold fewer than `limit` rows while older rows exist — fewer rows than `limit` is not the end of the history. | | `GET /api/events` | **Admin-only** SSE live stream (`text/event-stream`) for the dashboard. The collector diffs its snapshot ONCE per tick and fans `status`/`backends`/`llmcalls` events to every connection; a new connection gets the full state first, then diffs. The pull path additionally carries `guard_review_by_scope` (S6): one four-tuple per scope the CALLER may read, out of the same per-tick generation (0 extra queries), per-credential and therefore never in the shared snapshot or the push frame — the /guard page polls and compares this vector (list and counter run on two different scope predicates: `ReadScopes` vs. home scope) and reloads when it moves; absent section renders '—', never '0'. The `status` frame carries the `guard_review` section (same generation as the pull paths, S2): present-with-zeros means a freshly measured empty queue, an ABSENT section means no fresh generation — and its `built_at` stamp is diff-neutral (zeroed in the diff key like `as_of`), so a walking stamp alone never fires a frame. One tick costs at most ONE frame per event kind: the telemetry rows of a tick ride a single `llmcalls` frame `{rows, count}`, and above `events.llmcall_coalesce_threshold` it degrades to the content-free `{kind:"llmcalls-bulk", count, cursor}` refetch signal (the client reloads over `GET /api/llmlog`) — the same coalescing doctrine `project.events.coalesce_threshold` runs on the domain-event hub. `hb` keepalive event (`CTX_EVENTS_PING_INTERVAL`) carrying `{last_good_at, degraded, health}` — a REAL named event, not an SSE comment, so the client can observe it: `last_good_at` is the newest tick whose DB-backed reads all answered, so a stream that keeps arriving while that stamp freezes means "transport fine, server blind" (`as_of` cannot say this — it advances on failed reads too). The SPA consumes it (S4): the `/status` SSE client arms a payload+transport watchdog (2.5 × ping interval) that flips its state to `stale` when the stamp stops advancing or frames stop entirely — `stale ≠ open` reactivates the page's poll fallback with no call-site change, and a `ConnState` live-region indicator (dot + word, `degraded>0` → `partial`) renders it in the page head. The watchdog is opt-in per stream: `/api/project/events` keeps its comment keepalive and stays unwatched. A rolling 90s write deadline that outlives the absolute server `WriteTimeout`, the `CTX_EVENTS_MAX_CONNECTIONS` cap → 429 (client degrades to polling), and an in-stream re-auth every 12th tick that ends the stream on key revocation. | | `GET /api/project/events` | **Member** SSE domain-event stream (`text/event-stream`, workflow W9) for live board / issue-list updates. A key receives IDS-ONLY frames — `project` events `{kind, project_id, op, block_ids}` or the coalesced `{kind:"issues-bulk", project_id, count}`; NEVER title/content/body (the client refetches over the read API). Frames are **scope-filtered at the fan-out**: only the caller's readable project scopes, never another tenant's. Optional `?project_id=` pins the stream to one project (foreign/unknown ⇒ 404 uniform). Per-**tenant** connection cap (`project.events.max_connections`) → 429; `: ping` keepalive; a 10k-import burst collapses to one `issues-bulk` frame per tick (`project.events.flush_interval` / `coalesce_threshold`). In-stream re-auth recomputes the caller's scope tags from the FRESH read set every ~12 flush ticks: a revoked key or a tenant change ends the stream, and a revoked cross-tenant **scope grant** (tenant/role unchanged) drops that scope's frames — separate from the server-admin telemetry `/api/events`. | @@ -271,7 +271,7 @@ A **model consumer** is an external caller of the models ctx serves (`/v1`, not **Field rule — revoking is always allowed, granting needs a release.** On `model-consumer-update` each field is compared with the consumer as it stands (under its row lock, so a concurrent write is what the comparison sees): narrowing `allowed_cidrs` (a list whose every prefix lies inside a current one, or a list where there was none), `tenant_scope` → null, `all_models` → false, `allow_plaintext` → false, a higher `prompt_sensitivity`, a lower `fair_weight`, `admission_lane` `urgent` → `bulk`, deactivating (`active` false), `label` and `description` — always open to a tenant-admin. Removing an id from `models` is revoking too. Setting or changing `tenant_scope`, `all_models` true, adding an id to `models`, widening or removing `allowed_cidrs` and reactivating are **granting**: tenant-admin only with self-service. `kind = ctx-peer` (create), a lower `prompt_sensitivity`, `allow_plaintext = true`, a higher `fair_weight`, `admission_lane = urgent` and `record_bodies = true` stay **server-admin even with self-service**; on create they are measured against the defaults (`app`, `credentials`, `1`, `bulk`, no plaintext, no recording). `record_bodies` → `false` is revoking, open to a tenant-admin. **Peer row tier:** every granting change of a `ctx-peer` consumer — rotation, a granting update, reactivation — is server-admin only. `kind` is fixed at create; `tenant_id`, the peer binding and any key expiry cannot be updated — an unknown field is a `400`, `expires_at` included (a new expiry needs a new key: `model-key-rotate`). -**Recording** (`record_bodies`, migration 197, issue #571). With `record_bodies: true` every gateway row of the consumer keeps its request and answer **in full** — whatever `gateway.body_logging`, the alias, `prompt_sensitivity`, the body scan or `Ctx-Sensitivity` say, without the 64 KiB cut, credentials in a prompt included — and is marked `metadata.gw.recorded` ([telemetry](#telemetry--logging), [security](security.md#gateway-telemetry-v1-v2)). Switching it on (create, or update from `false`) needs `confirm_record_bodies: true`, else `400` with `record_bodies:true stores every request and answer of this consumer in full in the LLM log — credentials in a prompt included, in clear text, readable by server-admins — requires confirm_record_bodies:true`; the tier check comes first, so a tenant-admin gets the shared `403 admin key required` with or without the confirmation. Sending the value a consumer already has is no change (no tier, no confirmation); `confirm_record_bodies` alone changes nothing; `null` is a `400`. Every change is an audited `update` row (`record_bodies` in `old_value`/`new_value`). A switch applies from the consumer's next request (the door reads it with the key, migration 197's `ctx_model_auth` column); a request already running keeps what it was admitted with. +**Recording** (`record_bodies`, migration 197, issue #571). With `record_bodies: true` every request the consumer sends through the gateway is held in `context_llm_recordings` **before it is served**: the body as the gateway read it, byte for byte — whatever `gateway.body_logging`, the alias, `prompt_sensitivity`, the body scan or `Ctx-Sensitivity` say, no cut, credentials in a prompt included —, then the answer the client got and the outcome ([telemetry](#telemetry--logging), [security](security.md#gateway-telemetry-v1-v2), [operations](operations.md#recording-a-consumer)). Switching it on (create, or update from `false`) needs `confirm_record_bodies: true`, else `400` with `record_bodies:true holds every request and answer of this consumer in full in context_llm_recordings — credentials in a prompt included, in clear text, readable in the database — requires confirm_record_bodies:true`; the tier check comes first, so a tenant-admin gets the shared `403 admin key required` with or without the confirmation. Sending the value a consumer already has is no change (no tier, no confirmation); `confirm_record_bodies` alone changes nothing; `null` is a `400`. Every change is an audited `update` row (`record_bodies` in `old_value`/`new_value`). A switch applies from the consumer's next request (the door reads it with the key, migration 197's `ctx_model_auth` column); a request already running keeps what it was admitted with. **Model grants** (`models`, migration 164). `all_models: true` releases every model alias the consumer can see; otherwise only the aliases listed in `models` — by **id**, never by name: a deleted alias takes its grants with it, and an alias created later under the same name is granted to no one. `models` is a target set (duplicates and spellings are folded, the answer lists them sorted; on update `null` is a `400` and `[]` removes every grant; on create `null`, `[]` and an absent field all mean none); the server turns it into the grants to add and to remove, in the transaction of the update. Every id it **adds** must be one the consumer's own `tenant_scope` is offered — an enabled alias with a valid policy, `_global` or of that scope, and not a `_global` alias that a tenant alias of the same name (enabled or not) takes the place of; a consumer without `tenant_scope` is offered `_global` aliases only, and so is a `ctx-peer` consumer whatever its `tenant_scope` — a peer resolves model names against `_global` aliases only. The caller's own scope plays no part. Any other id — unknown, deleted, disabled, invalid, of another scope, shadowed — is `400` with `"param": "models"` and one text for all these reasons (a malformed id is a `400` at `models` as well); when the scope changes in the same update, the new scope decides. An id the consumer already holds is not judged again, so a grant stays when its alias is disabled later or a later `tenant_scope` change hides it — it then releases nothing (the request time checks visibility again). The list is judged against the server's in-memory alias catalog, which follows an alias write within moments; an alias created a moment ago may still be a `400`. Without the catalog (a wiring fault) a `models` write that adds an id is `503`; removing grants still works. Deleting an alias that an **active** consumer holds an explicit grant on is `409` with `"code": "model_granted"` and `"count"` — the number of such consumers, never who they are; `all_models` is no grant and does not count. Remove the alias from their `models`, or deactivate them, first; grants of inactive consumers go with the alias. A held grant that its consumer can no longer see — its alias was disabled, or a later `tenant_scope` change hid it — releases nothing but still counts for this `409` until it is removed from `models` (or the consumer is deactivated). The SPA's create dialog (`/gateway`, wave W05-06) is a client of exactly this rule: it offers the aliases of the chosen `tenant_scope` the way the server's offer does (enabled ones, a tenant alias in place of the `_global` one of the same name, shadowing by presence), sends the picked **ids** as `models` (or `all_models: true`), never sends `kind`, and shows a `400` at `models` in the dialog. @@ -285,7 +285,7 @@ A **model consumer** is an external caller of the models ctx serves (`/v1`, not **Reading.** A consumer reads as `{id, tenant_id, tenant_slug, label, description, kind, tenant_scope, all_models, models, prompt_sensitivity, fair_weight, admission_lane, allowed_cidrs, allow_plaintext, record_bodies, active, status, last_used_at, created_at, created_by_label, keys, keys_total, peer}` (`record_bodies` for every reader, tenant-admins included); a key as `{id, hint, status, created_at, expires_at, revoked_at, rotated_from, last_used_at}`. `status` of a consumer: `inactive`; `no_key` (no live key); `rotating` (two live keys); `expiring` (one live key expiring within `gateway.key_expiry_warn`, 14 d); `active`. Of a key: `revoked` ≻ `expired` ≻ `superseded` (live, but a newer live key exists — its grace runs) ≻ `expiring` ≻ `active`. The server computes both; a client never judges expiry by its own clock. `peer` (`{instance_id, bound_at}`) is null without a binding and for every reader below server-admin; `created_by_label` reads `"server-admin"` to a tenant-admin unless the creating key is a non-server-admin key of its own tenant, and is null once the creating key is deleted. `last_used_at` has 60 s resolution. -- `model-consumer-list` lists newest first. `status` is a list of the five statuses or `["all"]`; absent = the four statuses of an active consumer. `q` is a label prefix (case-insensitive, `%` and `_` literal). `limit` defaults to and is capped at `gateway.consumer_list_max_limit` (100); `next_cursor` is the opaque token of the next page, `null` on the last; a malformed cursor is a `400` (it is opaque, not signed: a well-formed one only moves the keyset position within the caller's own reach). Every filter runs in SQL — a page of inactive consumers never hides the active ones behind it. The list carries the live keys only; `keys_total` counts the whole chain. The SPA's `/gateway` list ([multi-tenancy](multi-tenancy.md#admin-tiers)) is a client of exactly this form: it sends the status set explicitly (`["all"]` for all five), sends no `limit` (its page size is the server's cap), hands `next_cursor` through untouched and renders `status` as received — and `record_bodies` as a `recording` badge on the row and a `recording` line in the consumer detail's policy card (the SPA does not switch it; that is `model-consumer-update`). +- `model-consumer-list` lists newest first. `status` is a list of the five statuses or `["all"]`; absent = the four statuses of an active consumer. `q` is a label prefix (case-insensitive, `%` and `_` literal). `limit` defaults to and is capped at `gateway.consumer_list_max_limit` (100); `next_cursor` is the opaque token of the next page, `null` on the last; a malformed cursor is a `400` (it is opaque, not signed: a well-formed one only moves the keyset position within the caller's own reach). Every filter runs in SQL — a page of inactive consumers never hides the active ones behind it. The list carries the live keys only; `keys_total` counts the whole chain. The SPA's `/gateway` list ([multi-tenancy](multi-tenancy.md#admin-tiers)) is a client of exactly this form: it sends the status set explicitly (`["all"]` for all five), sends no `limit` (its page size is the server's cap), hands `next_cursor` through untouched and renders `status` as received — and `record_bodies` as a `recording` badge on the row and, only while it is on, a `recording` line in the consumer detail's policy card (the SPA does not switch it; that is `model-consumer-update`). - `model-consumer-get` adds the chain (newest first, at most `gateway.consumer_chain_max` = 50; `keys_truncated` says more exist) and the **audit trail**: the newest `gateway.consumer_audit_trail_max` (20) rows of `model_consumer`, `model_key` and `gateway_limits` whose entity is the consumer or a key of the returned chain (older keys' rows need `GET /api/audit?entity=model_key&id=…`), each with its `entity_type`, redacted for a tenant-admin exactly as `GET /api/audit` redacts ([security](security.md#audit-trail)) — the cap applies before the redaction leaves out invisible updates, so a trail may hold fewer rows than the cap. - `model-key-history` pages through all keys of a consumer, revoked and expired ones included, with the same `cursor`/`limit`/`next_cursor` as the list. @@ -566,7 +566,7 @@ message — the verdict lives in the body, like every `backend-test` outcome. **Capabilities (probe).** Every row in `backend-list` (and in the `backend-create`/`-update` answers) carries `capabilities`: `{"vision": true|false|null, "probed_at": ""|null, "source": "…", "reason"?: "…"}` — what the row's engine reported it can do, asked by ctx itself instead of a setting someone has to know about. Sources by row: `protocol` `openai` with `provider_class` `generic` or `llamacpp` asks `GET /get_model_info` (SGLang, field `has_image_understanding` ⇒ `source` `sglang:/get_model_info has_image_understanding`) and then `GET /props` (llama.cpp, field `modalities.vision` ⇒ `llamacpp:/props modalities.vision`); `provider_class` `openrouter` reads `GET /v1/models` once per round and looks up the model the row sends for each of its roles (`model_map` per role, else `default`) — the row is image-capable only when every one of them lists `image` in `architecture.input_modalities` (`openrouter:/api/v1/models architecture.input_modalities`), one text model makes it `false`, one unlisted model `null`. Every other row (`ollama`, `anthropic`, `rerank`, a `ctx` peer) is not probed. The probe sends the row's key as `Bearer` and its `extra_headers`, to the row's own origin only, through the same client posture as its inference calls (a tenant row through the SSRF guard). At most 8 rows are probed at once; an engine answer is read up to 1 MiB, the model list up to 4 MiB. Fail-closed: a timeout (3 s per row), a non-200 answer, an answer past its cap, an unreadable body or a missing field leave `vision` `null` with `source` `unknown` and a value-free `reason` (`timeout`, `unreachable`, `http_status_`, `no_endpoint`, `no_field`, `bad_body`, `not_listed`, `no_model`, `not_probed`, `api_key_ref_unresolved`) — never a guessed `true`. A disabled row and a row of an active disable profile are not probed (`not_probed` until they serve again). The probe runs at boot and every `pool.capability_probe_interval` (default 600 s) over every row, and after every pool reload over the rows without an answer for their current configuration — see [operations](operations.md#backend-capability-probe); a row whose `base_url`, `protocol`, `provider_class` or role models change reads `null` until its next round. The server-admin `GET /api/status` lists the same per row under `dispatch.targets[].capabilities` (`[{backend, capabilities}]`, the rows behind each origin). The answers feed the effective vision of the [model aliases](#model-aliases-model-alias-). -**Failover classes.** Every failed attempt is classified once (`internal/backends.Classify`) into a class that decides whether the chain goes on to the next backend and how long the failed row sorts last (the cooldown is an order hint — a row in cooldown stays reachable at the end of the chain). By status: `500` stops the chain (the server ran the request); `502`/`503`/`504` and any other 5xx are `gateway` (next, 30 s); `429` is `rate_limit` (next, `Retry-After` or 60 s, at most 5 min); `402` is `billing` (next, 1 h); `401`/`403` are `auth` (next, 15 min); `400`/`404`/`413` and any other status below 500 are `bad_request` (next, no cooldown); OpenRouter's "no allowed providers" is `no_providers` (next, 1 h); a transport failure goes next with 30 s; the attempt timeout stops the chain. An error event inside an HTTP-200 stream is classified by its code, on every provider class: the anthropic wire's error types and the codes of the [gateway vocabulary](#openai-compatible-api-v1) each take the class their HTTP status gets — `rate_limit_exceeded`, `server_busy`, `concurrency_limit_exceeded`, `insufficient_quota` are `rate_limit`; `upstream_unavailable`, `server_overloaded`, `internal_error`, `service_unavailable`, `model_unavailable`, `no_eligible_backend`, `upstream_timeout`, the model-key door's `proxy_misconfigured`, `auth_overloaded`, `auth_unavailable` and the 508 federation codes are `gateway`; `upstream_error` stops the chain; `invalid_api_key`, `permission_denied`, `peer_instance_mismatch` are `auth`; the 400/404/405/413 codes are `bad_request` — and an unknown code still stops the chain. A row of provider class `ctx` (a peer ctx instance, writable since Migration 166) is read more closely: its code also comes from the JSON body of an error answer and wins over the status. There `server_busy` and `concurrency_limit_exceeded` are `busy` (a capacity refusal, not a health signal: no cooldown), `upstream_timeout` is `timeout` (stop, as on the peer itself), and `insufficient_quota` is `quota_exhausted` (cooldown = the full `Retry-After` up to 24 h, 1 h without one — the embed and rerank walks report no `Retry-After` yet, so there it is always 1 h); `busy` and `quota_exhausted` stop the chain for now rather than spill to the next, possibly paid, row within the request — a row in quota cooldown still sorts behind the others for the requests that follow. **Back-off after three consecutive failures:** the class cooldown doubles up to 10 minutes but never drops below the class cooldown itself — `billing` and `no_providers` keep their hour and `auth` its 15 minutes, where they previously fell to 10 minutes from the third failure on. `backend-list` shows the outcome per row as `effective_state: "cooldown"`, `cooldown_remaining_s` and `last_error` (the class name). +**Failover classes.** Every failed attempt is classified once (`internal/backends.Classify`) into a class that decides whether the chain goes on to the next backend and how long the failed row sorts last (the cooldown is an order hint — a row in cooldown stays reachable at the end of the chain). By status: `500` stops the chain (the server ran the request); `502`/`503`/`504` and any other 5xx are `gateway` (next, 30 s); `429` is `rate_limit` (next, `Retry-After` or 60 s, at most 5 min); `402` is `billing` (next, 1 h); `401`/`403` are `auth` (next, 15 min); `400`/`404`/`413` and any other status below 500 are `bad_request` (next, no cooldown); OpenRouter's "no allowed providers" is `no_providers` (next, 1 h); a transport failure goes next with 30 s; the attempt timeout stops the chain. An error event inside an HTTP-200 stream is classified by its code, on every provider class: the anthropic wire's error types and the codes of the [gateway vocabulary](#openai-compatible-api-v1) each take the class their HTTP status gets — `rate_limit_exceeded`, `server_busy`, `concurrency_limit_exceeded`, `insufficient_quota` are `rate_limit`; `upstream_unavailable`, `server_overloaded`, `internal_error`, `service_unavailable`, `model_unavailable`, `no_eligible_backend`, `upstream_timeout`, the model-key door's `proxy_misconfigured`, `auth_overloaded`, `auth_unavailable`, `recording_unavailable` and the 508 federation codes are `gateway`; `upstream_error` stops the chain; `invalid_api_key`, `permission_denied`, `peer_instance_mismatch` are `auth`; the 400/404/405/413 codes are `bad_request` — and an unknown code still stops the chain. A row of provider class `ctx` (a peer ctx instance, writable since Migration 166) is read more closely: its code also comes from the JSON body of an error answer and wins over the status. There `server_busy` and `concurrency_limit_exceeded` are `busy` (a capacity refusal, not a health signal: no cooldown), `upstream_timeout` is `timeout` (stop, as on the peer itself), and `insufficient_quota` is `quota_exhausted` (cooldown = the full `Retry-After` up to 24 h, 1 h without one — the embed and rerank walks report no `Retry-After` yet, so there it is always 1 h); `busy` and `quota_exhausted` stop the chain for now rather than spill to the next, possibly paid, row within the request — a row in quota cooldown still sorts behind the others for the requests that follow. **Back-off after three consecutive failures:** the class cooldown doubles up to 10 minutes but never drops below the class cooldown itself — `billing` and `no_providers` keep their hour and `auth` its 15 minutes, where they previously fell to 10 minutes from the third failure on. `backend-list` shows the outcome per row as `effective_state: "cooldown"`, `cooldown_remaining_s` and `last_error` (the class name). ## Web chat sessions @@ -655,7 +655,7 @@ External programs that hold a model key (`ctxm_…`, see [model consumers](#mode - **Statuses.** `401 invalid_api_key` (with `WWW-Authenticate: Bearer realm="ctx"`), `404 not_found`, `404 model_not_found` (one fixed body for a model that does not exist, belongs to another tenant, is not released to the key, is disabled or has a broken policy — no oracle: without `all_models` every name costs the same one grant probe, so the time does not tell the cases apart either), `405 method_not_allowed` (with `Allow`), `413 request_too_large`, `429 rate_limit_exceeded` (the door's failure lock, `Retry-After`), `503 proxy_misconfigured` (`X-Forwarded-For` without `CTX_TRUSTED_PROXY`, see [operations](operations.md#environment-variables)), `503 auth_overloaded` (`Retry-After: 1`) and `503 auth_unavailable` (the door's database step), `503 server_overloaded` with `Retry-After: 1` and `x-should-retry: true` when the in-flight budget (`gateway.inflight_budget`, 3 × the body plus a response reserve per request, and for an alias below `credentials` the sensitivity scan's 23 × the body + 128 KiB + 104 bytes per nesting level (up to 1 040 104 bytes at the decoder's depth limit) on top — for bodies up to the scan cap `gateway.scan_max_request_bytes`, a longer one is `413 request_too_large` before the scan; the JSON check's nesting state, up to 240 024 bytes at the decoder's depth limit, is booked before the check and takes the share's rest or grows it; the configuration refuses a budget that cannot hold one request at every cap) is exhausted — refused at once, never queued — and `503 internal_error` with `x-should-retry: false` for every fault inside ctx: a recovered panic, a failed grant read (one that does not answer within the door's 1-s deadline included), a wiring defect. A fault inside ctx is a `503`, not a `500`: a peer ctx falls over to its next backend on a `503` but stops its chain on a `500`. The only `500` the gateway will send is a relayed upstream `500` (`upstream_error`). - **Federation guard.** The group carries the federation loop guard and the ingress policy between the key door and the body cap (`EnabledGate → ModelAuth → LoopGuard → PeerIngress → body cap`), refusing in this envelope with the codes of [federation refusals](#federation-refusals-ctx-hop-ctx-path). `gateway.enabled` cannot be turned on while no model group with both stages is mounted: the settings write is a `409`, the boot refuses. - **Federation headers a client may send.** `Ctx-Sensitivity` (`public`, `internal`, `personal`, `credentials`) raises the sensitivity the serving chain must admit above the consumer's own level and never lowers it — from any consumer; an unknown value counts as `credentials`. `Ctx-Egress: local` (or an unreadable value) keeps the request on this instance's own engines: no other ctx instance, no row that answered as one, no external row; absent or `any`, at most one further hop to a row known as a ctx instance (provider class `ctx` or a learned instance — a ctx instance registered as `generic` is not known as one, see [security](security.md#federation-ingress-policy-peeringress)). A `ctx-peer` consumer that sends no `Ctx-Path` is always served as `local`. `Ctx-Max-Wait-Ms` can only shorten this instance's queue wait. `Ctx-Class` and `Ctx-Pipeline` take effect only from a `ctx-peer` consumer that also sends `Ctx-Path`; from an app they are ignored (no lane claim through a header). Prompts of a consumer below `credentials` are scanned for secrets over every string field of the body; a hit serves the request as `credentials` ([security](security.md#federation-ingress-policy-peeringress)). -- **Code vocabulary.** The full table of codes with their status and type is exported data (`oai.Codes()`, a copy): the statuses above plus `invalid_json`, `missing_required_parameter`, `invalid_type`, `unsupported_parameter`, `unsupported_value`, `model_not_supported`, `context_length_exceeded`, `upstream_rejected` (400), `permission_denied` (403), `server_busy`, `concurrency_limit_exceeded` (429 `rate_limit_error`), `insufficient_quota` (429 `insufficient_quota`), `service_unavailable`, `model_unavailable`, `no_eligible_backend`, `upstream_unavailable` (503), `upstream_error` (500), `upstream_timeout` (504) and the federation codes `federation_header_invalid`, `federation_hop_required` (400), `peer_instance_mismatch` (403), `federation_loop`, `federation_depth` (508). The three door codes `proxy_misconfigured`, `auth_overloaded`, `auth_unavailable` are `503 service_unavailable_error`. +- **Code vocabulary.** The full table of codes with their status and type is exported data (`oai.Codes()`, a copy): the statuses above plus `invalid_json`, `missing_required_parameter`, `invalid_type`, `unsupported_parameter`, `unsupported_value`, `model_not_supported`, `context_length_exceeded`, `upstream_rejected` (400), `permission_denied` (403), `server_busy`, `concurrency_limit_exceeded` (429 `rate_limit_error`), `insufficient_quota` (429 `insufficient_quota`), `service_unavailable`, `model_unavailable`, `no_eligible_backend`, `upstream_unavailable` (503), `upstream_error` (500), `upstream_timeout` (504) and the federation codes `federation_header_invalid`, `federation_hop_required` (400), `peer_instance_mismatch` (403), `federation_loop`, `federation_depth` (508). The three door codes `proxy_misconfigured`, `auth_overloaded`, `auth_unavailable` are `503 service_unavailable_error`, and so is `recording_unavailable` (`x-should-retry: true`, `Retry-After: 1`): a request of a [recording consumer](#model-consumer-administration) whose recording could not be committed — never served, no backend called. - **Conformance.** The envelope and the model list are checked against the official OpenAI SDKs — Go `openai-go/v3` in the regular test run, Python `openai` (`go test -tags=pyconformance ./internal/oai/`, needs `uv`; nightly in CI as `gateway-sdk-smoke`) — and against the `ErrorResponse`, `ListModelsResponse` and `Model` schemas of the OpenAI spec (vendored excerpts under `go/conformance/oai/testdata/`). The contract of the whole surface is `go/conformance/oai/contract.json`: every route of `/v1` and `/v2` with every answer form (chat also its stream chunk and error frame) and the pinned schema it validates against — the rerank answer against a ctx-owned schema (`ctx-rerank-response.json`), since OpenAI defines none — and every code of the vocabulary goes through the Go SDK as a valid `ErrorResponse` with its `x-should-retry`. The CI job `Conformance` runs exactly these checks on every pull request and is a required check; a route mounted without a contract, a form without a pinned schema or an answer without the envelope fails it. ### Admission @@ -848,7 +848,7 @@ The contract every gateway route writes against (`llmlog.GatewayEntry` / `llmlog - **One LLM-log row per request.** Chat, streamed chat, embeddings and rerank each write exactly one `context_llm_log` row, failover included: `attempt` is the number of physical attempts, `metadata.chain` lists them. Pipelines are `gateway-chat`, `gateway-embeddings` and `gateway-rerank`. - **Attribution.** The row names the consumer in `consumer_id`; `api_key_id` is always `NULL` (a row with both is refused by the database). `metadata.gw` (version 1) carries `v`, `op` (`chat`/`embed`/`rerank`), `alias`, `stream`, `hop` (0–16), `claimed_chain` (display only), `peer_pipeline` (ctx peers), `usage` (`backend`/`estimated`), `ttft_ms` (streams), `client_req_id` (`[A-Za-z0-9._:-]{1,128}`, else dropped), `finish` (`stop`, `length`, `tool_calls`, `content_filter`, `error`, `aborted`) and `model_key_id` — never an origin and never a second copy of the consumer. The hourly usage rollup counts such rows as `source = 'gateway'` with the alias. -- **Bodies.** `gateway.body_logging` (global-only, hot): `none` (default) stores no prompt and no answer (`''`, shown as `bodyless`), `errors` stores the serialized request and the answer only on rows with an error, `full` on every row (a streamed answer is not stored — its row carries the request only); each body is capped at 64 KiB with a visible truncation marker. A credentials-class row stays `sealed` under every policy — a tenant's `tenant.devmode` does not open it — and a row with an empty or unknown sensitivity stores no body either. **A recording consumer's rows** (`record_bodies`, see [model consumer administration](#model-consumer-administration)) are the one exception: whatever the policy and the class, the row stores the request whole (chat: the message array; embeddings: the `input`; rerank: the query, a line break and the documents) and the answer whole (a non-streamed chat answer as the client received it; a stream: its `data:` lines as relayed, in order, without the closing `[DONE]` or error frame; rerank: the answer as written to the client; embeddings: none — the vectors are not kept, the input is the record), with `metadata.gw.recorded: true`. A text the process's recording account (128 MiB, [operations](operations.md#recording-a-consumer)) cannot take is left out and named: `metadata.gw.record_lost` (`["request"]`, `["response"]` or both) with `record_lost_cause` `memory`; the shutdown's forced row of a request still open names both with cause `shutdown`. +- **Bodies.** `gateway.body_logging` (global-only, hot): `none` (default) stores no prompt and no answer (`''`, shown as `bodyless`), `errors` stores the serialized request and the answer only on rows with an error, `full` on every row (a streamed answer is not stored yet — its row carries the request only); each body is capped at 64 KiB with a visible truncation marker. A credentials-class row stays `sealed` under every policy — a tenant's `tenant.devmode` does not open it — and a row with an empty or unknown sensitivity stores no body either. A **recording consumer's** rows (`record_bodies`, see [model consumer administration](#model-consumer-administration)) are no exception: they follow the policy like every row and carry `metadata.gw.recorded: true` and `recording_id` — the request's row in `context_llm_recordings`, which holds the request as read and the answer whole ([operations](operations.md#recording-a-consumer)). - **Errors.** The `error` column of a gateway row is ` ` (for example `bad_request 400 upstream_rejected`) — never the upstream response body, which can echo the prompt. - **Access log.** One INFO line `gateway request` per successful request (`consumer_id`, `model_key_id`, `tenant_id`, `op`, `alias`, `status`, `stream`, token counts, `usage`, `duration_ms`, `queue_wait_ms`, `class`, `hop`, `request_id`), on while `gateway.access_log` is `true` (default); a client that left before the handler returned is logged with `status=499` and the handler's status in `handler_status` — `0` when it wrote nothing — (at WARN with `waited_for=admission` when it left while waiting for an admission slot) (see [operations](operations.md#requests-the-client-gave-up-on)). Refusals (status ≥ 400) are never logged per request: they are counted per consumer (empty before authentication) and reason — for a refusal the [refusal ledger](#refusal-ledger) counts its `reason`, with the window's details in `detail`; otherwise the error code of the gateway or the model-key door, else `http_` — and written as at most one WARN line `gateway rejections` with `count` and `window="1m"` per minute — the flag's `404` and the door's `401` included. The global `http request` line is not written for these requests: each gateway request is one line or one count. @@ -862,7 +862,7 @@ Read surfaces of the model API's usage, mounted with `/api/llmlog` behind **admi - **`null` is not `0`.** A bucket before the rollup's coverage (its first hour, or the hour migration 159 was applied) is `complete: false` with every counter `null`; a covered bucket without traffic is a real `0` with `complete: true`; the running bucket carries its partial values with `complete: false`. `rejected` is `null` for buckets before the refusal ledger existed (migration 167) and `[]` for a covered bucket without refusals. A percentile without samples is `null`, never `0`. - **Tenant-admin view.** Only the rows of the tenant's own model consumers: `?consumer=` is checked with a single-row membership query, and a foreign or unknown id answers `200` with no series — the same as a consumer without traffic, so the answer is no existence oracle. Internal rows (knowledge keys, background pipelines), refusals before the model-key door (`auth`, no consumer) and the refusal fields `target`/`dispatch_class` never appear; `group=instance` is `403`. - **`GET /api/usage/consumers`.** One entry per visible consumer and operation: `limits{server, tenant, defaults, effective}`, `day`/`month` `{used, limit, reset_at}` (UTC calendar windows), `cost_month{used_usd, limit_usd}`, `binding` (`consumer`, `tenant` or `instance` — the level with the least headroom), `live{reservations, inflight, rpm_remaining, tpm_remaining}` from the meter (no database read; `null` until the meter's boot seed has read the rollup — the meter is seeded at boot whether or not the gateway is enabled), `last_bucket` (newest hour with traffic in the last 30 days), `rejections_24h` and `usage_24h` (the 24 hourly buckets up to and including the running one). The rollup part is one batch per tenant, cached for 30 seconds — two polls within 30 seconds cost one statement. A tenant-admin sees the instance envelope only as `binding: "instance"`, without its values. -- **`GET /api/status` sections (model API).** While `gateway.enabled` is on, a server-admin's status carries `gateway` (`enabled`, `consumers`, `consumers_used_1h`, `consumers_expiring` — a live key expiring within `gateway.key_expiry_warn` —, `recording_consumers` — the ids of the active consumers with `record_bodies` on, sorted, `[]` when none —, `top_consumers_1h` from an in-memory ring of one-minute buckets, `auth` = the model-key door's counters, among them the in-flight registry's `inflight`, `inflight_keys`, `inflight_timers`, `inflight_cancelled`, `inflight_sweeps` and `inflight_sweep_errors` — every key of these sections is snake_case —, `events` = the usage-event recorder's counters, `generated_at`; `reservations_open` and `rejections_5m` are `null` until the meter and the in-memory ledger feed them), `usage_split_24h` (`[{target, source, class, calls, gpu_ms}]` over the last 24 hourly buckets) and `federation` (`header_ignored`, `peer_without_path`, `stamp_without_identity` since process start, `peer_bound` from the event recorder, and `loop_rejects`, `depth_rejects`, `header_invalid`, `peer_mismatch`, `busy` from the refusal ledger over the last 24 hourly buckets; `embed_space_rejects` has no ledger detail and stays `null`). A tenant-admin's status carries `gateway` with its own consumers only (`recording_consumers` included) — no `auth`, `events`, `usage_split_24h` or `federation`. The counts come from one database read at most every 30 seconds, never from the raw log; the sections are per caller on `GET /api/status` and are not part of the `/api/events` stream. With the gateway off the sections are absent. +- **`GET /api/status` sections (model API).** While `gateway.enabled` is on, a server-admin's status carries `gateway` (`enabled`, `consumers`, `consumers_used_1h`, `consumers_expiring` — a live key expiring within `gateway.key_expiry_warn` —, `recording_consumers` — the ids of the active consumers with `record_bodies` on, sorted, `[]` when none —, `recording` — this process's count of their requests: `{process_id, since, held_bytes, consumers: [{consumer_id, admitted, in_flight, recorded, unrecordable, unfinished, stream_answers_unrecorded}]}` ([operations](operations.md#recording-a-consumer)) —, `top_consumers_1h` from an in-memory ring of one-minute buckets, `auth` = the model-key door's counters, among them the in-flight registry's `inflight`, `inflight_keys`, `inflight_timers`, `inflight_cancelled`, `inflight_sweeps` and `inflight_sweep_errors` — every key of these sections is snake_case —, `events` = the usage-event recorder's counters, `generated_at`; `reservations_open` and `rejections_5m` are `null` until the meter and the in-memory ledger feed them), `usage_split_24h` (`[{target, source, class, calls, gpu_ms}]` over the last 24 hourly buckets) and `federation` (`header_ignored`, `peer_without_path`, `stamp_without_identity` since process start, `peer_bound` from the event recorder, and `loop_rejects`, `depth_rejects`, `header_invalid`, `peer_mismatch`, `busy` from the refusal ledger over the last 24 hourly buckets; `embed_space_rejects` has no ledger detail and stays `null`). A tenant-admin's status carries `gateway` with its own consumers only (`recording_consumers` included) — no `auth`, `events`, `recording`, `usage_split_24h` or `federation`. The counts come from one database read at most every 30 seconds, never from the raw log; the sections are per caller on `GET /api/status` and are not part of the `/api/events` stream. With the gateway off the sections are absent. - **`GET /api/llmlog?consumer_id=`.** The list now carries `consumer_id` on every row (`null` for knowledge-key and background rows). A tenant-admin's list is the union of two bounded reads — its knowledge keys and its model consumers, each limited to the last 30 days — and `consumer_id=` narrows to one of its own consumers (a foreign id: no rows). A server-admin's list is unchanged and `consumer_id=` narrows it. The detail `GET /api/llmlog/{id}` of a consumer row answers a tenant-admin with the uniform `404`. ### Quota warnings and usage events diff --git a/docs/operations.md b/docs/operations.md index 24bbb58ae..871530632 100644 --- a/docs/operations.md +++ b/docs/operations.md @@ -542,10 +542,7 @@ chunk exclusion. The JSON summary on stderr (always printed, also on failure) carries `rows_total`, `rows_body`, `rows_bodyless_slim` (credentials-class rows whose bodies were slimmed to `''`), -`rows_bodyless_null` (bodies NULLed by retention), `rows_recorded_sealed` (rows of a recording -consumer, and fail-closed every gateway row without a readable `metadata.gw` marker, written with -their bodies sealed — they count in `rows_bodyless_slim`/`rows_bodyless_null` too, see -[Recording a consumer](#recording-a-consumer)), `count_gate`, `bytes` (what was actually +`rows_bodyless_null` (bodies NULLed by retention), `count_gate`, `bytes` (what was actually flushed — valid even after a cancel), `watermark` + `watermark_id` (the last row). A delta run continues **exactly** behind the previous run with `-since -since-id `; `-since` alone is inclusive and re-exports every row sharing the watermark's `created_at`. @@ -974,38 +971,59 @@ Every LLM call ctx makes writes one row to `context_llm_log` (the telemetry behi - **Throttle.** At most **4** inserts run at once; further rows wait in a queue of at most **4 096** rows. Both numbers are fixed in the code (`internal/llmlog`): they bound ctx's own bookkeeping, not a policy anyone tunes. Before this, every row got its own goroutine and connection, so a slow database let a burst take all 20 connections. - **Losses are counted, not silent.** A row the full queue cannot take is dropped; an insert the database refuses (or that runs past its 5 s deadline) is lost. Both are counted since process start and shown to a server-admin on `GET /api/status` as `"llmlog": {"insert_failures": N, "insert_dropped": M}` — present at `0/0` too, so a zero means "nothing lost", not "not measured". The section is absent on a tenant-admin's view: the counters cover every tenant and the background. In the log, the first loss raises one `WARN` (`llmlog: insert failed, row lost` or `llmlog: insert queue full, row dropped`, with `insert_failures_total`/`insert_dropped_total`), and at most one more per minute after that however many rows are lost; every failure still has its `DEBUG` line. A rising `insert_failures` usually means the database is unreachable or `context_llm_log` is broken (missing table, failing trigger); a rising `insert_dropped` means the queue stayed full — the database has been slow or unreachable for long enough to back up 4 096 rows. - **Shutdown settles the queue, twice.** On `SIGTERM` ctxd stops HTTP (up to 15 s), settles the model gateway's meter reservations still open after that drain with their estimate and queues their request's row (up to 1 s, in memory; `gateway: open meter reservations settled with their estimate at shutdown` with the count — so the next start's budget seed counts what those requests used), writes the refusal ledger's last counts ([Migration 167](#migration-167-the-refusal-ledger-of-the-model-api); up to 5 s, `gateway: refusal ledger flushed at shutdown` in the log), ends the model gateway's loops with their final flush (up to 5 s, alongside the next step; a model key whose row another transaction holds at that moment — a rotation, a deactivation, a prune — keeps its `last_used_at` stamp pending, and the flush retries it every 100 ms for up to 4 s; stamps still unwritten then are counted in `WARN gateway: last_used_at stamps of model keys left unwritten at shutdown` with `stamps=N` — after a failed attempt an upper bound; should the gateway's own 5 s run out first, the older `WARN gateway: final flush incomplete at shutdown` appears instead, without a count) and waits up to **5 s** for every queued and running llmlog insert (the [read record](#the-read-record-in-context_access_log)'s queue settles alongside, within the same 5 s); then it waits for the scheduler to finish its running work, and settles the queue once more (up to 5 s) before it closes the pool. The first settle exists because the scheduler wait has no limit: a dream cycle that is running when the signal arrives is not cancelled, it runs to its end or to `dream.cycle_timeout` (700 s by default). If that outlasts the stop grace period, Docker kills ctxd during the wait — the HTTP side's rows have had their settle by then, and only the rows still queued from the scheduler are lost. The log says which way each settle went: `llmlog: settled at shutdown` (with `after=http` or `after=scheduler`, the elapsed time and the loss totals) or `WARN llmlog: settle at shutdown incomplete, pending rows are lost`. -- **Recorded rows** ([Recording a consumer](#recording-a-consumer)) take the same queue and the same counters: a recorded row the full queue cannot take is dropped whole and counted in `insert_dropped` like any row — nothing in the counter or the `WARN` line says that it was a recorded one or whose; a recorded row the database refuses is in `insert_failures`. +- **A recording consumer's requests** ([Recording a consumer](#recording-a-consumer)) do not depend on this queue: their content is written synchronously to `context_llm_recordings` before they are served; their `context_llm_log` rows are telemetry like every other and share the queue and its counters. - **`stop_grace_period`.** Docker waits 10 s between `SIGTERM` and `SIGKILL` unless told otherwise — too short for the 15 s HTTP drain alone. The shipped `docker-compose.yml` sets `stop_grace_period: 36s` on the `ctx` service: 15 s HTTP drain + 1 s forced meter settle + 5 s refusal ledger flush + 2 × 5 s llmlog settle = 31 s, plus 5 s margin for the scheduler wait; the model gateway's final flush (the batched `last_used_at` stamps of model keys and the last `gateway rejections` lines, at most 5 s — of it at most 4 s of retries while a key row is locked —, measured in milliseconds; `gateway: usage stamps and rejection counts flushed at shutdown` in the log, or the `WARN` with the count of stamps left unwritten) runs alongside the first settle and adds nothing. A test pins it at 31 s or more (25 s before the refusal ledger, 30 s before the forced meter settle). Keep it at least that long in your own compose file, and raise it if you raise the shutdown budget or want a running dream cycle to finish rather than be killed. ### Recording a consumer -A server-admin can make one model consumer's gateway rows keep their request and answer **in full** (migration 197, issue #571) — for example to rebuild what a client sent from the rows it leaves: +A server-admin can make ctx hold every request one model consumer sends through the gateway, whole, before it is served (migration 197, issue #571) — for example to rebuild what a client sent: ```bash ctx manage model-consumer-update '' '{"id":"","record_bodies":true,"confirm_record_bodies":true}' ``` -(The consumer's `id` goes into `data`; `model-consumer-create` takes the same two fields.) From the consumer's next request on, every gateway row of its own stores the whole request and the whole answer, whatever `gateway.body_logging`, the alias, the consumer's `prompt_sensitivity`, the body scan or `Ctx-Sensitivity` say ([api — Telemetry & logging](api.md#telemetry--logging)); a request already running keeps what it was admitted with. The request path is the same with and without the switch, and no other consumer's rows change. Switching off is `"record_bodies": false` — a tenant-admin of the consumer's tenant may do that too. The consumer view (API, CLI `--json`, `/gateway` in the SPA) shows the switch to every reader; `GET /api/status` lists the recording consumers in `gateway.recording_consumers`. +(The consumer's `id` goes into `data`; `model-consumer-create` takes the same two fields.) From the consumer's next request on — a request already running keeps what it was admitted with — every request of it gets one row in `context_llm_recordings`; switching off is `"record_bodies": false`, which a tenant-admin of the consumer's tenant may do too. The consumer view (API, CLI `--json`, `/gateway` in the SPA) shows the switch to every reader; `GET /api/status` lists the recording consumers in `gateway.recording_consumers` and counts their requests in `gateway.recording` (server-admin). -**What the rows can hold.** Everything the client sent: a password, a token or a private key in a prompt is stored in clear text. The row is marked `metadata.gw.recorded = true`; its bodies are for a server-admin only ([security](security.md#gateway-telemetry-v1-v2)) — `GET /api/llmlog/{id}` as server-admin, or psql. `ctx-llmlog-export` writes such rows with their bodies sealed (below). A database backup carries them like every other content of the database. +**What a row holds.** `request_body` is the body as the gateway read it, byte for byte (bytea: invalid UTF-8 and NUL bytes included, no cut, no seal — a password, a token or a private key in a prompt is stored in clear text); `request_complete` says whether that is the whole body (a body cut short holds the part read), `declared_bytes` its `Content-Length`. `response_body` is the answer the client got: a non-streamed chat or rerank answer as written, a stream's relayed `data:` lines in order (without keepalives, the closing `[DONE]` or an error frame); none for embeddings (the vectors are not kept — the input is the record) and none for a refusal. `state` is `open` from the hold until the outcome is recorded, then `done` with `status` (the HTTP status the client got; `NULL` when the gateway wrote nothing — the client had gone), `code` (the gateway's code of a refusal or an error, where the refusing stage names one — the catch-alls of an unknown path and a wrong method leave it `NULL`), `finished_at`. `op`, `model` and `stream` are what the route read (`NULL` when no route parsed the request), `path` the request's path, `process_id` the ctxd process that admitted it. The row's `id` is the request's id: a chat answer's `id` is `chatcmpl-`, a rerank answer's `rerank-`, and the request's `context_llm_log` row carries it as `metadata.gw.recording_id` (with `metadata.gw.recorded: true`; that row follows `gateway.body_logging` like every other). -**Reading a consumer's rows out** (psql, in order; `request_user` is the message array of a chat request, the `input` of an embeddings request, the query, a line break and the documents of a rerank request; `response_content` the answer of a chat or rerank request — a stream's `data:` lines; none for embeddings): +**Held before served.** The route commits the row — the whole request, state `open` — before the first backend attempt and before any queue wait; a request whose row cannot be committed is answered `503 recording_unavailable` (`Retry-After: 1`, `x-should-retry: true`) and no backend sees it: the database refuses the insert, or it does not answer within **5 s** (a fixed statement deadline), or the recording's memory account (below) has no room within `dispatch.external_max_wait` (20 s). A non-streamed answer is committed with the outcome before its first byte is written; if that fails, the client gets the same `503` instead of the answer (the backend ran: the meter books its usage; the client's retry is a second row). A stream relays a line only after the recording kept it in memory; its lines are committed when it ends — what a stream sent cannot be taken back, so a stream whose end cannot be committed leaves its row `open` with its request and is counted in `stream_answers_unrecorded`. A request the gateway refuses after the door accepted the key — a body that does not parse, an unknown model, a limit, a body over `gateway.max_request_bytes` (never read: the row holds its declared size), an unknown path, a wrong method — gets its row at its end, `done`, with what was read of the body. Refusals before the door (`401`, a wrong key) are not the consumer's and leave nothing. A process that dies between the hold and the outcome leaves the row `open`: its request is there, its outcome is not known. + +**Checking that nothing is missing.** `GET /api/status` (server-admin) carries `gateway.recording`: `process_id` and `since` (this process's start), `held_bytes` (the memory account's fill), and per recording consumer `admitted` (requests that passed the door as it), `in_flight`, `recorded` (requests whose row is in the table), `unrecordable` (requests for which no row could be written at all — refused with `recording_unavailable` while the database was away; never served), `unfinished` (rows that stayed `open` because their outcome could not be written) and `stream_answers_unrecorded` (the streams among them that had sent lines). `admitted = in_flight + recorded + unrecordable` holds at every moment, and `recorded` equals the table's rows of that consumer and process: ```sql -SELECT created_at, pipeline, metadata->'gw'->>'finish' AS finish, request_user, response_content, - metadata->'gw'->'record_lost' AS lost - FROM context_llm_log - WHERE consumer_id = '' AND metadata->'gw'->>'recorded' = 'true' +SELECT count(*) AS rows, + count(*) FILTER (WHERE state = 'open') AS unfinished, + count(*) FILTER (WHERE state = 'done' AND status BETWEEN 200 AND 299) AS answered, + count(*) FILTER (WHERE state = 'done' AND status BETWEEN 200 AND 299 + AND response_bytes = 0 AND op IS DISTINCT FROM 'embed' + AND stream IS NOT TRUE) AS answered_without_answer, + count(*) FILTER (WHERE state = 'done' AND (status IS NULL OR status >= 400)) AS refused, + count(*) FILTER (WHERE request_body IS NULL AND request_bytes > 0) AS past_retention + FROM context_llm_recordings + WHERE consumer_id = '' AND process_id = ''; +``` + +`answered_without_answer` is `0` by construction (a non-streamed answer is written only after its row holds it). For a time range instead of a process, filter on `created_at` (the rows of every process that ran then); the counts of processes that have ended are in their logs: every request that could not be recorded is an `ERROR` line (`a refused request of a recording consumer could not be recorded`, or `the outcome of a recorded request could not be recorded — its row stays open` with `recording_id` and `stream_answer_lost`). + +**Reading a consumer's requests out** (psql, in order): + +```sql +SELECT created_at, id, path, op, model, stream, state, status, code, + convert_from(request_body, 'UTF8') AS request, convert_from(response_body, 'UTF8') AS answer + FROM context_llm_recordings + WHERE consumer_id = '' ORDER BY created_at, id; ``` -The predicate rides `idx_llm_log_consumer` (migration 158). Rows of requests the gateway refused before the route (`401`, `429`, a limit) are not rows at all — they are only counted in `context_llm_rejections_hourly`. +(`convert_from` fails on a body that is not valid UTF-8 — select `request_body` itself, or `encode(request_body, 'escape')`, for those.) The predicate rides `idx_llm_recordings_consumer`. No ctx surface reads the bodies — no REST, MCP, CLI or web route, no export ([security](security.md#gateway-telemetry-v1-v2)); a database backup carries them like every other content of the database. + +**Cost on the request path.** Only for the recording consumer: two statements in the request's time (the insert before the walk, the outcome at the end — before the answer for a non-streamed answer), see the measurement in the pull request of issue #571 (p50/p99 of a small chat and a large embeddings request with and without recording). Every other consumer passes the recording stage untouched: no write, no wait, no allocation. -**Size and memory.** No cut: a request text is at most twice `gateway.max_request_bytes` (8 MiB; an invalid byte is stored as U+FFFD), a non-streamed chat answer is the answer the client received (its upstream read is capped by `gateway.max_response_bytes`, 4 MiB), a stream's answer grows with the stream. A row with an error carries the request; the error ctx answered is the row's `error` column. A stream's answer is its relayed `data:` lines, without the closing `[DONE]` or error frame. The texts are held against one process-wide account of **128 MiB** (fixed in the code, `internal/llmlog`, like the writer's queue bound) from the moment the route captures them until the row is inserted — never against `gateway.inflight_budget`, so recording books nothing on the request path; the container (1536 MiB) holds the default budget of 512 MiB, this account, the writer's copy of the rows being inserted (4 at a time) and the base. A text the account cannot take — many large recorded requests at once, or a slow database that keeps rows queued — is not captured: the row is written without it and says so (`metadata.gw.record_lost: ["request"]` or `["response"]`, `record_lost_cause: "memory"`), and `GET /api/status` counts such rows in `llmlog.recorded_bodies_lost` and shows the account's fill in `llmlog.recorded_held_bytes`. Measured on the test image: a row of 16 MiB request text and 24 MiB answer is inserted in 256 ms (compressible text, stored in 161 KiB) and 360 ms (incompressible, 40 MiB), against the insert's 5 s deadline. Embedding vectors are not stored (the input is the record); a rerank answer is stored as written to the client. **What the account counts:** a stream holds the capacity of its growing buffer — up to about twice the text so far (measured: 6.8 MB of text held 12.6 MB) — so streams reach the bound sooner than their text alone; the writer's copies of a row while it is inserted (pgx encodes the arguments, up to two transient copies per row, 4 inserts at a time) are not counted. `gateway.max_request_bytes` above 64 MiB can make a request text (up to twice the body) larger than the whole account: such a text is never captured. Deactivating and reactivating a recording consumer leaves the switch as it was. A request still open when the shutdown's forced settle writes its row gets a row without bodies (`record_lost` both, cause `shutdown`). +**Memory.** The request's own memory stays in `gateway.inflight_budget` with the same bookings as without recording. What the recording adds — the copies a statement makes of what it carries (pgx encodes a parameter into its own buffer and that into the connection's write buffer; booked at 3 × the bytes), a stream's kept lines (its buffer's capacity, up to twice the text), a rerank answer kept before it is written, and the body of a request refused before its walk while its row is written (its in-flight reservation has ended) — is held against **one process-wide account**: 128 MiB, or 3 × the larger of `gateway.max_request_bytes` and `gateway.max_response_bytes` when that is more, so the largest request always fits. A statement waits for room (backpressure, up to the request's wait budget, else `recording_unavailable`); a stream's next line that does not fit ends the stream with `recording_unavailable` before that line is sent. At the defaults the process holds at most the 512 MiB budget + 128 MiB + its base (measured idle at 21–32 MiB) — inside the image's `GOMEMLIMIT` of 768 MiB and the container's 1536 MiB. Nothing is dropped to stay in that bound: a request that does not fit waits or is refused. -**Retention.** Recorded bodies are NULLed after `scheduler.llmlog_retention_days` (90 days) like every other body; the row and its marker stay. Export or read them out before that if they are needed longer. +**Size.** A row holds at most `gateway.max_request_bytes` (8 MiB) of request; a non-streamed answer is capped by its read (`gateway.max_response_bytes`, 4 MiB); a stream's lines grow with the stream. A recording consumer at 30 requests a second writes about 2.6 M rows a day. -**Export.** `ctx-llmlog-export` leaves every recorded row's bodies sealed (`''`; a body retention already NULLed stays `null`) and counts the rows in `rows_recorded_sealed`; it does the same, fail-closed, for a gateway row whose `metadata.gw` is missing or does not read as an unrecorded call. The query above is the way to read them. +**Retention.** Both bodies of a recording are NULLed after `scheduler.llmlog_retention_days` (90 days) by the same janitor that NULLs `context_llm_log`'s (`request_bytes`, `response_bytes`, the outcome and the row stay). Read them out before that if they are needed longer. ### Upgrading to 5.33.1: the image's `GOMEMLIMIT` is 768MiB @@ -2367,11 +2385,11 @@ Issue #289. The Hermes plugin `ctx_checkpoint` stores, with `memory: true`, sess ### Migration 197: the recording switch of a model consumer -Issue #571. `context_model_consumers.record_bodies BOOLEAN NOT NULL DEFAULT false` — every consumer reads `false` after the upgrade, nothing records until a server-admin switches it on ([Recording a consumer](#recording-a-consumer)). The audit projection `audit_state_model_consumer` and the trigger `trg_model_consumers_audit_upd` gain the column, so every switch is an `update` row of `model_consumer` and every later audit row of a consumer carries the key `record_bodies` (older rows stay as written). `ctx_model_auth` gains `record_bodies` as its last column; the result type changes, so the migration drops and creates the function in its transaction. +Issue #571. `context_model_consumers.record_bodies BOOLEAN NOT NULL DEFAULT false` — every consumer reads `false` after the upgrade, nothing records until a server-admin switches it on ([Recording a consumer](#recording-a-consumer)). The audit projection `audit_state_model_consumer` and the trigger `trg_model_consumers_audit_upd` gain the column, so every switch is an `update` row of `model_consumer` and every later audit row of a consumer carries the key `record_bodies` (older rows stay as written). `ctx_model_auth` gains `record_bodies` as its last column; the result type changes, so the migration drops and creates the function in its transaction. The new table `context_llm_recordings` (a plain table, primary key `id`, indexes `idx_llm_recordings_consumer (consumer_id, created_at DESC)` and `idx_llm_recordings_bodies (created_at) WHERE request_body IS NOT NULL` for the janitor) holds the recordings. -**Locks.** `ADD COLUMN` with a constant default rewrites nothing: `ACCESS EXCLUSIVE` on `context_model_consumers` until the commit (the table holds at most `max_model_consumers`, 64 by default, rows per tenant) — milliseconds during which a `/v1` door check (`ctx_model_auth` reads the table) and every consumer write of another ctx process on the same database wait. `CREATE TRIGGER` takes `SHARE ROW EXCLUSIVE` on the same table inside that window; dropping and creating the function locks no table, a session calling it meanwhile uses the old definition until the commit. `lock_timeout 3s` fails the boot instead of queueing behind a long transaction; the next start retries. +**Locks.** `ADD COLUMN` with a constant default rewrites nothing: `ACCESS EXCLUSIVE` on `context_model_consumers` until the commit (the table holds at most `max_model_consumers`, 64 by default, rows per tenant) — milliseconds during which a `/v1` door check (`ctx_model_auth` reads the table) and every consumer write of another ctx process on the same database wait. `CREATE TRIGGER` takes `SHARE ROW EXCLUSIVE` on the same table inside that window; dropping and creating the function locks no table, a session calling it meanwhile uses the old definition until the commit; creating the new table locks nothing that exists. `lock_timeout 3s` fails the boot instead of queueing behind a long transaction; the next start retries. -**Rolling deploy and way back.** The release before (v5.89.0) runs unchanged on a database with 197 (executed: its auth, model-key door, consumer administration and `/v1` chat-row tests over a schema with 197): its door selects `ctx_model_auth`'s columns by name and does not see the new one, its consumer writes leave the column at its default, and its rows of a recording consumer are written as before — sealed or capped by `gateway.body_logging`, without the marker. Its schema-contract check reports the unknown migration as for every release ahead of it (`schema_contract: attention`; mode `enforce` refuses to start). The way back, in this order: `DROP FUNCTION ctx_model_auth(TEXT, INET, BOOLEAN);` the `CREATE OR REPLACE FUNCTION ctx_model_auth` of migration 161 (section 8); the `CREATE OR REPLACE FUNCTION audit_state_model_consumer` of 161 (section 7); `DROP TRIGGER trg_model_consumers_audit_upd ON context_model_consumers;` and the `CREATE TRIGGER trg_model_consumers_audit_upd` of 161; `ALTER TABLE context_model_consumers DROP COLUMN record_bodies;` `DELETE FROM _migrations WHERE version = 197;` — `TestMigration197Idempotent` runs exactly these and compares the catalog with 196's. Recorded rows already written keep their bodies and marker until the retention. +**Rolling deploy and way back.** The release before (v5.89.0) runs unchanged on a database with 197 (executed: its auth, model-key door, consumer administration and `/v1` chat-row tests over a schema with 197): its door selects `ctx_model_auth`'s columns by name and does not see the new one, its consumer writes leave the column at its default, and it serves a recording consumer as before — **without recording it** (it knows neither the switch nor the table). Run the two side by side only while no consumer records, or accept that the older process's share of that consumer's requests is not held. Its schema-contract check reports the unknown migration as for every release ahead of it (`schema_contract: attention`; mode `enforce` refuses to start). The way back, in this order: `DROP TABLE context_llm_recordings;` (its rows go with it — read them out first); `DROP FUNCTION ctx_model_auth(TEXT, INET, BOOLEAN);` the `CREATE OR REPLACE FUNCTION ctx_model_auth` of migration 161 (section 8); the `CREATE OR REPLACE FUNCTION audit_state_model_consumer` of 161 (section 7); `DROP TRIGGER trg_model_consumers_audit_upd ON context_model_consumers;` and the `CREATE TRIGGER trg_model_consumers_audit_upd` of 161; `ALTER TABLE context_model_consumers DROP COLUMN record_bodies;` `DELETE FROM _migrations WHERE version = 197;` — `TestMigration197Idempotent` runs exactly these and compares the catalog with 196's. ### `graph_overview.csr_loader`: the rebuild's input substrate diff --git a/docs/security.md b/docs/security.md index 99d0583d6..94e7fff0f 100644 --- a/docs/security.md +++ b/docs/security.md @@ -8,7 +8,7 @@ How the system defends itself is below. How to **report** a vulnerability — pr **Rationale.** Before this gate, ANY valid key of any `home_scope` could mint keys for arbitrary scopes — read access to foreign tenants — and the settings/secrets API must not inherit that model. The per-tenant admin tier (owner/admin/member) that layers on top is documented in [multi-tenancy](multi-tenancy.md#admin-tiers). -**Self-service stage (`tierSelfService`, W01-5).** The model consumer actions that grant a new credential — `model-consumer-create` and `model-key-rotate` — carry a fourth stage in the dispatch table: server-admin, and a tenant-admin of its own tenant only while `gateway.enabled` **and** `gateway.tenant_self_service` are on (both default off; a missing config snapshot counts as off). The switch is a setting, so it cannot be a payload-shaped tier function; as a stage of its own the lock sits in the pinned table, and the handlers check the same switch a second time. With the gateway off nobody below server-admin grants anything, whatever the self-service switch says (dark launch). The refusal is the shared `403 admin key required` — no tier, switch or field oracle. Inside `model-consumer-update` the rule is **revoking is always allowed, granting needs a release** ([api](api.md#model-consumer-administration)): narrowing a consumer stays open to tenant-admins; widening it needs self-service; `kind = ctx-peer`, a lower `prompt_sensitivity` (egress of foreign prompts to less trusted backends), `allow_plaintext = true` (credential transport without TLS), a higher `fair_weight` and `admission_lane = urgent` (the GPU is a host-global good) and `record_bodies = true` (every request and answer of the consumer in clear text in the LLM log, [below](#gateway-telemetry-v1-v2); also needs `confirm_record_bodies: true`) stay server-admin with self-service on. **Peer row tier:** any granting change of a `ctx-peer` consumer is server-admin only. The comparison runs against the row under its lock, so a concurrent server-admin write cannot be undone by a tenant-admin re-submitting the old value. +**Self-service stage (`tierSelfService`, W01-5).** The model consumer actions that grant a new credential — `model-consumer-create` and `model-key-rotate` — carry a fourth stage in the dispatch table: server-admin, and a tenant-admin of its own tenant only while `gateway.enabled` **and** `gateway.tenant_self_service` are on (both default off; a missing config snapshot counts as off). The switch is a setting, so it cannot be a payload-shaped tier function; as a stage of its own the lock sits in the pinned table, and the handlers check the same switch a second time. With the gateway off nobody below server-admin grants anything, whatever the self-service switch says (dark launch). The refusal is the shared `403 admin key required` — no tier, switch or field oracle. Inside `model-consumer-update` the rule is **revoking is always allowed, granting needs a release** ([api](api.md#model-consumer-administration)): narrowing a consumer stays open to tenant-admins; widening it needs self-service; `kind = ctx-peer`, a lower `prompt_sensitivity` (egress of foreign prompts to less trusted backends), `allow_plaintext = true` (credential transport without TLS), a higher `fair_weight` and `admission_lane = urgent` (the GPU is a host-global good) and `record_bodies = true` (every request and answer of the consumer in clear text in `context_llm_recordings`, [below](#gateway-telemetry-v1-v2); also needs `confirm_record_bodies: true`) stay server-admin with self-service on. **Peer row tier:** any granting change of a `ctx-peer` consumer is server-admin only. The comparison runs against the row under its lock, so a concurrent server-admin write cannot be undone by a tenant-admin re-submitting the old value. **Admin bootstrap** (one-time, host access required). Promote by `id`, never by label — `label` has no UNIQUE constraint and an UPDATE by label would escalate every same-named key, including inactive ones: @@ -160,14 +160,14 @@ Every refusal carries `x-should-retry: false`: the same request against the same - **Request identity.** ctx mints the answer id and a fresh upstream request id per attempt; the client's `X-Request-ID` is only recorded (`metadata.gw.client_req_id`), never sent to a backend — a client-chosen id would become the engine's request id (vLLM) or a correlation handle at a third party. - **Kill switch and revocation while running.** A watcher per request (streamed or not) ends a running request within 5 s when `gateway.enabled` goes `false` or the alias is disabled or removed; a non-streamed request checks the alias and the grant once more right before the answer is written. The lease is released with the aborted upstream call. - **Revocation of running requests.** Every request the door accepts runs on a context the door's in-flight registry can end (one registry per process, entries indexed by model key, consumer, tenant and tenant scope, gone when the request ends — a panic included). A key that stops authenticating — revoked, its expiry passed, its consumer deactivated, its tenant suspended, offboarded or pruned, its `tenant_scope` moved to another tenant or deleted (gates 1–4 of `ctx_model_auth`) — ends the requests running on it: `401 invalid_api_key` before anything is written, the error frame `invalid_api_key` in a committed stream; the upstream call is aborted, the lease and the consumer's concurrency slot are freed, and the key's hash leaves the door's known-good set (its next request pays the probe token). Four triggers: `model-key-revoke` and `model-consumer-delete` end them right after their commit and answer how many requests of this process they ended (`cancelled_inflight`); every write that can end a key's validity — psql and other ctx processes on the same database included — fires `NOTIFY ctx_model_access_write` (migration 165), and the registry checks the keys it touches with `ctx_model_auth_live` (one statement); a key's expiry ends its requests at that instant through one timer per key (a rotation's grace moves it through the same signal); and every `gateway.inflight_sweep_interval` (30 s) one `ctx_model_auth_live` statement over the keys of all running requests is the second line behind the signal — and the sweep right after the listener reconnects covers a signal lost while it was away. A failed sweep ends nothing (the next one, or the signal, does). **Boundary:** the registry checks liveness only (gates 1–4); the door's other checks run at a request's entry and are not repeated while it runs. A narrowed policy — `allowed_cidrs` narrowed so the request's client address is outside (gate 5), `allow_plaintext` set to `false` under a plaintext request (gate 6), a withdrawn `all_models`, a withdrawn alias grant (except as below), another `tenant_scope` that still belongs to the tenant, a lower `prompt_sensitivity`, another lane or weight — applies from the next request; none of these writes ends a request that is already running, and none fires the database signal. A running request keeps what it was admitted with (its egress has already happened, an abort would not take it back). A withdrawn grant of a consumer without `all_models` is read again right before a non-streamed answer is written (`404 model_not_found`) and by a stream's watcher when the alias registry changes during the stream; otherwise it too applies from the next request. A key's expiry is the one the request was authenticated with, moved by the database signal; a rotation's grace that lands while the listener is away ends the predecessor's requests at the first sweep after the grace (at most one `gateway.inflight_sweep_interval` late), and an expiry extended by hand in psql during such a gap still ends them at the old expiry (no admin action extends an expiry). The kill switch and a removed or disabled alias still end a running request through the watcher. Every grant read of a running request — and the one at its entry — has the door's 1-second deadline, and the kill switch and the alias registry are checked in memory before it: while the database hangs (an exhausted pool, a locked grants table) the kill switch and a removed or disabled alias still end a running request within one watcher tick (5 s) plus that second, and a new request whose grant read does not answer in time gets `503 internal_error`. With the database down, a revoked key's running requests end through the local action of the same process or at its expiry timer; the signal and the sweep need the database. -- **Telemetry.** The request's one LLM-log row stores only ` ` as its error, never the backend's body (which can echo the prompt), and bodies only as `gateway.body_logging` allows — or whole for a consumer a server-admin set to record (see below). +- **Telemetry.** The request's one LLM-log row stores only ` ` as its error, never the backend's body (which can echo the prompt), and bodies only as `gateway.body_logging` allows; a consumer a server-admin set to record has every request held whole in a table of its own (see below). ## Gateway telemetry (`/v1`, `/v2`) What the gateway writes about a request, and what it never writes (design 06 §4.6): -- **One body policy.** `gateway.body_logging` is the only switch for prompt and answer bodies of the gateway rows of every consumer that does not record (next point) in `context_llm_log` — global-only, so no tenant can raise it for itself. `none` (default) stores none; `errors` stores the serialized request and the answer on rows with an error only; `full` on every row, each capped at 64 KiB. Every row is then slimmed as for a tenant without developer mode: a credentials-class row stays sealed under every policy, whatever the tenant's `tenant.devmode` says — and so does a row whose sensitivity is empty or unknown (fail-closed, logged as a wiring defect). Embedded NUL bytes and invalid UTF-8 are cleaned before the write, so a crafted body cannot make the row — and its attribution — vanish. -- **The one exception: a recording consumer (migration 197, issue #571).** A model consumer with `record_bodies` on has every gateway row of its own — chat, a stream's relayed answer, embeddings, rerank, rows with an error (they carry the request; the error ctx answered is the row's `error` column, ` `) — written with the request and the answer in full: whatever `gateway.body_logging`, the alias, the consumer's `prompt_sensitivity`, the body scan or `Ctx-Sensitivity` say, without the 64 KiB cut and without the credentials seal. **Such a row can carry credentials in clear text** — a password or key a client puts into a prompt is stored as sent. Only a server-admin can switch it on (also with self-service, and only with `confirm_record_bodies: true`); switching it off is open to the consumer's tenant-admin; both are audited. The row is marked `metadata.gw.recorded = true`, and its bodies reach a server-admin only: `GET /api/llmlog/{id}` answers every other caller with the uniform `404` (a gateway row has no knowledge key, so the tenant gate never matches it), the LLM log list, the usage and status surfaces carry no body, `ctx-llmlog-export` writes the row with its bodies sealed (also, fail-closed, every gateway row whose marker is missing or unreadable), and no pipeline (distill, dream, digest) reads the log's bodies (`TestBodyColumnReadersCensus` lists every reader of the body columns). **What the switch does not change:** the request path — the required sensitivity, the chain and its egress rule, the body scan and its `413`, the limits and the answer are the same with and without it (the captured texts are held against a fixed account of their own, never against the request's in-flight budget; the one booking that differs is the body policy's own log text of at most 64 KiB, booked at the end of a request under `gateway.body_logging` `errors`/`full`, which a recorded row does not take); deactivating and reactivating the consumer (the switch stays as it was); every other consumer's rows, byte for byte under every `gateway.body_logging` value; the retention — recorded bodies are NULLed after `scheduler.llmlog_retention_days` (90) like every body; and a database backup (`backup.sh`), which carries them like every other content of the database. Embedding vectors are not stored (the input is the record); the shutdown's forced row of a request still open carries no body and names it (`metadata.gw.record_lost`). See [operations — Recording a consumer](operations.md#recording-a-consumer). +- **One body policy.** `gateway.body_logging` is the only switch for prompt and answer bodies of gateway rows in `context_llm_log` — of every consumer, a recording one (next point) included — global-only, so no tenant can raise it for itself. `none` (default) stores none; `errors` stores the serialized request and the answer on rows with an error only; `full` on every row, each capped at 64 KiB. Every row is then slimmed as for a tenant without developer mode: a credentials-class row stays sealed under every policy, whatever the tenant's `tenant.devmode` says — and so does a row whose sensitivity is empty or unknown (fail-closed, logged as a wiring defect). Embedded NUL bytes and invalid UTF-8 are cleaned before the write, so a crafted body cannot make the row — and its attribution — vanish. +- **The one exception: a recording consumer (migration 197, issue #571).** A model consumer with `record_bodies` on has every request it sends through the gateway held in `context_llm_recordings` — chat (a stream included), embeddings, rerank, and every request the gateway refuses after the door accepted its key: the body **as the gateway read it, byte for byte** (whatever `gateway.body_logging`, the alias, the consumer's `prompt_sensitivity`, the body scan or `Ctx-Sensitivity` say — no cut, no credentials seal), the answer the client got (a non-streamed chat or rerank answer; a stream's relayed lines; no embedding vectors), the status and the gateway's code. **Such a row can carry credentials in clear text** — a password or key a client puts into a prompt is stored as sent. Only a server-admin can switch it on (also with self-service, and only with `confirm_record_bodies: true`); switching it off is open to the consumer's tenant-admin; both are audited. **No ctx surface reads the table's bodies:** no REST, MCP, CLI or web route, no export, no pipeline (distill, dream, digest) — `TestRecordingsReadersCensus` fails on any production statement that names the table outside its writer and the retention janitor; a server operator reads them in the database ([operations — Recording a consumer](operations.md#recording-a-consumer)). The consumer's `context_llm_log` rows are the rows of every consumer (body policy, cap, seal), marked `metadata.gw.recorded` with the `recording_id`. **Held before served:** the request is committed to the table before the first backend attempt; a request that cannot be held — the database refuses it or does not answer within 5 s, or the recording's memory account has no room within the request's wait budget — is answered `503 recording_unavailable` (`x-should-retry: true`, `Retry-After: 1`) and reaches no backend; a non-streamed answer the table does not take is that `503` instead of the answer. **What the switch does not change:** the required sensitivity, the chain and its egress rule, the body scan and its `413`, the limits, the in-flight budget's bookings and the answer are the same with and without it — the one new refusal is `recording_unavailable`, and every database write of the recording is in the request's time; deactivating and reactivating the consumer (the switch stays as it was); every other consumer (no stage, no write, no wait — their requests pass the recording stage untouched); the retention — the bodies are NULLed after `scheduler.llmlog_retention_days` (90) like every body; and a database backup (`backup.sh`), which carries them like every other content of the database. - **Error redaction.** The `error` column of a gateway row holds only class, status and ctx code. The upstream response body (which can echo prompt fragments, and which tenant-admins would read in the LLM log list) never reaches it; class and code must have the shape of vocabulary words (lower snake case, at most 64 characters), anything else is stored as `[redacted]`; the writer takes the code from the gateway's own code vocabulary, never from the upstream answer. - **One identity.** A gateway row is attributed to the consumer (`consumer_id`); a knowledge key id that reached the row anyway is cleared with an ERROR line, and the database refuses any row carrying both. The model key id is kept in `metadata.gw.model_key_id` for key-leak forensics, never as a column. - **Access log.** A successful request is one `gateway request` line with ids, op, alias, status, token counts and timings (`gateway.access_log`, default on) — no consumer label, no content, never a key, its hint or a query string. Refusals are counted per (consumer, reason — a code of the gateway or door vocabulary, else `http_`) and logged as one `gateway rejections` WARN line per minute with the count, so a flood of `401`/`429` answers cannot rotate the error and security lines out of the 50 MB × 3 container log. The global request log stays silent for these requests. diff --git a/go/cmd/ctxd/gateway.go b/go/cmd/ctxd/gateway.go index 52f1d72d4..ecb8f573d 100644 --- a/go/cmd/ctxd/gateway.go +++ b/go/cmd/ctxd/gateway.go @@ -147,6 +147,9 @@ type modelGateway struct { // counts top_consumers_1h for the status (W06-16). events *usageevents.Recorder ring *handler.ConsumerRing + // recorder is the recording stage of /v1 and /v2 (issue #571): one per + // process, over the process pool (llmlog.Recordings). + recorder *oai.RecordingStage } // usageEventsFlushTimeout bounds the final flush of the usage events at @@ -263,6 +266,9 @@ func newModelGateway(pool *pgxpool.Pool, cfgStore *config.Store, meterClock ...f usage: usage, binder: auth.PeerBindings{Pool: pool}, requirePeerHop: federationRequirePeerHopGetter(cfgStore), + recorder: oai.NewRecordingStage(llmlog.Recordings{Pool: pool}, handler.ConsumerAuthFromContext, get, func() time.Duration { + return cfgStore.Snapshot().Dispatch.ExternalMaxWait //nolint:forbidigo // MT 06 BLIND: dispatch.external_max_wait is global-only (one dispatcher per process); the recording's wait for room is the wait budget of every consumer alike. + }), } } @@ -272,7 +278,7 @@ func newModelGateway(pool *pgxpool.Pool, cfgStore *config.Store, meterClock ...f // the in-flight budget (stage 5). routes are the group's endpoints. func (g *modelGateway) group(ingress *fedhop.Ingress, maxDepth func() int, routes []modelRoute) modelGroupDeps { return modelGroupDeps{ - access: g.access, gate: oai.EnabledGate(g.settings), door: g.door, ingress: ingress, maxDepth: maxDepth, + access: g.access, gate: oai.EnabledGate(g.settings), door: g.door, recorder: g.recorder, ingress: ingress, maxDepth: maxDepth, binder: g.binder, requirePeerHop: g.requirePeerHop, events: g.peerNoter(), inner: []func(http.Handler) http.Handler{ handler.MaxBodySizeStrictWith(func() int64 { return g.settings().MaxRequestBytes }, oai.RefuseRequestTooLarge), diff --git a/go/cmd/ctxd/model_group.go b/go/cmd/ctxd/model_group.go index 990e39463..dd9e1a912 100644 --- a/go/cmd/ctxd/model_group.go +++ b/go/cmd/ctxd/model_group.go @@ -34,6 +34,12 @@ type modelGroupDeps struct { // failure lock, probe bucket and DB semaphore, so two groups never hold // twice the database share. door *handler.ModelDoor + // recorder is the recording stage right behind the door (issue #571, + // oai.RecordingStage): a recording consumer's requests are held before + // they are served; every other consumer passes it untouched. nil mounts + // none — a recording consumer's request is then refused at its route + // (fail-closed), never served unrecorded. + recorder *oai.RecordingStage // ingress is the federation-ingress registration of the router the group // is mounted on (F-W8, design/04 §4.6): mountModelGroup marks it, the // boot assert and the gateway.enabled settings write read it. The @@ -104,7 +110,11 @@ func mountModelGroup(r chi.Router, prefix string, deps modelGroupDeps) { Binder: deps.binder, RequirePeerHop: deps.requirePeerHop, Events: deps.events, }) r.Route(prefix, func(g chi.Router) { - g.Use(deps.access.Handler, oai.Recover, deps.gate, deps.door.Handler, loopGuard, peerIngress) + g.Use(deps.access.Handler, oai.Recover, deps.gate, deps.door.Handler) + if deps.recorder != nil { + g.Use(deps.recorder.Handler) + } + g.Use(loopGuard, peerIngress) g.Use(deps.inner...) g.NotFound(oai.NotFound) g.MethodNotAllowed(methodNotAllowed(g, routeMethods(deps.routes))) diff --git a/go/cmd/ctxd/v1_record_integration_test.go b/go/cmd/ctxd/v1_record_integration_test.go index c9e5b1452..4989baf68 100644 --- a/go/cmd/ctxd/v1_record_integration_test.go +++ b/go/cmd/ctxd/v1_record_integration_test.go @@ -1,49 +1,56 @@ //go:build integration // Issue #571 over the PRODUCTION router (buildRouter, the v1ChatFixture of -// v1_chat_integration_test.go): a consumer whose recording switch a -// server-admin set through /api/manage has its /v1 chat row written by the -// production writer (llmlog.RecordGateway → the async insert) with the whole -// request and answer — a prompt past the 64 KiB cap that carries a -// credentials pattern included — marked metadata.gw.recorded; the same -// request of a consumer without the switch gets the same answer and the row -// it always got. Then every reader of the row (TestBodyColumnReadersCensus -// lists them) with that row: +// v1_chat_integration_test.go) and a real database: a consumer whose +// recording switch a server-admin set through /api/manage has every request +// held in context_llm_recordings by the recording stage behind the door — // -// - GET /api/llmlog/{id}: a server-admin reads the bodies; the tenant-admin -// of the consumer's tenant gets the uniform 404; -// - GET /api/llmlog (list): metadata only, for both — the pattern is in -// neither answer; -// - GET /api/status: recording_consumers names the consumer — for the -// server-admin and for its tenant-admin — and no body; -// - ctx-llmlog-export (llmlogexport.Export): the row leaves sealed; -// - the retention janitor (llmlog.EvictBodies): the row's bodies go after -// the retention like every row's; -// - switching off (the tenant-admin may) applies from the next request, and +// - before the backend: while the recordings table refuses inserts (a +// lock), the request waits and the engine sees nothing; the engine +// holding the request finds its row committed, open, byte for byte — +// what a process killed at that moment leaves; +// +// - not held, not served: an insert the database refuses, or one that +// hangs past the statement deadline, is 503 recording_unavailable and +// the engine is never called; an answer the database does not take is +// 503 instead of the answer, the row stays open; +// +// - refused after the door: an unparsable body, an unknown model, a body +// over the cap (never read: its declared size), an unknown path, a wrong +// method — each leaves one row with its status and code; +// +// - the consumer without the switch: no recording row, the same answer, +// the llmlog row's bodies of the same request; +// +// - GET /api/status: gateway.recording for a server-admin — admitted = +// in_flight + recorded + unrecordable, recorded = the process's rows —, +// none for a tenant-admin; switching off applies from the next request; // model-alias-preview answers the same with and without the switch. // -// go test -tags=integration -p 1 -count=1 -run 'TestV1RecordedConsumer' -v ./cmd/ctxd/ +// go test -tags=integration -p 1 -count=1 -run 'TestV1RecordedConsumer' -v ./cmd/ctxd/ package main import ( "bytes" "context" + "crypto/tls" "encoding/json" + "io" "net/http" "net/http/httptest" "regexp" - "sort" + "strconv" "strings" "testing" + "time" "github.com/GottZ/ctx/internal/backends" "github.com/GottZ/ctx/internal/llmlog" - "github.com/GottZ/ctx/internal/llmlogexport" "github.com/GottZ/ctx/internal/store" ) // v1RecSecret is a credentials pattern (the sensitivity scan's assignment -// rule) — the kind of text a recorded row can carry in clear. +// rule) — the kind of text a recording can carry in clear. const v1RecSecret = "password=Tr0ub4dor-recorded-571" // v1RecAPI calls the router's /api surface with a knowledge key. @@ -68,43 +75,88 @@ func v1RecAPI(t *testing.T, f *v1ChatFixture, method, path, key string, body any return rec.Code, rec.Body.Bytes(), out } -// v1RecRow is the stored row of one consumer's newest gateway-chat call. -type v1RecRow struct { - id, user, resp, sens string - recorded *string - userNull bool +// v1RecDo sends one /v1 request with key over TLS (prep edits it). +func v1RecDo(f *v1ChatFixture, key, method, path, body string, prep ...func(*http.Request)) v1Answer { + req := httptest.NewRequest(method, path, strings.NewReader(body)) + req.RemoteAddr = "192.0.2.1:40000" + req.TLS = &tls.ConnectionState{} + req.Header.Set("Authorization", "Bearer "+key) + req.Header.Set("Content-Type", "application/json") + for _, p := range prep { + p(req) + } + rec := httptest.NewRecorder() + f.router.ServeHTTP(rec, req) + return v1Answer{status: rec.Code, header: rec.Header().Clone(), body: rec.Body.Bytes()} +} + +// v1Recording is one row of context_llm_recordings. +type v1Recording struct { + id, state, path, process string + op, code *string + status *int16 + declared *int64 + body, response []byte } -func v1RecRead(t *testing.T, f *v1ChatFixture, consumerID string) v1RecRow { +func v1RecRows(t *testing.T, f *v1ChatFixture, consumerID string) []v1Recording { t.Helper() - f.settle(t) - var r v1RecRow - var user, resp *string - if err := f.seed.QueryRow(context.Background(), ` - SELECT id::text, request_user, response_content, COALESCE(required_sensitivity, ''), metadata->'gw'->>'recorded' - FROM context_llm_log WHERE consumer_id = $1::uuid AND pipeline = $2 - ORDER BY created_at DESC, id DESC LIMIT 1`, consumerID, llmlog.PipelineGatewayChat). - Scan(&r.id, &user, &resp, &r.sens, &r.recorded); err != nil { - t.Fatalf("read the row of %s: %v", consumerID, err) + rs, err := f.seed.Query(context.Background(), `SELECT id::text, state, path, process_id::text, op, code, status, declared_bytes, request_body, response_body + FROM context_llm_recordings WHERE consumer_id = $1::uuid ORDER BY created_at, id`, consumerID) + if err != nil { + t.Fatalf("read recordings: %v", err) } - r.userNull = user == nil - if user != nil { - r.user = *user + defer rs.Close() + var out []v1Recording + for rs.Next() { + var r v1Recording + if err := rs.Scan(&r.id, &r.state, &r.path, &r.process, &r.op, &r.code, &r.status, &r.declared, &r.body, &r.response); err != nil { + t.Fatalf("scan: %v", err) + } + out = append(out, r) } - if resp != nil { - r.resp = *resp + return out +} + +func v1RecLast(t *testing.T, f *v1ChatFixture, consumerID string) v1Recording { + t.Helper() + rows := v1RecRows(t, f, consumerID) + if len(rows) == 0 { + t.Fatalf("no recording of %s", consumerID) + } + return rows[len(rows)-1] +} + +func v1RecCode(a v1Answer) string { + var env struct { + Error struct { + Code string `json:"code"` + } `json:"error"` } - return r + _ = json.Unmarshal(a.body, &env) + return env.Error.Code +} + +func deref16(p *int16) int { + if p == nil { + return 0 + } + return int(*p) +} + +func derefS(p *string) string { + if p == nil { + return "" + } + return *p } var v1RecIdentity = regexp.MustCompile(`"(id|created)":("[^"]*"|\d+)`) -func TestV1RecordedConsumerRowAndItsReaders(t *testing.T) { +func TestV1RecordedConsumer(t *testing.T) { e := newV1ChatEngine(t, http.StatusOK) f := newV1ChatFixture(t, []backends.Backend{e.row("eng", 10)}) ctx := context.Background() - // The fixture minted the first key already, so the server-admin is a key - // promoted the way model_inflight_integration_test.go promotes one. k, adminKey, err := store.CreateApiKey(ctx, f.seed, "v1-rec-admin", "private", nil, "") if err != nil { t.Fatalf("admin key: %v", err) @@ -112,8 +164,7 @@ func TestV1RecordedConsumerRowAndItsReaders(t *testing.T) { if _, err := f.seed.Exec(ctx, `UPDATE context_api_keys SET is_admin = true, tenant_role = 'owner' WHERE id = $1::uuid`, k.ID); err != nil { t.Fatalf("promote admin key: %v", err) } - v1RecAdminKey := adminKey - status, body, resp := v1RecAPI(t, f, http.MethodPost, "/api/manage", v1RecAdminKey, map[string]any{ + status, body, resp := v1RecAPI(t, f, http.MethodPost, "/api/manage", adminKey, map[string]any{ "action": "tenant-create", "data": map[string]any{"slug": "v1rec", "display_name": "v1 rec"}}) tenantAdmin, _ := resp["owner_key"].(string) tn, _ := resp["tenant"].(map[string]any) @@ -127,7 +178,7 @@ func TestV1RecordedConsumerRowAndItsReaders(t *testing.T) { for k, v := range extra { data[k] = v } - status, body, resp := v1RecAPI(t, f, http.MethodPost, "/api/manage", v1RecAdminKey, map[string]any{"action": "model-consumer-create", "data": data}) + status, body, resp := v1RecAPI(t, f, http.MethodPost, "/api/manage", adminKey, map[string]any{"action": "model-consumer-create", "data": data}) c, _ := resp["consumer"].(map[string]any) id, _ = c["id"].(string) key, _ = resp["api_key"].(string) @@ -138,111 +189,213 @@ func TestV1RecordedConsumerRowAndItsReaders(t *testing.T) { } recID, recKey := mkConsumer("v1-rec-on", map[string]any{"record_bodies": true, "confirm_record_bodies": true}) plainID, plainKey := mkConsumer("v1-rec-off", nil) - // A recording consumer of another tenant: the tenant-admin's status must - // not name it, the server-admin's must. - status, body, resp = v1RecAPI(t, f, http.MethodPost, "/api/manage", v1RecAdminKey, map[string]any{ - "action": "tenant-create", "data": map[string]any{"slug": "v1rec-other", "display_name": "v1 rec other"}}) - otherTn, _ := resp["tenant"].(map[string]any) - otherTenant, _ := otherTn["id"].(string) - if status != http.StatusOK || otherTenant == "" { - t.Fatalf("tenant-create other: %d %s", status, body) - } - status, body, resp = v1RecAPI(t, f, http.MethodPost, "/api/manage", v1RecAdminKey, map[string]any{"action": "model-consumer-create", - "data": map[string]any{"label": "v1-rec-foreign", "tenant_id": otherTenant, "record_bodies": true, "confirm_record_bodies": true}}) - foreign, _ := resp["consumer"].(map[string]any) - foreignID, _ := foreign["id"].(string) - if status != http.StatusOK || foreignID == "" { - t.Fatalf("foreign recording consumer: %d %s", status, body) - } content := v1RecSecret + " " + strings.Repeat("0123456789abcdef", 5<<10) // 80 KiB chat := `{"model":"` + v1ChatAlias + `","messages":[{"role":"user","content":"` + content + `"}]}` - messages := `[{"role":"user","content":"` + content + `"}]` - onA := f.post(t, recKey, chat) - offA := f.post(t, plainKey, chat) - if onA.status != http.StatusOK || offA.status != http.StatusOK { - t.Fatalf("status on %d off %d, want 200: %s / %s", onA.status, offA.status, onA.body, offA.body) - } - if v1RecIdentity.ReplaceAllString(string(onA.body), "") != v1RecIdentity.ReplaceAllString(string(offA.body), "") { - t.Errorf("the answer differs with the switch:\n on %s\n off %s", onA.body, offA.body) - } - e.mu.Lock() - sameUpstream := len(e.bodies) == 2 && bytes.Equal(e.bodies[0], e.bodies[1]) - e.mu.Unlock() - if !sameUpstream { - t.Errorf("the engine saw different bodies with and without the switch") - } - - rec := v1RecRead(t, f, recID) - plain := v1RecRead(t, f, plainID) - if rec.user != messages || rec.resp != strings.TrimSuffix(string(onA.body), "\n") || rec.recorded == nil || *rec.recorded != "true" { - t.Fatalf("recorded row: request %d bytes (want %d), answer %d bytes (want %d), recorded %v", - len(rec.user), len(messages), len(rec.resp), len(onA.body)-1, rec.recorded) - } - if rec.sens != string(backends.SensCredentials) || plain.sens != rec.sens { - t.Errorf("required_sensitivity recorded %q plain %q, want credentials both (the switch changes no class)", rec.sens, plain.sens) - } - if plain.user != "" || plain.resp != "" || plain.recorded != nil { - t.Errorf("the plain consumer's row: %d/%d body bytes, recorded %v — want the sealed row it always got", len(plain.user), len(plain.resp), plain.recorded) - } - t.Run("detail", func(t *testing.T) { - st, b, out := v1RecAPI(t, f, http.MethodGet, "/api/llmlog/"+rec.id, v1RecAdminKey, nil) - d, _ := out["detail"].(map[string]any) - if st != http.StatusOK || d["recorded"] != true || !strings.Contains(string(b), "Tr0ub4dor-recorded-571") { - t.Errorf("server-admin detail: %d recorded %v, secret present %v — want 200, true, the whole bodies", st, d["recorded"], strings.Contains(string(b), "Tr0ub4dor")) + t.Run("held_before_the_backend_and_answered", func(t *testing.T) { + // The recordings table takes no insert while the lock is held: the + // request waits for its recording, the engine sees nothing. + tx, err := f.seed.Begin(ctx) + if err != nil { + t.Fatal(err) + } + if _, err := tx.Exec(ctx, `LOCK TABLE context_llm_recordings IN SHARE MODE`); err != nil { + t.Fatal(err) } - stT, bT, _ := v1RecAPI(t, f, http.MethodGet, "/api/llmlog/"+rec.id, tenantAdmin, nil) - stU, bU, _ := v1RecAPI(t, f, http.MethodGet, "/api/llmlog/0195a6f0-0000-7000-8000-000000000571", tenantAdmin, nil) - if stT != http.StatusNotFound || string(bT) != string(bU) || strings.Contains(string(bT), "Tr0ub4dor") { - t.Errorf("tenant-admin detail of the recorded row: %d %s — want the uniform 404 of an unknown id (%d %s)", stT, bT, stU, bU) + hits := e.hits.Load() + done := make(chan v1Answer, 1) + go func() { done <- f.post(t, recKey, chat) }() + time.Sleep(400 * time.Millisecond) + waiting := e.hits.Load() - hits + _ = tx.Commit(ctx) + on := <-done + if waiting != 0 { + t.Errorf("the engine was called %d times while the request's recording could not be committed", waiting) + } + off := f.post(t, plainKey, chat) + if on.status != 200 || off.status != 200 || v1RecIdentity.ReplaceAllString(string(on.body), "") != v1RecIdentity.ReplaceAllString(string(off.body), "") { + t.Fatalf("status on %d off %d, the same answer %v", on.status, off.status, + v1RecIdentity.ReplaceAllString(string(on.body), "") == v1RecIdentity.ReplaceAllString(string(off.body), "")) + } + r := v1RecLast(t, f, recID) + if r.state != llmlog.RecordingDone || string(r.body) != chat || string(r.response) != string(on.body) || deref16(r.status) != 200 || + r.process != llmlog.ProcessID || derefS(r.op) != llmlog.GatewayOpChat || r.path != "/v1/chat/completions" { + t.Errorf("recording: state %q, request %d bytes (want %d, exact), answer %d bytes (want the client's %d), status %d, process %v, op %q, path %q", + r.state, len(r.body), len(chat), len(r.response), len(on.body), deref16(r.status), r.process == llmlog.ProcessID, derefS(r.op), r.path) + } + if n := len(v1RecRows(t, f, plainID)); n != 0 { + t.Errorf("the consumer without the switch has %d recordings, want none", n) + } + // Its llmlog row is the row of every consumer, plus the marker. + f.settle(t) + var recUser, plainUser, sens, recorded, recordingID string + if err := f.seed.QueryRow(ctx, `SELECT COALESCE(request_user, ''), COALESCE(required_sensitivity, ''), COALESCE(metadata->'gw'->>'recorded', ''), + COALESCE(metadata->'gw'->>'recording_id', '') FROM context_llm_log WHERE consumer_id = $1::uuid ORDER BY created_at DESC LIMIT 1`, recID). + Scan(&recUser, &sens, &recorded, &recordingID); err != nil { + t.Fatalf("llmlog row: %v", err) + } + if err := f.seed.QueryRow(ctx, `SELECT COALESCE(request_user, '') FROM context_llm_log WHERE consumer_id = $1::uuid ORDER BY created_at DESC LIMIT 1`, plainID). + Scan(&plainUser); err != nil { + t.Fatalf("plain llmlog row: %v", err) + } + if recorded != "true" || recordingID != r.id || recUser != plainUser || sens != string(backends.SensCredentials) { + t.Errorf("llmlog row: recorded %q recording_id %q (want %q), bodies as the plain consumer's %v, class %q", + recorded, recordingID, r.id, recUser == plainUser, sens) } }) - t.Run("list", func(t *testing.T) { - for name, key := range map[string]string{"server_admin": v1RecAdminKey, "tenant_admin": tenantAdmin} { - st, b, out := v1RecAPI(t, f, http.MethodGet, "/api/llmlog?consumer_id="+recID, key, nil) - entries, _ := out["entries"].([]any) - if st != http.StatusOK || len(entries) == 0 || strings.Contains(string(b), "Tr0ub4dor") || strings.Contains(string(b), "0123456789abcdef0123") { - t.Errorf("%s list: %d, %d entries, a body in the answer %v — want 200, the row, metadata only", name, st, len(entries), strings.Contains(string(b), "Tr0ub4dor")) + t.Run("open_while_the_engine_holds_it", func(t *testing.T) { + release := e.holdUntilReleased(t) + done := make(chan v1Answer, 1) + go func() { done <- f.post(t, recKey, chat) }() + deadline := time.Now().Add(10 * time.Second) + for e.hits.Load() == 0 || len(v1RecRows(t, f, recID)) < 2 { + if time.Now().After(deadline) { + t.Fatal("the engine never got the request") } + time.Sleep(10 * time.Millisecond) + } + // What a process killed now leaves: the request, whole, open. + r := v1RecLast(t, f, recID) + release() + <-done + e.gate.Store(nil) + if r.state != llmlog.RecordingOpen || string(r.body) != chat || r.status != nil { + t.Errorf("while the engine held it: state %q, request exact %v, status %v — want open with the whole request", r.state, string(r.body) == chat, r.status) } }) - t.Run("status", func(t *testing.T) { - both := []string{recID, foreignID} - sort.Strings(both) - for name, c := range map[string]struct { - key string - want []string - }{"server_admin": {v1RecAdminKey, both}, "tenant_admin": {tenantAdmin, []string{recID}}} { - st, b, out := v1RecAPI(t, f, http.MethodGet, "/api/status", c.key, nil) - gw, _ := out["gateway"].(map[string]any) - raw, _ := json.Marshal(gw["recording_consumers"]) - want, _ := json.Marshal(c.want) - if st != http.StatusOK || string(raw) != string(want) || strings.Contains(string(b), "Tr0ub4dor") { - t.Errorf("%s status: %d recording_consumers %s — want exactly %s, no body", name, st, raw, want) - } + t.Run("insert_refused_not_served", func(t *testing.T) { + if _, err := f.seed.Exec(ctx, `CREATE FUNCTION zz_rec_refuse() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN RAISE EXCEPTION 'recordings refused'; END $$; + CREATE TRIGGER zz_rec_refuse BEFORE INSERT ON context_llm_recordings FOR EACH ROW EXECUTE FUNCTION zz_rec_refuse()`); err != nil { + t.Fatal(err) + } + hits, rows := e.hits.Load(), len(v1RecRows(t, f, recID)) + a := f.post(t, recKey, chat) + if _, err := f.seed.Exec(ctx, `DROP TRIGGER zz_rec_refuse ON context_llm_recordings; DROP FUNCTION zz_rec_refuse()`); err != nil { + t.Fatal(err) + } + if a.status != 503 || v1RecCode(a) != "recording_unavailable" || a.header.Get("X-Should-Retry") != "true" || a.header.Get("Retry-After") == "" { + t.Errorf("answer %d %q (x-should-retry %q, Retry-After %q), want 503 recording_unavailable, retryable", a.status, v1RecCode(a), + a.header.Get("X-Should-Retry"), a.header.Get("Retry-After")) + } + if n := e.hits.Load() - hits; n != 0 || len(v1RecRows(t, f, recID)) != rows { + t.Errorf("engine calls %d, recordings %d → %d — want none of either", n, rows, len(v1RecRows(t, f, recID))) } }) - t.Run("export", func(t *testing.T) { - var buf bytes.Buffer - sum, err := llmlogexport.Export(ctx, f.seed, &buf, llmlogexport.ExportOptions{UntilMargin: 1}) + t.Run("insert_hangs_not_served", func(t *testing.T) { + tx, err := f.seed.Begin(ctx) if err != nil { - t.Fatalf("export: %v", err) + t.Fatal(err) + } + if _, err := tx.Exec(ctx, `LOCK TABLE context_llm_recordings IN ACCESS EXCLUSIVE MODE`); err != nil { + t.Fatal(err) + } + hits := e.hits.Load() + start := time.Now() + a := f.post(t, recKey, chat) + took := time.Since(start) + _ = tx.Rollback(ctx) + if a.status != 503 || v1RecCode(a) != "recording_unavailable" || e.hits.Load() != hits { + t.Errorf("answer %d %q after %v, %d engine calls — want 503 recording_unavailable, none", a.status, v1RecCode(a), took, e.hits.Load()-hits) + } + if took < 5*time.Second { + t.Errorf("answered after %v — the statement deadline is 5 s", took) + } + }) + t.Run("answer_not_held_not_written", func(t *testing.T) { + if _, err := f.seed.Exec(ctx, `CREATE FUNCTION zz_rec_refuse() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN RAISE EXCEPTION 'outcome refused'; END $$; + CREATE TRIGGER zz_rec_refuse BEFORE UPDATE ON context_llm_recordings FOR EACH ROW EXECUTE FUNCTION zz_rec_refuse()`); err != nil { + t.Fatal(err) } - // The summary by its wire (the CLI's stderr JSON), so the file - // compiles against the base. - var counts map[string]any - _ = json.Unmarshal(llmlogexport.MarshalSummary(sum), &counts) - if strings.Contains(buf.String(), "Tr0ub4dor") || counts["rows_recorded_sealed"] != float64(1) { - t.Errorf("export: secret present %v, rows_recorded_sealed %v — want the recorded row sealed", strings.Contains(buf.String(), "Tr0ub4dor"), counts["rows_recorded_sealed"]) + a := f.post(t, recKey, chat) + if _, err := f.seed.Exec(ctx, `DROP TRIGGER zz_rec_refuse ON context_llm_recordings; DROP FUNCTION zz_rec_refuse()`); err != nil { + t.Fatal(err) } - if !strings.Contains(buf.String(), rec.id) { - t.Errorf("the export left the recorded row out — it keeps the row, without its bodies") + r := v1RecLast(t, f, recID) + if a.status != 503 || v1RecCode(a) != "recording_unavailable" || strings.Contains(string(a.body), "choices") { + t.Errorf("answer %d %q, want 503 recording_unavailable and no answer: %.200s", a.status, v1RecCode(a), a.body) + } + if r.state != llmlog.RecordingOpen || string(r.body) != chat { + t.Errorf("recording %q, request exact %v — want it open with the whole request", r.state, string(r.body) == chat) + } + }) + t.Run("refused_after_the_door", func(t *testing.T) { + over := int64(8<<20) + 1 // gateway.max_request_bytes at its default (the fixture's environment sets none) + for _, tc := range []struct { + name, method, path, body string + prep func(*http.Request) + status int + code string + wantBody string + declared int64 + }{ + {"unparsable", http.MethodPost, "/v1/chat/completions", `{"model":"` + v1ChatAlias + `","messages":[`, nil, 400, "invalid_json", `{"model":"` + v1ChatAlias + `","messages":[`, -2}, + {"unknown_model", http.MethodPost, "/v1/chat/completions", `{"model":"no-such-571","messages":[{"role":"user","content":"x"}]}`, nil, 404, "model_not_found", `{"model":"no-such-571","messages":[{"role":"user","content":"x"}]}`, -2}, + {"over_the_cap", http.MethodPost, "/v1/chat/completions", "{}", func(r *http.Request) { + r.ContentLength = over + r.Header.Set("Content-Length", strconv.FormatInt(over, 10)) + }, 413, "request_too_large", "", over}, + // The catch-alls name no reason on the access record: the row + // carries their status, no code. + {"unknown_path", http.MethodPost, "/v1/nowhere", "{}", nil, 404, "", "", -2}, + {"wrong_method", http.MethodGet, "/v1/chat/completions", "", nil, 405, "", "", -2}, + } { + t.Run(tc.name, func(t *testing.T) { + before := len(v1RecRows(t, f, recID)) + var prep []func(*http.Request) + if tc.prep != nil { + prep = append(prep, tc.prep) + } + a := v1RecDo(f, recKey, tc.method, tc.path, tc.body, prep...) + rows := v1RecRows(t, f, recID) + if a.status != tc.status || len(rows) != before+1 { + t.Fatalf("answer %d (want %d), recordings %d → %d (want one more)", a.status, tc.status, before, len(rows)) + } + r := rows[len(rows)-1] + if r.state != llmlog.RecordingDone || deref16(r.status) != tc.status || derefS(r.code) != tc.code || string(r.body) != tc.wantBody || r.path != tc.path { + t.Errorf("row: state %q status %d code %q body %q path %q — want done %d %q, body %q", r.state, deref16(r.status), derefS(r.code), r.body, r.path, tc.status, tc.code, tc.wantBody) + } + if tc.declared != -2 && (r.declared == nil || *r.declared != tc.declared) { + t.Errorf("declared size %v, want %d (the body was never read)", r.declared, tc.declared) + } + }) + } + }) + t.Run("status", func(t *testing.T) { + st, b, out := v1RecAPI(t, f, http.MethodGet, "/api/status", adminKey, nil) + gw, _ := out["gateway"].(map[string]any) + rec, _ := gw["recording"].(map[string]any) + if st != 200 || rec == nil || rec["process_id"] != llmlog.ProcessID { + t.Fatalf("server-admin status: %d recording %v — want the section with this process's id: %.300s", st, rec, b) + } + var mine map[string]any + cons, _ := rec["consumers"].([]any) + for _, c := range cons { + if m, _ := c.(map[string]any); m["consumer_id"] == recID { + mine = m + } + } + num := func(k string) int64 { v, _ := mine[k].(float64); return int64(v) } + var rows int64 + if err := f.seed.QueryRow(ctx, `SELECT count(*) FROM context_llm_recordings WHERE consumer_id = $1::uuid AND process_id = $2::uuid`, recID, llmlog.ProcessID).Scan(&rows); err != nil { + t.Fatal(err) + } + if mine == nil || num("admitted") != num("in_flight")+num("recorded")+num("unrecordable") || num("recorded") != rows || + num("unrecordable") < 1 || num("unfinished") < 1 { + t.Errorf("counts %v with %d rows of this process — want admitted = in_flight + recorded + unrecordable, recorded = rows, the refused insert and the open row counted", mine, rows) + } + _, bt, outT := v1RecAPI(t, f, http.MethodGet, "/api/status", tenantAdmin, nil) + gwT, _ := outT["gateway"].(map[string]any) + if _, ok := gwT["recording"]; ok || strings.Contains(string(bt), "Tr0ub4dor") { + t.Errorf("the tenant-admin's status carries the recording section or a body") + } + if strings.Contains(string(b), "Tr0ub4dor") { + t.Errorf("the server-admin's status carries a body") } }) preview := func() string { t.Helper() - st, b, _ := v1RecAPI(t, f, http.MethodPost, "/api/manage", v1RecAdminKey, map[string]any{ + st, b, _ := v1RecAPI(t, f, http.MethodPost, "/api/manage", adminKey, map[string]any{ "action": "model-alias-preview", "data": map[string]any{"consumer_id": recID, "alias": v1ChatAlias}}) if st != http.StatusOK { t.Fatalf("model-alias-preview: %d %s", st, b) @@ -259,41 +412,13 @@ func TestV1RecordedConsumerRowAndItsReaders(t *testing.T) { if previewOff := preview(); previewOff != previewOn { t.Errorf("model-alias-preview differs with the switch:\n on %s\n off %s", previewOn, previewOff) } + before := len(v1RecRows(t, f, recID)) if a := f.post(t, recKey, chat); a.status != http.StatusOK { t.Fatalf("request after the switch: %d", a.status) } - if r := v1RecRead(t, f, recID); r.id == rec.id || r.recorded != nil || r.user != "" { - t.Errorf("the next row after switching off: recorded %v, %d body bytes — want an unrecorded, sealed row", r.recorded, len(r.user)) - } - }) - t.Run("retention_janitor", func(t *testing.T) { - // A hypertable row cannot move to an older chunk, so the recorded row - // is copied 91 days back (its bodies and metadata as the writer - // stored them) and the janitor runs over both. - var old string - if err := f.seed.QueryRow(ctx, `INSERT INTO context_llm_log - SELECT (jsonb_populate_record(NULL::context_llm_log, to_jsonb(t) || - jsonb_build_object('id', gen_random_uuid(), 'created_at', now() - interval '91 days'))).* - FROM context_llm_log t WHERE t.id = $1::uuid - RETURNING id::text`, rec.id).Scan(&old); err != nil { - t.Fatalf("copy the row back: %v", err) - } - if _, err := llmlog.EvictBodies(ctx, f.seed, 90); err != nil { - t.Fatalf("evict: %v", err) - } - bodies := func(id string) (user, resp, recorded *string) { - t.Helper() - if err := f.seed.QueryRow(ctx, `SELECT request_user, response_content, metadata->'gw'->>'recorded' FROM context_llm_log WHERE id = $1::uuid`, id). - Scan(&user, &resp, &recorded); err != nil { - t.Fatalf("read: %v", err) - } - return user, resp, recorded - } - if u, r, m := bodies(old); u != nil || r != nil || m == nil || *m != "true" { - t.Errorf("past the retention: request %v answer %v recorded %v — want NULL bodies and the marker kept", u != nil, r != nil, m) - } - if u, _, _ := bodies(rec.id); u == nil || *u != messages { - t.Errorf("the janitor touched the recorded row inside the retention") + if n := len(v1RecRows(t, f, recID)); n != before { + t.Errorf("a request after switching off was recorded (%d → %d rows)", before, n) } }) + _ = io.EOF } diff --git a/go/cmd/ctxd/v1_record_latency_integration_test.go b/go/cmd/ctxd/v1_record_latency_integration_test.go new file mode 100644 index 000000000..242dc603d --- /dev/null +++ b/go/cmd/ctxd/v1_record_latency_integration_test.go @@ -0,0 +1,92 @@ +//go:build integration + +// The latency the recording of issue #571 adds to a request (opt-in probe, +// CTX_RECORD_PROBE=1): the production router over a throwaway database, +// a small chat request and a large embeddings request (1.5 MiB, below the +// scan cap), each sent alternately by the same consumer with the recording +// switch off and on — the switch flipped in the consumer row between the +// two (the door reads it on every request) — and the end-to-end time of the +// router's ServeHTTP per request. p50 and p99 per form and switch. +// +// CTX_RECORD_PROBE=1 go test -tags=integration -p 1 -count=1 -run TestV1RecordingLatency -v ./cmd/ctxd/ +package main + +import ( + "context" + "fmt" + "net/http" + "os" + "slices" + "strings" + "testing" + "time" + + "github.com/GottZ/ctx/internal/backends" +) + +func v1RecPercentiles(d []time.Duration) (p50, p99 time.Duration) { + s := slices.Clone(d) + slices.Sort(s) + at := func(q float64) time.Duration { return s[min(len(s)-1, int(q*float64(len(s))))] } + return at(0.50), at(0.99) +} + +func TestV1RecordingLatency(t *testing.T) { + if os.Getenv("CTX_RECORD_PROBE") != "1" { + t.Skip("opt-in probe (CTX_RECORD_PROBE=1)") + } + const n = 200 + ctx := context.Background() + measure := func(t *testing.T, name string, flip func(on bool), send func() int) { + t.Helper() + var off, on []time.Duration + for i := 0; i < 10; i++ { // warm both paths + flip(i%2 == 1) + send() + } + for i := 0; i < 2*n; i++ { + rec := i%2 == 1 + flip(rec) + start := time.Now() + if st := send(); st != http.StatusOK { + t.Fatalf("%s request %d (recording %v): status %d", name, i, rec, st) + } + d := time.Since(start) + if rec { + on = append(on, d) + } else { + off = append(off, d) + } + } + p50off, p99off := v1RecPercentiles(off) + p50on, p99on := v1RecPercentiles(on) + t.Logf("%s, %d requests each: off p50 %v p99 %v — on p50 %v p99 %v — Δp50 %v Δp99 %v", name, n, + p50off, p99off, p50on, p99on, p50on-p50off, p99on-p99off) + } + t.Run("chat_small", func(t *testing.T) { + e := newV1ChatEngine(t, http.StatusOK) + f := newV1ChatFixture(t, []backends.Backend{e.row("eng", 10)}) + body := `{"model":"` + v1ChatAlias + `","messages":[{"role":"user","content":"a short question of about a hundred bytes, as a chat client sends it"}]}` + flip := func(on bool) { + if _, err := f.seed.Exec(ctx, `UPDATE context_model_consumers SET record_bodies = $2 WHERE id = $1::uuid`, f.urgentID, on); err != nil { + t.Fatal(err) + } + } + measure(t, fmt.Sprintf("chat, %d-byte body", len(body)), flip, func() int { return f.post(t, f.urgentKey, body).status }) + }) + t.Run("embeddings_large", func(t *testing.T) { + eng := newV1EmbedEngine(t) + f := newV1EmbedFixture(t, eng) + inputs := make([]string, 48) + for i := range inputs { + inputs[i] = `"` + strings.Repeat(fmt.Sprintf("chunk %02d of a corpus document ", i), 1000) + `"` + } + body := `{"model":"` + v1EmbedAlias + `","input":[` + strings.Join(inputs, ",") + `]}` + flip := func(on bool) { + if _, err := f.seed.Exec(ctx, `UPDATE context_model_consumers SET record_bodies = $2 WHERE id = $1::uuid`, f.urgentID, on); err != nil { + t.Fatal(err) + } + } + measure(t, fmt.Sprintf("embeddings, %d-byte body", len(body)), flip, func() int { return f.post(t, f.urgentKey, body).status }) + }) +} diff --git a/go/internal/backends/classify.go b/go/internal/backends/classify.go index d707427fd..275970c56 100644 --- a/go/internal/backends/classify.go +++ b/go/internal/backends/classify.go @@ -271,6 +271,8 @@ var gatewayCodeClasses = map[string]ErrClass{ "proxy_misconfigured": ClassGateway, "auth_overloaded": ClassGateway, "auth_unavailable": ClassGateway, + // a recording consumer's request whose recording failed (issue #571) + "recording_unavailable": ClassGateway, // 500 — the one STOP code: the upstream ran the request "upstream_error": ClassServerFault, // 401, 403 diff --git a/go/internal/handler/llmlog.go b/go/internal/handler/llmlog.go index ddbf3a73e..4c5ee02e1 100644 --- a/go/internal/handler/llmlog.go +++ b/go/internal/handler/llmlog.go @@ -229,11 +229,6 @@ type llmlogDetail struct { RequestSystem *string `json:"request_system"` RequestUser *string `json:"request_user"` ResponseContent *string `json:"response_content"` - // Recorded marks the row of a recording consumer (metadata.gw.recorded, - // issue #571): its bodies are whole and can carry credentials in clear - // text. Only a server-admin reaches such a row here — a gateway row has - // no api_key_id, so the tenant gate below never matches it. - Recorded bool `json:"recorded"` } // HandleLLMLogDetail serves GET /api/llmlog/{id} — the gated prompt/reply body @@ -287,14 +282,13 @@ func (h *LLMLogHandler) HandleLLMLogDetail(w http.ResponseWriter, r *http.Reques err := h.pool.QueryRow(r.Context(), ` SELECT id::text, created_at, pipeline, model, COALESCE(backend_name, host) AS backend, - required_sensitivity, request_system, request_user, response_content, - COALESCE(metadata->'gw'->'recorded' = 'true'::jsonb, false) + required_sensitivity, request_system, request_user, response_content FROM context_llm_log WHERE id = $1::uuid AND ($2::uuid[] IS NULL OR api_key_id = ANY($2))`, id, keyFilter, ).Scan(&d.ID, &d.CreatedAt, &d.Pipeline, &d.Model, &d.Backend, - &sensitivity, &reqSystem, &reqUser, &respContent, &d.Recorded) + &sensitivity, &reqSystem, &reqUser, &respContent) if err != nil { if errors.Is(err, pgx.ErrNoRows) { // Unknown id OR a row the caller may not see — one uniform answer. diff --git a/go/internal/handler/llmlog_test.go b/go/internal/handler/llmlog_test.go index 65f8af561..f2edad99c 100644 --- a/go/internal/handler/llmlog_test.go +++ b/go/internal/handler/llmlog_test.go @@ -129,7 +129,7 @@ func TestLLMLogDetailGoldenKeys(t *testing.T) { assertKeys(t, "detail", top["detail"], []string{ "id", "created_at", "pipeline", "model", "backend", "required_sensitivity", "body_state", - "request_system", "request_user", "response_content", "recorded", + "request_system", "request_user", "response_content", }) } diff --git a/go/internal/handler/model_consumers.go b/go/internal/handler/model_consumers.go index aa041bdea..eb9ada6fe 100644 --- a/go/internal/handler/model_consumers.go +++ b/go/internal/handler/model_consumers.go @@ -580,8 +580,8 @@ func (d *consumerCreateRequest) grant() consumerGrant { // confirm_record_bodies (the confirm_trust_elevation pattern): the switch // stores what the consumer sends in clear text, credentials in a prompt // included. -const recordConfirmRefusal = "record_bodies:true stores every request and answer of this consumer in full in the LLM log — " + - "credentials in a prompt included, in clear text, readable by server-admins — requires confirm_record_bodies:true" +const recordConfirmRefusal = "record_bodies:true holds every request and answer of this consumer in full in context_llm_recordings — " + + "credentials in a prompt included, in clear text, readable in the database — requires confirm_record_bodies:true" // errRecordConfirm is the refusal of recordConfirmRefusal under the consumer // lock (store.UpdateConsumerChecked); it surfaces as that 400. diff --git a/go/internal/handler/model_consumers_record_integration_test.go b/go/internal/handler/model_consumers_record_integration_test.go index 628eb497c..fd467b1e5 100644 --- a/go/internal/handler/model_consumers_record_integration_test.go +++ b/go/internal/handler/model_consumers_record_integration_test.go @@ -47,8 +47,8 @@ func TestModelConsumerRecordSwitch(t *testing.T) { const adminRequired = "admin key required" // The wire text of the refusal (recordConfirmRefusal), spelled out so the // file compiles against the base. - const confirm = "record_bodies:true stores every request and answer of this consumer in full in the LLM log — " + - "credentials in a prompt included, in clear text, readable by server-admins — requires confirm_record_bodies:true" + const confirm = "record_bodies:true holds every request and answer of this consumer in full in context_llm_recordings — " + + "credentials in a prompt included, in clear text, readable in the database — requires confirm_record_bodies:true" recordOf := func(resp map[string]any) any { c, _ := resp["consumer"].(map[string]any) return c["record_bodies"] diff --git a/go/internal/handler/status.go b/go/internal/handler/status.go index 4854da395..ab277a16d 100644 --- a/go/internal/handler/status.go +++ b/go/internal/handler/status.go @@ -307,22 +307,11 @@ type statusResponse struct { type llmlogWriteStatus struct { InsertFailures int64 `json:"insert_failures"` InsertDropped int64 `json:"insert_dropped"` - // RecordedBodiesLost counts the rows of recording consumers written - // without a body they should carry (llmlog.RecordedBodiesLost; the row - // names it in metadata.gw.record_lost) — monotone since start, like the - // two above. - RecordedBodiesLost int64 `json:"recorded_bodies_lost"` - // RecordedHeldBytes is what the texts of recorded rows hold of their - // account now (llmlog.RecordedHeld, bounded at 128 MiB): captured by - // running requests, queued or being inserted — near the bound, the next - // large texts are left out. - RecordedHeldBytes int64 `json:"recorded_held_bytes"` } // readLLMLogWriteStatus is the production llmlogStats source. func readLLMLogWriteStatus() llmlogWriteStatus { - return llmlogWriteStatus{InsertFailures: llmlog.InsertFailures(), InsertDropped: llmlog.InsertDropped(), - RecordedBodiesLost: llmlog.RecordedBodiesLost(), RecordedHeldBytes: llmlog.RecordedHeld()} + return llmlogWriteStatus{InsertFailures: llmlog.InsertFailures(), InsertDropped: llmlog.InsertDropped()} } // advisoryRow is one named reason on the admin status surface (A02-W4): diff --git a/go/internal/handler/status_gateway.go b/go/internal/handler/status_gateway.go index 790cf6d14..50857d9aa 100644 --- a/go/internal/handler/status_gateway.go +++ b/go/internal/handler/status_gateway.go @@ -11,6 +11,7 @@ import ( "github.com/GottZ/ctx/internal/federation" "github.com/GottZ/ctx/internal/fedhop" "github.com/GottZ/ctx/internal/llmusage" + "github.com/GottZ/ctx/internal/oai" "github.com/GottZ/ctx/internal/usageevents" ) @@ -28,7 +29,7 @@ import ( // consumers, consumers_used_1h, consumers_expiring, recording_consumers, // top_consumers_1h, // reservations_open and rejections_5m of its consumers — and never -// instance_envelope, auth or events (pointers left nil). +// instance_envelope, auth, events or recording (pointers left nil). // - usage_split_24h, federation: server-admin only (foreign-load // aggregates; dispatcher.go exposure rule), never on the tenant path. // - Hub load (V-06-d, K-05-19): top_consumers_1h comes from an in-memory @@ -55,19 +56,25 @@ type gatewayStatus struct { Consumers int64 `json:"consumers"` // ReservationsOpen and Rejections5m are null until the meter and the // in-memory ledger feed them (null ≠ 0). - ReservationsOpen *int64 `json:"reservations_open"` - Rejections5m map[string]int64 `json:"rejections_5m"` - TopConsumers1h []TopConsumer `json:"top_consumers_1h"` - ConsumersUsed1h int64 `json:"consumers_used_1h"` - ConsumersExpiring int64 `json:"consumers_expiring"` - // RecordingConsumers are the ids of the active consumers whose gateway - // rows keep their request and answer in full (record_bodies, migration - // 197), sorted — every one for a server-admin, the tenant's own for a + ReservationsOpen *int64 `json:"reservations_open"` + Rejections5m map[string]int64 `json:"rejections_5m"` + TopConsumers1h []TopConsumer `json:"top_consumers_1h"` + ConsumersUsed1h int64 `json:"consumers_used_1h"` + ConsumersExpiring int64 `json:"consumers_expiring"` + // RecordingConsumers are the ids of the active consumers whose requests + // are recorded whole (record_bodies, migration 197; context_llm_recordings), + // sorted — every one for a server-admin, the tenant's own for a // tenant-admin; [] when none records. - RecordingConsumers []string `json:"recording_consumers"` - InstanceEnvelope *map[string]envelopeUse `json:"instance_envelope,omitempty"` - Auth *ModelAuthStats `json:"auth,omitempty"` - Events *usageevents.Stats `json:"events,omitempty"` + RecordingConsumers []string `json:"recording_consumers"` + // Recording is this process's count of the requests of recording + // consumers (oai.RecordingStats; docs/operations.md "Recording a + // consumer"): per consumer admitted = in_flight + recorded + + // unrecordable, the rows' process_id, the account's fill. Server-admin + // only. + Recording *oai.RecordingSnapshot `json:"recording,omitempty"` + InstanceEnvelope *map[string]envelopeUse `json:"instance_envelope,omitempty"` + Auth *ModelAuthStats `json:"auth,omitempty"` + Events *usageevents.Stats `json:"events,omitempty"` // GeneratedAt is when the 30-second generation behind the counts was // built (the counts are that old at most). GeneratedAt *time.Time `json:"generated_at,omitempty"` @@ -293,6 +300,8 @@ func (c *StatusCollector) stampGateway(ctx context.Context, resp *statusResponse ev := f.Events() gw.Events = &ev } + rec := oai.RecordingStats() + gw.Recording = &rec split := g.split if split == nil { split = []llmusage.SplitRow{} diff --git a/go/internal/handler/status_llmlog_test.go b/go/internal/handler/status_llmlog_test.go index 7f8304570..5df62b61a 100644 --- a/go/internal/handler/status_llmlog_test.go +++ b/go/internal/handler/status_llmlog_test.go @@ -11,8 +11,7 @@ import ( // TestStatusLLMLogSection is the status half of W06-1 gate (a): the server- // admin frame carries the llmlog write-path loss counters as a section that is -// PRESENT even when they are 0 (the two recording keys of issue #571 beside -// them) — a zero must read as "nothing lost", never as +// PRESENT even when both are 0 — a zero must read as "nothing lost", never as // "not measured" — and shows exactly what the counters hold. func TestStatusLLMLogSection(t *testing.T) { for _, tc := range []struct { @@ -20,9 +19,9 @@ func TestStatusLLMLogSection(t *testing.T) { failures, dropped int64 wire string }{ - {"zero_is_present", 0, 0, `"llmlog":{"insert_failures":0,"insert_dropped":0,"recorded_bodies_lost":0,"recorded_held_bytes":0}`}, - {"one_failure", 1, 0, `"llmlog":{"insert_failures":1,"insert_dropped":0,"recorded_bodies_lost":0,"recorded_held_bytes":0}`}, - {"drops", 3, 9, `"llmlog":{"insert_failures":3,"insert_dropped":9,"recorded_bodies_lost":0,"recorded_held_bytes":0}`}, + {"zero_is_present", 0, 0, `"llmlog":{"insert_failures":0,"insert_dropped":0}`}, + {"one_failure", 1, 0, `"llmlog":{"insert_failures":1,"insert_dropped":0}`}, + {"drops", 3, 9, `"llmlog":{"insert_failures":3,"insert_dropped":9}`}, } { t.Run(tc.name, func(t *testing.T) { c := &StatusCollector{llmlogStats: func() llmlogWriteStatus { @@ -51,9 +50,7 @@ func TestStatusCollectorWiresLLMLogCounters(t *testing.T) { t.Fatal("NewStatusCollector left the llmlog counter source unwired — the section would vanish in production") } got := c.llmlogStats() - if got.InsertFailures != llmlog.InsertFailures() || got.InsertDropped != llmlog.InsertDropped() || - got.RecordedBodiesLost != llmlog.RecordedBodiesLost() || got.RecordedHeldBytes != llmlog.RecordedHeld() { - t.Errorf("collector reads %+v, llmlog holds failures=%d dropped=%d recorded lost=%d held=%d", got, - llmlog.InsertFailures(), llmlog.InsertDropped(), llmlog.RecordedBodiesLost(), llmlog.RecordedHeld()) + if got.InsertFailures != llmlog.InsertFailures() || got.InsertDropped != llmlog.InsertDropped() { + t.Errorf("collector reads %+v, llmlog holds failures=%d dropped=%d", got, llmlog.InsertFailures(), llmlog.InsertDropped()) } } diff --git a/go/internal/handler/status_test.go b/go/internal/handler/status_test.go index 160fa910f..99335b6ff 100644 --- a/go/internal/handler/status_test.go +++ b/go/internal/handler/status_test.go @@ -296,9 +296,8 @@ func TestStatusGoldenKeys(t *testing.T) { assertKeys(t, "advisories.row", advs[0], []string{"subject", "state"}) // W06-1: the llmlog write-path section — two process-wide loss counters, - // nothing else (no pipeline names, no error text: those are log material); - // issue #571 adds the recording account's loss counter and fill. - assertKeys(t, "llmlog", top["llmlog"], []string{"insert_failures", "insert_dropped", "recorded_bodies_lost", "recorded_held_bytes"}) + // nothing else (no pipeline names, no error text: those are log material). + assertKeys(t, "llmlog", top["llmlog"], []string{"insert_failures", "insert_dropped"}) // FOLGE-Y: the query-synthesis latency block — exactly the four names // the bench contract reads (p95_ms only when samples >= 20). diff --git a/go/internal/llmlog/gateway.go b/go/internal/llmlog/gateway.go index cea6f3043..0ffbbce10 100644 --- a/go/internal/llmlog/gateway.go +++ b/go/internal/llmlog/gateway.go @@ -172,12 +172,11 @@ type Gateway struct { // forensics ("which requests ran over the leaked key?") through the // consumer index plus this field (§8 d01 (3)); never a column. ModelKeyID string - // Recorded, RecordLost and RecordLostCause are metadata.gw.recorded, - // record_lost and record_lost_cause (recorded.go). GatewayEntry sets - // them from the GatewayRow; a writer never sets them itself. - Recorded bool - RecordLost []string - RecordLostCause string + // Recorded and RecordingID are metadata.gw.recorded and recording_id + // (recordings.go): GatewayEntry sets them from the GatewayRow; a writer + // never sets them itself. + Recorded bool + RecordingID string } // gatewayWire is metadata.gw as stored: the keys the rollup trigger reads @@ -198,9 +197,8 @@ type gatewayWire struct { PeerInstance string `json:"peer_instance,omitempty"` // The recording marker (issue #571): absent on every row of a consumer // without the switch, so those rows stay byte-identical. - Recorded bool `json:"recorded,omitempty"` - RecordLost []string `json:"record_lost,omitempty"` - RecordLostCause string `json:"record_lost_cause,omitempty"` + Recorded bool `json:"recorded,omitempty"` + RecordingID string `json:"recording_id,omitempty"` } // StampGateway records WHO made a /v1 request and how it ran: the @@ -270,8 +268,8 @@ func (g Gateway) wire() gatewayWire { } if g.Recorded { w.Recorded = true - if w.RecordLost = cleanRecordLost(g.RecordLost); w.RecordLost != nil && recordLostCauses[g.RecordLostCause] { - w.RecordLostCause = g.RecordLostCause + if u, err := uuid.Parse(g.RecordingID); err == nil { + w.RecordingID = u.String() } } return w @@ -366,8 +364,7 @@ type GatewayRow struct { Err *RedactedErr // Request and Response are the serialized client input (messages or // input) and the answer the client received. Stored only as the body - // policy says, capped at 64 KiB each — on a Recorded row always and - // whole. + // policy says, capped at 64 KiB each. Request, Response string // BodyLogging is gateway.body_logging of the request's settings // snapshot; anything but errors or full stores no body, and neither @@ -375,18 +372,13 @@ type GatewayRow struct { // or unknown. BodyLogging string // Recorded is the consumer's recording switch as the door read it - // (auth.ConsumerAuth.RecordBodies, migration 197): the row stores - // Request and Response in full — no cap, no body policy, no seal — and - // carries metadata.gw.recorded (recorded.go). RecordLost and - // RecordLostCause name a body the route could not keep and why; they - // count only on a recorded row. - Recorded bool - RecordLost []string - RecordLostCause string - // RecordedHeld is what the route reserved for Request and Response - // (ReserveRecorded); the writer gives it back once the row is inserted - // or lost. 0 on every row that is not recorded. - RecordedHeld int64 + // (auth.ConsumerAuth.RecordBodies, migration 197), RecordingID the + // request's row in context_llm_recordings (recordings.go), which holds + // its request and answer whole. The row here is the row of every other + // consumer — the body policy, the cap and the seal apply as always — + // plus metadata.gw.recorded and recording_id. + Recorded bool + RecordingID string } // GatewayEntry builds the ONE row of a /v1 request: pipeline, StampGateway, @@ -394,53 +386,10 @@ type GatewayRow struct { // Slimmed(false) — always false, never the tenant's devmode: tenant.devmode // is tenant-overridable, and a tenant must not open the seal of a // credentials-class /v1 row for itself (design/06 §4.6, design/04 R-06-1). -// It builds the row of an unrecorded call: Recorded, RecordLost and -// RecordedHeld of r are not its business (a recorded row is -// RecordedGatewayEntry's). // A row without a consumer or with a pipeline outside the vocabulary is a // wiring defect: logged at ERROR (throttled per defect) and still built, so // the defect is visible in the log and the row is not lost. func GatewayEntry(r GatewayRow) Entry { - e := gatewayRowBase(r, false) - store := false - switch strings.ToLower(strings.TrimSpace(r.BodyLogging)) { - case BodyLoggingFull: - store = true - case BodyLoggingErrors: - store = r.Err != nil - } - if store && bodiesAllowed(e.RequiredSensitivity, e.Pipeline) { - e.RequestUser, e.ResponseContent = capBody(r.Request), capBody(r.Response) - } - return e.Slimmed(false) -} - -// RecordedGatewayEntry builds the ONE row of a recorded request (issue #571, -// recorded.go): GatewayEntry's row with metadata.gw.recorded (and -// record_lost, record_lost_cause) and both bodies as the route captured them -// — no body policy, no cap, and no seal: Slimmed would drop them at -// credentials, and the switch is the server-admin's, not a tenant setting. -// Their readers are server-admins only (SQLBodiesServerAdminOnly). The row -// carries what the texts hold of the recording account (RecordedHeld); the -// writer gives it back. RecordGateway takes this builder for a Recorded row -// and GatewayEntry for every other. -func RecordedGatewayEntry(r GatewayRow) Entry { - e := gatewayRowBase(r, true) - if !backends.ValidSensitivity(backends.Sensitivity(e.RequiredSensitivity)) { - // The bodies are kept whatever the class; the defect is still logged - // as bodiesAllowed logs it for every other row. - wiringError(&lastSensWarn, "llmlog: a gateway row without a defined required_sensitivity — recorded whole (recording consumer)", - "pipeline", e.Pipeline, "required_sensitivity", cleanText(e.RequiredSensitivity, gatewayTokenMax)) - } - e.RequestUser, e.ResponseContent = storable(r.Request), storable(r.Response) - e.recordedHeld = r.RecordedHeld - return e -} - -// gatewayRowBase is what both builders share: pipeline, StampGateway (with -// the recording marker only for a recorded row), the redacted error, the -// folded attempts, and no body yet. -func gatewayRowBase(r GatewayRow, recorded bool) Entry { e := r.Telemetry e.Pipeline = r.Pipeline g := r.Gateway @@ -452,9 +401,9 @@ func gatewayRowBase(r GatewayRow, recorded bool) Entry { if r.ConsumerID == "" { wiringError(&lastConsumerWarn, "llmlog: a gateway row without a consumer — the request is unattributed", "pipeline", r.Pipeline) } - g.Recorded, g.RecordLost, g.RecordLostCause = recorded, nil, "" - if recorded { - g.RecordLost, g.RecordLostCause = r.RecordLost, r.RecordLostCause + g.Recorded, g.RecordingID = r.Recorded, "" + if r.Recorded { + g.RecordingID = r.RecordingID } e.StampGateway(r.ConsumerID, g) @@ -471,7 +420,17 @@ func gatewayRowBase(r GatewayRow, recorded bool) Entry { } e.RequestSystem, e.RequestUser, e.ResponseContent = "", "", "" - return e + store := false + switch strings.ToLower(strings.TrimSpace(r.BodyLogging)) { + case BodyLoggingFull: + store = true + case BodyLoggingErrors: + store = r.Err != nil + } + if store && bodiesAllowed(e.RequiredSensitivity, e.Pipeline) { + e.RequestUser, e.ResponseContent = capBody(r.Request), capBody(r.Response) + } + return e.Slimmed(false) } // The wiring-defect ERRORs of the gateway row, one throttle per defect: a @@ -520,13 +479,6 @@ func bodiesAllowed(sensitivity, pipeline string) bool { // the gateway (census TestGatewayOAICensus: no llmlog.Record under // internal/oai). Asynchronous like Record. func RecordGateway(pool *pgxpool.Pool, r GatewayRow) { - if r.Recorded { - if len(cleanRecordLost(r.RecordLost)) > 0 { - recordedLost.Add(1) - } - Record(pool, RecordedGatewayEntry(r)) - return - } Record(pool, GatewayEntry(r)) } diff --git a/go/internal/llmlog/gateway_recorded_test.go b/go/internal/llmlog/gateway_recorded_test.go deleted file mode 100644 index dd5107445..000000000 --- a/go/internal/llmlog/gateway_recorded_test.go +++ /dev/null @@ -1,236 +0,0 @@ -package llmlog - -import ( - "encoding/json" - "strings" - "sync" - "sync/atomic" - "testing" - "time" - - "github.com/jackc/pgx/v5/pgxpool" -) - -// The recorded row (issue #571): a row of a consumer with record_bodies keeps -// its request and its answer whole — under every gateway.body_logging value -// and every required sensitivity (credentials, unset and unknown included), -// past the 64 KiB cap of the body policy — and says so in metadata.gw. - -// recordedRow is a chat row of a recording consumer with a request past the -// cap that carries a credentials pattern. -func recordedRow(pol, sens string) GatewayRow { - secret := "Authorization: Bearer sk-live-571-" + strings.Repeat("Z", 40) - return GatewayRow{ - Pipeline: PipelineGatewayChat, ConsumerID: "0195a6f0-0000-7000-8000-00000000c571", - Gateway: Gateway{Alias: "chat", Finish: FinishStop}, - Telemetry: Entry{RequiredSensitivity: sens, Metadata: map[string]any{}}, - Request: `[{"role":"user","content":"` + secret + strings.Repeat("x", 100<<10) + `"}]`, - Response: `{"choices":[{"message":{"content":"` + strings.Repeat("y", 90<<10) + `"}}]}`, - BodyLogging: pol, - Recorded: true, - } -} - -// gwWire reads metadata.gw back as JSON. -func gwWire(t *testing.T, e Entry) map[string]any { - t.Helper() - raw, err := json.Marshal(e.Metadata["gw"]) - if err != nil { - t.Fatalf("marshal gw: %v", err) - } - var m map[string]any - if err := json.Unmarshal(raw, &m); err != nil { - t.Fatalf("unmarshal gw: %v", err) - } - return m -} - -func TestRecordedRowKeepsWholeBodies(t *testing.T) { - for _, pol := range goldenPolicies { - for _, sens := range goldenSensitivities { - r := recordedRow(pol, sens) - e := RecordedGatewayEntry(r) - if e.RequestUser != r.Request || e.ResponseContent != r.Response || e.RequestSystem != "" { - t.Errorf("policy %q sensitivity %q: stored request %d / answer %d bytes, want the whole %d / %d", - pol, sens, len(e.RequestUser), len(e.ResponseContent), len(r.Request), len(r.Response)) - } - if !strings.Contains(e.RequestUser, "sk-live-571-") { - t.Errorf("policy %q sensitivity %q: the credentials pattern is not in the recorded row", pol, sens) - } - gw := gwWire(t, e) - if gw["recorded"] != true || gw["record_lost"] != nil { - t.Errorf("policy %q sensitivity %q: metadata.gw %v, want recorded true without record_lost", pol, sens, gw) - } - if e.ConsumerID != r.ConsumerID || e.Pipeline != PipelineGatewayChat || gw["op"] != GatewayOpChat { - t.Errorf("policy %q sensitivity %q: row %s/%s op %v — the attribution is GatewayEntry's", pol, sens, e.Pipeline, e.ConsumerID, gw["op"]) - } - } - } -} - -// TestGatewayEntryIgnoresTheRecordingFields: GatewayEntry builds the row of -// an unrecorded call; recording fields on its input change nothing (the -// marker and the whole bodies are RecordedGatewayEntry's), and a recorded row -// built by it would be sealed like any other. -func TestGatewayEntryIgnoresTheRecordingFields(t *testing.T) { - names, rows := unrecordedMatrix() - for _, n := range names { - r := rows[n] - base := goldenLine(n, GatewayEntry(r)) - r.RecordLost, r.RecordLostCause, r.RecordedHeld = []string{RecordLostRequest}, RecordLostMemory, 42 - if got := goldenLine(n, GatewayEntry(r)); got != base { - t.Fatalf("%s: recording fields on an unrecorded row changed it:\n got %s\n want %s", n, got, base) - } - } -} - -func TestRecordedRowNamesWhatItLost(t *testing.T) { - r := recordedRow(BodyLoggingNone, "credentials") - r.Request = "" - r.RecordLost = []string{"bogus", RecordLostResponse, RecordLostRequest, RecordLostRequest} - r.RecordLostCause = RecordLostMemory - gw := gwWire(t, RecordedGatewayEntry(r)) - lost, _ := json.Marshal(gw["record_lost"]) - if string(lost) != `["request","response"]` || gw["record_lost_cause"] != RecordLostMemory { - t.Errorf("record_lost %s cause %v, want [request response] (vocabulary order, once each, unknown dropped) and memory", lost, gw["record_lost_cause"]) - } - r.RecordLostCause = "made-up" - if gw := gwWire(t, RecordedGatewayEntry(r)); gw["record_lost_cause"] != nil { - t.Errorf("an unknown cause is stored: %v", gw["record_lost_cause"]) - } - r.RecordLost = []string{"bogus"} - if gw := gwWire(t, RecordedGatewayEntry(r)); gw["record_lost"] != nil || gw["record_lost_cause"] != nil { - t.Errorf("no known lost body, yet record_lost %v cause %v", gw["record_lost"], gw["record_lost_cause"]) - } -} - -// TestRecordedBodiesLostCounts: RecordGateway counts a recorded row written -// without a body it should carry (llmlog.recorded_bodies_lost on the status -// frame) — and nothing else: a whole recorded row, or an unrecorded row that -// names a loss it cannot have, leaves the counter. -func TestRecordedBodiesLostCounts(t *testing.T) { - before := RecordedBodiesLost() - whole := recordedRow(BodyLoggingNone, "public") - RecordGateway(nil, whole) - plain := recordedRow(BodyLoggingNone, "public") - plain.Recorded, plain.RecordLost = false, []string{RecordLostRequest} - RecordGateway(nil, plain) - if got := RecordedBodiesLost() - before; got != 0 { - t.Fatalf("a whole recorded row and an unrecorded one counted %d losses", got) - } - lost := recordedRow(BodyLoggingNone, "public") - lost.RecordLost, lost.RecordLostCause = []string{RecordLostResponse}, RecordLostMemory - RecordGateway(nil, lost) - if got := RecordedBodiesLost() - before; got != 1 { - t.Fatalf("a recorded row without its answer counted %d losses, want 1", got) - } -} - -// recordedAccount resets the recording account for a test and checks it is -// back at zero afterwards. -func recordedAccount(t *testing.T) { - t.Helper() - if n := recordedHeld.Load(); n != 0 { - t.Fatalf("the recording account holds %d bytes before the test", n) - } - t.Cleanup(func() { - if n := recordedHeld.Load(); n != 0 { - t.Errorf("the recording account holds %d bytes after the test, want 0", n) - recordedHeld.Store(0) - } - }) -} - -func TestRecordedAccountBound(t *testing.T) { - recordedAccount(t) - if !ReserveRecorded(maxRecordedHeld-10) || !ReserveRecorded(10) { - t.Fatal("the account refuses bytes within its bound") - } - if ReserveRecorded(1) { - t.Fatal("the account takes a byte past maxRecordedHeld") - } - if !ReserveRecorded(0) || !ReserveRecorded(-5) { - t.Fatal("a reservation of nothing is refused") - } - if RecordedHeld() != maxRecordedHeld { - t.Fatalf("held %d, want %d", RecordedHeld(), maxRecordedHeld) - } - ReleaseRecorded(maxRecordedHeld) - ReleaseRecorded(-3) - if RecordedHeld() != 0 { - t.Fatalf("held %d after the release, want 0", RecordedHeld()) - } - // Concurrent reservations never pass the bound together. - var wg sync.WaitGroup - var mu sync.Mutex - took := int64(0) - for range 64 { - wg.Add(1) - go func() { - defer wg.Done() - if ReserveRecorded(maxRecordedHeld / 8) { - mu.Lock() - took += maxRecordedHeld / 8 - mu.Unlock() - } - }() - } - wg.Wait() - if took != maxRecordedHeld || RecordedHeld() != maxRecordedHeld { - t.Fatalf("64 concurrent reservations of an eighth took %d (held %d), want exactly the bound %d", took, RecordedHeld(), int64(maxRecordedHeld)) - } - ReleaseRecorded(took) -} - -// TestWriterGivesTheRecordedTextsBack: a recorded row's texts go back to the -// account once the writer is done with them — inserted, failed, dropped at -// a full queue, or written to no pool at all. -func TestWriterGivesTheRecordedTextsBack(t *testing.T) { - recordedAccount(t) - pool := &pgxpool.Pool{} - block := make(chan struct{}) - var inserted atomic.Int64 - w := newWriter(pool, func(*pgxpool.Pool, Entry) error { - <-block - inserted.Add(1) - return nil - }) - row := recordedRow(BodyLoggingNone, "credentials") - if !ReserveRecorded(int64(len(row.Request) + len(row.Response))) { - t.Fatal("reserve") - } - row.RecordedHeld = int64(len(row.Request) + len(row.Response)) - w.enqueue(RecordedGatewayEntry(row)) - if RecordedHeld() != row.RecordedHeld { - t.Fatalf("held %d while the row is queued, want %d", RecordedHeld(), row.RecordedHeld) - } - close(block) - for deadline := time.Now().Add(10 * time.Second); w.pending.Load() > 0 && time.Now().Before(deadline); { - time.Sleep(time.Millisecond) - } - if RecordedHeld() != 0 || inserted.Load() != 1 { - t.Fatalf("after the insert held %d inserted %d, want 0 and 1", RecordedHeld(), inserted.Load()) - } - // A full queue drops the row and gives its texts back. - full := newWriter(pool, func(*pgxpool.Pool, Entry) error { return nil }) - full.queue = make([]Entry, maxQueuedInserts) - full.running = maxConcurrentInserts - if !ReserveRecorded(100) { - t.Fatal("reserve") - } - before := InsertDropped() - full.enqueue(Entry{Pipeline: PipelineGatewayChat, recordedHeld: 100}) - if RecordedHeld() != 0 || InsertDropped() != before+1 { - t.Fatalf("a dropped recorded row: held %d dropped +%d, want 0 and +1", RecordedHeld(), InsertDropped()-before) - } - // No pool: nothing is written, the texts go back. - if !ReserveRecorded(7) { - t.Fatal("reserve") - } - r := recordedRow(BodyLoggingNone, "public") - r.RecordedHeld = 7 - RecordGateway(nil, r) - if RecordedHeld() != 0 { - t.Fatalf("a row without a pool keeps %d bytes", RecordedHeld()) - } -} diff --git a/go/internal/llmlog/llmlog.go b/go/internal/llmlog/llmlog.go index de37c0e41..4d40ee2db 100644 --- a/go/internal/llmlog/llmlog.go +++ b/go/internal/llmlog/llmlog.go @@ -133,11 +133,6 @@ type Entry struct { // persists as NULL instead of a fake 0 — Duration measures the wire // call, and there was none. NoWireCall bool - - // recordedHeld is what a recorded gateway row's texts hold of the - // recording account (recorded.go); the writer releases it when the row - // is inserted, fails or is dropped. Set by GatewayEntry only. - recordedHeld int64 } // StampPrompt records WHICH prompt body produced this row: metadata.prompt_id @@ -204,7 +199,9 @@ func (e Entry) Slimmed(devmode bool) Entry { // retentionDays <= 0 disables retention entirely (bodies kept forever — the // operator opts in to unlimited). The IS NOT NULL guard makes a re-run // idempotent: already-evicted rows are skipped, so the periodic janitor never -// rewrites long-settled chunks. Returns the number of rows NULLed. +// rewrites long-settled chunks. The recordings of recording consumers +// (context_llm_recordings, recordings.go) lose their two bodies after the +// same retention. Returns the number of rows NULLed, both tables together. func EvictBodies(ctx context.Context, pool *pgxpool.Pool, retentionDays int) (int64, error) { if pool == nil || retentionDays <= 0 { return 0, nil @@ -221,7 +218,11 @@ func EvictBodies(ctx context.Context, pool *pgxpool.Pool, retentionDays int) (in if err != nil { return 0, fmt.Errorf("llmlog: evict bodies: %w", err) } - return tag.RowsAffected(), nil + rec, err := pool.Exec(ctx, evictRecordingBodies, retentionDays) + if err != nil { + return tag.RowsAffected(), fmt.Errorf("llmlog: evict recording bodies: %w", err) + } + return tag.RowsAffected() + rec.RowsAffected(), nil } // writer is the per-pool insert queue: Record appends, at most @@ -290,7 +291,6 @@ func InsertDropped() int64 { return insertDropped.Load() } // closed pool — is allowed: the row is then a counted failure. func Record(pool *pgxpool.Pool, e Entry) { if pool == nil || e.Pipeline == "" { - ReleaseRecorded(e.recordedHeld) return } writerFor(pool).enqueue(e) @@ -300,7 +300,6 @@ func (w *writer) enqueue(e Entry) { w.mu.Lock() if len(w.queue) >= maxQueuedInserts { w.mu.Unlock() - ReleaseRecorded(e.recordedHeld) insertDropped.Add(1) warnLoss("llmlog: insert queue full, row dropped", e.Pipeline, nil) return @@ -339,7 +338,6 @@ func (w *writer) drain() { slog.Debug("llmlog: insert failed", "pipeline", e.Pipeline, "error", err) warnLoss("llmlog: insert failed, row lost", e.Pipeline, err) } - ReleaseRecorded(e.recordedHeld) // the texts are no longer the writer's w.pending.Add(-1) } } diff --git a/go/internal/llmlog/llmlog_readers_census_test.go b/go/internal/llmlog/llmlog_readers_census_test.go deleted file mode 100644 index 389eb9288..000000000 --- a/go/internal/llmlog/llmlog_readers_census_test.go +++ /dev/null @@ -1,124 +0,0 @@ -package llmlog - -import ( - "fmt" - "go/ast" - "go/token" - "regexp" - "sort" - "strconv" - "strings" - "testing" -) - -// The readers of context_llm_log (issue #571, promise 5). A recorded row's -// request_system/request_user/response_content can carry credentials in -// clear text; its bodies are for a server-admin only and for no pipeline. -// This census walks every non-test .go file of the module and lists each file -// whose STRING LITERALS read or write the table (FROM, JOIN, TABLE, INTO, -// UPDATE context_llm_log) or name a body column — comments do not count. -// Every such file is classified below with what it reads and how many such -// literals it holds; a new reader of the table — a whole-row one included -// (SELECT l FROM context_llm_log l, to_jsonb, json_agg), and a new statement -// in a file already listed — turns this test red until it is classified here -// (and, if it reads bodies, given its test). -// -// Not covered, stated rather than assumed: SQL assembled from fragments that -// never spell the table's name, the shell scripts of the repository -// (backup.sh and coverage.sh dump the whole database — a backup, not a -// reader of the log), and the web frontend, which reads the bodies only -// through GET /api/llmlog/{id}. -// llmlogReader is one classified file: the number of its literals that -// read the table or name a body column (struct tags included), and what they -// read. -type llmlogReader struct { - n int - what string -} - -var llmlogReaders = map[string]llmlogReader{ - // Bodies: the writer's insert and the retention janitor (EvictBodies NULLs - // the bodies of every row past scheduler.llmlog_retention_days, recorded - // rows included — TestV1RecordedConsumerRowAndItsReaders/retention_janitor). - "internal/llmlog/llmlog.go": {2, "bodies: writer and retention janitor"}, - // Bodies: GET /api/llmlog/{id} — a server-admin reads every row, anyone - // else only rows of its own knowledge keys (api_key_id); a gateway row has - // none, so a recorded row is a uniform 404 below server-admin - // (TestV1RecordedConsumerRowAndItsReaders/detail). - "internal/handler/llmlog.go": {4, "bodies: per-id detail, server-admin only for gateway rows"}, - // Bodies: ctx-llmlog-export — the bodies of a recorded row, and fail-closed - // of a gateway row without a readable marker, leave sealed - // (SQLBodiesServerAdminOnly; TestExportSealsRecordedRows, - // TestV1RecordedConsumerRowAndItsReaders/export). - "internal/llmlogexport/export.go": {4, "bodies: bulk export, recorded rows sealed"}, - // Metadata only (the projections name no body column): - "internal/handler/llmlog_consumer.go": {2, "metadata: GET /api/llmlog list (llmlogListColumns)"}, - "internal/handler/events.go": {1, "metadata: the llmcalls SSE feed, server-admin"}, - "internal/handler/status.go": {1, "metadata: max(created_at) of the 24 h window"}, - "internal/llmusage/groups.go": {2, "metadata: per-pipeline counts and sums (SELECT * over its own CTEs)"}, - "internal/llmusage/window.go": {1, "metadata: usage windows of the tenant quota"}, - "internal/events/distill_spend.go": {1, "metadata: count and duration of the distill pipeline's own rows"}, - "cmd/ctx-armcost/report.go": {3, "metadata: an operator tool's cost report"}, - "cmd/ctx-armcost/pertopic.go": {2, "metadata: an operator tool's per-topic cost"}, -} - -// tableRE matches a literal that reads or writes the table; bodyColumnRE one -// that names a body column. -var ( - tableRE = regexp.MustCompile(`(?i)\b(from|join|table|into|update)\s+context_llm_log\b`) - bodyColumnRE = regexp.MustCompile(`\b(request_system|request_user|response_content)\b`) -) - -func TestLLMLogReadersCensus(t *testing.T) { - root := gatewayCensusModuleRoot(t) - fset := token.NewFileSet() - files := productionFiles(t, fset, root) - found := map[string][]string{} - for _, cf := range files { - ast.Inspect(cf.file, func(n ast.Node) bool { - lit, ok := n.(*ast.BasicLit) - if !ok || lit.Kind != token.STRING { - return true - } - s, err := strconv.Unquote(lit.Value) - if err != nil { - s = lit.Value - } - if tableRE.MatchString(s) || bodyColumnRE.MatchString(s) { - found[cf.rel] = append(found[cf.rel], fset.Position(lit.Pos()).String()) - } - return true - }) - } - var unclassified, gone []string - for rel, at := range found { - if r, ok := llmlogReaders[rel]; !ok || r.n != len(at) { - unclassified = append(unclassified, fmt.Sprintf("%s: %d literal(s), classified %d (%s)", rel, len(at), r.n, strings.Join(at, ", "))) - } - } - for rel := range llmlogReaders { - if _, ok := found[rel]; !ok { - gone = append(gone, rel) - } - } - sort.Strings(unclassified) - sort.Strings(gone) - t.Logf("census: %d production files, %d read or write context_llm_log: %v", len(files), len(found), keys(found)) - if len(unclassified) > 0 { - t.Errorf("files whose literals read context_llm_log without a classification in llmlogReaders "+ - "(a recorded row's bodies are for a server-admin only — classify the reader and give it its test):\n %s", - strings.Join(unclassified, "\n ")) - } - if len(gone) > 0 { - t.Errorf("classified readers that no longer read context_llm_log (drop them from llmlogReaders): %v", gone) - } -} - -func keys(m map[string][]string) []string { - out := make([]string, 0, len(m)) - for k := range m { - out = append(out, k) - } - sort.Strings(out) - return out -} diff --git a/go/internal/llmlog/recorded.go b/go/internal/llmlog/recorded.go deleted file mode 100644 index ec1fd1bc0..000000000 --- a/go/internal/llmlog/recorded.go +++ /dev/null @@ -1,124 +0,0 @@ -package llmlog - -import ( - "fmt" - "slices" - "sync/atomic" -) - -// Recording (issue #571, migration 197). A model consumer with the switch -// record_bodies on has every gateway row of its own written with the request -// and the answer in full — whatever gateway.body_logging, the alias, the -// consumer's floor, the body scan or Ctx-Sensitivity say, and without -// gatewayBodyCap. Such a row is marked metadata.gw.recorded = true and can -// carry credentials in clear text: its bodies are for a server-admin only -// (SQLBodiesServerAdminOnly). -// -// The texts a recorded row keeps are held against ONE process-wide account, -// not against the request's in-flight budget: from the moment a route -// captures a text (ReserveRecorded) until the writer has inserted the row or -// lost it (queue full, failed insert). The request path books nothing for -// them, so its chain, its refusals and its answer are the same with and -// without the switch — the one booking that differs is the body policy's own -// log text (at most 64 KiB, booked at the request's end under -// gateway.body_logging errors/full), which a recorded row does not take; and -// the rows of recorded calls the writer has not -// inserted yet — a slow database, a burst of large requests — hold at most -// maxRecordedHeld bytes of text. A text the account cannot take is not -// captured: the row is still written, without it, and says so -// (metadata.gw.record_lost, record_lost_cause "memory"). - -// maxRecordedHeld bounds the bytes of recorded texts the process holds at -// once — captured by running requests, queued and in insertion. Hardcoded on -// purpose, like maxQueuedInserts: it bounds the process's own bookkeeping, -// not anybody's policy. 128 MiB beside the default gateway.inflight_budget -// of 512 MiB stay inside the container's 1536 MiB (docs/operations.md -// "Recording a consumer"); the largest non-streamed row — a request text of -// at most 2 × gateway.max_request_bytes (an invalid byte becomes U+FFFD) and -// the answer the client received — fits it at the defaults. -const maxRecordedHeld = 128 << 20 - -// metadata.gw.record_lost — the bodies a recorded row should carry and does -// not. -const ( - RecordLostRequest = "request" - RecordLostResponse = "response" -) - -// metadata.gw.record_lost_cause — why. -const ( - // RecordLostMemory: maxRecordedHeld could not take the text. - RecordLostMemory = "memory" - // RecordLostShutdown: the shutdown's forced settle wrote the row of a - // request still open (W06-13); that row carries no body. - RecordLostShutdown = "shutdown" -) - -var ( - recordedHeld atomic.Int64 // bytes of recorded texts held (ReserveRecorded − ReleaseRecorded) - recordedLost atomic.Int64 // recorded rows written without a body they should carry -) - -// ReserveRecorded takes n bytes of a recorded text from the account; false -// when they do not fit (nothing is taken then). n <= 0 always fits. -func ReserveRecorded(n int64) bool { - if n <= 0 { - return true - } - for { - cur := recordedHeld.Load() - if cur+n > maxRecordedHeld { - return false - } - if recordedHeld.CompareAndSwap(cur, cur+n) { - return true - } - } -} - -// ReleaseRecorded gives n bytes back (n <= 0: nothing). -func ReleaseRecorded(n int64) { - if n > 0 { - recordedHeld.Add(-n) - } -} - -// RecordedHeld is the bytes of recorded texts the process holds now. -func RecordedHeld() int64 { return recordedHeld.Load() } - -// RecordedBodiesLost counts, since the process started, the recorded rows -// the writer was handed without a body they should carry (record_lost). A -// recorded row the queue drops or the database refuses is in InsertDropped -// or InsertFailures, like every row. -func RecordedBodiesLost() int64 { return recordedLost.Load() } - -// recordLostKinds and recordLostCauses are the vocabularies of the two keys. -var ( - recordLostKinds = []string{RecordLostRequest, RecordLostResponse} - recordLostCauses = map[string]bool{RecordLostMemory: true, RecordLostShutdown: true} -) - -// cleanRecordLost keeps the known bodies of lost, each once, in vocabulary -// order; nil when none is left. -func cleanRecordLost(lost []string) []string { - var out []string - for _, k := range recordLostKinds { - if slices.Contains(lost, k) { - out = append(out, k) - } - } - return out -} - -// SQLBodiesServerAdminOnly is the SQL condition, over the context_llm_log -// alias t, of a row whose bodies only a server-admin may read: a gateway row -// (consumer_id set, or a gateway pipeline) unless its metadata.gw is an -// object that does not mark it recorded — recorded = true, and fail-closed a -// gateway row whose marker is missing or unreadable (metadata.gw absent or -// not an object, recorded anything but absent or false). Every other row -// (knowledge-key and background pipelines) is untouched. Never NULL. -func SQLBodiesServerAdminOnly(t string) string { - return fmt.Sprintf(`((%[1]s.consumer_id IS NOT NULL OR COALESCE(%[1]s.pipeline LIKE 'gateway-%%', false)) - AND NOT (COALESCE(jsonb_typeof(%[1]s.metadata->'gw') = 'object', false) - AND COALESCE(%[1]s.metadata->'gw'->'recorded', 'false'::jsonb) = 'false'::jsonb))`, t) -} diff --git a/go/internal/llmlog/recorded_integration_test.go b/go/internal/llmlog/recorded_integration_test.go deleted file mode 100644 index fae76db5e..000000000 --- a/go/internal/llmlog/recorded_integration_test.go +++ /dev/null @@ -1,118 +0,0 @@ -//go:build integration - -// The recorded row (issue #571) over real inserts: -// -// - TestRecordedRowLandsWhole: a recorded row with a credentials-class -// sensitivity, a request and an answer past 64 KiB lands with both -// bodies whole and metadata.gw.recorded, and gives its texts back to the -// recording account once written; -// - TestRecordedRowInsertCost (opt-in, CTX_RECORD_PROBE=1): the insert time -// and the stored size of recorded rows up to the largest non-streamed row -// at the default caps (a request text of 2 × gateway.max_request_bytes = -// 16 MiB and a 24 MiB answer), against insertTimeout (5 s). -// -// go test -tags=integration -p 1 -count=1 -run 'TestRecordedRow' -v ./internal/llmlog/ -// CTX_RECORD_PROBE=1 go test -tags=integration -p 1 -count=1 -run TestRecordedRowInsertCost -v ./internal/llmlog/ -package llmlog_test - -import ( - "context" - "os" - "strings" - "testing" - "time" - - "github.com/GottZ/ctx/internal/llmlog" - "github.com/GottZ/ctx/internal/testdb" -) - -func recordedGwiRow(request, response string) llmlog.GatewayRow { - r := gwiRow(llmlog.PipelineGatewayChat) - r.Telemetry.RequiredSensitivity = "credentials" - r.Request, r.Response, r.Recorded = request, response, true - return r -} - -func TestRecordedRowLandsWhole(t *testing.T) { - if testing.Short() { - t.Skip("integration test") - } - ctx := context.Background() - pool := testdb.SetupTestDB(t) - req := `[{"role":"user","content":"password=s3cr3t-571 ` + strings.Repeat("r", 100<<10) + `"}]` - resp := `{"choices":[{"message":{"content":"` + strings.Repeat("a", 90<<10) + `"}}]}` - held := int64(len(req) + len(resp)) - before := llmlog.RecordedHeld() - if !llmlog.ReserveRecorded(held) { - t.Fatal("reserve") - } - row := recordedGwiRow(req, resp) - row.RecordedHeld = held - llmlog.RecordGateway(pool, row) - if err := llmlog.Settle(ctx, pool); err != nil { - t.Fatalf("settle: %v", err) - } - if got := llmlog.RecordedHeld(); got != before { - t.Errorf("the recording account holds %d bytes after the insert, want %d", got, before) - } - var user, answer, sens, recorded string - if err := pool.QueryRow(ctx, `SELECT request_user, response_content, required_sensitivity, metadata->'gw'->>'recorded' - FROM context_llm_log WHERE consumer_id = $1::uuid`, gwiConsumer).Scan(&user, &answer, &sens, &recorded); err != nil { - t.Fatalf("read: %v", err) - } - if user != req || answer != resp || sens != "credentials" || recorded != "true" { - t.Errorf("stored request %d/%d bytes, answer %d/%d, sensitivity %s, recorded %s — want both whole, credentials, true", - len(user), len(req), len(answer), len(resp), sens, recorded) - } -} - -func TestRecordedRowInsertCost(t *testing.T) { - if os.Getenv("CTX_RECORD_PROBE") == "" { - t.Skip("opt-in probe: CTX_RECORD_PROBE=1") - } - ctx := context.Background() - pool := testdb.SetupTestDB(t) - // Text that compresses like a prompt (repeated words) and text that does - // not (pseudo-random letters) — TOAST compresses the first. - words := func(n int) string { - var b strings.Builder - for b.Len() < n { - b.WriteString("the quick brown fox jumps over the lazy dog ") - } - return b.String()[:n] - } - noise := func(n int, seed uint64) string { - b := make([]byte, n) - x := seed - for i := range b { - x ^= x << 13 - x ^= x >> 7 - x ^= x << 17 - b[i] = 'a' + byte(x%26) - } - return string(b) - } - for _, c := range []struct { - name string - request, resp string - }{ - {"1 MiB words", words(1 << 20), words(64 << 10)}, - {"8 MiB words + 4 MiB", words(8 << 20), words(4 << 20)}, - {"16 MiB + 24 MiB words", words(16 << 20), words(24 << 20)}, - {"16 MiB + 24 MiB noise", noise(16<<20, 571), noise(24<<20, 197)}, - } { - start := time.Now() - llmlog.RecordGateway(pool, recordedGwiRow(c.request, c.resp)) - if err := llmlog.Settle(ctx, pool); err != nil { - t.Fatalf("%s: settle: %v", c.name, err) - } - took := time.Since(start) - var size int64 - if err := pool.QueryRow(ctx, `SELECT pg_column_size(request_user) + pg_column_size(response_content) - FROM context_llm_log ORDER BY created_at DESC LIMIT 1`).Scan(&size); err != nil { - t.Fatalf("%s: size: %v", c.name, err) - } - t.Logf("%s: %d bytes of text → insert %v, stored %d bytes (failures so far %d)", - c.name, len(c.request)+len(c.resp), took.Round(time.Millisecond), size, llmlog.InsertFailures()) - } -} diff --git a/go/internal/llmlog/recordings.go b/go/internal/llmlog/recordings.go new file mode 100644 index 000000000..12d893e8d --- /dev/null +++ b/go/internal/llmlog/recordings.go @@ -0,0 +1,204 @@ +package llmlog + +import ( + "context" + "errors" + "fmt" + + "github.com/google/uuid" + "github.com/jackc/pgx/v5/pgxpool" +) + +// Recording (issue #571, migration 197). A model consumer with the switch +// record_bodies on has every request it sends through the gateway held in +// context_llm_recordings: one row per request, keyed by the request's own +// id, with the body as the gateway read it, byte for byte (bytea — no +// cleaning, no cut, no seal), the answer the client got, and the outcome. +// The gateway writes the row synchronously and in order (internal/oai +// record.go): Open commits the request BEFORE the first backend attempt — +// a request that cannot be held is not served —, Finish ends it with its +// outcome (a non-streamed answer before it is written to the client), and +// Insert writes the row of a request the gateway refused before it opened +// one. Nothing here is queued: an error is the caller's, who answers the +// request with 503 recording_unavailable or counts the request as one it +// could not hold. +// +// A row can carry credentials in clear text. No ctx surface reads its +// bodies — no REST, MCP, CLI or web route, no export, no pipeline +// (TestRecordingsReadersCensus); a server operator reads them in the +// database (docs/operations.md "Recording a consumer"). The retention +// janitor NULLs them after the LLM log's retention (EvictBodies). + +// Recording states (context_llm_recordings.state). +const ( + // RecordingOpen: the request is held; its outcome is not recorded (yet). + RecordingOpen = "open" + // RecordingDone: the outcome is recorded. + RecordingDone = "done" +) + +// ProcessID names this ctxd process on every recording row it writes +// (context_llm_recordings.process_id): GET /api/status counts the same +// process's admissions, so the rows of a process can be checked against its +// count (docs/operations.md "Recording a consumer"). +var ProcessID = newProcessID() + +func newProcessID() string { + id, err := uuid.NewV7() + if err != nil { + return uuid.NewString() + } + return id.String() +} + +// RecordedRequest is a recording row's request side — what the door and the +// route know of the request. +type RecordedRequest struct { + // ID is the request's id (a UUID; the route's answer id carries it). + ID string + // ConsumerID and ModelKeyID come from the door (UUIDs; ModelKeyID may + // be empty). + ConsumerID, ModelKeyID string + // Path is the request's path; Op the route that took it (GatewayOp*), + // "" when no route did (a refusal of a stage, an unknown path). + Path, Op string + // ClientRequestID is the client's request id header as sent ("" none). + ClientRequestID string + // Model and Stream are what the route's parse read (nil Stream and "" + // Model: not parsed). + Model string + Stream *bool + // Declared is the request's Content-Length (-1: none declared). + Declared int64 + // Body is what the gateway read of the body (nil: nothing); Complete + // reports that it is the whole body. + Body []byte + Complete bool +} + +// RecordedOutcome is a recording row's outcome. +type RecordedOutcome struct { + // Status is the HTTP status the client got (0: the gateway wrote + // nothing — stored NULL). + Status int + // Code is the gateway's code of a refusal or an error ("" none). + Code string + // Response is the answer as the client got it (nil: none recorded). + Response []byte +} + +// Recordings writes context_llm_recordings over Pool. +type Recordings struct{ Pool *pgxpool.Pool } + +// errRecordingPool is the error of a Recordings without a pool. +var errRecordingPool = errors.New("llmlog: recordings without a database pool") + +func nullText(s string) *string { + if s == "" { + return nil + } + return &s +} + +func nullUUIDText(s string) *string { + if _, err := uuid.Parse(s); err != nil { + return nil + } + return &s +} + +func nullStatus(n int) *int16 { + if n <= 0 || n > 999 { + return nil + } + v := int16(n) + return &v +} + +// bodyBytes is b, NULL when empty: an empty body is no body. +func bodyBytes(b []byte) []byte { + if len(b) == 0 { + return nil + } + return b +} + +func declared(n int64) *int64 { + if n < 0 { + return nil + } + return &n +} + +// Open inserts the request's row in state open, its body whole; nil once the +// insert is committed. ctx bounds it (the caller's deadline). +func (r Recordings) Open(ctx context.Context, q RecordedRequest) error { + if r.Pool == nil { + return errRecordingPool + } + _, err := r.Pool.Exec(ctx, `INSERT INTO context_llm_recordings + (id, process_id, consumer_id, model_key_id, path, op, client_request_id, model, stream, + declared_bytes, request_bytes, request_complete, request_body, state) + VALUES ($1::uuid, $2::uuid, $3::uuid, $4::uuid, $5, $6, $7, $8, $9, $10, $11, $12, $13, 'open')`, + q.ID, ProcessID, q.ConsumerID, nullUUIDText(q.ModelKeyID), q.Path, nullText(q.Op), nullText(q.ClientRequestID), + nullText(q.Model), q.Stream, declared(q.Declared), int64(len(q.Body)), q.Complete, bodyBytes(q.Body)) + if err != nil { + return fmt.Errorf("llmlog: open recording: %w", err) + } + return nil +} + +// Finish ends the open row id with its outcome (state done); nil once the +// update is committed. A row that is not open is an error: an outcome is +// written once. +func (r Recordings) Finish(ctx context.Context, id string, o RecordedOutcome) error { + if r.Pool == nil { + return errRecordingPool + } + tag, err := r.Pool.Exec(ctx, `UPDATE context_llm_recordings + SET state = 'done', finished_at = now(), status = $2, code = $3, response_bytes = $4, response_body = $5 + WHERE id = $1::uuid AND state = 'open'`, + id, nullStatus(o.Status), nullText(o.Code), int64(len(o.Response)), bodyBytes(o.Response)) + if err != nil { + return fmt.Errorf("llmlog: finish recording: %w", err) + } + if tag.RowsAffected() != 1 { + return fmt.Errorf("llmlog: finish recording %s: no open row", id) + } + return nil +} + +// Insert writes the row of a request that was never opened — refused before +// its walk —, already done with its outcome; nil once committed. An open row +// of the same id (an Open whose commit the caller did not see) is ended +// instead, its request kept. +func (r Recordings) Insert(ctx context.Context, q RecordedRequest, o RecordedOutcome) error { + if r.Pool == nil { + return errRecordingPool + } + _, err := r.Pool.Exec(ctx, `INSERT INTO context_llm_recordings AS t + (id, process_id, consumer_id, model_key_id, path, op, client_request_id, model, stream, + declared_bytes, request_bytes, request_complete, request_body, state, finished_at, + status, code, response_bytes, response_body) + VALUES ($1::uuid, $2::uuid, $3::uuid, $4::uuid, $5, $6, $7, $8, $9, $10, $11, $12, $13, 'done', now(), + $14, $15, $16, $17) + ON CONFLICT (id) DO UPDATE + SET state = 'done', finished_at = now(), status = EXCLUDED.status, code = EXCLUDED.code, + response_bytes = EXCLUDED.response_bytes, response_body = EXCLUDED.response_body + WHERE t.state = 'open'`, + q.ID, ProcessID, q.ConsumerID, nullUUIDText(q.ModelKeyID), q.Path, nullText(q.Op), nullText(q.ClientRequestID), + nullText(q.Model), q.Stream, declared(q.Declared), int64(len(q.Body)), q.Complete, bodyBytes(q.Body), + nullStatus(o.Status), nullText(o.Code), int64(len(o.Response)), bodyBytes(o.Response)) + if err != nil { + return fmt.Errorf("llmlog: insert recording: %w", err) + } + return nil +} + +// evictRecordingBodies is EvictBodies' statement over the recordings: the two +// bodies of every row past the retention that still carries its request +// (idx_llm_recordings_bodies holds exactly those); the sizes stay. +const evictRecordingBodies = `UPDATE context_llm_recordings + SET request_body = NULL, response_body = NULL + WHERE created_at < now() - make_interval(days => $1) + AND request_body IS NOT NULL` diff --git a/go/internal/llmlog/recordings_integration_test.go b/go/internal/llmlog/recordings_integration_test.go new file mode 100644 index 000000000..1a952234e --- /dev/null +++ b/go/internal/llmlog/recordings_integration_test.go @@ -0,0 +1,203 @@ +//go:build integration + +// The recordings store (issue #571, migration 197) over a real database: +// +// - TestRecordingsRoundTrip: Open holds the body byte for byte (invalid +// UTF-8 and NUL included) in state open; Finish ends it once; Insert +// writes a refused request's row done, ends an open row of the same id +// (an Open whose commit its caller did not see) and leaves a done one; +// +// - TestRecordingsJanitor: EvictBodies NULLs both bodies of a recording +// past the retention, keeps its sizes and outcome, and leaves a fresh +// one alone; +// +// - TestRecordingStatementCost (opt-in, CTX_RECORD_PROBE=1): the time and +// the bytes one Open allocates for bodies up to 8 MiB +// (gateway.max_request_bytes) — the measure behind oai.recordCopyFactor. +// +// go test -tags=integration -p 1 -count=1 -run 'TestRecordings' -v ./internal/llmlog/ +// CTX_RECORD_PROBE=1 go test -tags=integration -p 1 -count=1 -run TestRecordingStatementCost -v ./internal/llmlog/ +package llmlog_test + +import ( + "bytes" + "context" + "os" + "runtime" + "testing" + "time" + + "github.com/google/uuid" + "github.com/jackc/pgx/v5/pgxpool" + + "github.com/GottZ/ctx/internal/llmlog" + "github.com/GottZ/ctx/internal/testdb" +) + +func recID(t *testing.T) string { + t.Helper() + id, err := uuid.NewV7() + if err != nil { + t.Fatal(err) + } + return id.String() +} + +type storedRecording struct { + state, path string + op, model, code, process *string + stream *bool + status *int16 + declared *int64 + reqBytes, respBytes int64 + complete bool + body, response []byte + finished *time.Time +} + +func readRecording(t *testing.T, ctx context.Context, q *pgxpool.Pool, id string) storedRecording { + t.Helper() + var r storedRecording + if err := q.QueryRow(ctx, `SELECT state, path, op, model, code, process_id::text, stream, status, declared_bytes, + request_bytes, response_bytes, request_complete, request_body, response_body, finished_at + FROM context_llm_recordings WHERE id = $1::uuid`, id). + Scan(&r.state, &r.path, &r.op, &r.model, &r.code, &r.process, &r.stream, &r.status, &r.declared, + &r.reqBytes, &r.respBytes, &r.complete, &r.body, &r.response, &r.finished); err != nil { + t.Fatalf("read recording %s: %v", id, err) + } + return r +} + +func TestRecordingsRoundTrip(t *testing.T) { + ctx := context.Background() + pool := testdb.SetupTestDB(t) + q := pool + st := llmlog.Recordings{Pool: pool} + body := append([]byte(`{"model":"m","input":"`), 0xff, 0xfe, 0x00, 'x') + body = append(body, `","secret":"password=s3cr3t-571"}`...) + stream := false + req := llmlog.RecordedRequest{ID: recID(t), ConsumerID: gwiConsumer, ModelKeyID: "not-a-uuid", Path: "/v1/embeddings", + Op: llmlog.GatewayOpEmbed, Model: "m", Stream: &stream, Declared: int64(len(body)), Body: body, Complete: true} + if err := st.Open(ctx, req); err != nil { + t.Fatalf("open: %v", err) + } + r := readRecording(t, ctx, q, req.ID) + if r.state != llmlog.RecordingOpen || r.finished != nil || !bytes.Equal(r.body, body) || r.reqBytes != int64(len(body)) || + !r.complete || r.process == nil || *r.process != llmlog.ProcessID || r.status != nil { + t.Fatalf("open row: state %q finished %v body exact %v (%d bytes) complete %v process %v status %v", + r.state, r.finished, bytes.Equal(r.body, body), r.reqBytes, r.complete, r.process, r.status) + } + answer := []byte("the answer \x00\xff") + if err := st.Finish(ctx, req.ID, llmlog.RecordedOutcome{Status: 200, Response: answer}); err != nil { + t.Fatalf("finish: %v", err) + } + r = readRecording(t, ctx, q, req.ID) + if r.state != llmlog.RecordingDone || r.finished == nil || r.status == nil || *r.status != 200 || r.code != nil || + !bytes.Equal(r.response, answer) || r.respBytes != int64(len(answer)) || !bytes.Equal(r.body, body) { + t.Fatalf("finished row: state %q status %v code %v answer exact %v", r.state, r.status, r.code, bytes.Equal(r.response, answer)) + } + if err := st.Finish(ctx, req.ID, llmlog.RecordedOutcome{Status: 503}); err == nil { + t.Errorf("a second Finish of the same row succeeded; an outcome is written once") + } + + // A request refused before its walk: done at once, with the part read. + refused := llmlog.RecordedRequest{ID: recID(t), ConsumerID: gwiConsumer, Path: "/v1/chat/completions", Op: llmlog.GatewayOpChat, + Declared: 400, Body: []byte(`{"model":`), Complete: false} + if err := st.Insert(ctx, refused, llmlog.RecordedOutcome{Status: 400, Code: "invalid_json"}); err != nil { + t.Fatalf("insert: %v", err) + } + r = readRecording(t, ctx, q, refused.ID) + if r.state != llmlog.RecordingDone || r.complete || string(r.body) != `{"model":` || r.declared == nil || *r.declared != 400 || + r.code == nil || *r.code != "invalid_json" || r.response != nil || r.stream != nil || r.model != nil { + t.Errorf("refused row: state %q complete %v body %q declared %v code %v response %v stream %v model %v", + r.state, r.complete, r.body, r.declared, r.code, r.response, r.stream, r.model) + } + // A refusal before any body was read: no body, the declared size, no op. + stage := llmlog.RecordedRequest{ID: recID(t), ConsumerID: gwiConsumer, Path: "/v1/nowhere", Declared: -1} + if err := st.Insert(ctx, stage, llmlog.RecordedOutcome{Status: 404, Code: "not_found"}); err != nil { + t.Fatalf("insert stage refusal: %v", err) + } + if r = readRecording(t, ctx, q, stage.ID); r.body != nil || r.reqBytes != 0 || r.declared != nil || r.op != nil { + t.Errorf("stage refusal row: body %v bytes %d declared %v op %v, want none of them", r.body, r.reqBytes, r.declared, r.op) + } + + // An Open the caller saw fail although it committed: Insert ends it and + // keeps its request. + lost := llmlog.RecordedRequest{ID: recID(t), ConsumerID: gwiConsumer, Path: "/v1/chat/completions", Body: []byte("held"), Complete: true} + if err := st.Open(ctx, lost); err != nil { + t.Fatalf("open: %v", err) + } + other := lost + other.Body = []byte("other") + if err := st.Insert(ctx, other, llmlog.RecordedOutcome{Status: 503, Code: "recording_unavailable"}); err != nil { + t.Fatalf("insert over an open row: %v", err) + } + if r = readRecording(t, ctx, q, lost.ID); r.state != llmlog.RecordingDone || string(r.body) != "held" || r.code == nil || *r.code != "recording_unavailable" { + t.Errorf("open row after Insert: state %q body %q code %v — want done, its own request kept", r.state, r.body, r.code) + } + // ... and an Insert over a done row changes nothing. + if err := st.Insert(ctx, other, llmlog.RecordedOutcome{Status: 200}); err != nil { + t.Fatalf("insert over a done row: %v", err) + } + if r = readRecording(t, ctx, q, lost.ID); r.status == nil || *r.status != 503 { + t.Errorf("a done row's outcome changed: %v", r.status) + } +} + +func TestRecordingsJanitor(t *testing.T) { + ctx := context.Background() + pool := testdb.SetupTestDB(t) + q := pool + st := llmlog.Recordings{Pool: pool} + old, fresh := recID(t), recID(t) + for _, id := range []string{old, fresh} { + if err := st.Open(ctx, llmlog.RecordedRequest{ID: id, ConsumerID: gwiConsumer, Path: "/v1/embeddings", Body: []byte("input"), Complete: true}); err != nil { + t.Fatalf("open: %v", err) + } + if err := st.Finish(ctx, id, llmlog.RecordedOutcome{Status: 200, Response: []byte("answer")}); err != nil { + t.Fatalf("finish: %v", err) + } + } + // The time shift is the fixture's only hand edit: rows are written by Open. + if _, err := pool.Exec(ctx, `UPDATE context_llm_recordings SET created_at = now() - interval '91 days' WHERE id = $1::uuid`, old); err != nil { + t.Fatal(err) + } + n, err := llmlog.EvictBodies(ctx, pool, 90) + if err != nil || n != 1 { + t.Fatalf("evict: %d rows, %v — want the one recording past the retention", n, err) + } + if r := readRecording(t, ctx, q, old); r.body != nil || r.response != nil || r.reqBytes != 5 || r.respBytes != 6 || r.state != llmlog.RecordingDone { + t.Errorf("past the retention: body %v answer %v sizes %d/%d state %q — want both NULL, sizes and outcome kept", r.body, r.response, r.reqBytes, r.respBytes, r.state) + } + if r := readRecording(t, ctx, q, fresh); string(r.body) != "input" || string(r.response) != "answer" { + t.Errorf("the janitor touched a fresh recording") + } + if n, _ := llmlog.EvictBodies(ctx, pool, 90); n != 0 { + t.Errorf("a second run evicted %d rows, want 0 (idempotent)", n) + } +} + +func TestRecordingStatementCost(t *testing.T) { + if os.Getenv("CTX_RECORD_PROBE") != "1" { + t.Skip("opt-in probe (CTX_RECORD_PROBE=1)") + } + ctx := context.Background() + pool := testdb.SetupTestDB(t) + st := llmlog.Recordings{Pool: pool} + // Warm the pool's connection and statement cache. + _ = st.Open(ctx, llmlog.RecordedRequest{ID: recID(t), ConsumerID: gwiConsumer, Path: "/warm", Body: []byte("x"), Complete: true}) + for _, n := range []int{64 << 10, 1 << 20, 4 << 20, 8 << 20} { + body := bytes.Repeat([]byte("0123456789abcdef"), n/16) + var before, after runtime.MemStats + runtime.GC() + runtime.ReadMemStats(&before) + start := time.Now() + if err := st.Open(ctx, llmlog.RecordedRequest{ID: recID(t), ConsumerID: gwiConsumer, Path: "/v1/embeddings", Body: body, Complete: true}); err != nil { + t.Fatalf("open %d: %v", n, err) + } + took := time.Since(start) + runtime.ReadMemStats(&after) + alloc := after.TotalAlloc - before.TotalAlloc + t.Logf("open of %d bytes: %v, allocated %d bytes = %.2f × the body", n, took, alloc, float64(alloc)/float64(n)) + } +} diff --git a/go/internal/llmlog/recordings_readers_census_test.go b/go/internal/llmlog/recordings_readers_census_test.go new file mode 100644 index 000000000..4872373c1 --- /dev/null +++ b/go/internal/llmlog/recordings_readers_census_test.go @@ -0,0 +1,105 @@ +package llmlog + +import ( + "fmt" + "go/ast" + "go/token" + "regexp" + "sort" + "strconv" + "strings" + "testing" +) + +// The readers of context_llm_recordings (issue #571, migration 197). A +// recording row's request_body and response_body are what a recording +// consumer sent and got, whole — credentials in a prompt included; no ctx +// surface reads them, only a server operator in the database +// (docs/operations.md "Recording a consumer"). This census walks every +// non-test .go file of the module and lists each file whose STRING LITERALS +// name the table or one of its body columns — comments do not count. Every +// such file is classified below with how many such literals it holds; a new +// reader or writer of the table — a whole-row one included, and a new +// statement in a file already listed — turns this test red until it is +// classified here (and, if it hands bodies to anybody, given its test). +// +// Not covered, stated rather than assumed: SQL assembled from fragments that +// never spell the table's name, the shell scripts of the repository +// (backup.sh and coverage.sh dump the whole database — a backup, not a +// reader), and the web frontend, which has no route to the table at all. +// recordingsReader is one classified file: the number of its literals that +// name the table or a body column, and what they do. +type recordingsReader struct { + n int + what string +} + +var recordingsReaders = map[string]recordingsReader{ + // The writer (Open, Finish, Insert) and the retention janitor's statement + // (evictRecordingBodies, run by EvictBodies) — no SELECT anywhere. + "internal/llmlog/recordings.go": {4, "writes: open, finish, insert; the retention janitor NULLs the bodies"}, + // Text only: the refusal of record_bodies without its confirmation names + // the table (recordConfirmRefusal) — no statement. + "internal/handler/model_consumers.go": {1, "text: the confirmation refusal names the table"}, +} + +// tableRE matches a literal that reads or writes the table; bodyColumnRE one +// that names a body column. +var ( + tableRE = regexp.MustCompile(`\bcontext_llm_recordings\b`) + bodyColumnRE = regexp.MustCompile(`\b(request_body|response_body)\b`) +) + +func TestRecordingsReadersCensus(t *testing.T) { + root := gatewayCensusModuleRoot(t) + fset := token.NewFileSet() + files := productionFiles(t, fset, root) + found := map[string][]string{} + for _, cf := range files { + ast.Inspect(cf.file, func(n ast.Node) bool { + lit, ok := n.(*ast.BasicLit) + if !ok || lit.Kind != token.STRING { + return true + } + s, err := strconv.Unquote(lit.Value) + if err != nil { + s = lit.Value + } + if tableRE.MatchString(s) || bodyColumnRE.MatchString(s) { + found[cf.rel] = append(found[cf.rel], fset.Position(lit.Pos()).String()) + } + return true + }) + } + var unclassified, gone []string + for rel, at := range found { + if r, ok := recordingsReaders[rel]; !ok || r.n != len(at) { + unclassified = append(unclassified, fmt.Sprintf("%s: %d literal(s), classified %d (%s)", rel, len(at), r.n, strings.Join(at, ", "))) + } + } + for rel := range recordingsReaders { + if _, ok := found[rel]; !ok { + gone = append(gone, rel) + } + } + sort.Strings(unclassified) + sort.Strings(gone) + t.Logf("census: %d production files, %d name context_llm_recordings or its bodies: %v", len(files), len(found), keys(found)) + if len(unclassified) > 0 { + t.Errorf("files whose literals name context_llm_recordings or its bodies without a classification in recordingsReaders "+ + "(a recording's bodies reach no ctx surface — classify the file and give it its test):\n %s", + strings.Join(unclassified, "\n ")) + } + if len(gone) > 0 { + t.Errorf("classified files that no longer name context_llm_recordings (drop them from recordingsReaders): %v", gone) + } +} + +func keys(m map[string][]string) []string { + out := make([]string, 0, len(m)) + for k := range m { + out = append(out, k) + } + sort.Strings(out) + return out +} diff --git a/go/internal/llmlogexport/export.go b/go/internal/llmlogexport/export.go index 3ddb00b58..c4ff5093e 100644 --- a/go/internal/llmlogexport/export.go +++ b/go/internal/llmlogexport/export.go @@ -24,7 +24,6 @@ import ( "github.com/jackc/pgx/v5" "github.com/jackc/pgx/v5/pgxpool" - "github.com/GottZ/ctx/internal/llmlog" "github.com/GottZ/ctx/internal/pgxdb" ) @@ -65,10 +64,6 @@ type ExportSummary struct { RowsBody int64 `json:"rows_body"` RowsBodylessSlim int64 `json:"rows_bodyless_slim"` RowsBodylessNull int64 `json:"rows_bodyless_null"` - // RowsRecordedSealed zählt die aufgezeichneten Gateway-Zeilen (issue - // #571), deren Bodies der Export versiegelt ausgibt (exportSelect); sie - // stehen zugleich in rows_bodyless_slim bzw. rows_bodyless_null. - RowsRecordedSealed int64 `json:"rows_recorded_sealed"` // CountGate ist count(*) mit demselben Fenster im selben Snapshot — // muss RowsTotal gleichen (Live-Gate KW1). CountGate int64 `json:"count_gate"` @@ -158,7 +153,6 @@ type exportRow struct { body []byte hasBody bool anyNull bool - sealed bool } // exportWindow baut das Fenster-Prädikat als Klausel-Liste + Argumente — @@ -189,31 +183,13 @@ func exportWindow(opts ExportOptions, until time.Time) (string, []any) { // Slim schreibt den Leerstring (Slimmed), EvictBodies schreibt NULL. Ein naiver // IS NOT NULL-Filter ließe Leer-Prompts als Replay-Kandidaten durch // (design/02 §5.2 — genau dieser Fehler steckte in der Erst-Inventur). -// -// Aufgezeichnete Gateway-Zeilen (issue #571, llmlog.SQLBodiesServerAdminOnly: -// metadata.gw.recorded, und fail-closed jede Gateway-Zeile ohne lesbare -// Markierung) verlassen den Export versiegelt: ihre Bodies stehen als -// Leerstring in der Zeile (NULL bleibt NULL — die Retention-Klassifikation -// bleibt gleich), has_body ist false, und sealed zählt sie. Ihre Bodies -// können Zugangsdaten im Klartext tragen; sie gehören in keinen Export und in -// keine Trainings-Pipeline — gelesen werden sie nur von einem Server-Admin -// (GET /api/llmlog/{id}, docs/operations.md „Recording a consumer"). -var exportSelect = ` - SELECT created_at, id::text, - CASE WHEN ` + exportSealed + ` THEN to_jsonb(t) || jsonb_build_object( - 'request_system', CASE WHEN t.request_system IS NULL THEN NULL ELSE '' END, - 'request_user', CASE WHEN t.request_user IS NULL THEN NULL ELSE '' END, - 'response_content', CASE WHEN t.response_content IS NULL THEN NULL ELSE '' END) - ELSE to_jsonb(t) END, - (NOT ` + exportSealed + ` AND (coalesce(request_system, '') <> '' OR coalesce(request_user, '') <> '')) AS has_body, - (request_system IS NULL OR request_user IS NULL OR response_content IS NULL) AS any_null, - ` + exportSealed + ` AS sealed +const exportSelect = ` + SELECT created_at, id::text, to_jsonb(t), + (coalesce(request_system, '') <> '' OR coalesce(request_user, '') <> '') AS has_body, + (request_system IS NULL OR request_user IS NULL OR response_content IS NULL) AS any_null FROM context_llm_log t WHERE ` -// exportSealed ist die Versiegelungs-Bedingung über dem Alias t. -var exportSealed = llmlog.SQLBodiesServerAdminOnly("t") - // pageSQL liefert die Seiten-Query. Der Cursor trägt neben der Rowcompare das // redundante `created_at >= $k`: logisch impliziert, aber die einzige Form, // die der Planner als Startbedingung auf dem created_at-Index UND für die @@ -341,14 +317,11 @@ func exportPage(ctx context.Context, pool *pgxpool.Pool, cw io.Writer, q string, defer rows.Close() for rows.Next() { var r exportRow - if err := rows.Scan(&r.createdAt, &r.id, &r.body, &r.hasBody, &r.anyNull, &r.sealed); err != nil { + if err := rows.Scan(&r.createdAt, &r.id, &r.body, &r.hasBody, &r.anyNull); err != nil { return fmt.Errorf("llmlog export: scan: %w", err) } n++ sum.RowsTotal++ - if r.sealed { - sum.RowsRecordedSealed++ - } switch { case r.anyNull: sum.RowsBodylessNull++ diff --git a/go/internal/llmlogexport/export_recorded_integration_test.go b/go/internal/llmlogexport/export_recorded_integration_test.go deleted file mode 100644 index 06d761dbd..000000000 --- a/go/internal/llmlogexport/export_recorded_integration_test.go +++ /dev/null @@ -1,76 +0,0 @@ -//go:build integration - -// The export's seal of recorded rows (issue #571), fail-closed: a gateway row -// leaves ctx-llmlog-export with its bodies sealed unless its metadata.gw is an -// object that does not mark it recorded. The production writer always stamps -// metadata.gw on a gateway row, so the rows without a readable marker are -// written by hand here — they are the states the predicate must not trust -// (llmlog.SQLBodiesServerAdminOnly). -// -// go test -tags=integration -p 1 -count=1 -run TestExportSealsRecordedRows -v ./internal/llmlogexport/ -package llmlogexport_test - -import ( - "bytes" - "context" - "fmt" - "strings" - "testing" - - "github.com/GottZ/ctx/internal/llmlogexport" - "github.com/GottZ/ctx/internal/testdb" -) - -func TestExportSealsRecordedRows(t *testing.T) { - if testing.Short() { - t.Skip("integration test") - } - ctx := context.Background() - pool := testdb.SetupTestDB(t) - const consumer = "0195a6f0-0000-7000-8000-00000000e571" - rows := []struct { - name, pipeline string - consumer bool - metadata string // JSON (the column is NOT NULL) - sealed bool - }{ - {"recorded", "gateway-chat", true, `{"gw":{"v":1,"recorded":true}}`, true}, - {"recorded as a string", "gateway-chat", true, `{"gw":{"v":1,"recorded":"true"}}`, true}, - {"recorded false", "gateway-chat", true, `{"gw":{"v":1,"recorded":false}}`, false}, - {"unrecorded", "gateway-embeddings", true, `{"gw":{"v":1,"op":"embed"}}`, false}, - {"marker missing", "gateway-chat", true, `{"chain":[]}`, true}, - {"gw JSON null", "gateway-rerank", true, `{"gw":null}`, true}, - {"gw not an object", "gateway-chat", true, `{"gw":[1]}`, true}, - {"gateway pipeline without consumer", "gateway-chat", false, `{}`, true}, - {"background pipeline", "query-synthesize", false, `{}`, false}, - } - for i, r := range rows { - var cons any - if r.consumer { - cons = consumer - } - if _, err := pool.Exec(ctx, `INSERT INTO context_llm_log (pipeline, model, host, request_user, response_content, request_system, metadata, consumer_id) - VALUES ($1, 'm', 'h', $2, $3, '', $4::jsonb, $5::uuid)`, - r.pipeline, fmt.Sprintf("SECRET-%d-%s", i, r.name), fmt.Sprintf("ANSWER-%d-%s", i, r.name), r.metadata, cons); err != nil { - t.Fatalf("row %d (%s): %v", i, r.name, err) - } - } - var buf bytes.Buffer - sum, err := llmlogexport.Export(ctx, pool, &buf, llmlogexport.ExportOptions{UntilMargin: 1}) - if err != nil { - t.Fatalf("export: %v", err) - } - want := 0 - for i, r := range rows { - inExport := strings.Contains(buf.String(), fmt.Sprintf("SECRET-%d-", i)) || strings.Contains(buf.String(), fmt.Sprintf("ANSWER-%d-", i)) - if r.sealed { - want++ - } - if inExport == r.sealed { - t.Errorf("%s: bodies in the export %v, want sealed %v", r.name, inExport, r.sealed) - } - } - if sum.RowsRecordedSealed != int64(want) || sum.RowsTotal != int64(len(rows)) { - t.Errorf("rows_recorded_sealed %d of %d, want %d of %d", sum.RowsRecordedSealed, sum.RowsTotal, want, len(rows)) - } -} diff --git a/go/internal/oai/chat.go b/go/internal/oai/chat.go index 1456af64e..95285781d 100644 --- a/go/internal/oai/chat.go +++ b/go/internal/oai/chat.go @@ -95,7 +95,13 @@ func ChatCompletions(d Deps) http.Handler { refuseInternal(w, r) return } + rr, ok := routeRecording(r, ca, llmlog.GatewayOpChat) + if !ok { + refuseRecording(AccessRecordFrom(r.Context()), w) + return + } c := newChatCall(d, w, r, ca, entry) + c.adoptRecording(rr) defer c.close() c.serve() }) @@ -155,15 +161,14 @@ type chatCall struct { // has allocated against it (cover). held, spent int64 - // recording is the capture of a recording consumer's request (record.go; - // off for every other consumer). - recording recording + // recording is the request's recording (record.go): nil for a consumer + // that does not record. + recording *requestRecording } func newChatCall(d Deps, w http.ResponseWriter, r *http.Request, ca *auth.ConsumerAuth, entry time.Time) *chatCall { s := d.Settings() c := &chatCall{d: d, w: w, s: s, ca: ca, entry: entry, client: r.Context(), rec: AccessRecordFrom(r.Context())} - c.recording.on = ca != nil && ca.RecordBodies if c.rec == nil { c.rec = &AccessRecord{} // outside a model group: filled, never read } @@ -225,7 +230,16 @@ func (c *chatCall) close() { for _, stop := range c.stops { stop() } - c.recording.release() // what no row of this request took +} + +// adoptRecording binds the request's recording (nil: the consumer does not +// record): the request's id becomes the recording's, so the answer's id +// ("chatcmpl-") names the recorded row. +func (c *chatCall) adoptRecording(rr *requestRecording) { + c.recording = rr + if rr != nil { + c.id = rr.req.ID + } } // refuse answers code and names it as the access record's reason. @@ -234,6 +248,11 @@ func (c *chatCall) refuse(code, message string, shouldRetry bool) { c.reply(func(w http.ResponseWriter) { WriteCode(w, code, message, shouldRetry) }) } +// refuseRecording answers a request whose recording failed (record.go). +func (c *chatCall) refuseRecording() { + c.reply(func(w http.ResponseWriter) { refuseRecording(c.rec, w) }) +} + func (c *chatCall) internal(msg string, args ...any) { slog.Error("gateway: "+msg, append(args, "path", c.r.URL.Path, "request_id", c.w.Header().Get("X-Request-ID"))...) c.rec.Reason = CodeInternalError @@ -287,6 +306,7 @@ func (c *chatCall) serve() { c.refuseParam(perr) return } + c.recording.parsed(req.model, req.stream) c.frame(req.stream) if !c.resolve(req.model, req.modelOverlong) { return @@ -389,7 +409,8 @@ func reasoningOff(a modelalias.Alias) bool { // The ledger starts here: the stage reserved requestReserveFactor × the // body, the read spent what readRequestBody allocated. func (c *chatCall) readBody() ([]byte, bool) { - body, spent, err := readRequestBody(c.r.Body, c.r.ContentLength) + body, spent, err := readBodyKeep(c.r.Body, c.r.ContentLength, c.recording != nil) + c.recording.setBody(body, err == nil) var tooLarge *http.MaxBytesError switch { case err == nil: @@ -420,6 +441,14 @@ func (c *chatCall) readBody() ([]byte, bool) { // there and spends about twice the body), an undeclared one in chunks that // double up to readChunkMax and are joined into one buffer at the end. func readRequestBody(r io.Reader, declared int64) ([]byte, int64, error) { + return readBodyKeep(r, declared, false) +} + +// readBodyKeep is readRequestBody; keep (a recording consumer's request, +// record.go) returns what an undeclared body's failed read got as well — +// its chunks joined — where readRequestBody returns nothing. A declared +// body's failed read returns its part either way. +func readBodyKeep(r io.Reader, declared int64, keep bool) ([]byte, int64, error) { if declared > 0 { buf := make([]byte, declared) n, err := io.ReadFull(r, buf) @@ -455,6 +484,9 @@ func readRequestBody(r io.Reader, declared int64) ([]byte, int64, error) { break } if err != nil { + if keep { + return slices.Concat(chunks...), spent + int64(total), err + } return nil, spent, err } size = min(2*size, readChunkMax) @@ -763,7 +795,7 @@ func (c *chatCall) admitLimiter(maxTokens int) bool { // The row the shutdown's forced settle writes should the request still // be open after the HTTP drain (W06-13 (e)). registerForcedRow(res, c.d.Record, func() llmlog.GatewayRow { - return llmlog.GatewayRow{Pipeline: chatPipeline, ConsumerID: c.ca.ConsumerID, Recorded: c.recording.on, + return llmlog.GatewayRow{Pipeline: chatPipeline, ConsumerID: c.ca.ConsumerID, Recorded: c.recording != nil, RecordingID: c.recording.id(), Gateway: withFederation(c.r.Context(), llmlog.Gateway{Alias: c.alias.Name, Hop: c.rec.Hop, ClientReqID: clientRequestID(c.r), ModelKeyID: c.ca.ModelKeyID, Stream: c.sse != nil})} }, string(c.required)) return true @@ -850,6 +882,13 @@ func (c *chatCall) walk(chain []backends.Backend, spec llm.UpstreamSpec) { return } c.rec.Class = planClass(plan) // the class of an L2 refusal (W06-12); a lease names it again + // A recording consumer's request is held before its first attempt and + // before any queue wait (record.go); one that cannot be is not served. + if !c.recording.open(c.ctx) { + c.endLimit(func(l LimitReservation) { l.Abort() }) + c.refuseRecording() + return + } c.target = newWatchTarget(c.ca, c.req.model, c.alias.ID, c.gen) stop := c.d.watch(c.ctx, c.cancel, c.target) defer stop() @@ -858,6 +897,9 @@ func (c *chatCall) walk(chain []backends.Backend, spec llm.UpstreamSpec) { rules := llm.WalkRules{WindowRule: true, AllowedClasses: c.d.Planner.AllowedClasses(), Timeout: c.attemptTimeout} served, attempts, werr := llm.WalkChain(c.ctx, plan.Chain, c.alias.Role, plan.Acquirer, llm.PoolReporter(c.d.Pool), rules, func(runCtx context.Context, b *backends.Backend, lease *dispatch.Lease, timeout time.Duration) (dispatch.Usage, bool, error) { + if !c.recording.ready() { + return dispatch.Usage{}, false, &llm.AdmissionError{Err: errRecordingUnavailable, Backend: b.Name, Host: b.Host} + } if c.sse != nil { return c.streamAttempt(&st, spec, plan.Lane, runCtx, b, lease, timeout) } @@ -1134,6 +1176,12 @@ func (c *chatCall) outcome(plan Plan, attempts []llm.ChainAttempt, err error, st // empty walk, and the route's own attempt mapping — as a status, or as the // error frame of a committed stream (reply). func (c *chatCall) outcomeError(plan Plan, attempts []llm.ChainAttempt, err error, st *walkState) chatOutcome { + if errors.Is(err, errRecordingUnavailable) { + // An attempt found the request's recording not open (ready): it went + // to no backend (record.go). + c.refuseRecording() + return chatOutcome{finish: llmlog.FinishAborted, redacted: &llmlog.RedactedErr{Class: "admission", Code: CodeRecordingUnavailable}} + } if errors.Is(err, ErrBudgetExhausted) { // The budget refused an attempt's upstream body (reserveUpstream): // the stage's 503. Without a wire call no row, and the meter's @@ -1211,6 +1259,11 @@ func (c *chatCall) verdict() (ended bool, code string) { // it still reads — the stream ends with its error frame. c.refuse(CodeServerOverloaded, relayOverflowMessage, true) return true, CodeServerOverloaded + case errors.Is(cause, errRecordingUnavailable): + // A recording consumer's stream had no room to keep its next line + // (record.go): it ends before that line, with its error frame. + c.refuseRecording() + return true, CodeRecordingUnavailable case errors.Is(cause, errClientGone): // A write to the client failed (it stopped reading): nothing more // can reach it (D4). @@ -1258,6 +1311,13 @@ func (c *chatCall) success(plan Plan, st *walkState) chatOutcome { c.rec.Usage = st.usageKind // The meter's view of the request's op bucket, on the successful answer // only (design/06 §4.4; lead decision M2 (c)). + answer := append(body, '\n') + // A recording consumer's answer is held before its first byte goes out + // (record.go); one that cannot be is refused instead. + if !c.recording.answer(c.ctx, answer) { + c.refuseRecording() + return chatOutcome{finish: llmlog.FinishError, redacted: &llmlog.RedactedErr{Class: "admission", Code: CodeRecordingUnavailable}} + } for k, v := range c.rateHeaders() { c.w.Header()[k] = v } @@ -1270,7 +1330,7 @@ func (c *chatCall) success(plan Plan, st *walkState) chatOutcome { // escape class, TestRewriteChatIsTheBase, FuzzRewriteChatIsTheBase) —, // served as application/json. The buffer has room for the newline: the // append does not copy the answer. - if _, err := c.w.Write(append(body, '\n')); err != nil { //nolint:gosec // G705: the body carries json.Marshal's HTML escape, written by the rewrite walk gosec's taint check does not know as a sanitizer (pinned byte-equal, see above) + if _, err := c.w.Write(answer); err != nil { //nolint:gosec // G705: the body carries json.Marshal's HTML escape, written by the rewrite walk gosec's taint check does not know as a sanitizer (pinned byte-equal, see above) slog.Warn("gateway: failed to write the answer", "error", err, "request_id", c.w.Header().Get("X-Request-ID")) } return chatOutcome{finish: finishOf(st.result.FinishReason), response: body} @@ -1325,18 +1385,7 @@ func (c *chatCall) record(plan Plan, served *backends.Backend, attempts []llm.Ch } } request, response := "", "" - switch { - case c.recording.on: - // A recording consumer's row (issue #571): the whole text of the - // array and the whole answer — a stream's relayed lines — reserved - // against the recording account, not booked in the ledger (record.go). - request = c.recording.text(c.req.messages, llmlog.RecordLostRequest) - if c.sse != nil { - response = c.recording.streamText() - } else if len(out.response) > 0 { - response = c.recording.bytes(out.response, llmlog.RecordLostResponse) - } - case c.s.BodyLogging == llmlog.BodyLoggingFull || (c.s.BodyLogging == llmlog.BodyLoggingErrors && out.redacted != nil): + if c.s.BodyLogging == llmlog.BodyLoggingFull || (c.s.BodyLogging == llmlog.BodyLoggingErrors && out.redacted != nil) { // The row's text of the array is sized, then booked, then written // (hardening 6): under an exhausted budget the row goes without it. if n := bodyLogSize(c.req.messages); c.cover(int64(n)) { @@ -1372,18 +1421,17 @@ func (c *chatCall) record(plan Plan, served *backends.Backend, attempts []llm.Ch // stores the same. Pinned by TestBodyLogTextStoresWhatTheArrayStored. const bodyLogTextMax = 64<<10 + utf8.UTFMax -// bodyLogWalkN yields the text of the message array raw for the log row as +// bodyLogWalk yields the text of the message array raw for the log row as // the row stores it before its cut — valid UTF-8 with each run of invalid // bytes one U+FFFD and no NUL (llmlog's storable) — piece by piece to put, -// up to limit bytes: bodyLogTextMax for the body policy (hardening 6, the -// class gate: string(raw) copied the whole array outside the reservation, -// and the row's cleaning grew a text of invalid bytes between ASCII ones to -// 8 × its size before cutting it), noLogLimit for a recorded row's whole -// text (record.go). -func bodyLogWalkN(raw []byte, limit int, put func(p []byte)) { +// up to bodyLogTextMax bytes (hardening 6, the class gate: string(raw) +// copied the whole array outside the reservation, and the row's cleaning +// grew a text of invalid bytes between ASCII ones to 8 × its size before +// cutting it). +func bodyLogWalk(raw []byte, put func(p []byte)) { n := 0 invalid := false // the byte before was part of an invalid sequence - for i := 0; i < len(raw) && n < limit; { + for i := 0; i < len(raw) && n < bodyLogTextMax; { c := raw[i] size := 1 switch { @@ -1414,24 +1462,18 @@ func bodyLogWalkN(raw []byte, limit int, put func(p []byte)) { var replacementChar = []byte(string(utf8.RuneError)) // bodyLogSize is the length of bodyLogText(raw). -func bodyLogSize(raw []byte) int { return bodyLogSizeN(raw, bodyLogTextMax) } - -// bodyLogSizeN is the length of bodyLogTextN(raw, …, limit). -func bodyLogSizeN(raw []byte, limit int) int { +func bodyLogSize(raw []byte) int { n := 0 - bodyLogWalkN(raw, limit, func(p []byte) { n += len(p) }) + bodyLogWalk(raw, func(p []byte) { n += len(p) }) return n } // bodyLogText is the log row's text of raw, written once into size bytes // (bodyLogSize). -func bodyLogText(raw []byte, size int) string { return bodyLogTextN(raw, size, bodyLogTextMax) } - -// bodyLogTextN is bodyLogText up to limit bytes (bodyLogSizeN). -func bodyLogTextN(raw []byte, size, limit int) string { +func bodyLogText(raw []byte, size int) string { var b strings.Builder b.Grow(size) - bodyLogWalkN(raw, limit, func(p []byte) { b.Write(p) }) + bodyLogWalk(raw, func(p []byte) { b.Write(p) }) return b.String() } diff --git a/go/internal/oai/chat_harness_test.go b/go/internal/oai/chat_harness_test.go index aa027ddbf..55af9ba18 100644 --- a/go/internal/oai/chat_harness_test.go +++ b/go/internal/oai/chat_harness_test.go @@ -308,6 +308,9 @@ type chatRig struct { // peerIngress edits the PeerIngress configuration before the mount // (F-W12: Binder, RequirePeerHop, Events); nil keeps the default. peerIngress func(*federation.PeerIngressConfig) + // recStage is the recording stage behind the rig's door (issue #571, + // withRecordings); nil mounts none. + recStage *oai.RecordingStage } // acceptPeerBinder is the PeerIngress binder of the harnesses whose subject @@ -456,6 +459,9 @@ func (r *chatRig) mount(h http.Handler) chi.Router { }) }) g.Use(oai.Recover) + if r.recStage != nil { + g.Use(r.recStage.Handler) // the recording stage behind the door (record.go) + } pcfg := federation.PeerIngressConfig{Consumer: r.deps.Consumer, Binder: acceptPeerBinder{}, Logger: slog.New(slog.DiscardHandler)} if r.peerIngress != nil { r.peerIngress(&pcfg) diff --git a/go/internal/oai/chat_stream.go b/go/internal/oai/chat_stream.go index 60c0599ff..4e2fe00c4 100644 --- a/go/internal/oai/chat_stream.go +++ b/go/internal/oai/chat_stream.go @@ -126,10 +126,18 @@ func (c *chatCall) streamAttempt(st *walkState, spec llm.UpstreamSpec, lane stri if chunk.skip { return nil } + // A recording consumer's stream keeps every line before the relay + // takes it (record.go): a line it has no room to keep is not sent — + // the run ends with recording_unavailable (verdict). + if !c.recording.addCapture(chunk.out) { + c.cancel(errRecordingUnavailable) + return &llm.AdmissionError{Err: errRecordingUnavailable, Backend: b.Name, Host: b.Host} + } // Into the relay buffer, not to the client (A03-W10, I-03-7): the // client writer drains it on its own goroutine, so this attempt — // and its lease — ends with the upstream, not with the client. if werr := c.relay.put(chunk.out); werr != nil { + c.recording.dropCaptureTail(len(chunk.out)) // the line the relay did not take if errors.Is(werr, ErrBudgetExhausted) { // The ledger refused the copy of an oversize chunk (FOLGE-S): // an admission outcome, as a refused upstream body — the @@ -146,9 +154,7 @@ func (c *chatCall) streamAttempt(st *walkState, spec llm.UpstreamSpec, lane stri } return werr } - // A recording consumer's row keeps every relayed line (record.go): - // after the relay took it, so the stream's own path is unchanged. - c.recording.addStream(chunk.out) + c.recording.noteStreamed() st.relayed++ return nil }) diff --git a/go/internal/oai/embed_harness_test.go b/go/internal/oai/embed_harness_test.go index 7377cb425..f43dc7260 100644 --- a/go/internal/oai/embed_harness_test.go +++ b/go/internal/oai/embed_harness_test.go @@ -248,6 +248,9 @@ func (r *chatRig) mountEmbed(h http.Handler) chi.Router { }) }) g.Use(oai.Recover) + if r.recStage != nil { + g.Use(r.recStage.Handler) // the recording stage behind the door (record.go) + } g.Use(federation.PeerIngress(federation.PeerIngressConfig{Consumer: r.deps.Consumer, Binder: acceptPeerBinder{}, Logger: slog.New(slog.DiscardHandler)})) g.Use(oai.InflightBudget(&r.budget, func() oai.Settings { return *r.settings.Load() })) g.Method(http.MethodPost, "/embeddings", h) diff --git a/go/internal/oai/embeddings.go b/go/internal/oai/embeddings.go index 0fbba2318..d71f3f858 100644 --- a/go/internal/oai/embeddings.go +++ b/go/internal/oai/embeddings.go @@ -175,7 +175,16 @@ func Embeddings(d Deps) http.Handler { refuseInternal(w, r) return } + rr, ok := routeRecording(r, ca, llmlog.GatewayOpEmbed) + if !ok { + refuseRecording(AccessRecordFrom(r.Context()), w) + return + } c := newEmbedCall(d, w, r, ca, entry) + c.recording = rr + if rr != nil { + c.id = rr.req.ID // the answer and the attempts name the recorded row + } defer c.close() c.serve() }) @@ -225,6 +234,9 @@ type embedCall struct { // booked before the acquire (reserveUpstreamTexts); the first attempt // books only the rest of its bodies (frames, slack, wire calls). textsBooked int64 + // recording is the request's recording (record.go): nil for a consumer + // that does not record. + recording *requestRecording } func newEmbedCall(d Deps, w http.ResponseWriter, r *http.Request, ca *auth.ConsumerAuth, entry time.Time) *embedCall { @@ -327,6 +339,7 @@ func (c *embedCall) serve() { c.refuseParam(perr) return } + c.recording.parsed(req.model, false) if !c.resolve(req.model, req.modelOverlong) { return } @@ -417,7 +430,8 @@ func (c *embedCall) coverScan(required backends.Sensitivity, body []byte, depth // allocated — one buffer of the declared length, where io.ReadAll grew its // way there and spent about twice the body. func (c *embedCall) readBody() ([]byte, bool) { - body, spent, err := readRequestBody(c.r.Body, c.r.ContentLength) + body, spent, err := readBodyKeep(c.r.Body, c.r.ContentLength, c.recording != nil) + c.recording.setBody(body, err == nil) var tooLarge *http.MaxBytesError switch { case err == nil: @@ -649,7 +663,7 @@ func (c *embedCall) admitLimiter() bool { // The row the shutdown's forced settle writes should the request still // be open after the HTTP drain (W06-13 (e)). registerForcedRow(res, c.d.Record, func() llmlog.GatewayRow { - return llmlog.GatewayRow{Pipeline: embedPipeline, ConsumerID: c.ca.ConsumerID, Recorded: c.ca.RecordBodies, + return llmlog.GatewayRow{Pipeline: embedPipeline, ConsumerID: c.ca.ConsumerID, Recorded: c.recording != nil, RecordingID: c.recording.id(), Gateway: withFederation(c.r.Context(), llmlog.Gateway{Alias: c.alias.Name, Hop: c.rec.Hop, ClientReqID: clientRequestID(c.r), ModelKeyID: c.ca.ModelKeyID})} }, string(c.required)) return true @@ -791,6 +805,13 @@ func (c *embedCall) walk(chain []backends.Backend) { c.refuseParam(unsupportedValue("input", fmt.Sprintf("at most %d inputs per request", c.lim.subBatch))) return } + // A recording consumer's request is held before its first attempt and + // before any queue wait (record.go); one that cannot be is not served. + if !c.recording.open(c.ctx) { + c.endLimit(func(l LimitReservation) { l.Abort() }) + refuseRecording(c.rec, c.w) + return + } stop := c.d.watch(c.ctx, c.cancel, newWatchTarget(c.ca, c.req.model, c.alias.ID, c.gen)) defer stop() @@ -798,6 +819,9 @@ func (c *embedCall) walk(chain []backends.Backend) { rules := llm.WalkRules{WindowRule: true, AllowedClasses: c.d.Planner.AllowedClasses(), Timeout: c.attemptTimeout} served, attempts, werr := llm.WalkChain(c.ctx, plan.Chain, c.alias.Role, plan.Acquirer, llm.PoolReporter(c.d.Pool), rules, func(runCtx context.Context, b *backends.Backend, lease *dispatch.Lease, timeout time.Duration) (dispatch.Usage, bool, error) { + if !c.recording.ready() { + return dispatch.Usage{}, false, &llm.AdmissionError{Err: errRecordingUnavailable, Backend: b.Name, Host: b.Host} + } return c.attempt(&st, plan, runCtx, b, lease, timeout) }) stop() @@ -1222,6 +1246,12 @@ func (c *embedCall) outcome(plan Plan, attempts []llm.ChainAttempt, err error, s if err == nil { return c.success(st) } + if errors.Is(err, errRecordingUnavailable) { + // An attempt found the request's recording not open (ready): it went + // to no backend (record.go). + refuseRecording(c.rec, c.w) + return embedOutcome{finish: llmlog.FinishAborted, redacted: &llmlog.RedactedErr{Class: "admission", Code: CodeRecordingUnavailable}} + } if isAdmissionFailure(err) { waited := time.Duration(0) if st.lease == nil { @@ -1362,6 +1392,13 @@ func (c *embedCall) success(st *embedState) embedOutcome { if c.req.dims > 0 { dims = c.req.dims } + // A recording consumer's request is ended as answered before the first + // byte of the answer goes out (record.go); the vectors are not kept — + // the input is what was sent. One that cannot be is refused instead. + if !c.recording.answer(c.ctx, nil) { + refuseRecording(c.rec, c.w) + return embedOutcome{finish: llmlog.FinishError, redacted: &llmlog.RedactedErr{Class: "admission", Code: CodeRecordingUnavailable}} + } // The meter's view of the request's op bucket, on the successful answer // only (design/06 §4.4; lead decision M2 (c)). if c.limit != nil { @@ -1548,14 +1585,7 @@ func (c *embedCall) record(plan Plan, served *backends.Backend, attempts []llm.C usage = llmlog.UsageBackend } request := "" - rc := recording{on: c.ca.RecordBodies} - switch { - case rc.on: - // A recording consumer's row (issue #571): the whole text of the - // input, reserved against the recording account (record.go). The - // answer — the vectors — is not kept: the input is what was sent. - request = rc.text(c.req.input, llmlog.RecordLostRequest) - case c.s.BodyLogging == llmlog.BodyLoggingFull || (c.s.BodyLogging == llmlog.BodyLoggingErrors && out.redacted != nil): + if c.s.BodyLogging == llmlog.BodyLoggingFull || (c.s.BodyLogging == llmlog.BodyLoggingErrors && out.redacted != nil) { // The row's text of the input is sized, then booked, then written // (FOLGE-E, as the chat route since FOLGE-P hardening 6): // string(input) copied the whole value outside the reservation, and @@ -1578,6 +1608,6 @@ func (c *embedCall) record(plan Plan, served *backends.Backend, attempts []llm.C Request: request, BodyLogging: c.s.BodyLogging, } - rc.mark(&row) + c.recording.mark(&row) c.d.Record(row) } diff --git a/go/internal/oai/errors.go b/go/internal/oai/errors.go index 2edf0ad53..b4d2e8b5c 100644 --- a/go/internal/oai/errors.go +++ b/go/internal/oai/errors.go @@ -74,6 +74,9 @@ const ( CodeProxyMisconfigured = "proxy_misconfigured" CodeAuthOverloaded = "auth_overloaded" CodeAuthUnavailable = "auth_unavailable" + // The 503 of a recording consumer's request whose recording could not + // be committed (record.go, issue #571). + CodeRecordingUnavailable = "recording_unavailable" ) // CodeSpec binds a code to the one status and type it is sent with. @@ -130,6 +133,7 @@ var codes = []CodeSpec{ {CodeProxyMisconfigured, http.StatusServiceUnavailable, TypeServiceUnavailable}, {CodeAuthOverloaded, http.StatusServiceUnavailable, TypeServiceUnavailable}, {CodeAuthUnavailable, http.StatusServiceUnavailable, TypeServiceUnavailable}, + {CodeRecordingUnavailable, http.StatusServiceUnavailable, TypeServiceUnavailable}, } // Codes returns the vocabulary as a copy (Fremd-Review 2, FR2-7): the table diff --git a/go/internal/oai/errors_test.go b/go/internal/oai/errors_test.go index c0d156954..ca2deaa70 100644 --- a/go/internal/oai/errors_test.go +++ b/go/internal/oai/errors_test.go @@ -139,6 +139,7 @@ func TestCodesVocabulary(t *testing.T) { "upstream_unavailable", "upstream_rejected", "context_length_exceeded", "upstream_error", "upstream_timeout", "federation_header_invalid", "federation_loop", "federation_depth", "federation_hop_required", "peer_instance_mismatch", "proxy_misconfigured", "auth_overloaded", "auth_unavailable", // the model-key door's 503s (W01-6, W02-05) + "recording_unavailable", // a recording consumer's request that could not be held (issue #571) } { if !seen[want] { t.Errorf("code %q missing from oai.Codes", want) diff --git a/go/internal/oai/export_test.go b/go/internal/oai/export_test.go index 4b069fcda..7df1ce76f 100644 --- a/go/internal/oai/export_test.go +++ b/go/internal/oai/export_test.go @@ -49,3 +49,18 @@ var ( // ScanDepthStateBytes is the scan's booking per nesting level (hardening 7). const ScanDepthStateBytes = scanDepthStateBytes + +// FillRecordingAccount takes n bytes of the recording account (issue #571) +// for a test and returns their release. +func FillRecordingAccount(n int64) (release func()) { + recAccount.mu.Lock() + recAccount.held += n + recAccount.mu.Unlock() + return func() { recAccount.release(n) } +} + +// RecordingAccountLimit is recordAccountLimit. +var RecordingAccountLimit = recordAccountLimit + +// RecordCopyFactor is recordCopyFactor. +const RecordCopyFactor = recordCopyFactor diff --git a/go/internal/oai/forced.go b/go/internal/oai/forced.go index be40f4279..6096f9a2f 100644 --- a/go/internal/oai/forced.go +++ b/go/internal/oai/forced.go @@ -50,7 +50,6 @@ func registerForcedRow(l LimitReservation, record func(llmlog.GatewayRow), build row.Gateway.Finish = llmlog.FinishAborted row.Err = &llmlog.RedactedErr{Class: "shutdown", Code: CodeServiceUnavailable} row.BodyLogging = llmlog.BodyLoggingNone - markForced(&row, row.Recorded) // a recording consumer's row says what it lacks fs.OnForcedSettle(func(u dispatch.Usage) { r := row r.Telemetry = llmlog.Entry{RequiredSensitivity: required, Metadata: map[string]any{}, diff --git a/go/internal/oai/record.go b/go/internal/oai/record.go index e717fdcad..eb30c9e5c 100644 --- a/go/internal/oai/record.go +++ b/go/internal/oai/record.go @@ -1,174 +1,667 @@ package oai import ( - "io" - "math" - "strings" + "context" + "errors" + "log/slog" + "net/http" + "sort" + "sync" + "time" + "github.com/google/uuid" + + "github.com/GottZ/ctx/internal/auth" "github.com/GottZ/ctx/internal/llmlog" ) -// recording is the capture of one request of a recording consumer (issue -// #571, auth.ConsumerAuth.RecordBodies): the texts its row keeps whole — the -// request as the body policy's text but without its cut, the answer the -// client received (a non-streamed chat answer as written, a stream's data -// lines as relayed). Every text is reserved against llmlog's recording -// account (llmlog.ReserveRecorded) before it is made — never against the -// request's in-flight budget, so the switch changes no refusal and no answer -// of the request (the one booking it drops is the body policy's own 64 KiB -// log text at the request's end, which a recorded row does not take). A text the account cannot take is not made: -// the row goes without it and names it (record_lost, cause "memory"). The -// zero value records nothing; on is set once, from the door's ConsumerAuth. -type recording struct { - on bool - // held is what this request reserved and has not handed to its row. +// Recording (issue #571, migration 197): a model consumer with the switch +// record_bodies on has every request it sends through this gateway held +// durably — nothing it sent is served without it, and nothing it sent is +// lost on the way to the log. +// +// - The stage (RecordingStage, right behind the model-key door) opens a +// recording for every request of such a consumer: an id, the door's +// identity, the declared length, and the status the client gets +// (recordingWriter). Every other consumer passes it untouched — no +// wrapper, no allocation, no database call. +// - The route hands it the body as soon as it is read (whole, or the part a +// failed read got) and, before its walk — before the first backend +// attempt and before any queue wait —, commits it (open: an INSERT of the +// row in state open). A request whose row cannot be committed — the +// database refuses, does not answer within recordWriteTimeout, or the +// recording account has no room within the wait the gateway grants a +// request anyway — is not served: 503 recording_unavailable, +// x-should-retry: true, nothing goes to a backend. Every attempt of the +// walk checks the commit again (ready). +// - A non-streamed answer (chat, rerank; embeddings without the vectors) +// is committed with the outcome before its first byte is written; a +// failure there answers the request 503 recording_unavailable instead. A +// stream keeps every line it relays (captured before the relay takes it) +// and commits them when it ends; what a stream already sent cannot be +// taken back, so a stream whose end cannot be committed leaves its row +// open — the request held, the answer not — and is counted +// (stream_answers_unrecorded). +// - When the request has ended — the stage, after the route returned or +// panicked — its outcome is committed: the open row is ended, or a +// request the gateway refused before it opened one gets its row there, +// with what was read of the body. A request for which no row could be +// written at all is counted (unrecordable); it was refused, never served. +// +// The writes are synchronous and never queued. What they copy — pgx encodes a +// parameter into its own buffer and that into the connection's write buffer +// — and what a stream or a rerank answer keeps is held against ONE +// process-wide account (recordingAccount), not against the request's +// in-flight reservation: the switch changes no booking of the request, so a +// recorded request meets the same refusals as any other plus the one of its +// own. A write waits for room in the account (backpressure); it never drops +// what it was given. + +// recordingMessage is its text. +const recordingMessage = "The request could not be recorded; retry shortly." + +// recordWriteTimeout bounds one recording statement (open, finish, insert): +// the database's share of the request frame. A named constant like llmlog's +// insertTimeout: it bounds the gateway's own bookkeeping, it is no policy of +// anybody's. +const recordWriteTimeout = 5 * time.Second + +// recordAccountFloor is the recording account's size at the default caps: +// with gateway.inflight_budget's default of 512 MiB inside the container's +// 1536 MiB (docs/operations.md "Recording a consumer"). Larger caps raise it +// (recordAccountLimit) so that the largest request always fits. +const recordAccountFloor = 128 << 20 + +// recordCopyFactor is what one recording statement allocates per byte it +// carries: pgx encodes the parameter into its argument buffer, the Bind +// message copies it into the connection's write buffer, which grows by +// append once more on the next field (TestRecordingInsertAllocates measures +// it). Garbage after the statement, held against the account until it +// returns. +const recordCopyFactor = 3 + +// recordAccountLimit is the account's size under s: the floor, or what one +// request's body or one answer at the caps costs a statement, whichever is +// larger. +func recordAccountLimit(s Settings) int64 { + return max(int64(recordAccountFloor), recordCopyFactor*int64(max(s.MaxRequestBytes, s.MaxResponseBytes))) +} + +// errRecordingUnavailable is the cause of a run whose recording failed (a +// stream's capture without room): verdict answers it. +var errRecordingUnavailable = errors.New("oai: the request could not be recorded") + +// recordingAccount is the process-wide account of recorded bytes held +// (statement copies, captured answers). acquire waits for room; release +// wakes every waiter. +type recordingAccount struct { + mu sync.Mutex held int64 - // lost names the texts the account refused. - lost []string - // stream is a stream's relayed data lines; streamLost once the account - // refused one of them (the lines after it are not kept either: a stream - // with a hole is not the answer the client received). - stream strings.Builder - streamHeld int64 // the part of held the stream's buffer takes: its capacity - streamLost bool -} - -// noLogLimit is the text limit of a recorded row: none (bodyLogWalkN). -const noLogLimit = math.MaxInt - -// reserve takes n bytes from the account for this request. -func (r *recording) reserve(n int64) bool { - if !llmlog.ReserveRecorded(n) { + wake chan struct{} +} + +var recAccount = &recordingAccount{wake: make(chan struct{})} + +// RecordingHeld is the bytes the recording account holds now. +func RecordingHeld() int64 { + recAccount.mu.Lock() + defer recAccount.mu.Unlock() + return recAccount.held +} + +// tryAcquire takes n bytes at once or not at all. +func (a *recordingAccount) tryAcquire(n, limit int64) bool { + if n <= 0 { + return true + } + a.mu.Lock() + defer a.mu.Unlock() + if a.held+n > limit { return false } - r.held += n + a.held += n return true } -// loseBody records that body (llmlog.RecordLostRequest/Response) was not -// kept. -func (r *recording) loseBody(body string) { - r.lost = append(r.lost, body) +// acquire takes n bytes, waiting for room until ctx ends; n beyond the +// whole account never fits. +func (a *recordingAccount) acquire(ctx context.Context, n, limit int64) error { + if n > limit { + return errors.New("oai: a recording larger than the recording account") + } + for { + a.mu.Lock() + if n <= 0 || a.held+n <= limit { + a.held += max(n, 0) + a.mu.Unlock() + return nil + } + wake := a.wake + a.mu.Unlock() + select { + case <-wake: + case <-ctx.Done(): + return ctx.Err() + } + } } -// text is the whole log text of raw (bodyLogWalkN without a limit), reserved -// first; "" and the body named lost when the account refuses it. -func (r *recording) text(raw []byte, body string) string { - n := bodyLogSizeN(raw, noLogLimit) - if !r.reserve(int64(n)) { - r.loseBody(body) - return "" +// release gives n bytes back and wakes the waiters. +func (a *recordingAccount) release(n int64) { + if n <= 0 { + return } - return bodyLogTextN(raw, n, noLogLimit) + a.mu.Lock() + a.held -= n + close(a.wake) + a.wake = make(chan struct{}) + a.mu.Unlock() } -// bytes is a copy of b, reserved first; "" and the body named lost when the -// account refuses it. -func (r *recording) bytes(b []byte, body string) string { - if !r.reserve(int64(len(b))) { - r.loseBody(body) - return "" - } - return string(b) +// RecordingStore is where the requests of recording consumers are held +// (llmlog.Recordings over the process pool, cmd/ctxd). Each call returns nil +// only once its statement is committed. +type RecordingStore interface { + Open(ctx context.Context, q llmlog.RecordedRequest) error + Finish(ctx context.Context, id string, o llmlog.RecordedOutcome) error + Insert(ctx context.Context, q llmlog.RecordedRequest, o llmlog.RecordedOutcome) error } -// recordWriter hands the bytes written to the client to the capture of a -// recording consumer's request — after the client write, so the answer the -// client gets is the one it gets without the switch (the rerank answer, -// which writeRerank writes piece by piece and never holds whole). -type recordWriter struct { - w io.Writer - r *recording +// RecordingStage is the stage right behind the model-key door that opens a +// recording for every request of a recording consumer (the package comment +// above). One per process, shared by /v1 and /v2 like the door. +type RecordingStage struct { + store RecordingStore + consumer func(context.Context) *auth.ConsumerAuth + settings func() Settings + maxWait func() time.Duration } -func (t recordWriter) Write(p []byte) (int, error) { - n, err := t.w.Write(p) - t.r.addStream(p[:n]) - return n, err +// NewRecordingStage builds the stage over store, the door's consumer +// (handler.ConsumerAuthFromContext), the gateway settings and the +// dispatcher's external wait budget (the longest a request waits for room +// in the recording account). A nil store refuses every request of a +// recording consumer (recording_unavailable) — fail-closed. +func NewRecordingStage(store RecordingStore, consumer func(context.Context) *auth.ConsumerAuth, + settings func() Settings, maxWait func() time.Duration) *RecordingStage { + return &RecordingStage{store: store, consumer: consumer, settings: settings, maxWait: maxWait} } -// addStream appends one piece of an answer written piece by piece — a -// stream's relayed data line, a part of a rerank answer. The buffer grows as -// strings.Builder.Grow grows it (to 2 × its capacity + the line, then the -// allocator's size class); the new capacity is reserved before the growth -// and the allocator's rounding right after it — the account holds the -// current buffer, the replaced one is garbage from then on. A refusal drops -// what the stream kept so far and every later line. -func (r *recording) addStream(line []byte) { - if !r.on || r.streamLost || len(line) == 0 { - return - } - if r.stream.Cap()-r.stream.Len() < len(line) { - grown := int64(2*r.stream.Cap() + len(line)) - if !r.reserve(grown - r.streamHeld) { - r.dropStream() +// Handler is the stage. +func (s *RecordingStage) Handler(next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + ca := s.consumer(r.Context()) + if ca == nil || !ca.RecordBodies { + next.ServeHTTP(w, r) return } - r.streamHeld = grown - r.stream.Grow(len(line)) - if c := int64(r.stream.Cap()); c > r.streamHeld { - if !r.reserve(c - r.streamHeld) { - r.dropStream() - return + rr := s.begin(ca, r) + defer func() { + p := recover() + rr.endStage(p) + if p != nil { + panic(p) } - r.streamHeld = c + }() + next.ServeHTTP(recordingWriter{ResponseWriter: w, rr: rr}, r.WithContext(withRecording(r.Context(), rr))) + }) +} + +// begin opens the request's recording and counts its admission. +func (s *RecordingStage) begin(ca *auth.ConsumerAuth, r *http.Request) *requestRecording { + id, err := uuid.NewV7() + if err != nil { + id = uuid.New() + } + rr := &requestRecording{stage: s, acct: recAccount, access: AccessRecordFrom(r.Context()), req: llmlog.RecordedRequest{ + ID: id.String(), ConsumerID: ca.ConsumerID, ModelKeyID: ca.ModelKeyID, Path: r.URL.Path, + ClientRequestID: clientRequestID(r), Declared: r.ContentLength, + }} + if r.ContentLength < 0 { + rr.req.Declared = -1 + } + rr.stats = recStats.admit(ca.ConsumerID, ca.TenantID) + return rr +} + +// requestRecording is one request's recording. Its fields are the request +// goroutine's (the route and the stage run on it); status alone is written +// by the response writer, which a stream's grace timer can call too. +type requestRecording struct { + stage *RecordingStage + acct *recordingAccount + access *AccessRecord // the access log's record: the refusal's code + req llmlog.RecordedRequest + stats *recordingConsumerStats + + statusMu sync.Mutex + status int + + // row: a row of the request is committed (open, or inserted at the + // end); opened: it was opened before the walk; ended: its outcome is + // committed (or known to be there). + row, opened, ended bool + // unfinished: the outcome of an opened row could not be committed. + unfinished bool + + // capture is a stream's relayed lines or a rerank answer; held is what + // it takes of the account; streamed: a stream relayed at least one line. + capture []byte + held int64 + streamed bool +} + +type recordingKey struct{} + +func withRecording(ctx context.Context, rr *requestRecording) context.Context { + return context.WithValue(ctx, recordingKey{}, rr) +} + +// recordingFrom is the request's recording; nil for a consumer that does not +// record. +func recordingFrom(ctx context.Context) *requestRecording { + rr, _ := ctx.Value(recordingKey{}).(*requestRecording) + return rr +} + +// routeRecording is the recording a route works with: the stage's, or — for +// a recording consumer whose request reached the route without the stage (a +// wiring defect) — false: the route refuses it, it does not serve it +// unrecorded. +func routeRecording(r *http.Request, ca *auth.ConsumerAuth, op string) (*requestRecording, bool) { + rr := recordingFrom(r.Context()) + if rr == nil { + if ca != nil && ca.RecordBodies { + slog.Error("gateway: a recording consumer's request reached the route without the recording stage (wiring defect) — refused", + "path", r.URL.Path) + return nil, false + } + return nil, true + } + rr.req.Op = op + return rr, true +} + +// setBody hands the recording what the route read of the body (whole when +// complete). Nil-safe: a request that does not record does nothing. +func (rr *requestRecording) setBody(body []byte, complete bool) { + if rr == nil { + return + } + rr.req.Body, rr.req.Complete = body, complete +} + +// parsed notes the model name and the stream flag the route's parse read. +func (rr *requestRecording) parsed(model string, stream bool) { + if rr == nil { + return + } + rr.req.Model, rr.req.Stream = model, &stream +} + +// ready reports whether the request may reach a backend: it does not record, +// or its row is open. +func (rr *requestRecording) ready() bool { return rr == nil || rr.opened } + +// open commits the request's row before the walk; false when it cannot — +// the caller refuses the request (refuseRecording) and serves nothing. The +// wait for room in the account is the dispatcher's external wait budget, +// the statement recordWriteTimeout. +func (rr *requestRecording) open(ctx context.Context) bool { + if rr == nil || rr.opened { + return true + } + if rr.stage.store == nil { + slog.Error("gateway: a recording consumer's request without a recording store (wiring defect) — refused") + return false + } + n := recordCopyFactor * int64(len(rr.req.Body)) + wctx, cancel := context.WithTimeout(ctx, rr.stage.maxWait()) + err := rr.acct.acquire(wctx, n, recordAccountLimit(rr.stage.settings())) + cancel() + if err != nil { + slog.Warn("gateway: no room to record a request — refused", "consumer_id", rr.req.ConsumerID, "bytes", len(rr.req.Body), "error", err) + return false + } + defer rr.acct.release(n) + sctx, cancel := context.WithTimeout(ctx, recordWriteTimeout) + defer cancel() + if err := rr.stage.store.Open(sctx, rr.req); err != nil { + slog.Warn("gateway: a request could not be recorded — refused", "consumer_id", rr.req.ConsumerID, "error", err) + return false + } + rr.row, rr.opened = true, true + return true +} + +// answer commits the outcome of a non-streamed answer — status 200 and body +// as the client will get it (nil: an answer not kept, the embedding +// vectors) — before it is written; false when it cannot: the caller answers +// refuseRecording instead. +func (rr *requestRecording) answer(ctx context.Context, body []byte) bool { + if rr == nil { + return true + } + if !rr.opened || rr.ended { + return false // the walk ran on an open row (ready); anything else is a defect + } + if err := rr.finish(ctx, llmlog.RecordedOutcome{Status: http.StatusOK, Response: body}); err != nil { + slog.Warn("gateway: an answer could not be recorded — refused", "consumer_id", rr.req.ConsumerID, "error", err) + return false + } + return true +} + +// finish commits o on the open row, the statement's copies of o.Response +// against the account — booked here for an answer of the request's own +// (a chat answer), with the capture for a captured one (addCapture). +func (rr *requestRecording) finish(ctx context.Context, o llmlog.RecordedOutcome) error { + n := recordCopyFactor * int64(len(o.Response)) + if len(o.Response) > 0 && len(rr.capture) > 0 && &o.Response[0] == &rr.capture[0] { + n = 0 // booked with the capture + } + wctx, cancel := context.WithTimeout(ctx, recordWriteTimeout) + defer cancel() + if err := rr.acct.acquire(wctx, n, recordAccountLimit(rr.stage.settings())); err != nil { + return err + } + defer rr.acct.release(n) + if err := rr.stage.store.Finish(wctx, rr.req.ID, o); err != nil { + return err + } + rr.ended = true + return nil +} + +// capture appends one piece of the answer — a stream's line before the +// relay takes it, a part of a rerank answer — against the account (no +// wait: the answer is being produced); false when there is no room: the +// caller ends the request (errRecordingUnavailable) instead of sending a +// piece it did not keep. Nil-safe. +func (rr *requestRecording) addCapture(p []byte) bool { + if rr == nil || len(p) == 0 { + return true + } + if need := len(rr.capture) + len(p); need > cap(rr.capture) { + grown := max(2*cap(rr.capture), need) + // The buffer and, booked with it, the copies of the statement that + // will carry it (finish takes nothing more for a captured answer: + // nobody holds account bytes while waiting for more). + booked := int64(grown) * (1 + recordCopyFactor) + if !rr.acct.tryAcquire(booked, recordAccountLimit(rr.stage.settings())) { + return false } + next := make([]byte, len(rr.capture), grown) + copy(next, rr.capture) + rr.acct.release(rr.held) // the old buffer: garbage from here on + rr.capture, rr.held = next, booked + } + rr.capture = append(rr.capture, p...) + return true +} + +// captureWriter writes into the request's capture (a rerank answer, kept +// whole before it goes out); a write it has no room for fails. +type captureWriter struct{ rr *requestRecording } + +func (w captureWriter) Write(p []byte) (int, error) { + if !w.rr.addCapture(p) { + return 0, errRecordingUnavailable } - r.stream.Write(line) + return len(p), nil } -// dropStream gives the stream's buffer back and names the answer lost. -func (r *recording) dropStream() { - r.held -= r.streamHeld - llmlog.ReleaseRecorded(r.streamHeld) - r.streamHeld = 0 - r.stream = strings.Builder{} - r.streamLost = true - r.loseBody(llmlog.RecordLostResponse) +// dropCaptureTail takes back the last n captured bytes (a line the relay +// refused after the capture took it). +func (rr *requestRecording) dropCaptureTail(n int) { + if rr == nil || n <= 0 || n > len(rr.capture) { + return + } + rr.capture = rr.capture[:len(rr.capture)-n] } -// streamText is the stream's kept answer ("" after a refusal). -func (r *recording) streamText() string { - if r.streamLost { +// id is the request's recording id ("" without a recording). +func (rr *requestRecording) id() string { + if rr == nil { return "" } - return r.stream.String() + return rr.req.ID } -// mark puts the recording on the row: Recorded, the lost bodies and what the -// texts hold of the account, which from now on is the writer's to give back. -// Not recording: the row stays as it is. -func (r *recording) mark(row *llmlog.GatewayRow) { - if !r.on { +// mark puts the recording on the request's llmlog row: metadata.gw.recorded +// and recording_id; the row's bodies stay the body policy's. Nil-safe. +func (rr *requestRecording) mark(row *llmlog.GatewayRow) { + if rr == nil { return } - row.Recorded = true - if len(r.lost) > 0 { - row.RecordLost, row.RecordLostCause = r.lost, llmlog.RecordLostMemory + row.Recorded, row.RecordingID = true, rr.req.ID +} + +// noteStreamed marks that a stream relayed a line. +func (rr *requestRecording) noteStreamed() { + if rr != nil { + rr.streamed = true } - row.RecordedHeld, r.held = r.held, 0 } -// release gives back what no row took (a request that wrote no row of its -// own: no wire attempt, the shutdown's forced settle). Runs at the request's -// end (close). -func (r *recording) release() { - llmlog.ReleaseRecorded(r.held) - r.held = 0 +// writeStatus is what recordingWriter saw first (0: nothing written). +func (rr *requestRecording) writeStatus() int { + rr.statusMu.Lock() + defer rr.statusMu.Unlock() + return rr.status } -// markForced puts the recording on the row the shutdown's forced settle -// writes: recorded, without a body (it is built at the admission, before -// there is an answer) — the request's text is named lost, and for chat and -// rerank the answer too (embeddings keep none). -func markForced(row *llmlog.GatewayRow, on bool) { - if !on { +func (rr *requestRecording) noteStatus(code int) { + rr.statusMu.Lock() + if rr.status == 0 { + rr.status = code + } + rr.statusMu.Unlock() +} + +// end commits the request's outcome once it has ended (endStage): the open +// row ends with the status the client got, code and a stream's or a rerank +// answer's captured bytes; a request refused before its walk gets its row +// with what was read of the body — the body itself held against the account +// with its copies, since the request's in-flight reservation has ended. A +// failure is counted, never retried later. +func (rr *requestRecording) end(code string) { + if rr.ended { + rr.dropCapture() return } - row.Recorded = true - row.RecordLost = []string{llmlog.RecordLostRequest} - if row.Pipeline != embedPipeline { - row.RecordLost = append(row.RecordLost, llmlog.RecordLostResponse) + defer rr.dropCapture() + ctx := context.Background() + o := llmlog.RecordedOutcome{Status: rr.writeStatus(), Code: code} + if len(rr.capture) > 0 { + o.Response = rr.capture + } + if rr.opened { + rr.req.Body = nil // in the row since the open + if err := rr.finish(ctx, o); err != nil { + rr.unfinished = true + slog.Error("gateway: the outcome of a recorded request could not be recorded — its row stays open", + "consumer_id", rr.req.ConsumerID, "recording_id", rr.req.ID, "stream_answer_lost", rr.streamed, "error", err) + } + return + } + if rr.stage.store == nil { + slog.Error("gateway: a recording consumer's request without a recording store (wiring defect) — not recorded", + "consumer_id", rr.req.ConsumerID) + return + } + n := (1+recordCopyFactor)*int64(len(rr.req.Body)) + recordCopyFactor*int64(len(o.Response)) + wctx, cancel := context.WithTimeout(ctx, recordWriteTimeout) + defer cancel() + if err := rr.acct.acquire(wctx, n, recordAccountLimit(rr.stage.settings())); err != nil { + slog.Error("gateway: a refused request of a recording consumer could not be recorded", "consumer_id", rr.req.ConsumerID, "error", err) + return + } + defer rr.acct.release(n) + if err := rr.stage.store.Insert(wctx, rr.req, o); err != nil { + slog.Error("gateway: a refused request of a recording consumer could not be recorded", "consumer_id", rr.req.ConsumerID, "error", err) + return + } + rr.row, rr.ended = true, true +} + +// dropCapture gives the captured answer back to the account. +func (rr *requestRecording) dropCapture() { + rr.acct.release(rr.held) + rr.capture, rr.held = nil, 0 +} + +// endStage is the stage's end of the request, after the route returned or +// panicked: the outcome with the access record's code — a recovered panic as +// the 503 internal_error oai.Recover answers, unless the response had begun +// —, then the request's count. +func (rr *requestRecording) endStage(p any) { + code := "" + if rr.access != nil { + code = rr.access.Reason + } + if p != nil && rr.writeStatus() == 0 { + rr.noteStatus(http.StatusServiceUnavailable) + code = CodeInternalError + } + rr.end(code) + recStats.done(rr.stats, rr.row, rr.unfinished, rr.unfinished && rr.streamed) +} + +// refuseRecording answers a request whose recording failed: 503 +// recording_unavailable, Retry-After: 1, x-should-retry: true — a fault of +// the gateway's database, not of the request, and no rule's refusal (no +// ledger note). +func refuseRecording(rec *AccessRecord, w http.ResponseWriter) { + if rec != nil { + rec.Reason = CodeRecordingUnavailable + } + w.Header().Set("Retry-After", overloadedRetryAfter) + WriteCode(w, CodeRecordingUnavailable, recordingMessage, true) +} + +// recordingWriter notes the status the client gets on the request's +// recording. Unwrap lets http.ResponseController reach the connection +// (flush, write deadlines). +type recordingWriter struct { + http.ResponseWriter + rr *requestRecording +} + +func (w recordingWriter) WriteHeader(code int) { + if code >= http.StatusOK { + w.rr.noteStatus(code) + } + w.ResponseWriter.WriteHeader(code) +} + +func (w recordingWriter) Write(p []byte) (int, error) { + w.rr.noteStatus(http.StatusOK) + return w.ResponseWriter.Write(p) +} + +func (w recordingWriter) FlushError() error { + w.rr.noteStatus(http.StatusOK) + return http.NewResponseController(w.ResponseWriter).Flush() +} + +func (w recordingWriter) Flush() { _ = w.FlushError() } + +func (w recordingWriter) Unwrap() http.ResponseWriter { return w.ResponseWriter } + +// recordingConsumerStats are one recording consumer's counts in this +// process (GET /api/status, docs/operations.md "Recording a consumer"): +// admitted = in_flight + recorded + unrecordable at every moment. +type recordingConsumerStats struct { + tenant string + admitted, inFlight, recorded, unrecordable int64 + unfinished, streamAnswersUnrecorded int64 +} + +// recordingStats are the counts of every recording consumer since the +// process started. +type recordingStats struct { + mu sync.Mutex + by map[string]*recordingConsumerStats + from time.Time +} + +var recStats = &recordingStats{by: map[string]*recordingConsumerStats{}, from: time.Now().UTC()} + +func (s *recordingStats) admit(consumer, tenant string) *recordingConsumerStats { + s.mu.Lock() + defer s.mu.Unlock() + c := s.by[consumer] + if c == nil { + c = &recordingConsumerStats{} + s.by[consumer] = c + } + c.tenant = tenant + c.admitted++ + c.inFlight++ + return c +} + +func (s *recordingStats) done(c *recordingConsumerStats, row, unfinished, streamLost bool) { + s.mu.Lock() + defer s.mu.Unlock() + c.inFlight-- + if row { + c.recorded++ + } else { + c.unrecordable++ + } + if unfinished { + c.unfinished++ + } + if streamLost { + c.streamAnswersUnrecorded++ + } +} + +// RecordingConsumer is one recording consumer's counts in GET /api/status +// (gateway.recording.consumers). +type RecordingConsumer struct { + ConsumerID string `json:"consumer_id"` + TenantID string `json:"-"` + // Admitted requests passed the door as this consumer; each is in + // flight, recorded (its row is in context_llm_recordings) or + // unrecordable (no row could be written; the request was refused, not + // served). + Admitted int64 `json:"admitted"` + InFlight int64 `json:"in_flight"` + Recorded int64 `json:"recorded"` + Unrecordable int64 `json:"unrecordable"` + // Unfinished rows were opened and their outcome could not be recorded + // (they stay open); StreamAnswersUnrecorded are the streams among them + // that had sent lines. + Unfinished int64 `json:"unfinished"` + StreamAnswersUnrecorded int64 `json:"stream_answers_unrecorded"` +} + +// RecordingSnapshot is gateway.recording of GET /api/status. +type RecordingSnapshot struct { + // ProcessID is context_llm_recordings.process_id of this process's + // rows, Since when its counts began. + ProcessID string `json:"process_id"` + Since time.Time `json:"since"` + // HeldBytes is what the recording account holds now. + HeldBytes int64 `json:"held_bytes"` + Consumers []RecordingConsumer `json:"consumers"` +} + +// RecordingStats is the snapshot of this process's recording counts, sorted +// by consumer. +func RecordingStats() RecordingSnapshot { + snap := RecordingSnapshot{ProcessID: llmlog.ProcessID, HeldBytes: RecordingHeld(), Consumers: []RecordingConsumer{}} + recStats.mu.Lock() + snap.Since = recStats.from + for id, c := range recStats.by { + snap.Consumers = append(snap.Consumers, RecordingConsumer{ConsumerID: id, TenantID: c.tenant, + Admitted: c.admitted, InFlight: c.inFlight, Recorded: c.recorded, Unrecordable: c.unrecordable, + Unfinished: c.unfinished, StreamAnswersUnrecorded: c.streamAnswersUnrecorded}) } - row.RecordLostCause = llmlog.RecordLostShutdown + recStats.mu.Unlock() + sort.Slice(snap.Consumers, func(i, j int) bool { return snap.Consumers[i].ConsumerID < snap.Consumers[j].ConsumerID }) + return snap } diff --git a/go/internal/oai/record_account_full_test.go b/go/internal/oai/record_account_full_test.go deleted file mode 100644 index 72dd59ed9..000000000 --- a/go/internal/oai/record_account_full_test.go +++ /dev/null @@ -1,53 +0,0 @@ -package oai_test - -import ( - "strings" - "testing" - - "github.com/GottZ/ctx/internal/backends" - "github.com/GottZ/ctx/internal/llmlog" -) - -// TestRecordedChatWithAFullAccount (issue #571, promise 3 under memory -// pressure): when the recording account cannot take a recorded request's -// texts, the request is answered exactly as without the switch and its row -// is written without them, naming both (record_lost, cause memory) — the -// account is never the request's budget. -func TestRecordedChatWithAFullAccount(t *testing.T) { - answer := `{"id":"gen-1","object":"chat.completion","created":1700000000,"model":"M",` + - `"choices":[{"index":0,"finish_reason":"stop","message":{"role":"assistant","content":"hello"}}],` + - `"usage":{"prompt_tokens":11,"completion_tokens":3,"total_tokens":14}}` - body := `{"model":"pub","messages":[{"role":"user","content":"` + strings.Repeat("w", 4096) + `"}]}` - u := newUpstream(t, answer) - rig := newChatRig(t, []backends.Backend{u.row("spark", backends.TrustFull, 10)}, 4, 1) - rig.ca.Store(recordingConsumer(false)) - off := rig.post(t, body) - // Fill the account to its last byte. - filled := int64(0) - for step := int64(1 << 26); step > 0; step /= 2 { - for llmlog.ReserveRecorded(step) { - filled += step - } - } - defer llmlog.ReleaseRecorded(filled) - rig.ca.Store(recordingConsumer(true)) - on := rig.post(t, body) - rows := rig.rows.all() - defer releaseRows(rows) - if off.status != 200 || on.status != 200 || !sameAnswer(off.body, on.body) { - t.Fatalf("status off %d on %d, answers equal %v — a full account must not change the answer", off.status, on.status, sameAnswer(off.body, on.body)) - } - if len(u.raws) != 2 || string(u.raws[0]) != string(u.raws[1]) { - t.Errorf("the upstream bodies differ with a full account") - } - if len(rows) != 2 { - t.Fatalf("%d rows, want 2", len(rows)) - } - r := rows[1] - stored := llmlog.RecordedGatewayEntry(r) - if !r.Recorded || stored.RequestUser != "" || stored.ResponseContent != "" || r.RecordedHeld != 0 || - strings.Join(r.RecordLost, ",") != "request,response" || r.RecordLostCause != llmlog.RecordLostMemory { - t.Errorf("row with a full account: recorded %v, %d/%d body bytes, holds %d, lost %v cause %q — want recorded, no bodies, nothing held, both lost, memory", - r.Recorded, len(stored.RequestUser), len(stored.ResponseContent), r.RecordedHeld, r.RecordLost, r.RecordLostCause) - } -} diff --git a/go/internal/oai/record_internal_test.go b/go/internal/oai/record_internal_test.go deleted file mode 100644 index ebab4b484..000000000 --- a/go/internal/oai/record_internal_test.go +++ /dev/null @@ -1,106 +0,0 @@ -package oai - -import ( - "strings" - "testing" - - "github.com/GottZ/ctx/internal/llmlog" -) - -// The capture of a recorded request (record.go): the recording account holds -// exactly the stream buffer's capacity while the stream grows, hands it to -// the row, and gives everything back on a refusal or when no row takes it; -// the shutdown's forced row of a recording consumer names what it lacks. - -func TestRecordingStreamHoldsItsCapacity(t *testing.T) { - base := llmlog.RecordedHeld() - r := recording{on: true} - line := []byte("data: " + strings.Repeat("x", 300) + "\n\n") - for range 1000 { - r.addStream(line) - if got := llmlog.RecordedHeld() - base; got != int64(r.stream.Cap()) || r.held != got || r.streamHeld != got { - t.Fatalf("held %d (request %d, stream %d), buffer capacity %d — the account must hold exactly the buffer", got, r.held, r.streamHeld, r.stream.Cap()) - } - } - if got := r.streamText(); got != strings.Repeat(string(line), 1000) || r.lost != nil { - t.Fatalf("stream text %d bytes, lost %v — want the 1000 lines whole", len(got), r.lost) - } - var row llmlog.GatewayRow - r.mark(&row) - if !row.Recorded || row.RecordedHeld != int64(r.stream.Cap()) || r.held != 0 || row.RecordLost != nil { - t.Fatalf("row recorded %v holds %d (request keeps %d), lost %v — want the buffer handed to the row", row.Recorded, row.RecordedHeld, r.held, row.RecordLost) - } - llmlog.ReleaseRecorded(row.RecordedHeld) - if llmlog.RecordedHeld() != base { - t.Fatalf("the account holds %d bytes after the row gave its texts back", llmlog.RecordedHeld()-base) - } -} - -func TestRecordingRefusalDropsTheStreamAndGivesBack(t *testing.T) { - base := llmlog.RecordedHeld() - r := recording{on: true} - r.addStream([]byte("data: first\n\n")) - // Fill the account to its last byte, so the next growth is refused. - rest := int64(0) - for step := int64(1 << 26); step > 0; step /= 2 { - for llmlog.ReserveRecorded(step) { - rest += step - } - } - defer llmlog.ReleaseRecorded(rest) - r.addStream([]byte(strings.Repeat("y", 4096))) - if r.streamText() != "" || !r.streamLost || len(r.lost) != 1 || r.lost[0] != llmlog.RecordLostResponse { - t.Fatalf("after a refused growth: text %q lost %v %v — want the stream dropped and the answer named lost", r.streamText(), r.streamLost, r.lost) - } - r.addStream([]byte("data: later\n\n")) - if r.streamText() != "" || r.held != 0 || llmlog.RecordedHeld()-base != rest { - t.Fatalf("after the refusal the request holds %d, the account %d beyond the filler — want 0 and 0", r.held, llmlog.RecordedHeld()-base-rest) - } - if got := r.text([]byte(`[{"role":"user","content":"z"}]`), llmlog.RecordLostRequest); got != "" || len(r.lost) != 2 { - t.Fatalf("a request text the full account cannot take: %q, lost %v", got, r.lost) - } - var row llmlog.GatewayRow - r.mark(&row) - if row.RecordLostCause != llmlog.RecordLostMemory || len(row.RecordLost) != 2 { - t.Fatalf("row lost %v cause %q, want both bodies, memory", row.RecordLost, row.RecordLostCause) - } -} - -func TestRecordingReleaseWithoutARow(t *testing.T) { - base := llmlog.RecordedHeld() - r := recording{on: true} - r.addStream([]byte("data: a\n\n")) - r.release() - if r.held != 0 || llmlog.RecordedHeld() != base { - t.Fatalf("release left %d held (account +%d)", r.held, llmlog.RecordedHeld()-base) - } - off := recording{} - off.addStream([]byte("data: b\n\n")) - var row llmlog.GatewayRow - off.mark(&row) - if off.stream.Len() != 0 || row.Recorded || llmlog.RecordedHeld() != base { - t.Fatalf("a consumer without the switch captured %d bytes, row recorded %v", off.stream.Len(), row.Recorded) - } -} - -func TestForcedRowOfARecordingConsumerNamesWhatItLacks(t *testing.T) { - for _, c := range []struct { - pipeline string - want []string - }{ - {chatPipeline, []string{llmlog.RecordLostRequest, llmlog.RecordLostResponse}}, - {embedPipeline, []string{llmlog.RecordLostRequest}}, - {rerankPipeline, []string{llmlog.RecordLostRequest, llmlog.RecordLostResponse}}, - } { - row := llmlog.GatewayRow{Pipeline: c.pipeline} - markForced(&row, true) - if !row.Recorded || strings.Join(row.RecordLost, ",") != strings.Join(c.want, ",") || row.RecordLostCause != llmlog.RecordLostShutdown { - t.Errorf("%s: forced row recorded %v lost %v cause %q, want %v shutdown", c.pipeline, row.Recorded, row.RecordLost, row.RecordLostCause, c.want) - } - plain := llmlog.GatewayRow{Pipeline: c.pipeline} - markForced(&plain, false) - if plain.Recorded || plain.RecordLost != nil { - t.Errorf("%s: the forced row of a consumer without the switch is marked", c.pipeline) - } - } -} diff --git a/go/internal/oai/record_route_test.go b/go/internal/oai/record_route_test.go new file mode 100644 index 000000000..b172bbc7c --- /dev/null +++ b/go/internal/oai/record_route_test.go @@ -0,0 +1,579 @@ +package oai_test + +import ( + "context" + "encoding/json" + "errors" + "net/http" + "net/http/httptest" + "regexp" + "strings" + "sync" + "sync/atomic" + "testing" + "time" + + "github.com/go-chi/chi/v5" + + "github.com/GottZ/ctx/internal/auth" + "github.com/GottZ/ctx/internal/backends" + "github.com/GottZ/ctx/internal/llmlog" + "github.com/GottZ/ctx/internal/oai" +) + +// The recording of a recording consumer on the routes (issue #571, record.go): +// the request is held — the store's Open returned — before the first +// backend attempt, or it is not served; a non-streamed answer is held before +// it is written, or the client gets 503 recording_unavailable instead; a +// stream's relayed lines are held when it ends; every request the gateway +// refuses after the door leaves its row with what was read; and a consumer +// without the switch never reaches the store. + +// recSecret is a credentials pattern in a prompt: the sensitivity scan raises +// a request carrying it to credentials, where the body policy stores nothing. +const recSecret = "password=hunter2-recorded-571" + +// recordingConsumer is the rig's consumer with the switch set to on or off. +func recordingConsumer(on bool) *auth.ConsumerAuth { + ca := urgentApp() + ca.RecordBodies = on + return ca +} + +// answerIdentity drops what differs between two requests by construction: +// the answer's id and created stamp. +var answerIdentity = regexp.MustCompile(`"(id|created)":("[^"]*"|\d+)`) + +func sameAnswer(a, b []byte) bool { + return answerIdentity.ReplaceAllString(string(a), "") == answerIdentity.ReplaceAllString(string(b), "") +} + +// recRow is one row of the fake store. +type recRow struct { + req llmlog.RecordedRequest + body []byte // a copy of req.Body at the write + state string + out llmlog.RecordedOutcome + response []byte // a copy of out.Response + hitsAtOpen int64 + opened bool +} + +// recStore is a RecordingStore in memory: it notes every call, the upstream +// hits at the open, and can refuse or hang any of the three statements. +type recStore struct { + mu sync.Mutex + rows map[string]*recRow + order []string + calls atomic.Int64 + hits func() int64 + + openErr, finishErr, insertErr error + openHang bool +} + +func newRecStore(hits func() int64) *recStore { + return &recStore{rows: map[string]*recRow{}, hits: hits} +} + +func (s *recStore) Open(ctx context.Context, q llmlog.RecordedRequest) error { + s.calls.Add(1) + s.mu.Lock() + hang, err := s.openHang, s.openErr + s.mu.Unlock() + if hang { + <-ctx.Done() + return ctx.Err() + } + if err != nil { + return err + } + s.mu.Lock() + defer s.mu.Unlock() + var hits int64 + if s.hits != nil { + hits = s.hits() + } + s.rows[q.ID] = &recRow{req: q, body: append([]byte(nil), q.Body...), state: llmlog.RecordingOpen, hitsAtOpen: hits, opened: true} + s.order = append(s.order, "open") + return nil +} + +func (s *recStore) Finish(_ context.Context, id string, o llmlog.RecordedOutcome) error { + s.calls.Add(1) + s.mu.Lock() + defer s.mu.Unlock() + if s.finishErr != nil { + return s.finishErr + } + r := s.rows[id] + if r == nil || r.state != llmlog.RecordingOpen { + return errors.New("no open row") + } + r.state, r.out, r.response = llmlog.RecordingDone, o, append([]byte(nil), o.Response...) + s.order = append(s.order, "finish") + return nil +} + +func (s *recStore) Insert(_ context.Context, q llmlog.RecordedRequest, o llmlog.RecordedOutcome) error { + s.calls.Add(1) + s.mu.Lock() + defer s.mu.Unlock() + if s.insertErr != nil { + return s.insertErr + } + s.rows[q.ID] = &recRow{req: q, body: append([]byte(nil), q.Body...), state: llmlog.RecordingDone, out: o, response: append([]byte(nil), o.Response...)} + s.order = append(s.order, "insert") + return nil +} + +func (s *recStore) set(f func(s *recStore)) { + s.mu.Lock() + f(s) + s.mu.Unlock() +} + +// only is the one row of the store. +func (s *recStore) only(t *testing.T) *recRow { + t.Helper() + s.mu.Lock() + defer s.mu.Unlock() + if len(s.rows) != 1 { + t.Fatalf("%d recording rows, want 1 (calls %v)", len(s.rows), s.order) + } + for _, r := range s.rows { + return r + } + return nil +} + +// withRecordings mounts the recording stage over store (its wait for room is +// the rig's MaxWait). +func withRecordings(store oai.RecordingStore) rigOption { + return func(r *chatRig) { + r.recStage = oai.NewRecordingStage(store, r.deps.Consumer, func() oai.Settings { return *r.settings.Load() }, + func() time.Duration { return r.deps.MaxWait() }) + } +} + +// statsOf is the consumer's counts in this process. +func statsOf(id string) oai.RecordingConsumer { + for _, c := range oai.RecordingStats().Consumers { + if c.ConsumerID == id { + return c + } + } + return oai.RecordingConsumer{ConsumerID: id} +} + +func checkRecordingRefusal(t *testing.T, status int, header http.Header, body []byte) { + t.Helper() + var env struct { + Error struct { + Code string `json:"code"` + } `json:"error"` + } + _ = json.Unmarshal(body, &env) + if status != http.StatusServiceUnavailable || env.Error.Code != oai.CodeRecordingUnavailable || + header.Get("Retry-After") != "1" || header.Get("X-Should-Retry") != "true" { + t.Errorf("answer %d %q (Retry-After %q, x-should-retry %q), want 503 recording_unavailable, Retry-After 1, x-should-retry true: %.200s", + status, env.Error.Code, header.Get("Retry-After"), header.Get("X-Should-Retry"), body) + } +} + +const recChatAnswer = `{"id":"gen-1","object":"chat.completion","created":1700000000,"model":"M",` + + `"choices":[{"index":0,"finish_reason":"stop","message":{"role":"assistant","content":"the answer"}}],` + + `"usage":{"prompt_tokens":11,"completion_tokens":3,"total_tokens":14}}` + +// TestRecordingHoldsTheRequestBeforeAnyBackend: for every route, the +// recording consumer's request is in the store — the exact bytes sent, a +// credentials pattern past 64 KiB included — before the backend saw it; the +// row ends done with the answer the client got (embeddings: none); the +// answer, the upstream body and the llmlog row's bodies are those of the +// same request without the switch; the llmlog row names the recording. +func TestRecordingHoldsTheRequestBeforeAnyBackend(t *testing.T) { + long := strings.Repeat("abcdefgh", 12<<10) // 96 KiB, past the 64 KiB cap + t.Run("chat", func(t *testing.T) { + u := newUpstream(t, recChatAnswer) + store := newRecStore(func() int64 { return u.hits.Load() }) + rig := newChatRig(t, []backends.Backend{u.row("spark", backends.TrustFull, 10)}, 4, 1, withRecordings(store)) + rig.setSettings(func(s *oai.Settings) { s.BodyLogging = llmlog.BodyLoggingFull }) + body := `{"model":"pub","messages":[{"role":"user","content":"` + recSecret + " " + long + `"}]}` + rig.ca.Store(recordingConsumer(false)) + off := rig.post(t, body) + if store.calls.Load() != 0 { + t.Fatalf("a consumer without the switch reached the store (%d calls)", store.calls.Load()) + } + rig.ca.Store(recordingConsumer(true)) + on := rig.post(t, body) + if off.status != 200 || on.status != 200 || !sameAnswer(off.body, on.body) { + t.Fatalf("status off %d on %d, answers equal %v", off.status, on.status, sameAnswer(off.body, on.body)) + } + if len(u.raws) != 2 || string(u.raws[0]) != string(u.raws[1]) { + t.Errorf("the upstream bodies differ with the switch (%d calls)", len(u.raws)) + } + r := store.only(t) + if !r.opened || r.hitsAtOpen != 1 { // the first hit was the unrecorded request + t.Errorf("open %v with %d upstream hits, want the open before the recorded request's backend call (1: the earlier unrecorded one)", r.opened, r.hitsAtOpen) + } + if string(r.body) != body || !r.req.Complete || r.req.Op != llmlog.GatewayOpChat || r.req.Model != "pub" || r.req.Stream == nil || *r.req.Stream { + t.Errorf("held request: %d bytes (want %d, exact), complete %v, op %q, model %q, stream %v", len(r.body), len(body), r.req.Complete, r.req.Op, r.req.Model, r.req.Stream) + } + if r.state != llmlog.RecordingDone || r.out.Status != 200 || string(r.response) != string(on.body) { + t.Errorf("row: state %q status %d answer %d bytes, want done 200 with the client's %d bytes", r.state, r.out.Status, len(r.response), len(on.body)) + } + if !strings.Contains(string(on.body), `"id":"chatcmpl-`+r.req.ID+`"`) { + t.Errorf("the answer's id does not name the recording %s: %.120s", r.req.ID, on.body) + } + rows := rig.rows.all() + if len(rows) != 2 || rows[0].Recorded || !rows[1].Recorded || rows[1].RecordingID != r.req.ID { + t.Fatalf("llmlog rows %d: recorded %v/%v, recording id %q (want %q)", len(rows), rows[0].Recorded, rows[1].Recorded, rows[1].RecordingID, r.req.ID) + } + eo, en := llmlog.GatewayEntry(rows[0]), llmlog.GatewayEntry(rows[1]) + if eo.RequestUser != en.RequestUser || eo.ResponseContent != en.ResponseContent || en.RequiredSensitivity != eo.RequiredSensitivity { + t.Errorf("the llmlog row's bodies or class differ with the switch: %d/%d vs %d/%d bytes, %q vs %q", + len(eo.RequestUser), len(eo.ResponseContent), len(en.RequestUser), len(en.ResponseContent), eo.RequiredSensitivity, en.RequiredSensitivity) + } + }) + t.Run("stream", func(t *testing.T) { + sh := streamShapes[0] + u := newUpstream(t, "") + u.setRespond(sseRespond(sh.steps(), nil, nil)) + store := newRecStore(func() int64 { return u.hits.Load() }) + rig := newChatRig(t, []backends.Backend{u.row("spark", backends.TrustFull, 10)}, 4, 1, withStreamSettings, withRecordings(store)) + srv := serveHTTP(t, rig.router) + rig.ca.Store(recordingConsumer(false)) + off := postStream(context.Background(), t, srv, streamBody("chat")) + rig.ca.Store(recordingConsumer(true)) + on := postStream(context.Background(), t, srv, streamBody("chat")) + checkRelay(t, on) + if !sameAnswer([]byte(off.raw), []byte(on.raw)) { + t.Errorf("the stream differs with the switch:\n off %q\n on %q", off.raw, on.raw) + } + r := store.only(t) + if r.hitsAtOpen != 1 || r.req.Stream == nil || !*r.req.Stream || string(r.body) != streamBody("chat") { + t.Errorf("open with %d upstream hits (want 1), stream %v, request %q", r.hitsAtOpen, r.req.Stream, r.body) + } + if r.state != llmlog.RecordingDone || r.out.Status != 200 || string(r.response)+"data: [DONE]\n\n" != on.raw { + t.Errorf("row: state %q status %d answer %q, want done 200 with the client's lines before [DONE]: %q", r.state, r.out.Status, r.response, on.raw) + } + }) + t.Run("embeddings", func(t *testing.T) { + e := newEmbedEngine(t, 8) + store := newRecStore(func() int64 { return e.hits.Load() }) + rig := newEmbedRig(t, []backends.Backend{e.row("spark-embed", backends.ProtocolOpenAI, 10)}, 4, 1, withRecordings(store)) + body := embedBody("emb1", []string{recSecret + " " + long, "second"}) + rig.ca.Store(recordingConsumer(false)) + off := rig.postEmbed(t, body) + offHits := e.hits.Load() + rig.ca.Store(recordingConsumer(true)) + on := rig.postEmbed(t, body) + if off.status != 200 || on.status != 200 || !sameAnswer(off.body, on.body) { + t.Fatalf("status off %d on %d, answers equal %v: %.200s", off.status, on.status, sameAnswer(off.body, on.body), on.body) + } + r := store.only(t) + if r.hitsAtOpen != offHits || e.hits.Load() != 2*offHits || string(r.body) != body || r.req.Op != llmlog.GatewayOpEmbed { + t.Errorf("open with %d engine hits (want %d, the unrecorded request's), request %d bytes (want %d), op %q", r.hitsAtOpen, offHits, len(r.body), len(body), r.req.Op) + } + if r.state != llmlog.RecordingDone || r.out.Status != 200 || r.response != nil { + t.Errorf("row: state %q status %d answer %d bytes, want done 200 without the vectors", r.state, r.out.Status, len(r.response)) + } + }) + t.Run("rerank", func(t *testing.T) { + e := newRerankEngine(t) + store := newRecStore(func() int64 { return e.hits.Load() }) + rig := newRerankRig(t, []backends.Backend{e.row("spark-rerank", 10)}, 4, 1, withRecordings(store)) + body := rerankBody("rrpub", "which document?", []string{recSecret + " " + long, "other"}) + rig.ca.Store(recordingConsumer(false)) + off := rig.postRerank(t, "/v1/rerank", body) + rig.ca.Store(recordingConsumer(true)) + on := rig.postRerank(t, "/v1/rerank", body) + if off.status != 200 || on.status != 200 || !sameAnswer(off.body, on.body) { + t.Fatalf("status off %d on %d, answers equal %v: %.200s", off.status, on.status, sameAnswer(off.body, on.body), on.body) + } + r := store.only(t) + if r.hitsAtOpen != 1 || string(r.body) != body || r.req.Op != llmlog.GatewayOpRerank { + t.Errorf("open with %d engine hits (want 1), request %d bytes (want %d), op %q", r.hitsAtOpen, len(r.body), len(body), r.req.Op) + } + if r.state != llmlog.RecordingDone || r.out.Status != 200 || string(r.response) != string(on.body) { + t.Errorf("row: state %q status %d answer %q, want done 200 with the client's answer %q", r.state, r.out.Status, r.response, on.body) + } + }) +} + +// TestRecordingUnheldIsNotServed: a request that cannot be held — the store +// refuses, hangs past recordWriteTimeout, or the account has no room within +// the wait — gets 503 recording_unavailable and never reaches a backend; its +// row is written at its end if the store takes it then. +func TestRecordingUnheldIsNotServed(t *testing.T) { + for _, tc := range []struct { + name string + prep func(s *recStore) (undo func()) + }{ + {"store_refuses", func(s *recStore) func() { + s.set(func(s *recStore) { s.openErr = errors.New("database down") }) + return func() {} + }}, + {"store_hangs", func(s *recStore) func() { + s.set(func(s *recStore) { s.openHang = true }) + return func() {} + }}, + {"account_full", func(*recStore) func() { + return oai.FillRecordingAccount(oai.RecordingAccountLimit(chatSettings())) + }}, + } { + t.Run(tc.name, func(t *testing.T) { + if tc.name == "store_hangs" && testing.Short() { + t.Skip("waits recordWriteTimeout (5 s)") + } + u := newUpstream(t, recChatAnswer) + store := newRecStore(func() int64 { return u.hits.Load() }) + rig := newChatRig(t, []backends.Backend{u.row("spark", backends.TrustFull, 10)}, 4, 1, + withDeps(func(d *oai.Deps) { d.MaxWait = func() time.Duration { return 50 * time.Millisecond } }), withRecordings(store)) + rig.ca.Store(recordingConsumer(true)) + before := statsOf(urgentApp().ConsumerID) + undo := tc.prep(store) + a := rig.post(t, chatBody("pub")) + undo() + checkRecordingRefusal(t, a.status, a.header, a.body) + if n := u.hits.Load(); n != 0 { + t.Errorf("the backend was called %d times for a request that was not held", n) + } + if rig.limiter.aborts.Load() != 1 { + t.Errorf("the meter's reservation: %d aborts, want 1 (no wire contact)", rig.limiter.aborts.Load()) + } + got := statsOf(urgentApp().ConsumerID) + if tc.name == "account_full" { + // The account stayed full through the request's end: no row + // could be written — counted, the request was refused. + if store.calls.Load() != 0 || got.Unrecordable-before.Unrecordable != 1 || got.Recorded != before.Recorded { + t.Errorf("full account: %d store calls, unrecordable +%d, recorded +%d — want 0, +1, +0", + store.calls.Load(), got.Unrecordable-before.Unrecordable, got.Recorded-before.Recorded) + } + return + } + // The store takes the row at the request's end: refused, with its body. + r := store.only(t) + if r.opened || r.out.Status != 503 || r.out.Code != oai.CodeRecordingUnavailable || string(r.body) != chatBody("pub") { + t.Errorf("row at the end: opened %v status %d code %q body %q", r.opened, r.out.Status, r.out.Code, r.body) + } + if got.Recorded-before.Recorded != 1 || got.Unrecordable != before.Unrecordable { + t.Errorf("recorded +%d unrecordable +%d, want +1 +0", got.Recorded-before.Recorded, got.Unrecordable-before.Unrecordable) + } + }) + } +} + +// TestRecordedAnswerHeldBeforeItIsWritten: a non-streamed answer the store +// cannot take is not written — the client gets 503 recording_unavailable, +// never the answer — on chat, embeddings and rerank; the row stays open and +// counts as unfinished. A stream cannot take its lines back: it ends as it +// would, its row stays open and counts as a stream answer not recorded. +func TestRecordedAnswerHeldBeforeItIsWritten(t *testing.T) { + failFinish := func(s *recStore) { s.finishErr = errors.New("database down") } + check := func(t *testing.T, store *recStore, status int, header http.Header, body []byte, before oai.RecordingConsumer) { + t.Helper() + checkRecordingRefusal(t, status, header, body) + if strings.Contains(string(body), "the answer") || strings.Contains(string(body), "relevance_score") || strings.Contains(string(body), `"embedding"`) { + t.Errorf("the client got the answer that was not held: %.200s", body) + } + r := store.only(t) + if r.state != llmlog.RecordingOpen { + t.Errorf("row state %q, want open (its outcome could not be held)", r.state) + } + got := statsOf(urgentApp().ConsumerID) + if got.Unfinished-before.Unfinished != 1 || got.Recorded-before.Recorded != 1 { + t.Errorf("unfinished +%d recorded +%d, want +1 +1", got.Unfinished-before.Unfinished, got.Recorded-before.Recorded) + } + } + t.Run("chat", func(t *testing.T) { + u := newUpstream(t, recChatAnswer) + store := newRecStore(nil) + rig := newChatRig(t, []backends.Backend{u.row("spark", backends.TrustFull, 10)}, 4, 1, withRecordings(store)) + rig.ca.Store(recordingConsumer(true)) + store.set(failFinish) + before := statsOf(urgentApp().ConsumerID) + a := rig.post(t, chatBody("pub")) + check(t, store, a.status, a.header, a.body, before) + }) + t.Run("embeddings", func(t *testing.T) { + e := newEmbedEngine(t, 8) + store := newRecStore(nil) + rig := newEmbedRig(t, []backends.Backend{e.row("spark-embed", backends.ProtocolOpenAI, 10)}, 4, 1, withRecordings(store)) + rig.ca.Store(recordingConsumer(true)) + store.set(failFinish) + before := statsOf(urgentApp().ConsumerID) + a := rig.postEmbed(t, embedBody("emb1", []string{"a"})) + check(t, store, a.status, a.header, a.body, before) + }) + t.Run("rerank", func(t *testing.T) { + e := newRerankEngine(t) + store := newRecStore(nil) + rig := newRerankRig(t, []backends.Backend{e.row("spark-rerank", 10)}, 4, 1, withRecordings(store)) + rig.ca.Store(recordingConsumer(true)) + store.set(failFinish) + before := statsOf(urgentApp().ConsumerID) + a := rig.postRerank(t, "/v1/rerank", rerankBody("rrpub", "q", []string{"d1", "d2"})) + check(t, store, a.status, a.header, a.body, before) + }) + t.Run("stream", func(t *testing.T) { + sh := streamShapes[0] + u := newUpstream(t, "") + u.setRespond(sseRespond(sh.steps(), nil, nil)) + store := newRecStore(nil) + rig := newChatRig(t, []backends.Backend{u.row("spark", backends.TrustFull, 10)}, 4, 1, withStreamSettings, withRecordings(store)) + srv := serveHTTP(t, rig.router) + rig.ca.Store(recordingConsumer(true)) + store.set(failFinish) + before := statsOf(urgentApp().ConsumerID) + on := postStream(context.Background(), t, srv, streamBody("chat")) + checkRelay(t, on) + r := store.only(t) + got := statsOf(urgentApp().ConsumerID) + if r.state != llmlog.RecordingOpen || got.StreamAnswersUnrecorded-before.StreamAnswersUnrecorded != 1 || got.Unfinished-before.Unfinished != 1 { + t.Errorf("row %q, stream answers unrecorded +%d, unfinished +%d — want open, +1, +1", + r.state, got.StreamAnswersUnrecorded-before.StreamAnswersUnrecorded, got.Unfinished-before.Unfinished) + } + }) +} + +// TestRecordingStreamWithoutRoomEnds: a stream whose next line the account +// cannot take ends before that line with recording_unavailable — every line +// the client got is a line the recording kept. +func TestRecordingStreamWithoutRoomEnds(t *testing.T) { + sh := streamShapes[0] + u := newUpstream(t, "") + u.setRespond(sseRespond(sh.steps(), nil, nil)) + store := newRecStore(nil) + rig := newChatRig(t, []backends.Backend{u.row("spark", backends.TrustFull, 10)}, 4, 1, withStreamSettings, withRecordings(store)) + srv := serveHTTP(t, rig.router) + rig.ca.Store(recordingConsumer(true)) + // The open's copies fit; the stream's first line does not. + limit := oai.RecordingAccountLimit(chatSettings()) + release := oai.FillRecordingAccount(limit - int64(oai.RecordCopyFactor*len(streamBody("chat")))) + on := postStream(context.Background(), t, srv, streamBody("chat")) + release() + r := store.only(t) + if !strings.Contains(on.raw, oai.CodeRecordingUnavailable) { + t.Errorf("the stream did not end with recording_unavailable: %d %q", on.status, on.raw) + } + if strings.Contains(on.raw, `"delta"`) || len(r.response) != 0 { + t.Errorf("a line went out that the recording did not keep: client %q, kept %q", on.raw, r.response) + } +} + +// TestRecordingRefusedRequestsLeaveTheirRow: a request the gateway refuses +// after the door — a body that does not parse, a body cut short, an unknown +// model, the meter's refusal — leaves one row, never opened, with what was +// read of the body and the status and code the client got. +func TestRecordingRefusedRequestsLeaveTheirRow(t *testing.T) { + for _, tc := range []struct { + name, body string + declared int64 + limiter bool + status int + code string + complete bool + }{ + {"unparsable", `{"model":"pub","messages":[{"role":"user","content":"` + recSecret + `"`, -1, false, 400, "invalid_json", true}, + {"cut_short", `{"model":"pub","messages":`, 400, false, 400, "invalid_json", false}, + {"unknown_model", `{"model":"no-such-model","messages":[{"role":"user","content":"hi"}]}`, -1, false, 404, "model_not_found", true}, + {"limiter", chatBody("pub"), -1, true, 429, "rate_limit_exceeded", true}, + } { + t.Run(tc.name, func(t *testing.T) { + u := newUpstream(t, recChatAnswer) + store := newRecStore(nil) + rig := newChatRig(t, []backends.Backend{u.row("spark", backends.TrustFull, 10)}, 4, 1, withRecordings(store)) + rig.ca.Store(recordingConsumer(true)) + if tc.limiter { + rig.limiter.refuse = &oai.LimitRefusal{Code: oai.CodeRateLimitExceeded, Message: "slow down", ShouldRetry: true, RetryAfter: time.Second} + } + req := httptest.NewRequest(http.MethodPost, "/v1/chat/completions", strings.NewReader(tc.body)) + if tc.declared >= 0 { + req.ContentLength = tc.declared + } + w := httptest.NewRecorder() + rig.router.ServeHTTP(w, req) + r := store.only(t) + if w.Code != tc.status || r.opened || r.out.Status != tc.status || r.out.Code != tc.code { + t.Errorf("client %d, row opened %v status %d code %q — want %d %q, never opened", w.Code, r.opened, r.out.Status, r.out.Code, tc.status, tc.code) + } + if string(r.body) != tc.body || r.req.Complete != tc.complete { + t.Errorf("row body %q complete %v, want %q complete %v", r.body, r.req.Complete, tc.body, tc.complete) + } + if u.hits.Load() != 0 { + t.Errorf("a refused request reached the backend") + } + }) + } +} + +// TestRecordingStagePassesOtherConsumers: for a consumer without the switch +// the stage hands the route the very writer and request it got — no +// wrapper, no context value, no store call; for a recording consumer it does +// not. +func TestRecordingStagePassesOtherConsumers(t *testing.T) { + store := newRecStore(nil) + var ca atomic.Pointer[auth.ConsumerAuth] + stage := oai.NewRecordingStage(store, func(context.Context) *auth.ConsumerAuth { return ca.Load() }, + func() oai.Settings { return chatSettings() }, func() time.Duration { return time.Second }) + var sawW http.ResponseWriter + var sawR *http.Request + h := stage.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { sawW, sawR = w, r })) + for _, on := range []bool{false, true} { + ca.Store(recordingConsumer(on)) + w := httptest.NewRecorder() + req := httptest.NewRequest(http.MethodPost, "/v1/models", nil) + h.ServeHTTP(w, req) + same := sawW == http.ResponseWriter(w) && sawR == req + if same == on { + t.Errorf("switch %v: the route got the stage's own writer and request %v, want %v", on, same, !on) + } + } + if n := store.calls.Load(); n != 1 { + t.Errorf("%d store calls, want 1 (the recording consumer's row, none for the other)", n) + } +} + +// TestRecordingPanicLeavesTheRow: a request that panics behind the stage +// leaves its row with the 503 internal_error oai.Recover answers. +func TestRecordingPanicLeavesTheRow(t *testing.T) { + store := newRecStore(nil) + stage := oai.NewRecordingStage(store, func(context.Context) *auth.ConsumerAuth { return recordingConsumer(true) }, + func() oai.Settings { return chatSettings() }, func() time.Duration { return time.Second }) + rt := chi.NewRouter() + rt.Use(oai.Recover, stage.Handler) + rt.Post("/v1/chat/completions", func(http.ResponseWriter, *http.Request) { panic("boom") }) + w := httptest.NewRecorder() + rt.ServeHTTP(w, httptest.NewRequest(http.MethodPost, "/v1/chat/completions", strings.NewReader("{}"))) + r := store.only(t) + if w.Code != 503 || r.out.Status != 503 || r.out.Code != oai.CodeInternalError { + t.Errorf("client %d, row status %d code %q — want 503 internal_error both", w.Code, r.out.Status, r.out.Code) + } +} + +// TestRecordingCountsBalance: whatever happened to the requests, a recording +// consumer's counts hold admitted = in_flight + recorded + unrecordable, and +// recorded is the number of rows the store holds for it. +func TestRecordingCountsBalance(t *testing.T) { + u := newUpstream(t, recChatAnswer) + store := newRecStore(nil) + rig := newChatRig(t, []backends.Backend{u.row("spark", backends.TrustFull, 10)}, 4, 1, withRecordings(store)) + ca := recordingConsumer(true) + ca.ConsumerID = "0195a6f0-0000-7000-8000-0000000c0571" + rig.ca.Store(ca) + rig.post(t, chatBody("pub")) // served + rig.post(t, `{"model":"pub"`) // refused before the walk + store.set(func(s *recStore) { s.openErr = errors.New("down"); s.insertErr = errors.New("down") }) + rig.post(t, chatBody("pub")) // not held, not served, no row at all + store.set(func(s *recStore) { s.openErr, s.insertErr, s.finishErr = nil, nil, errors.New("down") }) + rig.post(t, chatBody("pub")) // held, its answer not: refused, the row stays open + got := statsOf(ca.ConsumerID) + store.mu.Lock() + rows := int64(len(store.rows)) + store.mu.Unlock() + if got.Admitted != 4 || got.InFlight != 0 || got.Recorded != 3 || got.Unrecordable != 1 || got.Unfinished != 1 || + got.Admitted != got.InFlight+got.Recorded+got.Unrecordable || got.Recorded != rows { + t.Errorf("counts %+v with %d rows — want admitted 4 = in flight 0 + recorded 3 + unrecordable 1, unfinished 1, recorded = rows", got, rows) + } +} diff --git a/go/internal/oai/record_test.go b/go/internal/oai/record_test.go deleted file mode 100644 index 906d2e6f0..000000000 --- a/go/internal/oai/record_test.go +++ /dev/null @@ -1,199 +0,0 @@ -package oai_test - -import ( - "context" - "encoding/json" - "regexp" - "strings" - "testing" - - "github.com/GottZ/ctx/internal/auth" - "github.com/GottZ/ctx/internal/backends" - "github.com/GottZ/ctx/internal/llmlog" - "github.com/GottZ/ctx/internal/oai" -) - -// The recording switch on the routes (issue #571): a consumer with -// RecordBodies has its row carry the whole request and the whole answer the -// client received — a non-streamed chat answer as written, a stream's relayed -// data lines, the inputs of embeddings and the query and documents of rerank -// — under every gateway.body_logging value and every alias class; and the -// request path is the same with and without the switch: the same upstream -// body (so the same chain, scan and limits), the same status, the same answer -// up to the request's own id and clock. - -// recSecret is a credentials pattern in a prompt: the sensitivity scan raises -// a request carrying it to credentials, where the body policy stores nothing. -const recSecret = "password=hunter2-recorded-571" - -// recordingConsumer is the rig's consumer with the switch set to on. -func recordingConsumer(on bool) *auth.ConsumerAuth { - ca := urgentApp() - ca.RecordBodies = on - return ca -} - -// releaseRows gives the rows' reservations back (the rig's sink is no writer). -func releaseRows(rows []llmlog.GatewayRow) { - for _, r := range rows { - llmlog.ReleaseRecorded(r.RecordedHeld) - } -} - -// answerIdentity drops what differs between two requests by construction: -// the answer's id and created stamp. -var answerIdentity = regexp.MustCompile(`"(id|created)":("[^"]*"|\d+)`) - -func sameAnswer(a, b []byte) bool { - return answerIdentity.ReplaceAllString(string(a), "") == answerIdentity.ReplaceAllString(string(b), "") -} - -func TestRecordedChatKeepsWholeBodiesAndChangesNoAnswer(t *testing.T) { - long := strings.Repeat("abcdefgh", 12<<10) // 96 KiB, past the 64 KiB cap - answer := `{"id":"gen-1","object":"chat.completion","created":1700000000,"model":"M",` + - `"choices":[{"index":0,"finish_reason":"stop","message":{"role":"assistant","content":"` + strings.Repeat("y", 80<<10) + `"}}],` + - `"usage":{"prompt_tokens":11,"completion_tokens":3,"total_tokens":14}}` - body := `{"model":"pub","messages":[{"role":"user","content":"` + recSecret + " " + long + `"}]}` - messages := `[{"role":"user","content":"` + recSecret + " " + long + `"}]` - for _, pol := range []string{llmlog.BodyLoggingNone, llmlog.BodyLoggingErrors, llmlog.BodyLoggingFull} { - t.Run(pol, func(t *testing.T) { - u := newUpstream(t, answer) - rig := newChatRig(t, []backends.Backend{u.row("spark", backends.TrustFull, 10)}, 4, 1) - rig.setSettings(func(s *oai.Settings) { s.BodyLogging = pol }) - rig.ca.Store(recordingConsumer(false)) - off := rig.post(t, body) - rig.ca.Store(recordingConsumer(true)) - on := rig.post(t, body) - rows := rig.rows.all() - defer releaseRows(rows) - if off.status != 200 || on.status != 200 { - t.Fatalf("status off %d on %d, want 200 both: %.200s / %.200s", off.status, on.status, off.body, on.body) - } - if !sameAnswer(off.body, on.body) { - t.Errorf("the answer differs with the switch on") - } - if len(u.raws) != 2 || string(u.raws[0]) != string(u.raws[1]) { - t.Errorf("the upstream bodies differ with the switch on (%d calls)", len(u.raws)) - } - if len(rows) != 2 { - t.Fatalf("%d rows, want 2", len(rows)) - } - ro, rn := rows[0], rows[1] - // The scan raised both to credentials: the switch changes no class. - if ro.Telemetry.RequiredSensitivity != string(backends.SensCredentials) || rn.Telemetry.RequiredSensitivity != ro.Telemetry.RequiredSensitivity { - t.Errorf("required sensitivity off %q on %q, want credentials both", ro.Telemetry.RequiredSensitivity, rn.Telemetry.RequiredSensitivity) - } - if ro.Recorded || ro.RecordedHeld != 0 { - t.Errorf("the row of the consumer without the switch is marked recorded") - } - if stored := llmlog.GatewayEntry(ro); stored.RequestUser != "" || stored.ResponseContent != "" { - t.Errorf("the unrecorded credentials row stores %d/%d bytes, want 0/0 (sealed)", len(stored.RequestUser), len(stored.ResponseContent)) - } - if !rn.Recorded || rn.RecordLost != nil { - t.Fatalf("the recording consumer's row: recorded %v lost %v, want recorded without a loss", rn.Recorded, rn.RecordLost) - } - stored := llmlog.RecordedGatewayEntry(rn) - if stored.RequestUser != messages { - t.Errorf("recorded request %d bytes, want the whole message array (%d bytes)", len(stored.RequestUser), len(messages)) - } - if !strings.HasSuffix(string(on.body), "\n") || stored.ResponseContent != strings.TrimSuffix(string(on.body), "\n") { - t.Errorf("recorded answer %d bytes, want the whole answer the client received (%d bytes)", len(stored.ResponseContent), len(on.body)) - } - if want := int64(len(stored.RequestUser) + len(stored.ResponseContent)); rn.RecordedHeld != want { - t.Errorf("the row holds %d bytes of the recording account, want %d", rn.RecordedHeld, want) - } - }) - } -} - -// TestRecordedStreamKeepsTheRelayedLines: a stream's recorded answer is the -// data lines the relay handed to the client, in order — the client's body is -// exactly those lines and the closing [DONE] — and the client gets the same -// stream with and without the switch. -func TestRecordedStreamKeepsTheRelayedLines(t *testing.T) { - sh := streamShapes[0] - u := newUpstream(t, "") - u.setRespond(sseRespond(sh.steps(), nil, nil)) - rig := newChatRig(t, []backends.Backend{u.row("spark", backends.TrustFull, 10)}, 4, 1, withStreamSettings) - srv := serveHTTP(t, rig.router) - rig.ca.Store(recordingConsumer(false)) - off := postStream(context.Background(), t, srv, streamBody("chat")) - rig.ca.Store(recordingConsumer(true)) - on := postStream(context.Background(), t, srv, streamBody("chat")) - rows := rig.rows.all() - defer releaseRows(rows) - checkRelay(t, on) - if !sameAnswer([]byte(off.raw), []byte(on.raw)) { - t.Errorf("the stream differs with the switch on:\n off %q\n on %q", off.raw, on.raw) - } - if len(rows) != 2 || rows[0].Recorded || rows[0].Response != "" || !rows[1].Recorded { - t.Fatalf("rows %d: off recorded %v response %d bytes, on recorded %v", len(rows), rows[0].Recorded, len(rows[0].Response), rows[1].Recorded) - } - got := llmlog.RecordedGatewayEntry(rows[1]).ResponseContent - if got == "" || got+"data: [DONE]\n\n" != on.raw { - t.Errorf("recorded stream answer %q, want the client's body without its closing [DONE]: %q", got, on.raw) - } - if !strings.Contains(llmlog.RecordedGatewayEntry(rows[1]).RequestUser, `"content":"hi"`) { - t.Errorf("recorded stream request %q, want the message array", rows[1].Request) - } -} - -func TestRecordedEmbeddingsKeepTheWholeInput(t *testing.T) { - inputs := []string{recSecret + " " + strings.Repeat("e", 70<<10), "second " + strings.Repeat("f", 1000)} - body := embedBody("emb1", inputs) - for _, pol := range []string{llmlog.BodyLoggingNone, llmlog.BodyLoggingFull} { - t.Run(pol, func(t *testing.T) { - e := newEmbedEngine(t, 8) - rig := newEmbedRig(t, []backends.Backend{e.row("spark-embed", backends.ProtocolOpenAI, 10)}, 4, 1) - rig.setSettings(func(s *oai.Settings) { s.BodyLogging = pol }) - rig.ca.Store(recordingConsumer(false)) - off := rig.postEmbed(t, body) - rig.ca.Store(recordingConsumer(true)) - on := rig.postEmbed(t, body) - rows := rig.rows.all() - defer releaseRows(rows) - if off.status != 200 || on.status != 200 || !sameAnswer(off.body, on.body) { - t.Fatalf("status off %d on %d (answers equal %v): %.300s", off.status, on.status, sameAnswer(off.body, on.body), on.body) - } - if len(rows) != 2 || rows[0].Recorded || !rows[1].Recorded { - t.Fatalf("rows %d, recorded off/on want false/true", len(rows)) - } - in, _ := json.Marshal(inputs) - stored := llmlog.RecordedGatewayEntry(rows[1]) - if stored.RequestUser != string(in) || stored.ResponseContent != "" { - t.Errorf("recorded embeddings row: request %d bytes (want the whole input, %d), answer %d bytes (want none — the vectors are not kept)", - len(stored.RequestUser), len(in), len(stored.ResponseContent)) - } - }) - } -} - -func TestRecordedRerankKeepsQueryAndDocuments(t *testing.T) { - docs := []string{recSecret + " " + strings.Repeat("d", 70<<10), "other"} - query := "which document? " + strings.Repeat("q", 100) - body := rerankBody("rrpub", query, docs) - e := newRerankEngine(t) - rig := newRerankRig(t, []backends.Backend{e.row("spark-rerank", 10)}, 4, 1) - rig.ca.Store(recordingConsumer(false)) - off := rig.postRerank(t, "/v1/rerank", body) - rig.ca.Store(recordingConsumer(true)) - on := rig.postRerank(t, "/v1/rerank", body) - rows := rig.rows.all() - defer releaseRows(rows) - if off.status != 200 || on.status != 200 || !sameAnswer(off.body, on.body) { - t.Fatalf("status off %d on %d (answers equal %v): %.300s", off.status, on.status, sameAnswer(off.body, on.body), on.body) - } - if len(rows) != 2 || rows[0].Recorded || !rows[1].Recorded { - t.Fatalf("rows %d, recorded off/on want false/true", len(rows)) - } - q, _ := json.Marshal(query) - d, _ := json.Marshal(docs) - stored := llmlog.RecordedGatewayEntry(rows[1]) - if want := string(q) + "\n" + string(d); stored.RequestUser != want { - t.Errorf("recorded rerank request %d bytes, want query, line break and documents (%d bytes)", len(stored.RequestUser), len(want)) - } - if stored.ResponseContent != string(on.body) || rows[0].Response != "" { - t.Errorf("recorded rerank answer %q, want the answer the client received %q (the unrecorded row keeps none: %q)", - stored.ResponseContent, on.body, rows[0].Response) - } -} diff --git a/go/internal/oai/rerank.go b/go/internal/oai/rerank.go index f657cb982..dba32b805 100644 --- a/go/internal/oai/rerank.go +++ b/go/internal/oai/rerank.go @@ -126,7 +126,16 @@ func Rerank(d Deps, dialect RerankDialect) http.Handler { refuseInternal(w, r) return } + rr, ok := routeRecording(r, ca, llmlog.GatewayOpRerank) + if !ok { + refuseRecording(AccessRecordFrom(r.Context()), w) + return + } c := newRerankCall(d, w, r, ca, entry, dialect) + c.recording = rr + if rr != nil { + c.id = rr.req.ID // the answer ("rerank-") names the recorded row + } defer c.close() c.serve() }) @@ -176,16 +185,14 @@ type rerankCall struct { // scores (sigmoid, in place) — one slice of the answer reserve, made // once per request. logits []float64 - // recording is the capture of a recording consumer's request (record.go; - // off for every other consumer): the query and documents, and the answer - // as written to the client. - recording recording + // recording is the request's recording (record.go): nil for a consumer + // that does not record. + recording *requestRecording } func newRerankCall(d Deps, w http.ResponseWriter, r *http.Request, ca *auth.ConsumerAuth, entry time.Time, dialect RerankDialect) *rerankCall { s := d.Settings() c := &rerankCall{d: d, w: w, s: s, ca: ca, entry: entry, client: r.Context(), rec: AccessRecordFrom(r.Context()), dialect: dialect} - c.recording.on = ca != nil && ca.RecordBodies if c.rec == nil { c.rec = &AccessRecord{} // outside a model group: filled, never read } @@ -227,7 +234,6 @@ func (c *rerankCall) close() { for _, stop := range c.stops { stop() } - c.recording.release() // what no row of this request took } func (c *rerankCall) refuse(code, message string, shouldRetry bool) { @@ -280,6 +286,7 @@ func (c *rerankCall) serve() { c.refuseParam(perr) return } + c.recording.parsed(req.model, false) if !c.resolve(req.model, req.modelOverlong) { return } @@ -317,7 +324,8 @@ func (c *rerankCall) serve() { // readBody reads the body under the strict cap and the in-flight budget // (embedCall.readBody): the ledger starts here. func (c *rerankCall) readBody() ([]byte, bool) { - body, spent, err := readRequestBody(c.r.Body, c.r.ContentLength) + body, spent, err := readBodyKeep(c.r.Body, c.r.ContentLength, c.recording != nil) + c.recording.setBody(body, err == nil) var tooLarge *http.MaxBytesError switch { case err == nil: @@ -495,7 +503,7 @@ func (c *rerankCall) admitLimiter() bool { // The row the shutdown's forced settle writes should the request still // be open after the HTTP drain (W06-13 (e)). registerForcedRow(res, c.d.Record, func() llmlog.GatewayRow { - return llmlog.GatewayRow{Pipeline: rerankPipeline, ConsumerID: c.ca.ConsumerID, Recorded: c.ca.RecordBodies, + return llmlog.GatewayRow{Pipeline: rerankPipeline, ConsumerID: c.ca.ConsumerID, Recorded: c.recording != nil, RecordingID: c.recording.id(), Gateway: withFederation(c.r.Context(), llmlog.Gateway{Alias: c.alias.Name, Hop: c.rec.Hop, ClientReqID: clientRequestID(c.r), ModelKeyID: c.ca.ModelKeyID})} }, string(c.required)) return true @@ -592,6 +600,13 @@ func (c *rerankCall) walk(chain []backends.Backend) { c.refuseParam(unsupportedValue("documents", fmt.Sprintf("at most %d documents per request", c.lim.subBatch))) return } + // A recording consumer's request is held before its first attempt and + // before any queue wait (record.go); one that cannot be is not served. + if !c.recording.open(c.ctx) { + c.endLimit(func(l LimitReservation) { l.Abort() }) + refuseRecording(c.rec, c.w) + return + } stop := c.d.watch(c.ctx, c.cancel, newWatchTarget(c.ca, c.req.model, c.alias.ID, c.gen)) defer stop() @@ -600,6 +615,9 @@ func (c *rerankCall) walk(chain []backends.Backend) { rules := llm.WalkRules{WindowRule: true, AllowedClasses: c.d.Planner.AllowedClasses(), Timeout: c.attemptTimeout} served, attempts, werr := llm.WalkChain(c.ctx, plan.Chain, c.alias.Role, plan.Acquirer, llm.PoolReporter(c.d.Pool), rules, func(runCtx context.Context, b *backends.Backend, lease *dispatch.Lease, timeout time.Duration) (dispatch.Usage, bool, error) { + if !c.recording.ready() { + return dispatch.Usage{}, false, &llm.AdmissionError{Err: errRecordingUnavailable, Backend: b.Name, Host: b.Host} + } return c.attempt(&st, plan, runCtx, b, lease, timeout) }) stop() @@ -820,6 +838,12 @@ func (c *rerankCall) outcome(plan Plan, attempts []llm.ChainAttempt, err error, if err == nil { return c.success(st) } + if errors.Is(err, errRecordingUnavailable) { + // An attempt found the request's recording not open (ready): it went + // to no backend (record.go). + refuseRecording(c.rec, c.w) + return embedOutcome{finish: llmlog.FinishAborted, redacted: &llmlog.RedactedErr{Class: "admission", Code: CodeRecordingUnavailable}} + } if isAdmissionFailure(err) { waited := time.Duration(0) if st.lease == nil { @@ -937,6 +961,22 @@ func (c *rerankCall) success(st *rerankState) embedOutcome { returnDocs = c.req.returnDocs } order := rankDocuments(c.logits, c.req.topN) + a := rerankAnswer{id: "rerank-" + c.id, model: c.alias.Name, scores: c.logits, order: order, promptTokens: st.usage.PromptTokens} + if returnDocs { + a.docs = c.req.docs + } + var held []byte + if c.recording != nil { + // A recording consumer's answer is written into its recording first + // and held before its first byte goes out (record.go): the client + // gets the same bytes in one write. One that cannot be kept or held + // is refused instead. + if err := writeRerank(captureWriter{c.recording}, a); err != nil || !c.recording.answer(c.ctx, c.recording.capture) { + refuseRecording(c.rec, c.w) + return embedOutcome{finish: llmlog.FinishError, redacted: &llmlog.RedactedErr{Class: "admission", Code: CodeRecordingUnavailable}} + } + held = c.recording.capture + } if c.limit != nil { for k, v := range c.limit.Headers() { c.w.Header()[k] = v @@ -944,15 +984,13 @@ func (c *rerankCall) success(st *rerankState) embedOutcome { } c.w.Header().Set("Content-Type", "application/json") c.w.WriteHeader(http.StatusOK) - a := rerankAnswer{id: "rerank-" + c.id, model: c.alias.Name, scores: c.logits, order: order, promptTokens: st.usage.PromptTokens} - if returnDocs { - a.docs = c.req.docs - } - var out io.Writer = c.w - if c.recording.on { - out = recordWriter{w: c.w, r: &c.recording} // the bytes the client was written, for its row + var err error + if held != nil { + _, err = c.w.Write(held) //nolint:gosec // G705: held is writeRerank's own output — every text through writeJSONText's escape —, the bytes the unrecorded path writes (TestRecordingHoldsTheRequestBeforeAnyBackend/rerank) + } else { + err = writeRerank(c.w, a) } - if err := writeRerank(out, a); err != nil { + if err != nil { slog.Warn("gateway: failed to write the answer", "error", err, "request_id", c.w.Header().Get("X-Request-ID")) return embedOutcome{finish: llmlog.FinishAborted} } @@ -1124,23 +1162,12 @@ func (c *rerankCall) record(plan Plan, served *backends.Backend, attempts []llm. if st.usage.PromptTokens > 0 { usage = llmlog.UsageBackend } - request, response := "", "" - switch { - case c.recording.on: - // A recording consumer's row (issue #571): the whole text of the - // query and the documents and the answer as the client was written - // it (success), reserved against the recording account (record.go). - if n := rerankLogSize(c.req, noLogLimit); c.recording.reserve(int64(n)) { - request = rerankLogText(c.req, n, noLogLimit) - } else { - c.recording.loseBody(llmlog.RecordLostRequest) - } - response = c.recording.streamText() - case c.s.BodyLogging == llmlog.BodyLoggingFull || (c.s.BodyLogging == llmlog.BodyLoggingErrors && out.redacted != nil): + request := "" + if c.s.BodyLogging == llmlog.BodyLoggingFull || (c.s.BodyLogging == llmlog.BodyLoggingErrors && out.redacted != nil) { // The row's text of the query and the documents is sized, then // booked, then written (the embeddings route's rule). - if n := rerankLogSize(c.req, bodyLogTextMax); c.ledger.cover(int64(n)) { - request = rerankLogText(c.req, n, bodyLogTextMax) + if n := rerankLogSize(c.req); c.ledger.cover(int64(n)) { + request = rerankLogText(c.req, n) } } row := llmlog.GatewayRow{ @@ -1154,7 +1181,6 @@ func (c *rerankCall) record(plan Plan, served *backends.Backend, attempts []llm. Attempts: attempts, Err: out.redacted, Request: request, - Response: response, BodyLogging: c.s.BodyLogging, } c.recording.mark(&row) @@ -1162,19 +1188,18 @@ func (c *rerankCall) record(plan Plan, served *backends.Backend, attempts []llm. } // rerankLogSize is the length of rerankLogText: the query's text, a line -// break and the documents' text (bodyLogSizeN of each raw value, each up to -// limit — bodyLogTextMax, or noLogLimit for a recorded row). -func rerankLogSize(req *rerankRequest, limit int) int { - return bodyLogSizeN(req.queryRaw, limit) + 1 + bodyLogSizeN(req.docsRaw, limit) +// break and the documents' text (bodyLogSize of each raw value). +func rerankLogSize(req *rerankRequest) int { + return bodyLogSize(req.queryRaw) + 1 + bodyLogSize(req.docsRaw) } // rerankLogText is the log row's text of the request, written once into // size bytes (bodyLogText's form over two values). -func rerankLogText(req *rerankRequest, size, limit int) string { +func rerankLogText(req *rerankRequest, size int) string { var b strings.Builder b.Grow(size) - bodyLogWalkN(req.queryRaw, limit, func(p []byte) { b.Write(p) }) + bodyLogWalk(req.queryRaw, func(p []byte) { b.Write(p) }) b.WriteByte('\n') - bodyLogWalkN(req.docsRaw, limit, func(p []byte) { b.Write(p) }) + bodyLogWalk(req.docsRaw, func(p []byte) { b.Write(p) }) return b.String() } diff --git a/go/internal/oai/rerank_harness_test.go b/go/internal/oai/rerank_harness_test.go index b60d31e37..1304bbd6d 100644 --- a/go/internal/oai/rerank_harness_test.go +++ b/go/internal/oai/rerank_harness_test.go @@ -234,6 +234,9 @@ func (r *chatRig) mountRerank(v1, v2 http.Handler) chi.Router { }) }) gr.Use(oai.Recover) + if r.recStage != nil { + gr.Use(r.recStage.Handler) // the recording stage behind the door (record.go) + } gr.Use(federation.PeerIngress(federation.PeerIngressConfig{Consumer: r.deps.Consumer, Binder: acceptPeerBinder{}, Logger: slog.New(slog.DiscardHandler)})) gr.Use(oai.InflightBudget(&r.budget, func() oai.Settings { return *r.settings.Load() })) gr.Method(http.MethodPost, "/rerank", g.h) diff --git a/go/internal/schemacontract/manifest.json b/go/internal/schemacontract/manifest.json index 85799e2f8..2d9995130 100644 --- a/go/internal/schemacontract/manifest.json +++ b/go/internal/schemacontract/manifest.json @@ -3,7 +3,7 @@ "generated_against": { "migration_max": 197, "migration_count": 85, - "migration_chain_sha256": "0af84720c017d6df9610f248d304edcb869f9ff57ef76a59da7ef17f22b71eb5", + "migration_chain_sha256": "3c827789b6c673076fba296c300cda4dcd4b260e42205646e1e5d3e80e15465c", "pg_major": 18, "image": "pgvector-timescaledb:pg18" }, @@ -2132,6 +2132,131 @@ ], "row_security": false }, + "context_llm_recordings": { + "columns": [ + { + "name": "id", + "type": "uuid", + "not_null": true, + "storage": "p" + }, + { + "name": "created_at", + "type": "timestamp with time zone", + "not_null": true, + "storage": "p" + }, + { + "name": "finished_at", + "type": "timestamp with time zone", + "not_null": false, + "storage": "p" + }, + { + "name": "process_id", + "type": "uuid", + "not_null": true, + "storage": "p" + }, + { + "name": "consumer_id", + "type": "uuid", + "not_null": true, + "storage": "p" + }, + { + "name": "model_key_id", + "type": "uuid", + "not_null": false, + "storage": "p" + }, + { + "name": "path", + "type": "text", + "not_null": true, + "storage": "x" + }, + { + "name": "op", + "type": "text", + "not_null": false, + "storage": "x" + }, + { + "name": "client_request_id", + "type": "text", + "not_null": false, + "storage": "x" + }, + { + "name": "model", + "type": "text", + "not_null": false, + "storage": "x" + }, + { + "name": "stream", + "type": "boolean", + "not_null": false, + "storage": "p" + }, + { + "name": "declared_bytes", + "type": "bigint", + "not_null": false, + "storage": "p" + }, + { + "name": "request_bytes", + "type": "bigint", + "not_null": true, + "storage": "p" + }, + { + "name": "request_complete", + "type": "boolean", + "not_null": true, + "storage": "p" + }, + { + "name": "request_body", + "type": "bytea", + "not_null": false, + "storage": "x" + }, + { + "name": "state", + "type": "text", + "not_null": true, + "storage": "x" + }, + { + "name": "status", + "type": "smallint", + "not_null": false, + "storage": "p" + }, + { + "name": "code", + "type": "text", + "not_null": false, + "storage": "x" + }, + { + "name": "response_bytes", + "type": "bigint", + "not_null": true, + "storage": "p" + }, + { + "name": "response_body", + "type": "bytea", + "not_null": false, + "storage": "x" + } + ], + "row_security": false + }, "context_llm_rejections_hourly": { "columns": [ { @@ -5306,6 +5431,9 @@ "context_llm_log_pkey": { "def_hash": "71bc1db96f8018863b268c53999b6e62059c08f2db9b05631d8ebf2f184eef7b" }, + "context_llm_recordings_pkey": { + "def_hash": "82c959bc21671d3c30d1ed226d473fc4de21a3db327309cc925c5c17105c5b56" + }, "context_model_aliases_pkey": { "def_hash": "0c24f3b4e9d05b5be6df0b45b6793e1e196c6f5e63883b60b79520aba078011b" }, @@ -5781,6 +5909,12 @@ "idx_llm_log_pipeline": { "def_hash": "1020ca37593bb524a6fd456e8c4a241d30b313aed45a98c4cf83fdbab3d37eea" }, + "idx_llm_recordings_bodies": { + "def_hash": "945c90a1ccf00390a20d3871915f5020fe07228ef1dc65d09dd8c01eaace13a2" + }, + "idx_llm_recordings_consumer": { + "def_hash": "05189b7ee2df578c3b060ed85efbc2a5fd782bbf948efcb903db065ab209dab0" + }, "idx_llm_rejections_bucket": { "def_hash": "2bdc46170c4c02e44f7ae2c94f273ebc01cbea468f25295288a8151a08b443bb" }, diff --git a/go/internal/store/model_consumer_record_bodies_migration_integration_test.go b/go/internal/store/model_consumer_record_bodies_migration_integration_test.go index d602e8bc7..28c045879 100644 --- a/go/internal/store/model_consumer_record_bodies_migration_integration_test.go +++ b/go/internal/store/model_consumer_record_bodies_migration_integration_test.go @@ -10,6 +10,7 @@ // consumer's value, the sentinel with false; // - the audit: switching writes one 'update' row whose old/new state carry // record_bodies; an UPDATE that leaves it as it is writes none; +// - context_llm_recordings: its columns, constraints and indexes; // - the way back of the header, in a rolled-back transaction, leaves the // catalog of 196; a second run of 197 leaves its own catalog unchanged. package store_test @@ -31,7 +32,8 @@ const ( ) // m197Catalog is what 197 touches: the two functions, the consumer -// triggers, the consumer columns and the version row. +// triggers, the consumer columns, the recordings table (columns, +// constraints, indexes) and the version row. func m197Catalog(ctx context.Context, t *testing.T, q func(context.Context, string) ([]string, error)) string { t.Helper() var parts []string @@ -43,6 +45,13 @@ func m197Catalog(ctx context.Context, t *testing.T, q func(context.Context, stri `SELECT 'column: ' || column_name || ' ' || data_type || ' ' || is_nullable || ' ' || COALESCE(column_default, '') FROM information_schema.columns WHERE table_schema = current_schema() AND table_name = 'context_model_consumers' ORDER BY ordinal_position`, + `SELECT 'recordings column: ' || column_name || ' ' || data_type || ' ' || is_nullable || ' ' || COALESCE(column_default, '') + FROM information_schema.columns + WHERE table_schema = current_schema() AND table_name = 'context_llm_recordings' ORDER BY ordinal_position`, + `SELECT 'recordings constraint: ' || pg_get_constraintdef(oid) FROM pg_constraint + WHERE conrelid = to_regclass('context_llm_recordings') ORDER BY 1`, + `SELECT 'recordings index: ' || indexdef FROM pg_indexes + WHERE schemaname = current_schema() AND tablename = 'context_llm_recordings' ORDER BY indexname`, `SELECT 'migration: ' || version FROM _migrations WHERE version = 197`, } { lines, err := q(ctx, sql) @@ -74,6 +83,7 @@ func m197WayBack(t *testing.T) string { state := pick(`(?s)CREATE OR REPLACE FUNCTION audit_state_model_consumer\(.*?\$\$ LANGUAGE sql STABLE;`) trig := pick(`(?s)CREATE TRIGGER trg_model_consumers_audit_upd\s.*?EXECUTE FUNCTION audit_model_consumers_write\(\);`) return strings.Join([]string{ + `DROP TABLE context_llm_recordings;`, `DROP FUNCTION ctx_model_auth(TEXT, INET, BOOLEAN);`, auth, state, @@ -167,6 +177,28 @@ func TestMigration197Idempotent(t *testing.T) { t.Errorf("switching off wrote %d update row(s), want 1", rows()-n0-1) } }) + t.Run("recordings_table", func(t *testing.T) { + cat := m197Catalog(ctx, t, onPool) + for _, want := range []string{"recordings column: request_body bytea YES", "recordings column: response_body bytea YES", + "recordings column: process_id uuid NO", "recordings column: state text NO", + "recordings index: CREATE UNIQUE INDEX context_llm_recordings_pkey", "(consumer_id, created_at DESC)", + "(created_at) WHERE (request_body IS NOT NULL)"} { + if !strings.Contains(cat, want) { + t.Errorf("the recordings table lacks %q:\n%s", want, cat) + } + } + // An open row has no finished_at, a done one has one; a state outside + // the two is refused. + for _, sql := range []string{ + `INSERT INTO context_llm_recordings (id, process_id, consumer_id, path, state) VALUES (gen_random_uuid(), gen_random_uuid(), gen_random_uuid(), '/v1', 'done')`, + `INSERT INTO context_llm_recordings (id, process_id, consumer_id, path, state, finished_at) VALUES (gen_random_uuid(), gen_random_uuid(), gen_random_uuid(), '/v1', 'open', now())`, + `INSERT INTO context_llm_recordings (id, process_id, consumer_id, path, state) VALUES (gen_random_uuid(), gen_random_uuid(), gen_random_uuid(), '/v1', 'lost')`, + } { + if _, err := pool.Exec(ctx, sql); mcSQLState(err) != "23514" { + t.Errorf("%s: %v (SQLSTATE %s), want the check's 23514", sql, err, mcSQLState(err)) + } + } + }) t.Run("way_back_is_clean", func(t *testing.T) { tx, err := pool.Begin(ctx) if err != nil { diff --git a/go/migrations/197_model_consumer_record_bodies.sql b/go/migrations/197_model_consumer_record_bodies.sql index 6b977f7f3..ac15b6480 100644 --- a/go/migrations/197_model_consumer_record_bodies.sql +++ b/go/migrations/197_model_consumer_record_bodies.sql @@ -1,20 +1,25 @@ -- ============================================================================= -- 197_model_consumer_record_bodies.sql — the recording switch of a model -- consumer: record_bodies, off by default, set by a server-admin only; its --- audit, and ctx_model_auth carrying it to the /v1 door (issue #571) +-- audit; ctx_model_auth carrying it to the /v1 door; and +-- context_llm_recordings, where a recording consumer's requests are held +-- before they are served (issue #571) -- Part of ctx by GottZ (https://github.com/GottZ/ctx) -- ============================================================================= --- What. A consumer with record_bodies = true has every gateway row of its own --- (chat, a stream included, embeddings, rerank, rows with an error) written to --- context_llm_log with the request and the answer in full — whatever --- gateway.body_logging, the alias, the consumer's prompt_sensitivity, the --- body scan or Ctx-Sensitivity say, without the 64 KiB cut of the body --- policy, and marked metadata.gw.recorded = true. Such a row can carry --- credentials in clear text: its bodies are read by a server-admin only, every --- other reader gets it as a sealed row (internal/llmlog/recorded.go). The --- switch changes nothing on the request path (required sensitivity, chain, --- scan, limits, answer) and nothing for any other consumer. Who may set it is --- the handler's rule (model-consumer-create/-update: switching on is +-- What. Every request a consumer with record_bodies = true sends through the +-- gateway — chat (a stream included), embeddings, rerank, and every request +-- the gateway refuses after the door accepted the key — gets one row in +-- context_llm_recordings (4): the request body as the gateway read it, byte +-- for byte, committed BEFORE the first backend attempt; a request that +-- cannot be held is not served (503 recording_unavailable). A non-streamed +-- answer is committed before it is written to the client; a stream's relayed +-- lines when it ends. Whatever gateway.body_logging, the alias, the +-- consumer's prompt_sensitivity, the body scan or Ctx-Sensitivity say: no +-- cut, no seal — a row can carry credentials in clear text, and no ctx +-- surface reads its bodies (internal/llmlog/recordings.go). The gateway's +-- context_llm_log row of such a request is the row every consumer gets, with +-- metadata.gw.recorded and recording_id. Who may set the switch is the +-- handler's rule (model-consumer-create/-update: switching on is -- server-admin only, also with self-service, and needs -- confirm_record_bodies; switching off is open to a tenant-admin); the column -- is the state. @@ -40,6 +45,25 @@ -- positive answer (165: design/01 E-01-9), so a switch applies from the -- next request on; a request already running keeps the value it was -- admitted with — a narrowed policy fires nothing (165). +-- (4) context_llm_recordings: one row per request of a recording consumer, +-- keyed by the request's own id (the uuid v7 the answer's id carries, +-- "chatcmpl-"). state 'open' from the insert before the first +-- backend attempt until the request ended; 'done' with the status the +-- client got, the gateway's code and the answer. A row that stays 'open' +-- is unfinished: the process ended (or the database failed) between +-- holding the request and recording its outcome — its request is there, +-- its outcome is not known; a stream row that stays 'open' may have +-- sent the client lines that are not recorded. process_id names the +-- ctxd process that admitted the request: GET /api/status counts the +-- same process's admissions, rows and the requests it could not hold +-- (docs/operations.md "Recording a consumer"). A plain table, not a +-- hypertable: the outcome is an UPDATE of the row by its primary key +-- seconds after its insert, no insert trigger counts it (the usage +-- rollup is context_llm_log's), and nothing compresses it. No foreign +-- key to the consumer: a deleted consumer's recordings stay. The +-- retention janitor (llmlog.EvictBodies) NULLs the two bodies after +-- the LLM log's retention, as it does context_llm_log's; request_bytes +-- and response_bytes keep their sizes. -- -- Cost and locks. ADD COLUMN with a constant default is a catalog change: -- ACCESS EXCLUSIVE on context_model_consumers until the commit — milliseconds; @@ -48,14 +72,24 @@ -- TRIGGER takes SHARE ROW EXCLUSIVE on the same table, inside the same -- window. DROP/CREATE FUNCTION locks no table; a session that calls -- ctx_model_auth meanwhile uses the old definition until the commit. --- lock_timeout 3s fails the boot instead of queueing behind a long --- transaction; the next start retries. The table holds at most --- max_model_consumers (64 by default) rows per tenant. +-- CREATE TABLE and its indexes lock nothing that exists. lock_timeout 3s +-- fails the boot instead of queueing behind a long transaction; the next +-- start retries. The consumer table holds at most max_model_consumers (64 by +-- default) rows per tenant. A recording consumer at 30 requests a second +-- adds 2.6 M recording rows a day: three index entries per insert (the +-- primary key, the consumer's time line, the janitor's partial index), one +-- update of the same row by its primary key that changes no indexed column +-- and no index predicate (it can stay on its page, HOT), and the janitor's +-- UPDATE over the rows that left the retention since its last run — its +-- partial index holds only rows that still carry a body. -- -- Idempotent: ADD COLUMN IF NOT EXISTS, CREATE OR REPLACE FUNCTION, DROP --- TRIGGER IF EXISTS + CREATE, DROP FUNCTION IF EXISTS + CREATE. +-- TRIGGER IF EXISTS + CREATE, DROP FUNCTION IF EXISTS + CREATE, CREATE TABLE +-- / INDEX IF NOT EXISTS. -- --- Way back, in this order, one statement each: DROP FUNCTION ctx_model_auth( +-- Way back, in this order, one statement each: DROP TABLE +-- context_llm_recordings (its rows go with it — export them first); DROP +-- FUNCTION ctx_model_auth( -- TEXT, INET, BOOLEAN); the CREATE FUNCTION ctx_model_auth of 161 section 8; -- the CREATE OR REPLACE FUNCTION audit_state_model_consumer of 161 section 7; -- DROP TRIGGER trg_model_consumers_audit_upd ON context_model_consumers and @@ -192,3 +226,34 @@ BEGIN 'bulk'::text, NULL::uuid, false; END; $$; + +-- 4. The recordings (header (4)). +CREATE TABLE IF NOT EXISTS context_llm_recordings ( + id UUID PRIMARY KEY, + created_at TIMESTAMPTZ NOT NULL DEFAULT now(), + finished_at TIMESTAMPTZ, + process_id UUID NOT NULL, + consumer_id UUID NOT NULL, + model_key_id UUID, + path TEXT NOT NULL, + op TEXT, + client_request_id TEXT, + model TEXT, + stream BOOLEAN, + declared_bytes BIGINT, + request_bytes BIGINT NOT NULL DEFAULT 0, + request_complete BOOLEAN NOT NULL DEFAULT false, + request_body BYTEA, + state TEXT NOT NULL CHECK (state IN ('open', 'done')), + status SMALLINT, + code TEXT, + response_bytes BIGINT NOT NULL DEFAULT 0, + response_body BYTEA, + CHECK ((state = 'open') = (finished_at IS NULL)) +); + +CREATE INDEX IF NOT EXISTS idx_llm_recordings_consumer + ON context_llm_recordings (consumer_id, created_at DESC); +CREATE INDEX IF NOT EXISTS idx_llm_recordings_bodies + ON context_llm_recordings (created_at) + WHERE request_body IS NOT NULL; diff --git a/go/web/src/lib/api/types.ts b/go/web/src/lib/api/types.ts index 661df7272..4265b8df1 100644 --- a/go/web/src/lib/api/types.ts +++ b/go/web/src/lib/api/types.ts @@ -694,8 +694,6 @@ export interface LLMLogDetail { request_system: string | null request_user: string | null response_content: string | null - /** The row of a recording consumer (metadata.gw.recorded, issue #571): its bodies are whole and can hold credentials in clear text. */ - recorded: boolean } // Source: go/internal/handler/llmlog.go (HandleLLMLogDetail happy path). An @@ -1526,7 +1524,7 @@ export interface ConsumerView { /** null = any source address. */ allowed_cidrs: string[] | null allow_plaintext: boolean - /** Recording (migration 197): every gateway row of the consumer keeps its request and answer in full in the LLM log — set by a server-admin, readable by server-admins only. */ + /** Recording (migration 197): every request of the consumer is held in full in context_llm_recordings before it is served — set by a server-admin, readable in the database only. */ record_bodies: boolean active: boolean status: ConsumerStatus @@ -2094,6 +2092,25 @@ export interface GatewayEnvelopeUse { * tenant tile reads the coarse depth class from `dispatch_tenant.targets` * (never a number, V-03-b). */ +/** One recording consumer's requests in this process: admitted = in_flight + recorded + unrecordable. */ +export interface GatewayRecordingConsumer { + consumer_id: string + admitted: number + in_flight: number + recorded: number + unrecordable: number + unfinished: number + stream_answers_unrecorded: number +} + +/** gateway.recording of GET /api/status (server-admin). */ +export interface GatewayRecording { + process_id: string + since: string + held_bytes: number + consumers: GatewayRecordingConsumer[] +} + export interface GatewayStatus { enabled: boolean consumers: number @@ -2110,6 +2127,8 @@ export interface GatewayStatus { consumers_expiring: number /** Ids of the active consumers with record_bodies on, sorted (the tenant's own on the tenant path); [] when none. */ recording_consumers: string[] + /** Server-admin only: this process's count of the recording consumers' requests (docs/operations.md "Recording a consumer"). */ + recording?: GatewayRecording /** Server-admin only; not assigned by stampGateway yet (S3) — absent today. */ instance_envelope?: Record /** diff --git a/go/web/src/routes/gateway/ConsumerDetail.svelte b/go/web/src/routes/gateway/ConsumerDetail.svelte index 39b754c56..89e0c7d47 100644 --- a/go/web/src/routes/gateway/ConsumerDetail.svelte +++ b/go/web/src/routes/gateway/ConsumerDetail.svelte @@ -90,10 +90,10 @@
{c.admission_lane}
network
{c.allowed_cidrs === null ? 'any source' : c.allowed_cidrs.join(', ')}
-
recording
-
- {recordingText(c.record_bodies)} -
+ {#if c.record_bodies} +
recording
+
{recordingText}
+ {/if}
last used
{c.last_used_at === null ? 'never' : fmtMinute(c.last_used_at)}
diff --git a/go/web/src/routes/gateway/ConsumerRow.svelte b/go/web/src/routes/gateway/ConsumerRow.svelte index 223dbf4b9..295c2da6c 100644 --- a/go/web/src/routes/gateway/ConsumerRow.svelte +++ b/go/web/src/routes/gateway/ConsumerRow.svelte @@ -63,10 +63,7 @@ {c.label} {#if c.description}{c.description}{/if} - - {c.kind} - {#if c.record_bodies}recording{/if} - + {c.kind}{#if c.record_bodies}recording{/if} {STATUS_LABEL[c.status] ?? c.status} diff --git a/go/web/src/routes/gateway/ConsumerRow.svelte.test.ts b/go/web/src/routes/gateway/ConsumerRow.svelte.test.ts index b4d786f9e..7c85e3b8b 100644 --- a/go/web/src/routes/gateway/ConsumerRow.svelte.test.ts +++ b/go/web/src/routes/gateway/ConsumerRow.svelte.test.ts @@ -1,7 +1,8 @@ // The recording switch in the consumer views (issue #571): a consumer with // record_bodies shows a "recording" badge in its list row and says so in the -// detail's policy card (recordingText); one without shows no badge. The flag -// is the server's — the views only render it. Server-rendered and asserted on +// detail's policy card (recordingText); one without shows neither, and its +// kind cell is the markup it always was (the visual baselines). The flag is +// the server's — the views only render it. Server-rendered and asserted on // the markup (BlockDetail test pattern: mount() is unavailable in the // node-only vitest env). @@ -33,16 +34,19 @@ describe('consumer recording', () => { expect(markup).toMatch(/>recording { + it('a consumer without the switch carries none, its kind cell as it always was', () => { const markup = row(false) expect(markup).not.toContain('data-consumer-recording') expect(markup).not.toMatch(/>recording]*>app<\/span>()?<\/td>/) }) - it('the detail text names what the rows hold and who reads them', () => { - expect(recordingText(true)).toMatch(/in full/) - expect(recordingText(true)).toMatch(/credentials/) - expect(recordingText(true)).toMatch(/server-admins/) - expect(recordingText(false)).toBe('off') + it('the detail text names what is held, where, and who reads it', () => { + expect(recordingText).toMatch(/in full/) + expect(recordingText).toMatch(/credentials/) + expect(recordingText).toMatch(/context_llm_recordings/) + expect(recordingText).toMatch(/database/) }) }) diff --git a/go/web/src/routes/gateway/format.ts b/go/web/src/routes/gateway/format.ts index 8237fd315..b2092abbe 100644 --- a/go/web/src/routes/gateway/format.ts +++ b/go/web/src/routes/gateway/format.ts @@ -22,12 +22,9 @@ export function consumerTone(status: string): 'ok' | 'warn' | 'off' { return 'off' } -/** What the consumer view says about recording (record_bodies, issue #571) — the server's flag, shown to every reader. */ -export function recordingText(on: boolean): string { - return on - ? 'on — every request and answer of this consumer is kept in full in the LLM log, credentials in a prompt included; server-admins read it' - : 'off' -} +/** What the consumer view says while recording is on (record_bodies, issue #571) — the server's flag, shown to every reader. */ +export const recordingText = + 'on — every request and answer of this consumer is held in full in context_llm_recordings, credentials in a prompt included; readable in the database only' /** Badge tone of a key status: active ok, expiring/superseded (grace running) warn, dead off. */ export function keyTone(status: ModelKeyStatus | string): 'ok' | 'warn' | 'off' { diff --git a/go/web/src/routes/status/llmlog-detail.svelte.test.ts b/go/web/src/routes/status/llmlog-detail.svelte.test.ts index edafe281f..4f847cf0a 100644 --- a/go/web/src/routes/status/llmlog-detail.svelte.test.ts +++ b/go/web/src/routes/status/llmlog-detail.svelte.test.ts @@ -22,7 +22,6 @@ function detail(over: Partial = {}): LLMLogDetail { request_system: 'you are ctx', request_user: 'hello', response_content: 'hi', - recorded: false, ...over, } } diff --git a/test.sh b/test.sh index 2e0e1deaa..04f12038c 100755 --- a/test.sh +++ b/test.sh @@ -422,8 +422,9 @@ T="T07 SCHEMA_INTEGRITY" # Tabellen, Spalten unverändert; 190 fügt context_temporal_reviews.extraction # hinzu → 71 Tabellen, context_blocks-Spalten unverändert; 191 fügt keine # Tabelle hinzu; 192 fügt context_install hinzu → 72 Tabellen, Spalten -# unverändert). -T07_EXPECT_TABLES=72 +# unverändert; 197 fügt context_llm_recordings hinzu → 73 Tabellen, +# context_blocks-Spalten unverändert). +T07_EXPECT_TABLES=73 T07_EXPECT_COLUMNS=45 t07_count_fallback() { @@ -434,7 +435,7 @@ t07_count_fallback() { if [[ "$tc" == "$T07_EXPECT_TABLES" ]] && [[ "$col" == "$T07_EXPECT_COLUMNS" ]]; then pass "$T (contract-CLI nicht verfügbar — Zähl-Fallback (Prä-Deploy); tables=$tc, columns=$col; $reason)" else - fail "$T" "Zähl-Fallback (Prä-Deploy, $reason): expected $T07_EXPECT_TABLES tables + $T07_EXPECT_COLUMNS columns (Stand Mig 192), got tables=$tc columns=$col" + fail "$T" "Zähl-Fallback (Prä-Deploy, $reason): expected $T07_EXPECT_TABLES tables + $T07_EXPECT_COLUMNS columns (Stand Mig 197), got tables=$tc columns=$col" fi } From cc6c2cfd0c5c3d230e077912f0090de25cd0cfc0 Mon Sep 17 00:00:00 2001 From: Jan-Stefan Janetzky Date: Fri, 27 Nov 2026 05:18:53 +0100 Subject: [PATCH 08/27] test(gateway): the recording account gets back what a stream's and a rerank answer's captures took Co-Authored-By: Claude Opus 5.5 --- go/internal/oai/record_route_test.go | 30 ++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) diff --git a/go/internal/oai/record_route_test.go b/go/internal/oai/record_route_test.go index b172bbc7c..6e6480a5c 100644 --- a/go/internal/oai/record_route_test.go +++ b/go/internal/oai/record_route_test.go @@ -562,6 +562,7 @@ func TestRecordingCountsBalance(t *testing.T) { ca := recordingConsumer(true) ca.ConsumerID = "0195a6f0-0000-7000-8000-0000000c0571" rig.ca.Store(ca) + held := oai.RecordingHeld() rig.post(t, chatBody("pub")) // served rig.post(t, `{"model":"pub"`) // refused before the walk store.set(func(s *recStore) { s.openErr = errors.New("down"); s.insertErr = errors.New("down") }) @@ -576,4 +577,33 @@ func TestRecordingCountsBalance(t *testing.T) { got.Admitted != got.InFlight+got.Recorded+got.Unrecordable || got.Recorded != rows { t.Errorf("counts %+v with %d rows — want admitted 4 = in flight 0 + recorded 3 + unrecordable 1, unfinished 1, recorded = rows", got, rows) } + if after := oai.RecordingHeld(); after != held { + t.Errorf("the recording account holds %d bytes after the requests ended, %d before — a request kept what it took", after, held) + } +} + +// TestRecordingAccountGivesBack: a stream's and a rerank answer's captures +// go back to the account when their requests end — served or not. +func TestRecordingAccountGivesBack(t *testing.T) { + held := oai.RecordingHeld() + sh := streamShapes[0] + u := newUpstream(t, "") + u.setRespond(sseRespond(sh.steps(), nil, nil)) + store := newRecStore(nil) + rig := newChatRig(t, []backends.Backend{u.row("spark", backends.TrustFull, 10)}, 4, 1, withStreamSettings, withRecordings(store)) + srv := serveHTTP(t, rig.router) + rig.ca.Store(recordingConsumer(true)) + _ = postStream(context.Background(), t, srv, streamBody("chat")) + store.set(func(s *recStore) { s.finishErr = errors.New("down") }) + _ = postStream(context.Background(), t, srv, streamBody("chat")) + e := newRerankEngine(t) + rstore := newRecStore(nil) + rr := newRerankRig(t, []backends.Backend{e.row("spark-rerank", 10)}, 4, 1, withRecordings(rstore)) + rr.ca.Store(recordingConsumer(true)) + _ = rr.postRerank(t, "/v1/rerank", rerankBody("rrpub", "q", []string{"d1", "d2"})) + rstore.set(func(s *recStore) { s.finishErr = errors.New("down") }) + _ = rr.postRerank(t, "/v1/rerank", rerankBody("rrpub", "q", []string{"d1", "d2"})) + if after := oai.RecordingHeld(); after != held { + t.Errorf("the recording account holds %d bytes after the requests ended, %d before", after, held) + } } From 451a3340bfc9903385463d6b83e6ffb24c6ae0e6 Mon Sep 17 00:00:00 2001 From: Jan-Stefan Janetzky Date: Fri, 27 Nov 2026 05:46:28 +0100 Subject: [PATCH 09/27] fix(gateway): recording statements take one of four slots, a stream's capture books its buffer once, and a recording refusal reaches the client before the row's second attempt From the fresh review of the round: a stream booked four times its buffer against the recording account, so long streams ended mid-way under normal load; the recording statements could bind the whole process pool while the database hung; a refused hold made the client wait for the row's second attempt too (10 s instead of 5 s). Now at most four recording statements run at once (bytes before slot, so no slot holder waits), a capture books its buffer and its final statement takes its copies past the bound, the recording_unavailable refusal is flushed before the row's last attempt, the account holds the largest refused request's row (4 x the cap), a refused rerank answer leaves no answer in its row, and a ready answer's commit is not cut by the request deadline. Docs and the migration's cost note follow. Co-Authored-By: Claude Opus 5.5 --- docs/operations.md | 12 +- go/cmd/ctxd/v1_record_integration_test.go | 20 ++- go/internal/oai/record.go | 162 ++++++++++-------- go/internal/oai/record_route_test.go | 64 +++++++ go/internal/oai/rerank.go | 1 + go/internal/schemacontract/manifest.json | 2 +- .../197_model_consumer_record_bodies.sql | 9 +- 7 files changed, 190 insertions(+), 80 deletions(-) diff --git a/docs/operations.md b/docs/operations.md index 871530632..93c7d538e 100644 --- a/docs/operations.md +++ b/docs/operations.md @@ -986,16 +986,16 @@ ctx manage model-consumer-update '' '{"id":"","record_bodies":true, **What a row holds.** `request_body` is the body as the gateway read it, byte for byte (bytea: invalid UTF-8 and NUL bytes included, no cut, no seal — a password, a token or a private key in a prompt is stored in clear text); `request_complete` says whether that is the whole body (a body cut short holds the part read), `declared_bytes` its `Content-Length`. `response_body` is the answer the client got: a non-streamed chat or rerank answer as written, a stream's relayed `data:` lines in order (without keepalives, the closing `[DONE]` or an error frame); none for embeddings (the vectors are not kept — the input is the record) and none for a refusal. `state` is `open` from the hold until the outcome is recorded, then `done` with `status` (the HTTP status the client got; `NULL` when the gateway wrote nothing — the client had gone), `code` (the gateway's code of a refusal or an error, where the refusing stage names one — the catch-alls of an unknown path and a wrong method leave it `NULL`), `finished_at`. `op`, `model` and `stream` are what the route read (`NULL` when no route parsed the request), `path` the request's path, `process_id` the ctxd process that admitted it. The row's `id` is the request's id: a chat answer's `id` is `chatcmpl-`, a rerank answer's `rerank-`, and the request's `context_llm_log` row carries it as `metadata.gw.recording_id` (with `metadata.gw.recorded: true`; that row follows `gateway.body_logging` like every other). -**Held before served.** The route commits the row — the whole request, state `open` — before the first backend attempt and before any queue wait; a request whose row cannot be committed is answered `503 recording_unavailable` (`Retry-After: 1`, `x-should-retry: true`) and no backend sees it: the database refuses the insert, or it does not answer within **5 s** (a fixed statement deadline), or the recording's memory account (below) has no room within `dispatch.external_max_wait` (20 s). A non-streamed answer is committed with the outcome before its first byte is written; if that fails, the client gets the same `503` instead of the answer (the backend ran: the meter books its usage; the client's retry is a second row). A stream relays a line only after the recording kept it in memory; its lines are committed when it ends — what a stream sent cannot be taken back, so a stream whose end cannot be committed leaves its row `open` with its request and is counted in `stream_answers_unrecorded`. A request the gateway refuses after the door accepted the key — a body that does not parse, an unknown model, a limit, a body over `gateway.max_request_bytes` (never read: the row holds its declared size), an unknown path, a wrong method — gets its row at its end, `done`, with what was read of the body. Refusals before the door (`401`, a wrong key) are not the consumer's and leave nothing. A process that dies between the hold and the outcome leaves the row `open`: its request is there, its outcome is not known. +**Held before served.** The route commits the row — the whole request, state `open` — before the first backend attempt and before any queue wait; a request whose row cannot be committed is answered `503 recording_unavailable` (`Retry-After: 1`, `x-should-retry: true`) and no backend sees it: the database refuses the insert, or it does not answer within **5 s** (a fixed statement deadline), or the recording's memory account or its statement slots (below) have no room within `dispatch.external_max_wait` (20 s). The `503` reaches the client at once; the gateway then tries once more to leave the request's row (up to another 5 s, the client does not wait for it). A non-streamed answer is committed with the outcome before its first byte is written; if that fails, the client gets the same `503` instead of the answer (the backend ran: the meter books its usage; the client's retry is a second row). A stream relays a line only after the recording kept it in memory; its lines are committed when it ends — what a stream sent cannot be taken back, so a stream whose end cannot be committed leaves its row `open` with its request and is counted in `stream_answers_unrecorded`. A request the gateway refuses after the door accepted the key — a body that does not parse, an unknown model, a limit, a body over `gateway.max_request_bytes` (never read: the row holds its declared size), an unknown path, a wrong method — gets its row at its end, `done`, with what was read of the body. Refusals before the door (`401`, a wrong key) are not the consumer's and leave nothing. A process that dies between the hold and the outcome leaves the row `open`: its request is there, its outcome is not known. -**Checking that nothing is missing.** `GET /api/status` (server-admin) carries `gateway.recording`: `process_id` and `since` (this process's start), `held_bytes` (the memory account's fill), and per recording consumer `admitted` (requests that passed the door as it), `in_flight`, `recorded` (requests whose row is in the table), `unrecordable` (requests for which no row could be written at all — refused with `recording_unavailable` while the database was away; never served), `unfinished` (rows that stayed `open` because their outcome could not be written) and `stream_answers_unrecorded` (the streams among them that had sent lines). `admitted = in_flight + recorded + unrecordable` holds at every moment, and `recorded` equals the table's rows of that consumer and process: +**Checking that nothing is missing.** `GET /api/status` (server-admin) carries `gateway.recording`: `process_id` and `since` (this process's start), `held_bytes` (the memory account's fill), and per recording consumer `admitted` (requests that passed the door as it), `in_flight`, `recorded` (requests whose row is in the table), `unrecordable` (requests for which no row could be written at all — an inference request is then refused with `recording_unavailable`, never served; see the model list below), `unfinished` (rows that stayed `open` because their outcome could not be written) and `stream_answers_unrecorded` (the streams among them that had sent lines). `admitted = in_flight + recorded + unrecordable` holds at every moment, and `recorded` equals the table's rows of that consumer and process: ```sql SELECT count(*) AS rows, count(*) FILTER (WHERE state = 'open') AS unfinished, count(*) FILTER (WHERE state = 'done' AND status BETWEEN 200 AND 299) AS answered, count(*) FILTER (WHERE state = 'done' AND status BETWEEN 200 AND 299 - AND response_bytes = 0 AND op IS DISTINCT FROM 'embed' + AND response_bytes = 0 AND op IN ('chat', 'rerank') AND stream IS NOT TRUE) AS answered_without_answer, count(*) FILTER (WHERE state = 'done' AND (status IS NULL OR status >= 400)) AS refused, count(*) FILTER (WHERE request_body IS NULL AND request_bytes > 0) AS past_retention @@ -1003,7 +1003,7 @@ SELECT count(*) AS WHERE consumer_id = '' AND process_id = ''; ``` -`answered_without_answer` is `0` by construction (a non-streamed answer is written only after its row holds it). For a time range instead of a process, filter on `created_at` (the rows of every process that ran then); the counts of processes that have ended are in their logs: every request that could not be recorded is an `ERROR` line (`a refused request of a recording consumer could not be recorded`, or `the outcome of a recorded request could not be recorded — its row stays open` with `recording_id` and `stream_answer_lost`). +`answered_without_answer` is `0` by construction (a non-streamed chat or rerank answer is written only after its row holds it). The group's other routes — the model list `GET /v1/models` — get a row too, with their status and no body (`op` `NULL`); nothing of theirs goes to a backend, so they are not held first, and one whose row cannot be written counts as `unrecordable` although it was answered. For a time range instead of a process, filter on `created_at` (the rows of every process that ran then); the counts of processes that have ended are in their logs: every request that could not be recorded is an `ERROR` line (`a refused request of a recording consumer could not be recorded`, or `the outcome of a recorded request could not be recorded — its row stays open` with `recording_id` and `stream_answer_lost`). **Reading a consumer's requests out** (psql, in order): @@ -1019,9 +1019,9 @@ SELECT created_at, id, path, op, model, stream, state, status, code, **Cost on the request path.** Only for the recording consumer: two statements in the request's time (the insert before the walk, the outcome at the end — before the answer for a non-streamed answer), see the measurement in the pull request of issue #571 (p50/p99 of a small chat and a large embeddings request with and without recording). Every other consumer passes the recording stage untouched: no write, no wait, no allocation. -**Memory.** The request's own memory stays in `gateway.inflight_budget` with the same bookings as without recording. What the recording adds — the copies a statement makes of what it carries (pgx encodes a parameter into its own buffer and that into the connection's write buffer; booked at 3 × the bytes), a stream's kept lines (its buffer's capacity, up to twice the text), a rerank answer kept before it is written, and the body of a request refused before its walk while its row is written (its in-flight reservation has ended) — is held against **one process-wide account**: 128 MiB, or 3 × the larger of `gateway.max_request_bytes` and `gateway.max_response_bytes` when that is more, so the largest request always fits. A statement waits for room (backpressure, up to the request's wait budget, else `recording_unavailable`); a stream's next line that does not fit ends the stream with `recording_unavailable` before that line is sent. At the defaults the process holds at most the 512 MiB budget + 128 MiB + its base (measured idle at 21–32 MiB) — inside the image's `GOMEMLIMIT` of 768 MiB and the container's 1536 MiB. Nothing is dropped to stay in that bound: a request that does not fit waits or is refused. +**Memory and the pool.** The request's own memory stays in `gateway.inflight_budget` with the same bookings as without recording. What the recording adds — the copies a statement makes of what it carries (pgx encodes a parameter into its own buffer and that into the connection's write buffer; measured 2.0–2.3 × the bytes, booked at 3 ×), a stream's kept lines (its buffer's capacity, up to twice the text), a rerank answer kept before it is written, and the body of a request refused before its walk while its row is written (its in-flight reservation has ended) — is held against **one process-wide account**: 128 MiB, or 4 × the larger of `gateway.max_request_bytes` and `gateway.max_response_bytes` when that is more, so the row of the largest refused request always fits. At most **4** recording statements run at once (fixed in the code, like the LLM-log writer's 4 inserts): a database that hangs binds 4 of the pool's connections, never the rest the other consumers and the knowledge API use. A statement waits for room and a slot — the hold up to `dispatch.external_max_wait`, an outcome up to its 5 s deadline — and the request is refused with `recording_unavailable` if none comes (backpressure); a stream's next line that does not fit ends the stream with `recording_unavailable` before that line is sent. The final statement of a captured answer (a stream's lines, a rerank answer) takes its copies even past the account's bound — it holds its capture already, and waiting for the room other captures hold could wait on itself —, so the account can be exceeded by at most 4 such statements' copies at once. At the defaults the process holds at most the 512 MiB budget + 128 MiB + its base (measured idle at 21–32 MiB) — inside the image's `GOMEMLIMIT` of 768 MiB — plus, while captured answers are written, the copies of at most 4 of them (3 × their size; streams of ordinary length: a few MiB) — inside the container's 1536 MiB. Nothing is dropped to stay in that bound: a request that does not fit waits or is refused. -**Size.** A row holds at most `gateway.max_request_bytes` (8 MiB) of request; a non-streamed answer is capped by its read (`gateway.max_response_bytes`, 4 MiB); a stream's lines grow with the stream. A recording consumer at 30 requests a second writes about 2.6 M rows a day. +**Size.** A row holds at most `gateway.max_request_bytes` (8 MiB) of request; a non-streamed answer is capped by its read (`gateway.max_response_bytes`, 4 MiB); a stream's lines grow with the stream. A recording consumer at 30 requests a second writes about 2.6 M rows a day. The retention NULLs the bodies but deletes no row: each row leaves a skeleton of a few hundred bytes (measured 0.2–2 KB a row before a vacuum, depending on how many of the outcome updates stayed on their page) — delete old rows by hand (`DELETE FROM context_llm_recordings WHERE created_at < …`) if that matters. **Retention.** Both bodies of a recording are NULLed after `scheduler.llmlog_retention_days` (90 days) by the same janitor that NULLs `context_llm_log`'s (`request_bytes`, `response_bytes`, the outcome and the row stay). Read them out before that if they are needed longer. diff --git a/go/cmd/ctxd/v1_record_integration_test.go b/go/cmd/ctxd/v1_record_integration_test.go index 4989baf68..35d076ca9 100644 --- a/go/cmd/ctxd/v1_record_integration_test.go +++ b/go/cmd/ctxd/v1_record_integration_test.go @@ -283,6 +283,10 @@ func TestV1RecordedConsumer(t *testing.T) { } }) t.Run("insert_hangs_not_served", func(t *testing.T) { + // Over a real server: the client gets its 503 when the hold gives up + // (the 5 s statement deadline), not after the row's second attempt. + srv := httptest.NewTLSServer(f.router) + defer srv.Close() tx, err := f.seed.Begin(ctx) if err != nil { t.Fatal(err) @@ -291,15 +295,25 @@ func TestV1RecordedConsumer(t *testing.T) { t.Fatal(err) } hits := e.hits.Load() + req, _ := http.NewRequest(http.MethodPost, srv.URL+"/v1/chat/completions", strings.NewReader(chat)) + req.Header.Set("Authorization", "Bearer "+recKey) + req.Header.Set("Content-Type", "application/json") start := time.Now() - a := f.post(t, recKey, chat) + resp, err := srv.Client().Do(req) took := time.Since(start) + if err != nil { + _ = tx.Rollback(ctx) + t.Fatalf("request: %v", err) + } + raw, _ := io.ReadAll(resp.Body) + _ = resp.Body.Close() _ = tx.Rollback(ctx) + a := v1Answer{status: resp.StatusCode, header: resp.Header, body: raw} if a.status != 503 || v1RecCode(a) != "recording_unavailable" || e.hits.Load() != hits { t.Errorf("answer %d %q after %v, %d engine calls — want 503 recording_unavailable, none", a.status, v1RecCode(a), took, e.hits.Load()-hits) } - if took < 5*time.Second { - t.Errorf("answered after %v — the statement deadline is 5 s", took) + if took < 5*time.Second || took > 8*time.Second { + t.Errorf("the client had its answer after %v — the statement deadline is 5 s", took) } }) t.Run("answer_not_held_not_written", func(t *testing.T) { diff --git a/go/internal/oai/record.go b/go/internal/oai/record.go index eb30c9e5c..5cabeefc8 100644 --- a/go/internal/oai/record.go +++ b/go/internal/oai/record.go @@ -3,6 +3,7 @@ package oai import ( "context" "errors" + "fmt" "log/slog" "net/http" "sort" @@ -48,14 +49,19 @@ import ( // with what was read of the body. A request for which no row could be // written at all is counted (unrecordable); it was refused, never served. // -// The writes are synchronous and never queued. What they copy — pgx encodes a -// parameter into its own buffer and that into the connection's write buffer -// — and what a stream or a rerank answer keeps is held against ONE -// process-wide account (recordingAccount), not against the request's -// in-flight reservation: the switch changes no booking of the request, so a -// recorded request meets the same refusals as any other plus the one of its -// own. A write waits for room in the account (backpressure); it never drops -// what it was given. +// The writes are synchronous and never queued; at most +// maxRecordingStatements of them run at once (a slot), so a hanging +// database binds that many connections of the process pool, never all of +// them. What they copy — pgx encodes a parameter into its own buffer and that +// into the connection's write buffer — and what a stream or a rerank answer +// keeps is held against ONE process-wide account (recordingAccount), not +// against the request's in-flight reservation: the switch changes no booking +// of the request, so a recorded request meets the same refusals as any other +// plus the one of its own. A write waits for a slot and for room in the +// account (backpressure); it never drops what it was given. The final +// statement of a captured answer takes its copies even past the account's +// bound (at most maxRecordingStatements at once): it already holds its +// capture, and waiting for room the other captures hold could wait on itself. // recordingMessage is its text. const recordingMessage = "The request could not be recorded; retry shortly." @@ -72,19 +78,27 @@ const recordWriteTimeout = 5 * time.Second // (recordAccountLimit) so that the largest request always fits. const recordAccountFloor = 128 << 20 +// maxRecordingStatements bounds the recording statements that run at once, +// process-wide — fixed in the code like llmlog's maxConcurrentInserts: it +// bounds the process's own use of its pool, it is no policy of anybody's. +const maxRecordingStatements = 4 + +// recordSlots are the statement slots. +var recordSlots = make(chan struct{}, maxRecordingStatements) + // recordCopyFactor is what one recording statement allocates per byte it // carries: pgx encodes the parameter into its argument buffer, the Bind // message copies it into the connection's write buffer, which grows by -// append once more on the next field (TestRecordingInsertAllocates measures -// it). Garbage after the statement, held against the account until it -// returns. +// append once more on the next field (llmlog's TestRecordingStatementCost +// measured 2.0–2.3 × for bodies of 64 KiB to 8 MiB). Garbage after the +// statement, held against the account until it returns. const recordCopyFactor = 3 -// recordAccountLimit is the account's size under s: the floor, or what one -// request's body or one answer at the caps costs a statement, whichever is -// larger. +// recordAccountLimit is the account's size under s: the floor, or what the +// row of a refused request at the caps holds while it is written — its body +// and the statement's copies —, whichever is larger. func recordAccountLimit(s Settings) int64 { - return max(int64(recordAccountFloor), recordCopyFactor*int64(max(s.MaxRequestBytes, s.MaxResponseBytes))) + return max(int64(recordAccountFloor), (1+recordCopyFactor)*int64(max(s.MaxRequestBytes, s.MaxResponseBytes))) } // errRecordingUnavailable is the cause of a run whose recording failed (a @@ -146,6 +160,16 @@ func (a *recordingAccount) acquire(ctx context.Context, n, limit int64) error { } } +// take adds n bytes whatever the bound (a captured answer's final copies). +func (a *recordingAccount) take(n int64) { + if n <= 0 { + return + } + a.mu.Lock() + a.held += n + a.mu.Unlock() +} + // release gives n bytes back and wakes the waiters. func (a *recordingAccount) release(n int64) { if n <= 0 { @@ -198,7 +222,7 @@ func (s *RecordingStage) Handler(next http.Handler) http.Handler { rr := s.begin(ca, r) defer func() { p := recover() - rr.endStage(p) + rr.endStage(p, w) if p != nil { panic(p) } @@ -220,7 +244,7 @@ func (s *RecordingStage) begin(ca *auth.ConsumerAuth, r *http.Request) *requestR if r.ContentLength < 0 { rr.req.Declared = -1 } - rr.stats = recStats.admit(ca.ConsumerID, ca.TenantID) + rr.stats = recStats.admit(ca.ConsumerID) return rr } @@ -305,8 +329,8 @@ func (rr *requestRecording) ready() bool { return rr == nil || rr.opened } // open commits the request's row before the walk; false when it cannot — // the caller refuses the request (refuseRecording) and serves nothing. The -// wait for room in the account is the dispatcher's external wait budget, -// the statement recordWriteTimeout. +// wait for room and a slot is the dispatcher's external wait budget, the +// statement recordWriteTimeout. func (rr *requestRecording) open(ctx context.Context) bool { if rr == nil || rr.opened { return true @@ -315,29 +339,46 @@ func (rr *requestRecording) open(ctx context.Context) bool { slog.Error("gateway: a recording consumer's request without a recording store (wiring defect) — refused") return false } - n := recordCopyFactor * int64(len(rr.req.Body)) - wctx, cancel := context.WithTimeout(ctx, rr.stage.maxWait()) - err := rr.acct.acquire(wctx, n, recordAccountLimit(rr.stage.settings())) - cancel() + err := rr.statement(ctx, rr.stage.maxWait(), recordCopyFactor*int64(len(rr.req.Body)), false, + func(sctx context.Context) error { return rr.stage.store.Open(sctx, rr.req) }) if err != nil { - slog.Warn("gateway: no room to record a request — refused", "consumer_id", rr.req.ConsumerID, "bytes", len(rr.req.Body), "error", err) - return false - } - defer rr.acct.release(n) - sctx, cancel := context.WithTimeout(ctx, recordWriteTimeout) - defer cancel() - if err := rr.stage.store.Open(sctx, rr.req); err != nil { - slog.Warn("gateway: a request could not be recorded — refused", "consumer_id", rr.req.ConsumerID, "error", err) + slog.Warn("gateway: a request could not be recorded — refused", "consumer_id", rr.req.ConsumerID, "bytes", len(rr.req.Body), "error", err) return false } rr.row, rr.opened = true, true return true } +// statement runs one recording statement: n bytes of the account first +// (waiting for room until wait ends; force: taken past the bound), then a +// slot (waiting until wait ends), then fn under recordWriteTimeout. In this +// order nobody waits while holding a slot — a slot holder only waits for the +// database. +func (rr *requestRecording) statement(ctx context.Context, wait time.Duration, n int64, force bool, fn func(context.Context) error) error { + wctx, cancel := context.WithTimeout(ctx, wait) + defer cancel() + if force { + rr.acct.take(n) + } else if err := rr.acct.acquire(wctx, n, recordAccountLimit(rr.stage.settings())); err != nil { + return fmt.Errorf("oai: no room to record: %w", err) + } + defer rr.acct.release(n) + select { + case recordSlots <- struct{}{}: + case <-wctx.Done(): + return fmt.Errorf("oai: no recording slot: %w", wctx.Err()) + } + defer func() { <-recordSlots }() + sctx, scancel := context.WithTimeout(ctx, recordWriteTimeout) + defer scancel() + return fn(sctx) +} + // answer commits the outcome of a non-streamed answer — status 200 and body // as the client will get it (nil: an answer not kept, the embedding // vectors) — before it is written; false when it cannot: the caller answers -// refuseRecording instead. +// refuseRecording instead. The answer is ready: the request's own deadline +// does not cut its commit short (only recordWriteTimeout does). func (rr *requestRecording) answer(ctx context.Context, body []byte) bool { if rr == nil { return true @@ -345,28 +386,22 @@ func (rr *requestRecording) answer(ctx context.Context, body []byte) bool { if !rr.opened || rr.ended { return false // the walk ran on an open row (ready); anything else is a defect } - if err := rr.finish(ctx, llmlog.RecordedOutcome{Status: http.StatusOK, Response: body}); err != nil { + if err := rr.finish(context.WithoutCancel(ctx), llmlog.RecordedOutcome{Status: http.StatusOK, Response: body}); err != nil { slog.Warn("gateway: an answer could not be recorded — refused", "consumer_id", rr.req.ConsumerID, "error", err) return false } return true } -// finish commits o on the open row, the statement's copies of o.Response -// against the account — booked here for an answer of the request's own -// (a chat answer), with the capture for a captured one (addCapture). +// finish commits o on the open row. The statement's copies of o.Response +// wait for room for an answer of the request's own (a chat answer); for a +// captured one (a stream's lines, a rerank answer) they are taken past the +// bound — the capture is held already. func (rr *requestRecording) finish(ctx context.Context, o llmlog.RecordedOutcome) error { - n := recordCopyFactor * int64(len(o.Response)) - if len(o.Response) > 0 && len(rr.capture) > 0 && &o.Response[0] == &rr.capture[0] { - n = 0 // booked with the capture - } - wctx, cancel := context.WithTimeout(ctx, recordWriteTimeout) - defer cancel() - if err := rr.acct.acquire(wctx, n, recordAccountLimit(rr.stage.settings())); err != nil { - return err - } - defer rr.acct.release(n) - if err := rr.stage.store.Finish(wctx, rr.req.ID, o); err != nil { + captured := len(o.Response) > 0 && len(rr.capture) > 0 && &o.Response[0] == &rr.capture[0] + err := rr.statement(ctx, recordWriteTimeout, recordCopyFactor*int64(len(o.Response)), captured, + func(sctx context.Context) error { return rr.stage.store.Finish(sctx, rr.req.ID, o) }) + if err != nil { return err } rr.ended = true @@ -384,10 +419,7 @@ func (rr *requestRecording) addCapture(p []byte) bool { } if need := len(rr.capture) + len(p); need > cap(rr.capture) { grown := max(2*cap(rr.capture), need) - // The buffer and, booked with it, the copies of the statement that - // will carry it (finish takes nothing more for a captured answer: - // nobody holds account bytes while waiting for more). - booked := int64(grown) * (1 + recordCopyFactor) + booked := int64(grown) // the buffer; its final statement's copies come at finish if !rr.acct.tryAcquire(booked, recordAccountLimit(rr.stage.settings())) { return false } @@ -491,14 +523,8 @@ func (rr *requestRecording) end(code string) { return } n := (1+recordCopyFactor)*int64(len(rr.req.Body)) + recordCopyFactor*int64(len(o.Response)) - wctx, cancel := context.WithTimeout(ctx, recordWriteTimeout) - defer cancel() - if err := rr.acct.acquire(wctx, n, recordAccountLimit(rr.stage.settings())); err != nil { - slog.Error("gateway: a refused request of a recording consumer could not be recorded", "consumer_id", rr.req.ConsumerID, "error", err) - return - } - defer rr.acct.release(n) - if err := rr.stage.store.Insert(wctx, rr.req, o); err != nil { + if err := rr.statement(ctx, recordWriteTimeout, n, false, + func(sctx context.Context) error { return rr.stage.store.Insert(sctx, rr.req, o) }); err != nil { slog.Error("gateway: a refused request of a recording consumer could not be recorded", "consumer_id", rr.req.ConsumerID, "error", err) return } @@ -515,7 +541,7 @@ func (rr *requestRecording) dropCapture() { // panicked: the outcome with the access record's code — a recovered panic as // the 503 internal_error oai.Recover answers, unless the response had begun // —, then the request's count. -func (rr *requestRecording) endStage(p any) { +func (rr *requestRecording) endStage(p any, w http.ResponseWriter) { code := "" if rr.access != nil { code = rr.access.Reason @@ -524,6 +550,11 @@ func (rr *requestRecording) endStage(p any) { rr.noteStatus(http.StatusServiceUnavailable) code = CodeInternalError } + if p == nil && code == CodeRecordingUnavailable { + // The database is in trouble: the client gets its 503 now, not after + // the row's own attempt below (up to recordWriteTimeout more). + _ = http.NewResponseController(w).Flush() + } rr.end(code) recStats.done(rr.stats, rr.row, rr.unfinished, rr.unfinished && rr.streamed) } @@ -573,7 +604,6 @@ func (w recordingWriter) Unwrap() http.ResponseWriter { return w.ResponseWriter // process (GET /api/status, docs/operations.md "Recording a consumer"): // admitted = in_flight + recorded + unrecordable at every moment. type recordingConsumerStats struct { - tenant string admitted, inFlight, recorded, unrecordable int64 unfinished, streamAnswersUnrecorded int64 } @@ -588,7 +618,7 @@ type recordingStats struct { var recStats = &recordingStats{by: map[string]*recordingConsumerStats{}, from: time.Now().UTC()} -func (s *recordingStats) admit(consumer, tenant string) *recordingConsumerStats { +func (s *recordingStats) admit(consumer string) *recordingConsumerStats { s.mu.Lock() defer s.mu.Unlock() c := s.by[consumer] @@ -596,7 +626,6 @@ func (s *recordingStats) admit(consumer, tenant string) *recordingConsumerStats c = &recordingConsumerStats{} s.by[consumer] = c } - c.tenant = tenant c.admitted++ c.inFlight++ return c @@ -623,11 +652,10 @@ func (s *recordingStats) done(c *recordingConsumerStats, row, unfinished, stream // (gateway.recording.consumers). type RecordingConsumer struct { ConsumerID string `json:"consumer_id"` - TenantID string `json:"-"` // Admitted requests passed the door as this consumer; each is in // flight, recorded (its row is in context_llm_recordings) or - // unrecordable (no row could be written; the request was refused, not - // served). + // unrecordable (no row could be written: an inference request was + // refused, not served; a model list may have been answered). Admitted int64 `json:"admitted"` InFlight int64 `json:"in_flight"` Recorded int64 `json:"recorded"` @@ -657,7 +685,7 @@ func RecordingStats() RecordingSnapshot { recStats.mu.Lock() snap.Since = recStats.from for id, c := range recStats.by { - snap.Consumers = append(snap.Consumers, RecordingConsumer{ConsumerID: id, TenantID: c.tenant, + snap.Consumers = append(snap.Consumers, RecordingConsumer{ConsumerID: id, Admitted: c.admitted, InFlight: c.inFlight, Recorded: c.recorded, Unrecordable: c.unrecordable, Unfinished: c.unfinished, StreamAnswersUnrecorded: c.streamAnswersUnrecorded}) } diff --git a/go/internal/oai/record_route_test.go b/go/internal/oai/record_route_test.go index 6e6480a5c..6c3aa12aa 100644 --- a/go/internal/oai/record_route_test.go +++ b/go/internal/oai/record_route_test.go @@ -70,6 +70,8 @@ type recStore struct { openErr, finishErr, insertErr error openHang bool + // finishFailures refuses that many Finish calls before it takes one. + finishFailures int } func newRecStore(hits func() int64) *recStore { @@ -106,6 +108,10 @@ func (s *recStore) Finish(_ context.Context, id string, o llmlog.RecordedOutcome if s.finishErr != nil { return s.finishErr } + if s.finishFailures > 0 { + s.finishFailures-- + return errors.New("finish refused once") + } r := s.rows[id] if r == nil || r.state != llmlog.RecordingOpen { return errors.New("no open row") @@ -607,3 +613,61 @@ func TestRecordingAccountGivesBack(t *testing.T) { t.Errorf("the recording account holds %d bytes after the requests ended, %d before", after, held) } } + +// TestRecordingWithoutStageIsRefused: a recording consumer's request that +// reaches a route without the recording stage (a wiring defect) is refused +// with recording_unavailable — never served unrecorded. +func TestRecordingWithoutStageIsRefused(t *testing.T) { + u := newUpstream(t, recChatAnswer) + rig := newChatRig(t, []backends.Backend{u.row("spark", backends.TrustFull, 10)}, 4, 1) + rig.ca.Store(recordingConsumer(true)) + a := rig.post(t, chatBody("pub")) + checkRecordingRefusal(t, a.status, a.header, a.body) + if n := u.hits.Load(); n != 0 { + t.Errorf("the backend was called %d times for a recording consumer without the stage", n) + } +} + +// TestRecordingStreamBooksItsBuffer: a stream's capture holds its buffer of +// the account, not a multiple of it — a stream whose lines fit twice into +// the room left is served whole and kept. +func TestRecordingStreamBooksItsBuffer(t *testing.T) { + sh := streamShapes[0] + u := newUpstream(t, "") + u.setRespond(sseRespond(sh.steps(), nil, nil)) + store := newRecStore(nil) + rig := newChatRig(t, []backends.Backend{u.row("spark", backends.TrustFull, 10)}, 4, 1, withStreamSettings, withRecordings(store)) + srv := serveHTTP(t, rig.router) + rig.ca.Store(recordingConsumer(true)) + first := postStream(context.Background(), t, srv, streamBody("chat")) + lines := len(store.only(t).response) + if lines == 0 { + t.Fatalf("the first stream kept nothing: %q", first.raw) + } + store.set(func(s *recStore) { s.rows = map[string]*recRow{} }) + limit := oai.RecordingAccountLimit(chatSettings()) + release := oai.FillRecordingAccount(limit - int64(oai.RecordCopyFactor*len(streamBody("chat"))) - int64(2*lines) - 64) + on := postStream(context.Background(), t, srv, streamBody("chat")) + release() + checkRelay(t, on) + if r := store.only(t); string(r.response)+"data: [DONE]\n\n" != on.raw || strings.Contains(on.raw, oai.CodeRecordingUnavailable) { + t.Errorf("a stream of %d bytes with room for twice its lines: kept %d bytes, client %q", lines, len(r.response), on.raw) + } +} + +// TestRecordingRefusedRerankKeepsNoAnswer: a rerank answer whose commit +// fails is refused, and the row it ends with carries the refusal, not the +// answer the client never got. +func TestRecordingRefusedRerankKeepsNoAnswer(t *testing.T) { + e := newRerankEngine(t) + store := newRecStore(nil) + rig := newRerankRig(t, []backends.Backend{e.row("spark-rerank", 10)}, 4, 1, withRecordings(store)) + rig.ca.Store(recordingConsumer(true)) + store.set(func(s *recStore) { s.finishFailures = 1 }) + a := rig.postRerank(t, "/v1/rerank", rerankBody("rrpub", "q", []string{"d1", "d2"})) + checkRecordingRefusal(t, a.status, a.header, a.body) + r := store.only(t) + if r.state != llmlog.RecordingDone || r.out.Status != 503 || r.out.Code != oai.CodeRecordingUnavailable || len(r.response) != 0 { + t.Errorf("row %q status %d code %q answer %d bytes — want done 503 recording_unavailable without an answer", r.state, r.out.Status, r.out.Code, len(r.response)) + } +} diff --git a/go/internal/oai/rerank.go b/go/internal/oai/rerank.go index dba32b805..7cf299351 100644 --- a/go/internal/oai/rerank.go +++ b/go/internal/oai/rerank.go @@ -972,6 +972,7 @@ func (c *rerankCall) success(st *rerankState) embedOutcome { // gets the same bytes in one write. One that cannot be kept or held // is refused instead. if err := writeRerank(captureWriter{c.recording}, a); err != nil || !c.recording.answer(c.ctx, c.recording.capture) { + c.recording.dropCapture() // not the client's answer: the row ends with the refusal only refuseRecording(c.rec, c.w) return embedOutcome{finish: llmlog.FinishError, redacted: &llmlog.RedactedErr{Class: "admission", Code: CodeRecordingUnavailable}} } diff --git a/go/internal/schemacontract/manifest.json b/go/internal/schemacontract/manifest.json index 2d9995130..fbc0ab3b6 100644 --- a/go/internal/schemacontract/manifest.json +++ b/go/internal/schemacontract/manifest.json @@ -3,7 +3,7 @@ "generated_against": { "migration_max": 197, "migration_count": 85, - "migration_chain_sha256": "3c827789b6c673076fba296c300cda4dcd4b260e42205646e1e5d3e80e15465c", + "migration_chain_sha256": "967937ebdbc2d3a32349c38bea877590899ff089bc25da34a13c2e06f1490264", "pg_major": 18, "image": "pgvector-timescaledb:pg18" }, diff --git a/go/migrations/197_model_consumer_record_bodies.sql b/go/migrations/197_model_consumer_record_bodies.sql index ac15b6480..3361bd071 100644 --- a/go/migrations/197_model_consumer_record_bodies.sql +++ b/go/migrations/197_model_consumer_record_bodies.sql @@ -79,9 +79,12 @@ -- adds 2.6 M recording rows a day: three index entries per insert (the -- primary key, the consumer's time line, the janitor's partial index), one -- update of the same row by its primary key that changes no indexed column --- and no index predicate (it can stay on its page, HOT), and the janitor's --- UPDATE over the rows that left the retention since its last run — its --- partial index holds only rows that still carry a body. +-- and no index predicate (HOT where its page has room: measured 25 % of the +-- updates for small chat rows and 78 % for 20 KB requests, before a vacuum), +-- and the janitor's UPDATE over the rows that left the retention since its +-- last run — its partial index holds only rows that still carry a body. The +-- janitor NULLs the bodies, it deletes no row: a row's skeleton (a few +-- hundred bytes) stays. -- -- Idempotent: ADD COLUMN IF NOT EXISTS, CREATE OR REPLACE FUNCTION, DROP -- TRIGGER IF EXISTS + CREATE, DROP FUNCTION IF EXISTS + CREATE, CREATE TABLE From 3198712c82f401ec5e207542d1084aee098ef347 Mon Sep 17 00:00:00 2001 From: Jan-Stefan Janetzky Date: Fri, 27 Nov 2026 05:51:10 +0100 Subject: [PATCH 10/27] test(gateway): at most four recording statements run at once while the database holds them Co-Authored-By: Claude Opus 5.5 --- go/internal/oai/record_route_test.go | 45 +++++++++++++++++++++++++++- 1 file changed, 44 insertions(+), 1 deletion(-) diff --git a/go/internal/oai/record_route_test.go b/go/internal/oai/record_route_test.go index 6c3aa12aa..61c4548d6 100644 --- a/go/internal/oai/record_route_test.go +++ b/go/internal/oai/record_route_test.go @@ -70,6 +70,10 @@ type recStore struct { openErr, finishErr, insertErr error openHang bool + // openGate, when set, holds every Open until it is closed; inOpen and + // maxInOpen count the Opens running at once. + openGate chan struct{} + inOpen, maxInOpen atomic.Int64 // finishFailures refuses that many Finish calls before it takes one. finishFailures int } @@ -80,9 +84,20 @@ func newRecStore(hits func() int64) *recStore { func (s *recStore) Open(ctx context.Context, q llmlog.RecordedRequest) error { s.calls.Add(1) + n := s.inOpen.Add(1) + defer s.inOpen.Add(-1) + for m := s.maxInOpen.Load(); n > m && !s.maxInOpen.CompareAndSwap(m, n); m = s.maxInOpen.Load() { + } s.mu.Lock() - hang, err := s.openHang, s.openErr + hang, err, gate := s.openHang, s.openErr, s.openGate s.mu.Unlock() + if gate != nil { + select { + case <-gate: + case <-ctx.Done(): + return ctx.Err() + } + } if hang { <-ctx.Done() return ctx.Err() @@ -671,3 +686,31 @@ func TestRecordingRefusedRerankKeepsNoAnswer(t *testing.T) { t.Errorf("row %q status %d code %q answer %d bytes — want done 503 recording_unavailable without an answer", r.state, r.out.Status, r.out.Code, len(r.response)) } } + +// TestRecordingStatementSlots: however many recording consumers' requests +// arrive while the database holds their statements, at most four statements +// run at once — the rest wait for a slot (and the pool keeps its other +// connections). +func TestRecordingStatementSlots(t *testing.T) { + u := newUpstream(t, recChatAnswer) + store := newRecStore(nil) + gate := make(chan struct{}) + store.set(func(s *recStore) { s.openGate = gate }) + rig := newChatRig(t, []backends.Backend{u.row("spark", backends.TrustFull, 10)}, 16, 1, withoutCensus, withRecordings(store)) + rig.ca.Store(recordingConsumer(true)) + var wg sync.WaitGroup + for range 10 { + wg.Go(func() { rig.post(t, chatBody("pub")) }) + } + deadline := time.Now().Add(3 * time.Second) + for store.inOpen.Load() < 4 && time.Now().Before(deadline) { + time.Sleep(5 * time.Millisecond) + } + time.Sleep(100 * time.Millisecond) // room for a fifth, should one get in + running := store.inOpen.Load() + close(gate) + wg.Wait() + if running != 4 || store.maxInOpen.Load() != 4 { + t.Errorf("%d Opens ran at once while the database held them (at most %d over the run) — want exactly 4", running, store.maxInOpen.Load()) + } +} From 3bbbba55bda4d61e86d2f9602f2366b78f1c6c6b Mon Sep 17 00:00:00 2001 From: Jan-Stefan Janetzky Date: Fri, 27 Nov 2026 05:53:13 +0100 Subject: [PATCH 11/27] test(gateway): the recording latency probe sends 32 embedding inputs (the alias's limit) and names a refused warm-up Co-Authored-By: Claude Opus 5.5 --- .../ctxd/v1_record_latency_integration_test.go | 18 ++++++++++-------- 1 file changed, 10 insertions(+), 8 deletions(-) diff --git a/go/cmd/ctxd/v1_record_latency_integration_test.go b/go/cmd/ctxd/v1_record_latency_integration_test.go index 242dc603d..564a002c5 100644 --- a/go/cmd/ctxd/v1_record_latency_integration_test.go +++ b/go/cmd/ctxd/v1_record_latency_integration_test.go @@ -2,7 +2,7 @@ // The latency the recording of issue #571 adds to a request (opt-in probe, // CTX_RECORD_PROBE=1): the production router over a throwaway database, -// a small chat request and a large embeddings request (1.5 MiB, below the +// a small chat request and a large embeddings request (32 inputs, 1.4 MiB, below the // scan cap), each sent alternately by the same consumer with the recording // switch off and on — the switch flipped in the consumer row between the // two (the door reads it on every request) — and the end-to-end time of the @@ -37,18 +37,20 @@ func TestV1RecordingLatency(t *testing.T) { } const n = 200 ctx := context.Background() - measure := func(t *testing.T, name string, flip func(on bool), send func() int) { + measure := func(t *testing.T, name string, flip func(on bool), send func() (int, []byte)) { t.Helper() var off, on []time.Duration for i := 0; i < 10; i++ { // warm both paths flip(i%2 == 1) - send() + if st, b := send(); st != http.StatusOK { + t.Fatalf("%s warm-up: status %d: %.300s", name, st, b) + } } for i := 0; i < 2*n; i++ { rec := i%2 == 1 flip(rec) start := time.Now() - if st := send(); st != http.StatusOK { + if st, _ := send(); st != http.StatusOK { t.Fatalf("%s request %d (recording %v): status %d", name, i, rec, st) } d := time.Since(start) @@ -72,14 +74,14 @@ func TestV1RecordingLatency(t *testing.T) { t.Fatal(err) } } - measure(t, fmt.Sprintf("chat, %d-byte body", len(body)), flip, func() int { return f.post(t, f.urgentKey, body).status }) + measure(t, fmt.Sprintf("chat, %d-byte body", len(body)), flip, func() (int, []byte) { a := f.post(t, f.urgentKey, body); return a.status, a.body }) }) t.Run("embeddings_large", func(t *testing.T) { eng := newV1EmbedEngine(t) f := newV1EmbedFixture(t, eng) - inputs := make([]string, 48) + inputs := make([]string, 32) for i := range inputs { - inputs[i] = `"` + strings.Repeat(fmt.Sprintf("chunk %02d of a corpus document ", i), 1000) + `"` + inputs[i] = `"` + strings.Repeat(fmt.Sprintf("chunk %02d of a corpus document ", i), 1500) + `"` } body := `{"model":"` + v1EmbedAlias + `","input":[` + strings.Join(inputs, ",") + `]}` flip := func(on bool) { @@ -87,6 +89,6 @@ func TestV1RecordingLatency(t *testing.T) { t.Fatal(err) } } - measure(t, fmt.Sprintf("embeddings, %d-byte body", len(body)), flip, func() int { return f.post(t, f.urgentKey, body).status }) + measure(t, fmt.Sprintf("embeddings, %d-byte body", len(body)), flip, func() (int, []byte) { a := f.post(t, f.urgentKey, body); return a.status, a.body }) }) } From 3c51ee02a2ad7a24a266d88947e4463777145573 Mon Sep 17 00:00:00 2001 From: Jan-Stefan Janetzky Date: Fri, 27 Nov 2026 06:09:48 +0100 Subject: [PATCH 12/27] test(gateway): the counts-balance test gives its consumer its own id, so repeated runs do not add up Co-Authored-By: Claude Opus 5.5 --- go/internal/oai/record_route_test.go | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/go/internal/oai/record_route_test.go b/go/internal/oai/record_route_test.go index 61c4548d6..2bee59140 100644 --- a/go/internal/oai/record_route_test.go +++ b/go/internal/oai/record_route_test.go @@ -14,6 +14,7 @@ import ( "time" "github.com/go-chi/chi/v5" + "github.com/google/uuid" "github.com/GottZ/ctx/internal/auth" "github.com/GottZ/ctx/internal/backends" @@ -581,7 +582,7 @@ func TestRecordingCountsBalance(t *testing.T) { store := newRecStore(nil) rig := newChatRig(t, []backends.Backend{u.row("spark", backends.TrustFull, 10)}, 4, 1, withRecordings(store)) ca := recordingConsumer(true) - ca.ConsumerID = "0195a6f0-0000-7000-8000-0000000c0571" + ca.ConsumerID = uuid.NewString() // its own counts: the stats are process-wide (-count=N runs again) rig.ca.Store(ca) held := oai.RecordingHeld() rig.post(t, chatBody("pub")) // served From 85a6aeef41f2b3c30e8ee94d96fb1eaf20e8d755 Mon Sep 17 00:00:00 2001 From: Jan-Stefan Janetzky Date: Fri, 27 Nov 2026 06:52:38 +0100 Subject: [PATCH 13/27] fix(llmlog): the retention janitor skips the recordings on a schema without their table TestUsageRollupSurvivesEvictBodies runs EvictBodies on the schema of migration 159; a database after the way back of 197 has no table either. Co-Authored-By: Claude Opus 5.5 --- go/internal/llmlog/llmlog.go | 9 +++++++++ go/internal/llmlog/recordings_readers_census_test.go | 3 +++ 2 files changed, 12 insertions(+) diff --git a/go/internal/llmlog/llmlog.go b/go/internal/llmlog/llmlog.go index 4d40ee2db..6ecddf912 100644 --- a/go/internal/llmlog/llmlog.go +++ b/go/internal/llmlog/llmlog.go @@ -218,6 +218,15 @@ func EvictBodies(ctx context.Context, pool *pgxpool.Pool, retentionDays int) (in if err != nil { return 0, fmt.Errorf("llmlog: evict bodies: %w", err) } + // A schema before migration 197 (or after its way back) has no + // recordings: nothing to evict there. + var present bool + if err := pool.QueryRow(ctx, `SELECT to_regclass('context_llm_recordings') IS NOT NULL`).Scan(&present); err != nil { + return tag.RowsAffected(), fmt.Errorf("llmlog: evict recording bodies: %w", err) + } + if !present { + return tag.RowsAffected(), nil + } rec, err := pool.Exec(ctx, evictRecordingBodies, retentionDays) if err != nil { return tag.RowsAffected(), fmt.Errorf("llmlog: evict recording bodies: %w", err) diff --git a/go/internal/llmlog/recordings_readers_census_test.go b/go/internal/llmlog/recordings_readers_census_test.go index 4872373c1..f7c61d135 100644 --- a/go/internal/llmlog/recordings_readers_census_test.go +++ b/go/internal/llmlog/recordings_readers_census_test.go @@ -38,6 +38,9 @@ var recordingsReaders = map[string]recordingsReader{ // The writer (Open, Finish, Insert) and the retention janitor's statement // (evictRecordingBodies, run by EvictBodies) — no SELECT anywhere. "internal/llmlog/recordings.go": {4, "writes: open, finish, insert; the retention janitor NULLs the bodies"}, + // The janitor's presence probe (EvictBodies: no table before migration + // 197) — a catalog lookup, no row read. + "internal/llmlog/llmlog.go": {1, "catalog: to_regclass presence probe of the janitor"}, // Text only: the refusal of record_bodies without its confirmation names // the table (recordConfirmRefusal) — no statement. "internal/handler/model_consumers.go": {1, "text: the confirmation refusal names the table"}, From 851e571bceb8d0ce21a7ed4b513977d853070efa Mon Sep 17 00:00:00 2001 From: Jan-Stefan Janetzky Date: Fri, 27 Nov 2026 07:27:52 +0100 Subject: [PATCH 14/27] =?UTF-8?q?fix(gateway):=20a=20recording=20consumer'?= =?UTF-8?q?s=20LLM-log=20row=20carries=20no=20bodies=20under=20any=20body?= =?UTF-8?q?=20policy=20=E2=80=94=20the=20recording=20is=20their=20one=20pl?= =?UTF-8?q?ace?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Under gateway.body_logging=full (or errors) the context_llm_log row of a recording consumer kept the request and answer the body policy allows, next to context_llm_recordings — a second copy that every reader of the LLM log (detail, export) hands out. llmlog.GatewayEntry now stores no bodies for a row marked recorded; every other column stays the row of every consumer, and the rows of other consumers are byte-identical to the base (golden, 864 rows). Co-Authored-By: Claude Opus 5.5 --- docs/api.md | 2 +- docs/operations.md | 4 +- docs/security.md | 2 +- go/cmd/ctxd/v1_record_integration_test.go | 22 ++--- go/internal/llmlog/gateway.go | 10 +- go/internal/llmlog/gateway_recorded_test.go | 51 ++++++++++ go/internal/oai/record.go | 3 +- go/internal/oai/record_route_test.go | 97 ++++++++++++++++++- go/internal/schemacontract/manifest.json | 2 +- .../197_model_consumer_record_bodies.sql | 3 +- 10 files changed, 169 insertions(+), 27 deletions(-) create mode 100644 go/internal/llmlog/gateway_recorded_test.go diff --git a/docs/api.md b/docs/api.md index a7995be66..4adbebafb 100644 --- a/docs/api.md +++ b/docs/api.md @@ -848,7 +848,7 @@ The contract every gateway route writes against (`llmlog.GatewayEntry` / `llmlog - **One LLM-log row per request.** Chat, streamed chat, embeddings and rerank each write exactly one `context_llm_log` row, failover included: `attempt` is the number of physical attempts, `metadata.chain` lists them. Pipelines are `gateway-chat`, `gateway-embeddings` and `gateway-rerank`. - **Attribution.** The row names the consumer in `consumer_id`; `api_key_id` is always `NULL` (a row with both is refused by the database). `metadata.gw` (version 1) carries `v`, `op` (`chat`/`embed`/`rerank`), `alias`, `stream`, `hop` (0–16), `claimed_chain` (display only), `peer_pipeline` (ctx peers), `usage` (`backend`/`estimated`), `ttft_ms` (streams), `client_req_id` (`[A-Za-z0-9._:-]{1,128}`, else dropped), `finish` (`stop`, `length`, `tool_calls`, `content_filter`, `error`, `aborted`) and `model_key_id` — never an origin and never a second copy of the consumer. The hourly usage rollup counts such rows as `source = 'gateway'` with the alias. -- **Bodies.** `gateway.body_logging` (global-only, hot): `none` (default) stores no prompt and no answer (`''`, shown as `bodyless`), `errors` stores the serialized request and the answer only on rows with an error, `full` on every row (a streamed answer is not stored yet — its row carries the request only); each body is capped at 64 KiB with a visible truncation marker. A credentials-class row stays `sealed` under every policy — a tenant's `tenant.devmode` does not open it — and a row with an empty or unknown sensitivity stores no body either. A **recording consumer's** rows (`record_bodies`, see [model consumer administration](#model-consumer-administration)) are no exception: they follow the policy like every row and carry `metadata.gw.recorded: true` and `recording_id` — the request's row in `context_llm_recordings`, which holds the request as read and the answer whole ([operations](operations.md#recording-a-consumer)). +- **Bodies.** `gateway.body_logging` (global-only, hot): `none` (default) stores no prompt and no answer (`''`, shown as `bodyless`), `errors` stores the serialized request and the answer only on rows with an error, `full` on every row (a streamed answer is not stored yet — its row carries the request only); each body is capped at 64 KiB with a visible truncation marker. A credentials-class row stays `sealed` under every policy — a tenant's `tenant.devmode` does not open it — and a row with an empty or unknown sensitivity stores no body either. A **recording consumer's** rows (`record_bodies`, see [model consumer administration](#model-consumer-administration)) carry **no bodies under any policy** — the recording is the one place of their request and answer — and carry `metadata.gw.recorded: true` and `recording_id` — the request's row in `context_llm_recordings`, which holds the request as read and the answer whole ([operations](operations.md#recording-a-consumer)). - **Errors.** The `error` column of a gateway row is ` ` (for example `bad_request 400 upstream_rejected`) — never the upstream response body, which can echo the prompt. - **Access log.** One INFO line `gateway request` per successful request (`consumer_id`, `model_key_id`, `tenant_id`, `op`, `alias`, `status`, `stream`, token counts, `usage`, `duration_ms`, `queue_wait_ms`, `class`, `hop`, `request_id`), on while `gateway.access_log` is `true` (default); a client that left before the handler returned is logged with `status=499` and the handler's status in `handler_status` — `0` when it wrote nothing — (at WARN with `waited_for=admission` when it left while waiting for an admission slot) (see [operations](operations.md#requests-the-client-gave-up-on)). Refusals (status ≥ 400) are never logged per request: they are counted per consumer (empty before authentication) and reason — for a refusal the [refusal ledger](#refusal-ledger) counts its `reason`, with the window's details in `detail`; otherwise the error code of the gateway or the model-key door, else `http_` — and written as at most one WARN line `gateway rejections` with `count` and `window="1m"` per minute — the flag's `404` and the door's `401` included. The global `http request` line is not written for these requests: each gateway request is one line or one count. diff --git a/docs/operations.md b/docs/operations.md index 93c7d538e..db310a5b2 100644 --- a/docs/operations.md +++ b/docs/operations.md @@ -971,7 +971,7 @@ Every LLM call ctx makes writes one row to `context_llm_log` (the telemetry behi - **Throttle.** At most **4** inserts run at once; further rows wait in a queue of at most **4 096** rows. Both numbers are fixed in the code (`internal/llmlog`): they bound ctx's own bookkeeping, not a policy anyone tunes. Before this, every row got its own goroutine and connection, so a slow database let a burst take all 20 connections. - **Losses are counted, not silent.** A row the full queue cannot take is dropped; an insert the database refuses (or that runs past its 5 s deadline) is lost. Both are counted since process start and shown to a server-admin on `GET /api/status` as `"llmlog": {"insert_failures": N, "insert_dropped": M}` — present at `0/0` too, so a zero means "nothing lost", not "not measured". The section is absent on a tenant-admin's view: the counters cover every tenant and the background. In the log, the first loss raises one `WARN` (`llmlog: insert failed, row lost` or `llmlog: insert queue full, row dropped`, with `insert_failures_total`/`insert_dropped_total`), and at most one more per minute after that however many rows are lost; every failure still has its `DEBUG` line. A rising `insert_failures` usually means the database is unreachable or `context_llm_log` is broken (missing table, failing trigger); a rising `insert_dropped` means the queue stayed full — the database has been slow or unreachable for long enough to back up 4 096 rows. - **Shutdown settles the queue, twice.** On `SIGTERM` ctxd stops HTTP (up to 15 s), settles the model gateway's meter reservations still open after that drain with their estimate and queues their request's row (up to 1 s, in memory; `gateway: open meter reservations settled with their estimate at shutdown` with the count — so the next start's budget seed counts what those requests used), writes the refusal ledger's last counts ([Migration 167](#migration-167-the-refusal-ledger-of-the-model-api); up to 5 s, `gateway: refusal ledger flushed at shutdown` in the log), ends the model gateway's loops with their final flush (up to 5 s, alongside the next step; a model key whose row another transaction holds at that moment — a rotation, a deactivation, a prune — keeps its `last_used_at` stamp pending, and the flush retries it every 100 ms for up to 4 s; stamps still unwritten then are counted in `WARN gateway: last_used_at stamps of model keys left unwritten at shutdown` with `stamps=N` — after a failed attempt an upper bound; should the gateway's own 5 s run out first, the older `WARN gateway: final flush incomplete at shutdown` appears instead, without a count) and waits up to **5 s** for every queued and running llmlog insert (the [read record](#the-read-record-in-context_access_log)'s queue settles alongside, within the same 5 s); then it waits for the scheduler to finish its running work, and settles the queue once more (up to 5 s) before it closes the pool. The first settle exists because the scheduler wait has no limit: a dream cycle that is running when the signal arrives is not cancelled, it runs to its end or to `dream.cycle_timeout` (700 s by default). If that outlasts the stop grace period, Docker kills ctxd during the wait — the HTTP side's rows have had their settle by then, and only the rows still queued from the scheduler are lost. The log says which way each settle went: `llmlog: settled at shutdown` (with `after=http` or `after=scheduler`, the elapsed time and the loss totals) or `WARN llmlog: settle at shutdown incomplete, pending rows are lost`. -- **A recording consumer's requests** ([Recording a consumer](#recording-a-consumer)) do not depend on this queue: their content is written synchronously to `context_llm_recordings` before they are served; their `context_llm_log` rows are telemetry like every other and share the queue and its counters. +- **A recording consumer's requests** ([Recording a consumer](#recording-a-consumer)) do not depend on this queue: their content is written synchronously to `context_llm_recordings` before they are served; their `context_llm_log` rows are telemetry without bodies and share the queue and its counters. - **`stop_grace_period`.** Docker waits 10 s between `SIGTERM` and `SIGKILL` unless told otherwise — too short for the 15 s HTTP drain alone. The shipped `docker-compose.yml` sets `stop_grace_period: 36s` on the `ctx` service: 15 s HTTP drain + 1 s forced meter settle + 5 s refusal ledger flush + 2 × 5 s llmlog settle = 31 s, plus 5 s margin for the scheduler wait; the model gateway's final flush (the batched `last_used_at` stamps of model keys and the last `gateway rejections` lines, at most 5 s — of it at most 4 s of retries while a key row is locked —, measured in milliseconds; `gateway: usage stamps and rejection counts flushed at shutdown` in the log, or the `WARN` with the count of stamps left unwritten) runs alongside the first settle and adds nothing. A test pins it at 31 s or more (25 s before the refusal ledger, 30 s before the forced meter settle). Keep it at least that long in your own compose file, and raise it if you raise the shutdown budget or want a running dream cycle to finish rather than be killed. ### Recording a consumer @@ -984,7 +984,7 @@ ctx manage model-consumer-update '' '{"id":"","record_bodies":true, (The consumer's `id` goes into `data`; `model-consumer-create` takes the same two fields.) From the consumer's next request on — a request already running keeps what it was admitted with — every request of it gets one row in `context_llm_recordings`; switching off is `"record_bodies": false`, which a tenant-admin of the consumer's tenant may do too. The consumer view (API, CLI `--json`, `/gateway` in the SPA) shows the switch to every reader; `GET /api/status` lists the recording consumers in `gateway.recording_consumers` and counts their requests in `gateway.recording` (server-admin). -**What a row holds.** `request_body` is the body as the gateway read it, byte for byte (bytea: invalid UTF-8 and NUL bytes included, no cut, no seal — a password, a token or a private key in a prompt is stored in clear text); `request_complete` says whether that is the whole body (a body cut short holds the part read), `declared_bytes` its `Content-Length`. `response_body` is the answer the client got: a non-streamed chat or rerank answer as written, a stream's relayed `data:` lines in order (without keepalives, the closing `[DONE]` or an error frame); none for embeddings (the vectors are not kept — the input is the record) and none for a refusal. `state` is `open` from the hold until the outcome is recorded, then `done` with `status` (the HTTP status the client got; `NULL` when the gateway wrote nothing — the client had gone), `code` (the gateway's code of a refusal or an error, where the refusing stage names one — the catch-alls of an unknown path and a wrong method leave it `NULL`), `finished_at`. `op`, `model` and `stream` are what the route read (`NULL` when no route parsed the request), `path` the request's path, `process_id` the ctxd process that admitted it. The row's `id` is the request's id: a chat answer's `id` is `chatcmpl-`, a rerank answer's `rerank-`, and the request's `context_llm_log` row carries it as `metadata.gw.recording_id` (with `metadata.gw.recorded: true`; that row follows `gateway.body_logging` like every other). +**What a row holds.** `request_body` is the body as the gateway read it, byte for byte (bytea: invalid UTF-8 and NUL bytes included, no cut, no seal — a password, a token or a private key in a prompt is stored in clear text); `request_complete` says whether that is the whole body (a body cut short holds the part read), `declared_bytes` its `Content-Length`. `response_body` is the answer the client got: a non-streamed chat or rerank answer as written, a stream's relayed `data:` lines in order (without keepalives, the closing `[DONE]` or an error frame); none for embeddings (the vectors are not kept — the input is the record) and none for a refusal. `state` is `open` from the hold until the outcome is recorded, then `done` with `status` (the HTTP status the client got; `NULL` when the gateway wrote nothing — the client had gone), `code` (the gateway's code of a refusal or an error, where the refusing stage names one — the catch-alls of an unknown path and a wrong method leave it `NULL`), `finished_at`. `op`, `model` and `stream` are what the route read (`NULL` when no route parsed the request), `path` the request's path, `process_id` the ctxd process that admitted it. The row's `id` is the request's id: a chat answer's `id` is `chatcmpl-`, a rerank answer's `rerank-`, and the request's `context_llm_log` row carries it as `metadata.gw.recording_id` (with `metadata.gw.recorded: true`; that row carries no bodies under any `gateway.body_logging` value — the recording is their one place). **Held before served.** The route commits the row — the whole request, state `open` — before the first backend attempt and before any queue wait; a request whose row cannot be committed is answered `503 recording_unavailable` (`Retry-After: 1`, `x-should-retry: true`) and no backend sees it: the database refuses the insert, or it does not answer within **5 s** (a fixed statement deadline), or the recording's memory account or its statement slots (below) have no room within `dispatch.external_max_wait` (20 s). The `503` reaches the client at once; the gateway then tries once more to leave the request's row (up to another 5 s, the client does not wait for it). A non-streamed answer is committed with the outcome before its first byte is written; if that fails, the client gets the same `503` instead of the answer (the backend ran: the meter books its usage; the client's retry is a second row). A stream relays a line only after the recording kept it in memory; its lines are committed when it ends — what a stream sent cannot be taken back, so a stream whose end cannot be committed leaves its row `open` with its request and is counted in `stream_answers_unrecorded`. A request the gateway refuses after the door accepted the key — a body that does not parse, an unknown model, a limit, a body over `gateway.max_request_bytes` (never read: the row holds its declared size), an unknown path, a wrong method — gets its row at its end, `done`, with what was read of the body. Refusals before the door (`401`, a wrong key) are not the consumer's and leave nothing. A process that dies between the hold and the outcome leaves the row `open`: its request is there, its outcome is not known. diff --git a/docs/security.md b/docs/security.md index 94e7fff0f..2491fecc6 100644 --- a/docs/security.md +++ b/docs/security.md @@ -167,7 +167,7 @@ Every refusal carries `x-should-retry: false`: the same request against the same What the gateway writes about a request, and what it never writes (design 06 §4.6): - **One body policy.** `gateway.body_logging` is the only switch for prompt and answer bodies of gateway rows in `context_llm_log` — of every consumer, a recording one (next point) included — global-only, so no tenant can raise it for itself. `none` (default) stores none; `errors` stores the serialized request and the answer on rows with an error only; `full` on every row, each capped at 64 KiB. Every row is then slimmed as for a tenant without developer mode: a credentials-class row stays sealed under every policy, whatever the tenant's `tenant.devmode` says — and so does a row whose sensitivity is empty or unknown (fail-closed, logged as a wiring defect). Embedded NUL bytes and invalid UTF-8 are cleaned before the write, so a crafted body cannot make the row — and its attribution — vanish. -- **The one exception: a recording consumer (migration 197, issue #571).** A model consumer with `record_bodies` on has every request it sends through the gateway held in `context_llm_recordings` — chat (a stream included), embeddings, rerank, and every request the gateway refuses after the door accepted its key: the body **as the gateway read it, byte for byte** (whatever `gateway.body_logging`, the alias, the consumer's `prompt_sensitivity`, the body scan or `Ctx-Sensitivity` say — no cut, no credentials seal), the answer the client got (a non-streamed chat or rerank answer; a stream's relayed lines; no embedding vectors), the status and the gateway's code. **Such a row can carry credentials in clear text** — a password or key a client puts into a prompt is stored as sent. Only a server-admin can switch it on (also with self-service, and only with `confirm_record_bodies: true`); switching it off is open to the consumer's tenant-admin; both are audited. **No ctx surface reads the table's bodies:** no REST, MCP, CLI or web route, no export, no pipeline (distill, dream, digest) — `TestRecordingsReadersCensus` fails on any production statement that names the table outside its writer and the retention janitor; a server operator reads them in the database ([operations — Recording a consumer](operations.md#recording-a-consumer)). The consumer's `context_llm_log` rows are the rows of every consumer (body policy, cap, seal), marked `metadata.gw.recorded` with the `recording_id`. **Held before served:** the request is committed to the table before the first backend attempt; a request that cannot be held — the database refuses it or does not answer within 5 s, or the recording's memory account has no room within the request's wait budget — is answered `503 recording_unavailable` (`x-should-retry: true`, `Retry-After: 1`) and reaches no backend; a non-streamed answer the table does not take is that `503` instead of the answer. **What the switch does not change:** the required sensitivity, the chain and its egress rule, the body scan and its `413`, the limits, the in-flight budget's bookings and the answer are the same with and without it — the one new refusal is `recording_unavailable`, and every database write of the recording is in the request's time; deactivating and reactivating the consumer (the switch stays as it was); every other consumer (no stage, no write, no wait — their requests pass the recording stage untouched); the retention — the bodies are NULLed after `scheduler.llmlog_retention_days` (90) like every body; and a database backup (`backup.sh`), which carries them like every other content of the database. +- **The one exception: a recording consumer (migration 197, issue #571).** A model consumer with `record_bodies` on has every request it sends through the gateway held in `context_llm_recordings` — chat (a stream included), embeddings, rerank, and every request the gateway refuses after the door accepted its key: the body **as the gateway read it, byte for byte** (whatever `gateway.body_logging`, the alias, the consumer's `prompt_sensitivity`, the body scan or `Ctx-Sensitivity` say — no cut, no credentials seal), the answer the client got (a non-streamed chat or rerank answer; a stream's relayed lines; no embedding vectors), the status and the gateway's code. **Such a row can carry credentials in clear text** — a password or key a client puts into a prompt is stored as sent. Only a server-admin can switch it on (also with self-service, and only with `confirm_record_bodies: true`); switching it off is open to the consumer's tenant-admin; both are audited. **No ctx surface reads the table's bodies:** no REST, MCP, CLI or web route, no export, no pipeline (distill, dream, digest) — `TestRecordingsReadersCensus` fails on any production statement that names the table outside its writer and the retention janitor; a server operator reads them in the database ([operations — Recording a consumer](operations.md#recording-a-consumer)). The consumer's `context_llm_log` rows carry **no bodies under any `gateway.body_logging` value** — the recording is the one place of its request and answer, so no reader of the LLM log (its list, detail and export) has them — and are marked `metadata.gw.recorded` with the `recording_id`; their other columns are those of every consumer's. **Held before served:** the request is committed to the table before the first backend attempt; a request that cannot be held — the database refuses it or does not answer within 5 s, or the recording's memory account has no room within the request's wait budget — is answered `503 recording_unavailable` (`x-should-retry: true`, `Retry-After: 1`) and reaches no backend; a non-streamed answer the table does not take is that `503` instead of the answer. **What the switch does not change:** the required sensitivity, the chain and its egress rule, the body scan and its `413`, the limits, the in-flight budget's bookings and the answer are the same with and without it — the one new refusal is `recording_unavailable`, and every database write of the recording is in the request's time; deactivating and reactivating the consumer (the switch stays as it was); every other consumer (no stage, no write, no wait — their requests pass the recording stage untouched); the retention — the bodies are NULLed after `scheduler.llmlog_retention_days` (90) like every body; and a database backup (`backup.sh`), which carries them like every other content of the database. - **Error redaction.** The `error` column of a gateway row holds only class, status and ctx code. The upstream response body (which can echo prompt fragments, and which tenant-admins would read in the LLM log list) never reaches it; class and code must have the shape of vocabulary words (lower snake case, at most 64 characters), anything else is stored as `[redacted]`; the writer takes the code from the gateway's own code vocabulary, never from the upstream answer. - **One identity.** A gateway row is attributed to the consumer (`consumer_id`); a knowledge key id that reached the row anyway is cleared with an ERROR line, and the database refuses any row carrying both. The model key id is kept in `metadata.gw.model_key_id` for key-leak forensics, never as a column. - **Access log.** A successful request is one `gateway request` line with ids, op, alias, status, token counts and timings (`gateway.access_log`, default on) — no consumer label, no content, never a key, its hint or a query string. Refusals are counted per (consumer, reason — a code of the gateway or door vocabulary, else `http_`) and logged as one `gateway rejections` WARN line per minute with the count, so a flood of `401`/`429` answers cannot rotate the error and security lines out of the 50 MB × 3 container log. The global request log stays silent for these requests. diff --git a/go/cmd/ctxd/v1_record_integration_test.go b/go/cmd/ctxd/v1_record_integration_test.go index 35d076ca9..f361962b6 100644 --- a/go/cmd/ctxd/v1_record_integration_test.go +++ b/go/cmd/ctxd/v1_record_integration_test.go @@ -227,21 +227,19 @@ func TestV1RecordedConsumer(t *testing.T) { if n := len(v1RecRows(t, f, plainID)); n != 0 { t.Errorf("the consumer without the switch has %d recordings, want none", n) } - // Its llmlog row is the row of every consumer, plus the marker. + // Its llmlog row is the row of every consumer without bodies, plus + // the marker. f.settle(t) - var recUser, plainUser, sens, recorded, recordingID string - if err := f.seed.QueryRow(ctx, `SELECT COALESCE(request_user, ''), COALESCE(required_sensitivity, ''), COALESCE(metadata->'gw'->>'recorded', ''), - COALESCE(metadata->'gw'->>'recording_id', '') FROM context_llm_log WHERE consumer_id = $1::uuid ORDER BY created_at DESC LIMIT 1`, recID). - Scan(&recUser, &sens, &recorded, &recordingID); err != nil { + var recUser, recAnswer, sens, recorded, recordingID string + if err := f.seed.QueryRow(ctx, `SELECT COALESCE(request_user, ''), COALESCE(response_content, ''), COALESCE(required_sensitivity, ''), + COALESCE(metadata->'gw'->>'recorded', ''), COALESCE(metadata->'gw'->>'recording_id', '') + FROM context_llm_log WHERE consumer_id = $1::uuid ORDER BY created_at DESC LIMIT 1`, recID). + Scan(&recUser, &recAnswer, &sens, &recorded, &recordingID); err != nil { t.Fatalf("llmlog row: %v", err) } - if err := f.seed.QueryRow(ctx, `SELECT COALESCE(request_user, '') FROM context_llm_log WHERE consumer_id = $1::uuid ORDER BY created_at DESC LIMIT 1`, plainID). - Scan(&plainUser); err != nil { - t.Fatalf("plain llmlog row: %v", err) - } - if recorded != "true" || recordingID != r.id || recUser != plainUser || sens != string(backends.SensCredentials) { - t.Errorf("llmlog row: recorded %q recording_id %q (want %q), bodies as the plain consumer's %v, class %q", - recorded, recordingID, r.id, recUser == plainUser, sens) + if recorded != "true" || recordingID != r.id || recUser != "" || recAnswer != "" || sens != string(backends.SensCredentials) { + t.Errorf("llmlog row: recorded %q recording_id %q (want %q), bodies %d/%d bytes (want none), class %q", + recorded, recordingID, r.id, len(recUser), len(recAnswer), sens) } }) t.Run("open_while_the_engine_holds_it", func(t *testing.T) { diff --git a/go/internal/llmlog/gateway.go b/go/internal/llmlog/gateway.go index 0ffbbce10..798b34232 100644 --- a/go/internal/llmlog/gateway.go +++ b/go/internal/llmlog/gateway.go @@ -375,8 +375,9 @@ type GatewayRow struct { // (auth.ConsumerAuth.RecordBodies, migration 197), RecordingID the // request's row in context_llm_recordings (recordings.go), which holds // its request and answer whole. The row here is the row of every other - // consumer — the body policy, the cap and the seal apply as always — - // plus metadata.gw.recorded and recording_id. + // consumer without its bodies — none under any body policy: the + // recording is their one place — plus metadata.gw.recorded and + // recording_id. Recorded bool RecordingID string } @@ -427,7 +428,10 @@ func GatewayEntry(r GatewayRow) Entry { case BodyLoggingErrors: store = r.Err != nil } - if store && bodiesAllowed(e.RequiredSensitivity, e.Pipeline) { + // A recording consumer's request and answer are in context_llm_recordings + // alone (recordings.go): its row here carries no bodies under any policy, + // so no reader of the LLM log — its detail, its export — has them. + if store && !r.Recorded && bodiesAllowed(e.RequiredSensitivity, e.Pipeline) { e.RequestUser, e.ResponseContent = capBody(r.Request), capBody(r.Response) } return e.Slimmed(false) diff --git a/go/internal/llmlog/gateway_recorded_test.go b/go/internal/llmlog/gateway_recorded_test.go new file mode 100644 index 000000000..3929cfac4 --- /dev/null +++ b/go/internal/llmlog/gateway_recorded_test.go @@ -0,0 +1,51 @@ +package llmlog + +import ( + "testing" +) + +// The context_llm_log row of a recording consumer (issue #571) carries no +// bodies under any gateway.body_logging value: its request and answer live in +// context_llm_recordings alone, the one place only a server operator reads. +// Every other column of the row is the row the same request of an unrecorded +// consumer gets (the golden of TestGatewayUnrecordedRowsMatchTheBase), plus +// the marker metadata.gw.recorded with its recording_id, so a reader can +// tell the row apart. The matrix is the golden's: every pipeline, policy, +// sensitivity, error and body shape. +func TestGatewayRecordedRowsCarryNoBodies(t *testing.T) { + const recordingID = "0195a6f0-0000-7000-8000-0000000f0571" + names, rows := unrecordedMatrix() + withBodies := 0 + for _, n := range names { + plain := GatewayEntry(rows[n]) + if plain.RequestUser != "" || plain.ResponseContent != "" { + withBodies++ + } + r := rows[n] + r.Recorded, r.RecordingID = true, recordingID + e := GatewayEntry(r) + if e.RequestSystem != "" || e.RequestUser != "" || e.ResponseContent != "" { + t.Errorf("%s: the recorded row carries bodies (system %d, user %d, response %d bytes) — want none", + n, len(e.RequestSystem), len(e.RequestUser), len(e.ResponseContent)) + continue + } + gw, _ := e.Metadata["gw"].(gatewayWire) + if !gw.Recorded || gw.RecordingID != recordingID { + t.Errorf("%s: metadata.gw recorded %v recording_id %q — want true %q", n, gw.Recorded, gw.RecordingID, recordingID) + continue + } + // Without the bodies and the marker, the row is the unrecorded one. + plainGW, _ := plain.Metadata["gw"].(gatewayWire) + gw.Recorded, gw.RecordingID = false, "" + e.Metadata["gw"] = gw + plain.RequestUser, plain.ResponseContent = "", "" + plain.Metadata["gw"] = plainGW + if got, want := goldenLine(n, e), goldenLine(n, plain); got != want { + t.Errorf("the recorded row differs from the unrecorded one beyond bodies and marker:\n got %s\n want %s", got, want) + } + } + if withBodies == 0 { + t.Fatal("no unrecorded row of the matrix carries bodies: the matrix does not reach a body policy that stores them") + } + t.Logf("%d rows; %d of them carry bodies unrecorded, none recorded", len(names), withBodies) +} diff --git a/go/internal/oai/record.go b/go/internal/oai/record.go index 5cabeefc8..9d9629956 100644 --- a/go/internal/oai/record.go +++ b/go/internal/oai/record.go @@ -461,7 +461,8 @@ func (rr *requestRecording) id() string { } // mark puts the recording on the request's llmlog row: metadata.gw.recorded -// and recording_id; the row's bodies stay the body policy's. Nil-safe. +// and recording_id — and the row carries no bodies (llmlog.GatewayEntry): +// the recording is their one place. Nil-safe. func (rr *requestRecording) mark(row *llmlog.GatewayRow) { if rr == nil { return diff --git a/go/internal/oai/record_route_test.go b/go/internal/oai/record_route_test.go index 2bee59140..07f25d0ef 100644 --- a/go/internal/oai/record_route_test.go +++ b/go/internal/oai/record_route_test.go @@ -211,8 +211,9 @@ const recChatAnswer = `{"id":"gen-1","object":"chat.completion","created":170000 // recording consumer's request is in the store — the exact bytes sent, a // credentials pattern past 64 KiB included — before the backend saw it; the // row ends done with the answer the client got (embeddings: none); the -// answer, the upstream body and the llmlog row's bodies are those of the -// same request without the switch; the llmlog row names the recording. +// answer, the upstream body and the required class are those of the same +// request without the switch; the llmlog row names the recording and +// carries no bodies (TestRecordedLLMLogRowCarriesNoBodies). func TestRecordingHoldsTheRequestBeforeAnyBackend(t *testing.T) { long := strings.Repeat("abcdefgh", 12<<10) // 96 KiB, past the 64 KiB cap t.Run("chat", func(t *testing.T) { @@ -252,9 +253,9 @@ func TestRecordingHoldsTheRequestBeforeAnyBackend(t *testing.T) { t.Fatalf("llmlog rows %d: recorded %v/%v, recording id %q (want %q)", len(rows), rows[0].Recorded, rows[1].Recorded, rows[1].RecordingID, r.req.ID) } eo, en := llmlog.GatewayEntry(rows[0]), llmlog.GatewayEntry(rows[1]) - if eo.RequestUser != en.RequestUser || eo.ResponseContent != en.ResponseContent || en.RequiredSensitivity != eo.RequiredSensitivity { - t.Errorf("the llmlog row's bodies or class differ with the switch: %d/%d vs %d/%d bytes, %q vs %q", - len(eo.RequestUser), len(eo.ResponseContent), len(en.RequestUser), len(en.ResponseContent), eo.RequiredSensitivity, en.RequiredSensitivity) + if en.RequestUser != "" || en.ResponseContent != "" || en.RequiredSensitivity != eo.RequiredSensitivity { + t.Errorf("the recorded llmlog row: %d/%d body bytes (want none), class %q vs %q without the switch", + len(en.RequestUser), len(en.ResponseContent), en.RequiredSensitivity, eo.RequiredSensitivity) } }) t.Run("stream", func(t *testing.T) { @@ -715,3 +716,89 @@ func TestRecordingStatementSlots(t *testing.T) { t.Errorf("%d Opens ran at once while the database held them (at most %d over the run) — want exactly 4", running, store.maxInOpen.Load()) } } + +// TestRecordedLLMLogRowCarriesNoBodies: under gateway.body_logging=full, the +// context_llm_log row of a recording consumer's request carries no bodies — +// its request and answer are in context_llm_recordings alone — while the row +// of the same request without the switch carries both; the recorded row is +// marked with its recording id. Chat, a stream, embeddings and rerank. +func TestRecordedLLMLogRowCarriesNoBodies(t *testing.T) { + check := func(t *testing.T, rig *chatRig, store *recStore) { + t.Helper() + rows := rig.rows.all() + if len(rows) != 2 { + t.Fatalf("%d llmlog rows, want 2 (off, on)", len(rows)) + } + off, on := llmlog.GatewayEntry(rows[0]), llmlog.GatewayEntry(rows[1]) + if off.RequestUser == "" { + t.Fatalf("the unrecorded row carries no request under body_logging=full (handed %d bytes, sensitivity %q) — the test does not reach the body policy", + len(rows[0].Request), off.RequiredSensitivity) + } + if on.RequestSystem != "" || on.RequestUser != "" || on.ResponseContent != "" { + t.Errorf("the recorded llmlog row carries bodies (request %d, response %d bytes) — want none, the recording holds them", + len(on.RequestUser), len(on.ResponseContent)) + } + if r := store.only(t); !rows[1].Recorded || rows[1].RecordingID != r.req.ID { + t.Errorf("recorded row: recorded %v recording_id %q, want true %q", rows[1].Recorded, rows[1].RecordingID, r.req.ID) + } + } + full := func(s *oai.Settings) { s.BodyLogging = llmlog.BodyLoggingFull } + t.Run("chat", func(t *testing.T) { + u := newUpstream(t, recChatAnswer) + store := newRecStore(nil) + rig := newChatRig(t, []backends.Backend{u.row("spark", backends.TrustFull, 10)}, 4, 1, withRecordings(store)) + rig.setSettings(full) + for _, on := range []bool{false, true} { + rig.ca.Store(recordingConsumer(on)) + if a := rig.post(t, chatBody("pub")); a.status != 200 { + t.Fatalf("switch %v: %d %s", on, a.status, a.body) + } + } + check(t, rig, store) + }) + t.Run("stream", func(t *testing.T) { + u := newUpstream(t, "") + u.setRespond(sseRespond(streamShapes[0].steps(), nil, nil)) + store := newRecStore(nil) + rig := newChatRig(t, []backends.Backend{u.row("spark", backends.TrustFull, 10)}, 4, 1, withStreamSettings, withRecordings(store)) + rig.setSettings(full) + srv := serveHTTP(t, rig.router) + for _, on := range []bool{false, true} { + rig.ca.Store(recordingConsumer(on)) + if a := postStream(context.Background(), t, srv, streamBody("pub")); a.status != 200 || !strings.Contains(a.raw, "data: [DONE]") { + t.Fatalf("switch %v: stream %d %q", on, a.status, a.raw) + } + } + check(t, rig, store) + }) + t.Run("embeddings", func(t *testing.T) { + e := newEmbedEngine(t, 8) + store := newRecStore(nil) + rig := newEmbedRig(t, []backends.Backend{e.row("spark-embed", backends.ProtocolOpenAI, 10)}, 4, 1, withRecordings(store)) + rig.setSettings(full) + // A public embedding alias: the body policy stores bodies only below + // credentials. + rig.reg.reload(t, append(embedAliases(), chatAlias{"00000000-0000-4000-8000-0000000e0571", backends.GlobalScope, "embpub", + "embedding", "embed", backends.SensPublic, `{"embedding.native_dims":8,"embedding.max_inputs":8}`, true})) + for _, on := range []bool{false, true} { + rig.ca.Store(recordingConsumer(on)) + if a := rig.postEmbed(t, embedBody("embpub", []string{"first", "second"})); a.status != 200 { + t.Fatalf("switch %v: %d %s", on, a.status, a.body) + } + } + check(t, rig, store) + }) + t.Run("rerank", func(t *testing.T) { + e := newRerankEngine(t) + store := newRecStore(nil) + rig := newRerankRig(t, []backends.Backend{e.row("spark-rerank", 10)}, 4, 1, withRecordings(store)) + rig.setSettings(full) + for _, on := range []bool{false, true} { + rig.ca.Store(recordingConsumer(on)) + if a := rig.postRerank(t, "/v1/rerank", rerankBody("rrpub", "which?", []string{"d1", "d2"})); a.status != 200 { + t.Fatalf("switch %v: %d %s", on, a.status, a.body) + } + } + check(t, rig, store) + }) +} diff --git a/go/internal/schemacontract/manifest.json b/go/internal/schemacontract/manifest.json index fbc0ab3b6..d92b1d8c4 100644 --- a/go/internal/schemacontract/manifest.json +++ b/go/internal/schemacontract/manifest.json @@ -3,7 +3,7 @@ "generated_against": { "migration_max": 197, "migration_count": 85, - "migration_chain_sha256": "967937ebdbc2d3a32349c38bea877590899ff089bc25da34a13c2e06f1490264", + "migration_chain_sha256": "2eba65c81991bb709597a4ac27591a014897f1c4e7ea1416347af4af115fbdf3", "pg_major": 18, "image": "pgvector-timescaledb:pg18" }, diff --git a/go/migrations/197_model_consumer_record_bodies.sql b/go/migrations/197_model_consumer_record_bodies.sql index 3361bd071..e38f87e39 100644 --- a/go/migrations/197_model_consumer_record_bodies.sql +++ b/go/migrations/197_model_consumer_record_bodies.sql @@ -17,7 +17,8 @@ -- consumer's prompt_sensitivity, the body scan or Ctx-Sensitivity say: no -- cut, no seal — a row can carry credentials in clear text, and no ctx -- surface reads its bodies (internal/llmlog/recordings.go). The gateway's --- context_llm_log row of such a request is the row every consumer gets, with +-- context_llm_log row of such a request is the row every consumer gets +-- without its bodies (none under any gateway.body_logging value), with -- metadata.gw.recorded and recording_id. Who may set the switch is the -- handler's rule (model-consumer-create/-update: switching on is -- server-admin only, also with self-service, and needs From 4e734042506a46380a98689559148a39163e6658 Mon Sep 17 00:00:00 2001 From: Jan-Stefan Janetzky Date: Fri, 27 Nov 2026 07:32:23 +0100 Subject: [PATCH 15/27] fix(handler): model-consumer-update names the recording switch as read, also when its re-read after the write fails An update that did not name record_bodies returned the written row with the switch unread (false); when the re-read after the write failed, the answer fell back to that row and reported a recording consumer as not recording. The update now always reads the switch beside the consumer it judges, and an update that does not touch it answers with that value. Co-Authored-By: Claude Opus 5.5 --- go/internal/handler/model_consumers.go | 11 +- ..._consumers_record_view_integration_test.go | 137 ++++++++++++++++++ 2 files changed, 147 insertions(+), 1 deletion(-) create mode 100644 go/internal/handler/model_consumers_record_view_integration_test.go diff --git a/go/internal/handler/model_consumers.go b/go/internal/handler/model_consumers.go index eb9ada6fe..50c4cc4d8 100644 --- a/go/internal/handler/model_consumers.go +++ b/go/internal/handler/model_consumers.go @@ -964,7 +964,9 @@ func (h *ManageHandler) handleModelConsumerUpdate(w http.ResponseWriter, r *http pol := h.consumerPolicy() access := accessOf(ar) cur, err := store.GetConsumer(r.Context(), h.pool, u.id, access, time.Now()) - if err == nil && u.patch.RecordBodies != nil { + if err == nil { + // Always read: the tiers compare it when the patch names it, and the + // answer's fallback below names it when the patch does not. err = h.readRecordBodies(r, []*store.ModelConsumer{&cur}) } if err != nil { @@ -1007,6 +1009,13 @@ func (h *ManageHandler) handleModelConsumerUpdate(w http.ResponseWriter, r *http writeConsumerStoreError(w, r, err, "model-consumer-update") return } + if u.patch.RecordBodies == nil { + // The update neither read nor wrote the switch (store + // ModelConsumer.RecordBodies): the written row carries it as read + // above, never an unread false — freshConsumerView falls back to + // that row when its re-read fails. + c.RecordBodies = cur.RecordBodies + } writeJSON(w, http.StatusOK, map[string]any{"success": true, "consumer": h.freshConsumerView(r, ar, pol, c, nil)}) } diff --git a/go/internal/handler/model_consumers_record_view_integration_test.go b/go/internal/handler/model_consumers_record_view_integration_test.go new file mode 100644 index 000000000..fa2fe4202 --- /dev/null +++ b/go/internal/handler/model_consumers_record_view_integration_test.go @@ -0,0 +1,137 @@ +//go:build integration + +// The read form of model-consumer-update never reports a recording state it +// did not read (issue #571, T1 of the review of PR #573): an update that does +// not name record_bodies leaves the switch as it is, and the consumer it +// answers with names the switch as read — also when the re-read after the +// write fails and the answer falls back to the written row, whose update did +// not read the column. +// +// The re-read is made to fail through the handler's own pool: a query tracer +// notes the commit of the transaction that updated context_model_consumers, +// and from then on the pool's PrepareConn refuses every acquire — the +// production handler, store and database, with the one fault the fallback +// exists for. +// +// go test -tags=integration -p 1 -run 'TestModelConsumerUpdateViewNamesTheReadSwitch' ./internal/handler/ -count=1 -v +package handler + +import ( + "context" + "errors" + "net/http" + "strings" + "sync" + "sync/atomic" + "testing" + + "github.com/jackc/pgx/v5" + "github.com/jackc/pgx/v5/pgxpool" + + "github.com/GottZ/ctx/internal/testdb" +) + +// errReReadRefused is the fault the pool injects after the update's commit. +var errReReadRefused = errors.New("test: the pool refuses connections after the update committed") + +// commitTrap is a query tracer: once a connection that ran an UPDATE of +// context_model_consumers commits, tripped is set. +type commitTrap struct { + armed atomic.Bool + tripped atomic.Bool + mu sync.Mutex + updated map[*pgx.Conn]bool +} + +type commitTrapSQL struct{} + +func (c *commitTrap) TraceQueryStart(ctx context.Context, conn *pgx.Conn, data pgx.TraceQueryStartData) context.Context { + if c.armed.Load() && strings.Contains(data.SQL, "UPDATE context_model_consumers") { + c.mu.Lock() + c.updated[conn] = true + c.mu.Unlock() + } + return context.WithValue(ctx, commitTrapSQL{}, data.SQL) +} + +func (c *commitTrap) TraceQueryEnd(ctx context.Context, conn *pgx.Conn, data pgx.TraceQueryEndData) { + sql, _ := ctx.Value(commitTrapSQL{}).(string) + if data.Err != nil || !strings.EqualFold(strings.TrimSpace(sql), "commit") { + return + } + c.mu.Lock() + hit := c.updated[conn] + delete(c.updated, conn) + c.mu.Unlock() + if hit { + c.tripped.Store(true) + } +} + +func TestModelConsumerUpdateViewNamesTheReadSwitch(t *testing.T) { + if testing.Short() { + t.Skip("integration test") + } + ctx := context.Background() + pool := testdb.SetupTestDB(t) + h := mcHandler(t, pool, false, false) + admin, _ := kaServerAdmin(ctx, t, pool) + a := auMakeTenant(ctx, t, pool, h, admin, "rec-view") + recordOf := func(resp map[string]any) any { + c, _ := resp["consumer"].(map[string]any) + return c["record_bodies"] + } + status, body, resp := mcCall(t, h, admin, "model-consumer-create", + map[string]any{"label": "rec-view-on", "tenant_id": a.id, "record_bodies": true, "confirm_record_bodies": true}) + if status != http.StatusOK || recordOf(resp) != true { + t.Fatalf("create the recording consumer: %d %s", status, body) + } + id := resp["consumer"].(map[string]any)["id"].(string) + + // The handler under test runs over a pool of its own that refuses every + // connection once the update's transaction has committed. + trap := &commitTrap{updated: map[*pgx.Conn]bool{}} + cfg := pool.Config().Copy() + cfg.ConnConfig.Tracer = trap + cfg.PrepareConn = func(context.Context, *pgx.Conn) (bool, error) { + if trap.tripped.Load() { + return true, errReReadRefused + } + return true, nil + } + faulty, err := pgxpool.NewWithConfig(ctx, cfg) + if err != nil { + t.Fatalf("pool: %v", err) + } + t.Cleanup(faulty.Close) + hf := mcHandler(t, faulty, false, false) + + for _, tc := range []struct { + name string + data map[string]any + }{ + {"label_only", map[string]any{"id": id, "label": "rec-view-renamed"}}, + {"active_only", map[string]any{"id": id, "active": true}}, + } { + t.Run(tc.name, func(t *testing.T) { + trap.tripped.Store(false) + trap.armed.Store(true) + status, body, resp := mcCall(t, hf, admin, "model-consumer-update", tc.data) + trap.armed.Store(false) + if !trap.tripped.Load() { + t.Fatalf("the update's commit was not seen (%d %s): the re-read did not fail, the test does not reach the fallback", status, body) + } + trap.tripped.Store(false) + if status != http.StatusOK { + t.Fatalf("update: %d %s, want 200 (the update committed)", status, body) + } + if got := recordOf(resp); got != true { + t.Errorf("the update's answer reads record_bodies %v for a consumer that records (re-read failed) — want true, the state as read", got) + } + // The consumer still records: the update did not touch the switch. + if _, _, r := mcCall(t, h, admin, "model-consumer-get", map[string]any{"id": id}); recordOf(r) != true { + t.Fatalf("model-consumer-get reads record_bodies %v after an update that did not name it", recordOf(r)) + } + }) + } +} From a44cf2761992136bdaf681148ed0f34f2f4a214a Mon Sep 17 00:00:00 2001 From: Jan-Stefan Janetzky Date: Fri, 27 Nov 2026 07:40:31 +0100 Subject: [PATCH 16/27] fix(gateway): an answer of a recording consumer that is not a 2xx is held until its row holds it with its bytes MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The recording kept a non-streamed answer's body only on success: an error the client got after the walk — a backend's rejection whose text the gateway relays, an embeddings refusal naming its input — left the row with status and code only, although its body is neither fixed nor derivable from them. The stage's writer now holds every answer that is not a 2xx (except the 503 recording_unavailable, which goes out at once) until the request's outcome is committed with its bytes, then writes it; a row that cannot take it after a backend was asked is that 503 in its place. A refusal before the walk keeps its bytes in its row too. Co-Authored-By: Claude Opus 5.5 --- docs/operations.md | 4 +- docs/security.md | 2 +- go/internal/oai/record.go | 153 ++++++++++++++++-- go/internal/oai/record_route_test.go | 83 +++++++++- go/internal/schemacontract/manifest.json | 2 +- .../197_model_consumer_record_bodies.sql | 4 +- 6 files changed, 232 insertions(+), 16 deletions(-) diff --git a/docs/operations.md b/docs/operations.md index db310a5b2..e4770e981 100644 --- a/docs/operations.md +++ b/docs/operations.md @@ -984,9 +984,9 @@ ctx manage model-consumer-update '' '{"id":"","record_bodies":true, (The consumer's `id` goes into `data`; `model-consumer-create` takes the same two fields.) From the consumer's next request on — a request already running keeps what it was admitted with — every request of it gets one row in `context_llm_recordings`; switching off is `"record_bodies": false`, which a tenant-admin of the consumer's tenant may do too. The consumer view (API, CLI `--json`, `/gateway` in the SPA) shows the switch to every reader; `GET /api/status` lists the recording consumers in `gateway.recording_consumers` and counts their requests in `gateway.recording` (server-admin). -**What a row holds.** `request_body` is the body as the gateway read it, byte for byte (bytea: invalid UTF-8 and NUL bytes included, no cut, no seal — a password, a token or a private key in a prompt is stored in clear text); `request_complete` says whether that is the whole body (a body cut short holds the part read), `declared_bytes` its `Content-Length`. `response_body` is the answer the client got: a non-streamed chat or rerank answer as written, a stream's relayed `data:` lines in order (without keepalives, the closing `[DONE]` or an error frame); none for embeddings (the vectors are not kept — the input is the record) and none for a refusal. `state` is `open` from the hold until the outcome is recorded, then `done` with `status` (the HTTP status the client got; `NULL` when the gateway wrote nothing — the client had gone), `code` (the gateway's code of a refusal or an error, where the refusing stage names one — the catch-alls of an unknown path and a wrong method leave it `NULL`), `finished_at`. `op`, `model` and `stream` are what the route read (`NULL` when no route parsed the request), `path` the request's path, `process_id` the ctxd process that admitted it. The row's `id` is the request's id: a chat answer's `id` is `chatcmpl-`, a rerank answer's `rerank-`, and the request's `context_llm_log` row carries it as `metadata.gw.recording_id` (with `metadata.gw.recorded: true`; that row carries no bodies under any `gateway.body_logging` value — the recording is their one place). +**What a row holds.** `request_body` is the body as the gateway read it, byte for byte (bytea: invalid UTF-8 and NUL bytes included, no cut, no seal — a password, a token or a private key in a prompt is stored in clear text); `request_complete` says whether that is the whole body (a body cut short holds the part read), `declared_bytes` its `Content-Length`. `response_body` is the answer the client got: a non-streamed chat or rerank answer as written, a stream's relayed `data:` lines in order (without keepalives, the closing `[DONE]` or an error frame), and for every answer that is not a `2xx` — a refusal, an error, a backend's rejection whose text the gateway relays (`gateway.relay_upstream_4xx_messages`) — its error body as written; none for a successful embeddings answer (the vectors are not kept — the input is the record) and none for `503 recording_unavailable` (its bytes are fixed). `state` is `open` from the hold until the outcome is recorded, then `done` with `status` (the HTTP status the client got; `NULL` when the gateway wrote nothing — the client had gone), `code` (the gateway's code of a refusal or an error, where the refusing stage names one — the catch-alls of an unknown path and a wrong method leave it `NULL`), `finished_at`. `op`, `model` and `stream` are what the route read (`NULL` when no route parsed the request), `path` the request's path, `process_id` the ctxd process that admitted it. The row's `id` is the request's id: a chat answer's `id` is `chatcmpl-`, a rerank answer's `rerank-`, and the request's `context_llm_log` row carries it as `metadata.gw.recording_id` (with `metadata.gw.recorded: true`; that row carries no bodies under any `gateway.body_logging` value — the recording is their one place). -**Held before served.** The route commits the row — the whole request, state `open` — before the first backend attempt and before any queue wait; a request whose row cannot be committed is answered `503 recording_unavailable` (`Retry-After: 1`, `x-should-retry: true`) and no backend sees it: the database refuses the insert, or it does not answer within **5 s** (a fixed statement deadline), or the recording's memory account or its statement slots (below) have no room within `dispatch.external_max_wait` (20 s). The `503` reaches the client at once; the gateway then tries once more to leave the request's row (up to another 5 s, the client does not wait for it). A non-streamed answer is committed with the outcome before its first byte is written; if that fails, the client gets the same `503` instead of the answer (the backend ran: the meter books its usage; the client's retry is a second row). A stream relays a line only after the recording kept it in memory; its lines are committed when it ends — what a stream sent cannot be taken back, so a stream whose end cannot be committed leaves its row `open` with its request and is counted in `stream_answers_unrecorded`. A request the gateway refuses after the door accepted the key — a body that does not parse, an unknown model, a limit, a body over `gateway.max_request_bytes` (never read: the row holds its declared size), an unknown path, a wrong method — gets its row at its end, `done`, with what was read of the body. Refusals before the door (`401`, a wrong key) are not the consumer's and leave nothing. A process that dies between the hold and the outcome leaves the row `open`: its request is there, its outcome is not known. +**Held before served.** The route commits the row — the whole request, state `open` — before the first backend attempt and before any queue wait; a request whose row cannot be committed is answered `503 recording_unavailable` (`Retry-After: 1`, `x-should-retry: true`) and no backend sees it: the database refuses the insert, or it does not answer within **5 s** (a fixed statement deadline), or the recording's memory account or its statement slots (below) have no room within `dispatch.external_max_wait` (20 s). The `503` reaches the client at once; the gateway then tries once more to leave the request's row (up to another 5 s, the client does not wait for it). A non-streamed answer is committed with the outcome before its first byte is written; if that fails, the client gets the same `503` instead of the answer (the backend ran: the meter books its usage; the client's retry is a second row). An answer that is not a `2xx` is held from the client until the row holds it with its bytes; if that row cannot be written after a backend was asked, the client gets the `503` in its place — a refusal before the walk (no backend asked) goes out as it is. A stream relays a line only after the recording kept it in memory; its lines are committed when it ends — what a stream sent cannot be taken back, so a stream whose end cannot be committed leaves its row `open` with its request and is counted in `stream_answers_unrecorded`. A request the gateway refuses after the door accepted the key — a body that does not parse, an unknown model, a limit, a body over `gateway.max_request_bytes` (never read: the row holds its declared size), an unknown path, a wrong method — gets its row at its end, `done`, with what was read of the body. Refusals before the door (`401`, a wrong key) are not the consumer's and leave nothing. A process that dies between the hold and the outcome leaves the row `open`: its request is there, its outcome is not known. **Checking that nothing is missing.** `GET /api/status` (server-admin) carries `gateway.recording`: `process_id` and `since` (this process's start), `held_bytes` (the memory account's fill), and per recording consumer `admitted` (requests that passed the door as it), `in_flight`, `recorded` (requests whose row is in the table), `unrecordable` (requests for which no row could be written at all — an inference request is then refused with `recording_unavailable`, never served; see the model list below), `unfinished` (rows that stayed `open` because their outcome could not be written) and `stream_answers_unrecorded` (the streams among them that had sent lines). `admitted = in_flight + recorded + unrecordable` holds at every moment, and `recorded` equals the table's rows of that consumer and process: diff --git a/docs/security.md b/docs/security.md index 2491fecc6..565b854ad 100644 --- a/docs/security.md +++ b/docs/security.md @@ -167,7 +167,7 @@ Every refusal carries `x-should-retry: false`: the same request against the same What the gateway writes about a request, and what it never writes (design 06 §4.6): - **One body policy.** `gateway.body_logging` is the only switch for prompt and answer bodies of gateway rows in `context_llm_log` — of every consumer, a recording one (next point) included — global-only, so no tenant can raise it for itself. `none` (default) stores none; `errors` stores the serialized request and the answer on rows with an error only; `full` on every row, each capped at 64 KiB. Every row is then slimmed as for a tenant without developer mode: a credentials-class row stays sealed under every policy, whatever the tenant's `tenant.devmode` says — and so does a row whose sensitivity is empty or unknown (fail-closed, logged as a wiring defect). Embedded NUL bytes and invalid UTF-8 are cleaned before the write, so a crafted body cannot make the row — and its attribution — vanish. -- **The one exception: a recording consumer (migration 197, issue #571).** A model consumer with `record_bodies` on has every request it sends through the gateway held in `context_llm_recordings` — chat (a stream included), embeddings, rerank, and every request the gateway refuses after the door accepted its key: the body **as the gateway read it, byte for byte** (whatever `gateway.body_logging`, the alias, the consumer's `prompt_sensitivity`, the body scan or `Ctx-Sensitivity` say — no cut, no credentials seal), the answer the client got (a non-streamed chat or rerank answer; a stream's relayed lines; no embedding vectors), the status and the gateway's code. **Such a row can carry credentials in clear text** — a password or key a client puts into a prompt is stored as sent. Only a server-admin can switch it on (also with self-service, and only with `confirm_record_bodies: true`); switching it off is open to the consumer's tenant-admin; both are audited. **No ctx surface reads the table's bodies:** no REST, MCP, CLI or web route, no export, no pipeline (distill, dream, digest) — `TestRecordingsReadersCensus` fails on any production statement that names the table outside its writer and the retention janitor; a server operator reads them in the database ([operations — Recording a consumer](operations.md#recording-a-consumer)). The consumer's `context_llm_log` rows carry **no bodies under any `gateway.body_logging` value** — the recording is the one place of its request and answer, so no reader of the LLM log (its list, detail and export) has them — and are marked `metadata.gw.recorded` with the `recording_id`; their other columns are those of every consumer's. **Held before served:** the request is committed to the table before the first backend attempt; a request that cannot be held — the database refuses it or does not answer within 5 s, or the recording's memory account has no room within the request's wait budget — is answered `503 recording_unavailable` (`x-should-retry: true`, `Retry-After: 1`) and reaches no backend; a non-streamed answer the table does not take is that `503` instead of the answer. **What the switch does not change:** the required sensitivity, the chain and its egress rule, the body scan and its `413`, the limits, the in-flight budget's bookings and the answer are the same with and without it — the one new refusal is `recording_unavailable`, and every database write of the recording is in the request's time; deactivating and reactivating the consumer (the switch stays as it was); every other consumer (no stage, no write, no wait — their requests pass the recording stage untouched); the retention — the bodies are NULLed after `scheduler.llmlog_retention_days` (90) like every body; and a database backup (`backup.sh`), which carries them like every other content of the database. +- **The one exception: a recording consumer (migration 197, issue #571).** A model consumer with `record_bodies` on has every request it sends through the gateway held in `context_llm_recordings` — chat (a stream included), embeddings, rerank, and every request the gateway refuses after the door accepted its key: the body **as the gateway read it, byte for byte** (whatever `gateway.body_logging`, the alias, the consumer's `prompt_sensitivity`, the body scan or `Ctx-Sensitivity` say — no cut, no credentials seal), the answer the client got (a non-streamed chat or rerank answer; a stream's relayed lines; the error body of every answer that is not a `2xx`, a backend's relayed rejection included; no embedding vectors), the status and the gateway's code. **Such a row can carry credentials in clear text** — a password or key a client puts into a prompt is stored as sent. Only a server-admin can switch it on (also with self-service, and only with `confirm_record_bodies: true`); switching it off is open to the consumer's tenant-admin; both are audited. **No ctx surface reads the table's bodies:** no REST, MCP, CLI or web route, no export, no pipeline (distill, dream, digest) — `TestRecordingsReadersCensus` fails on any production statement that names the table outside its writer and the retention janitor; a server operator reads them in the database ([operations — Recording a consumer](operations.md#recording-a-consumer)). The consumer's `context_llm_log` rows carry **no bodies under any `gateway.body_logging` value** — the recording is the one place of its request and answer, so no reader of the LLM log (its list, detail and export) has them — and are marked `metadata.gw.recorded` with the `recording_id`; their other columns are those of every consumer's. **Held before served:** the request is committed to the table before the first backend attempt; a request that cannot be held — the database refuses it or does not answer within 5 s, or the recording's memory account has no room within the request's wait budget — is answered `503 recording_unavailable` (`x-should-retry: true`, `Retry-After: 1`) and reaches no backend; a non-streamed answer the table does not take is that `503` instead of the answer. **What the switch does not change:** the required sensitivity, the chain and its egress rule, the body scan and its `413`, the limits, the in-flight budget's bookings and the answer are the same with and without it — the one new refusal is `recording_unavailable`, and every database write of the recording is in the request's time; deactivating and reactivating the consumer (the switch stays as it was); every other consumer (no stage, no write, no wait — their requests pass the recording stage untouched); the retention — the bodies are NULLed after `scheduler.llmlog_retention_days` (90) like every body; and a database backup (`backup.sh`), which carries them like every other content of the database. - **Error redaction.** The `error` column of a gateway row holds only class, status and ctx code. The upstream response body (which can echo prompt fragments, and which tenant-admins would read in the LLM log list) never reaches it; class and code must have the shape of vocabulary words (lower snake case, at most 64 characters), anything else is stored as `[redacted]`; the writer takes the code from the gateway's own code vocabulary, never from the upstream answer. - **One identity.** A gateway row is attributed to the consumer (`consumer_id`); a knowledge key id that reached the row anyway is cleared with an ERROR line, and the database refuses any row carrying both. The model key id is kept in `metadata.gw.model_key_id` for key-leak forensics, never as a column. - **Access log.** A successful request is one `gateway request` line with ids, op, alias, status, token counts and timings (`gateway.access_log`, default on) — no consumer label, no content, never a key, its hint or a query string. Refusals are counted per (consumer, reason — a code of the gateway or door vocabulary, else `http_`) and logged as one `gateway rejections` WARN line per minute with the count, so a flood of `401`/`429` answers cannot rotate the error and security lines out of the 50 MB × 3 container log. The global request log stays silent for these requests. diff --git a/go/internal/oai/record.go b/go/internal/oai/record.go index 9d9629956..b7ac7a43a 100644 --- a/go/internal/oai/record.go +++ b/go/internal/oai/record.go @@ -37,7 +37,12 @@ import ( // walk checks the commit again (ready). // - A non-streamed answer (chat, rerank; embeddings without the vectors) // is committed with the outcome before its first byte is written; a -// failure there answers the request 503 recording_unavailable instead. A +// failure there answers the request 503 recording_unavailable instead. +// Every answer that is not a 2xx — a refusal, an error, a backend's +// rejection whose text the gateway relays — is held from the client by +// the stage's writer until the request's outcome is committed with its +// bytes (release); one whose row cannot take it after a backend was +// asked is 503 recording_unavailable in its place. A // stream keeps every line it relays (captured before the relay takes it) // and commits them when it ends; what a stream already sent cannot be // taken back, so a stream whose end cannot be committed leaves its row @@ -220,6 +225,7 @@ func (s *RecordingStage) Handler(next http.Handler) http.Handler { return } rr := s.begin(ca, r) + rr.entry = w.Header().Clone() // what a replaced answer starts from (release) defer func() { p := recover() rr.endStage(p, w) @@ -260,11 +266,21 @@ type requestRecording struct { statusMu sync.Mutex status int + // The answer held from the client (hold, keep, release; under + // statusMu): a non-2xx answer the route wrote — its status heldCode and + // its bytes heldBody — is kept until its outcome is committed. passed: + // something went to the client unheld. entry: the response headers at + // the stage, which a replaced answer starts from. + holding, passed bool + heldCode int + heldBody []byte + entry http.Header // row: a row of the request is committed (open, or inserted at the // end); opened: it was opened before the walk; ended: its outcome is - // committed (or known to be there). - row, opened, ended bool + // committed (or known to be there); settled: the row holds the outcome + // the client gets (end). + row, opened, ended, settled bool // unfinished: the outcome of an opened row could not be committed. unfinished bool @@ -500,13 +516,16 @@ func (rr *requestRecording) noteStatus(code int) { // failure is counted, never retried later. func (rr *requestRecording) end(code string) { if rr.ended { + rr.settled = true rr.dropCapture() return } defer rr.dropCapture() ctx := context.Background() o := llmlog.RecordedOutcome{Status: rr.writeStatus(), Code: code} - if len(rr.capture) > 0 { + if held := rr.heldAnswer(); held != nil { + o.Response = held // what the client gets: the held answer, not a capture + } else if len(rr.capture) > 0 { o.Response = rr.capture } if rr.opened { @@ -515,7 +534,9 @@ func (rr *requestRecording) end(code string) { rr.unfinished = true slog.Error("gateway: the outcome of a recorded request could not be recorded — its row stays open", "consumer_id", rr.req.ConsumerID, "recording_id", rr.req.ID, "stream_answer_lost", rr.streamed, "error", err) + return } + rr.settled = true return } if rr.stage.store == nil { @@ -529,7 +550,7 @@ func (rr *requestRecording) end(code string) { slog.Error("gateway: a refused request of a recording consumer could not be recorded", "consumer_id", rr.req.ConsumerID, "error", err) return } - rr.row, rr.ended = true, true + rr.row, rr.ended, rr.settled = true, true, true } // dropCapture gives the captured answer back to the account. @@ -547,8 +568,9 @@ func (rr *requestRecording) endStage(p any, w http.ResponseWriter) { if rr.access != nil { code = rr.access.Reason } - if p != nil && rr.writeStatus() == 0 { - rr.noteStatus(http.StatusServiceUnavailable) + if p != nil && !rr.answerPassed() { + // oai.Recover answers the panic: nothing of the route's went out. + rr.dropHeld(http.StatusServiceUnavailable) code = CodeInternalError } if p == nil && code == CodeRecordingUnavailable { @@ -557,9 +579,112 @@ func (rr *requestRecording) endStage(p any, w http.ResponseWriter) { _ = http.NewResponseController(w).Flush() } rr.end(code) + if p == nil { + rr.release(w) + } recStats.done(rr.stats, rr.row, rr.unfinished, rr.unfinished && rr.streamed) } +// hold reports whether the answer that starts with status code is held from +// the client until the request's outcome is committed (release): every +// answer that is not a 2xx, except the 503 recording_unavailable — that one +// goes out at once (the database is in trouble; endStage flushes it before +// the row's own attempt). A second status of a held answer is dropped, as +// net/http drops a superfluous WriteHeader. +func (rr *requestRecording) hold(code int) bool { + rr.statusMu.Lock() + defer rr.statusMu.Unlock() + switch { + case rr.holding: + return true + case rr.passed || code < http.StatusMultipleChoices || (rr.access != nil && rr.access.Reason == CodeRecordingUnavailable): + rr.passed = true + return false + } + rr.holding, rr.heldCode = true, code + return true +} + +// keep takes p into the held answer; false when nothing is held — p goes +// to the client. A held answer is an error envelope of the gateway's +// (WriteCode, refuseParam: a message of at most relayTextMax runes), bounded +// like the bytes the client gets. +func (rr *requestRecording) keep(p []byte) bool { + rr.statusMu.Lock() + defer rr.statusMu.Unlock() + if !rr.holding { + rr.passed = true + return false + } + rr.heldBody = append(rr.heldBody, p...) + return true +} + +// holdingAnswer reports a held answer. +func (rr *requestRecording) holdingAnswer() bool { + rr.statusMu.Lock() + defer rr.statusMu.Unlock() + return rr.holding +} + +// heldAnswer is the held answer's bytes (nil: none held). +func (rr *requestRecording) heldAnswer() []byte { + rr.statusMu.Lock() + defer rr.statusMu.Unlock() + if !rr.holding { + return nil + } + if rr.heldBody == nil { + return []byte{} + } + return rr.heldBody +} + +// answerPassed reports that something of the route's answer went to the +// client. +func (rr *requestRecording) answerPassed() bool { + rr.statusMu.Lock() + defer rr.statusMu.Unlock() + return rr.passed +} + +// dropHeld forgets a held answer; the client gets status from elsewhere +// (oai.Recover's 503). +func (rr *requestRecording) dropHeld(status int) { + rr.statusMu.Lock() + rr.holding, rr.heldCode, rr.heldBody = false, 0, nil + rr.status = status + rr.statusMu.Unlock() +} + +// release writes the held answer once the request's outcome is decided: +// as held when the row holds it (settled) or when the request never reached +// a backend (no open row: a refusal in the gateway's own words); otherwise — +// a backend was asked and the row could not take what the client would get — +// 503 recording_unavailable in its place, from the headers at the stage. +func (rr *requestRecording) release(w http.ResponseWriter) { + rr.statusMu.Lock() + holding, code, body := rr.holding, rr.heldCode, rr.heldBody + rr.holding, rr.heldBody, rr.passed = false, nil, true + rr.statusMu.Unlock() + if !holding { + return + } + if !rr.settled && rr.opened { + h := w.Header() + clear(h) + for k, v := range rr.entry { + h[k] = v + } + refuseRecording(rr.access, w) + return + } + w.WriteHeader(code) + if _, err := w.Write(body); err != nil { //nolint:gosec // G705: body is the route's own error envelope (WriteCode, refuseParam — encoding/json's escape), held and written unchanged: the bytes the unrecorded path writes + slog.Warn("gateway: failed to write a held answer", "error", err, "recording_id", rr.req.ID) + } +} + // refuseRecording answers a request whose recording failed: 503 // recording_unavailable, Retry-After: 1, x-should-retry: true — a fault of // the gateway's database, not of the request, and no rule's refusal (no @@ -573,8 +698,9 @@ func refuseRecording(rec *AccessRecord, w http.ResponseWriter) { } // recordingWriter notes the status the client gets on the request's -// recording. Unwrap lets http.ResponseController reach the connection -// (flush, write deadlines). +// recording and holds a non-2xx answer until its outcome is committed +// (hold). Unwrap lets http.ResponseController reach the connection (flush, +// write deadlines). type recordingWriter struct { http.ResponseWriter rr *requestRecording @@ -583,17 +709,26 @@ type recordingWriter struct { func (w recordingWriter) WriteHeader(code int) { if code >= http.StatusOK { w.rr.noteStatus(code) + if w.rr.hold(code) { + return // held until the outcome is committed (release) + } } w.ResponseWriter.WriteHeader(code) } func (w recordingWriter) Write(p []byte) (int, error) { w.rr.noteStatus(http.StatusOK) + if w.rr.keep(p) { + return len(p), nil + } return w.ResponseWriter.Write(p) } func (w recordingWriter) FlushError() error { w.rr.noteStatus(http.StatusOK) + if w.rr.holdingAnswer() { + return nil // nothing of a held answer goes out before release + } return http.NewResponseController(w.ResponseWriter).Flush() } diff --git a/go/internal/oai/record_route_test.go b/go/internal/oai/record_route_test.go index 07f25d0ef..fc8a7bfce 100644 --- a/go/internal/oai/record_route_test.go +++ b/go/internal/oai/record_route_test.go @@ -488,7 +488,8 @@ func TestRecordingStreamWithoutRoomEnds(t *testing.T) { // TestRecordingRefusedRequestsLeaveTheirRow: a request the gateway refuses // after the door — a body that does not parse, a body cut short, an unknown // model, the meter's refusal — leaves one row, never opened, with what was -// read of the body and the status and code the client got. +// read of the body and the status, code and body of the refusal the client +// got. func TestRecordingRefusedRequestsLeaveTheirRow(t *testing.T) { for _, tc := range []struct { name, body string @@ -524,6 +525,9 @@ func TestRecordingRefusedRequestsLeaveTheirRow(t *testing.T) { if string(r.body) != tc.body || r.req.Complete != tc.complete { t.Errorf("row body %q complete %v, want %q complete %v", r.body, r.req.Complete, tc.body, tc.complete) } + if string(r.response) != w.Body.String() { + t.Errorf("row answer %q — want the refusal the client got %q", r.response, w.Body.String()) + } if u.hits.Load() != 0 { t.Errorf("a refused request reached the backend") } @@ -802,3 +806,80 @@ func TestRecordedLLMLogRowCarriesNoBodies(t *testing.T) { check(t, rig, store) }) } + +// recRejection is a backend's own refusal text: with +// gateway.relay_upstream_4xx_messages on, the client's 400 carries it. +const recRejection = "the engine refuses this prompt: marker-571-rejected" + +// TestRecordingErrorAnswerHeldBeforeItIsWritten: an error answer the client +// gets after the walk — here a backend's 400 whose text the gateway relays — +// is in the recording's row with its status and code, byte for byte the body +// the client got, and it is held before it is written: when its row cannot +// take it the client gets 503 recording_unavailable, never the backend's +// text. Chat (non-streamed), embeddings and rerank. +func TestRecordingErrorAnswerHeldBeforeItIsWritten(t *testing.T) { + reject := func(w http.ResponseWriter) { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(http.StatusBadRequest) + _, _ = w.Write([]byte(`{"error":{"message":"` + recRejection + `","type":"invalid_request_error"}}`)) + } + relay := func(s *oai.Settings) { s.RelayUpstream4xxMessages = true } + routes := []struct { + name string + rig func(t *testing.T, store *recStore) (post func() chatAnswer) + }{ + {"chat", func(t *testing.T, store *recStore) func() chatAnswer { + u := newUpstream(t, recChatAnswer) + u.setRespond(func(w http.ResponseWriter, _ *http.Request) { reject(w) }) + rig := newChatRig(t, []backends.Backend{u.row("spark", backends.TrustFull, 10)}, 4, 1, withRecordings(store)) + rig.setSettings(relay) + rig.ca.Store(recordingConsumer(true)) + return func() chatAnswer { return rig.post(t, chatBody("pub")) } + }}, + {"embeddings", func(t *testing.T, store *recStore) func() chatAnswer { + e := newEmbedEngine(t, 8) + e.setRespond(func(w http.ResponseWriter, _ *http.Request, _ int64, _ []string) bool { reject(w); return true }) + rig := newEmbedRig(t, []backends.Backend{e.row("spark-embed", backends.ProtocolOpenAI, 10)}, 4, 1, withRecordings(store)) + rig.setSettings(relay) + rig.ca.Store(recordingConsumer(true)) + return func() chatAnswer { return rig.postEmbed(t, embedBody("emb1", []string{"a"})) } + }}, + {"rerank", func(t *testing.T, store *recStore) func() chatAnswer { + e := newRerankEngine(t) + e.setRespond(func(w http.ResponseWriter, _ *http.Request, _ int64, _ rerankCall) bool { reject(w); return true }) + rig := newRerankRig(t, []backends.Backend{e.row("spark-rerank", 10)}, 4, 1, withRecordings(store)) + rig.setSettings(relay) + rig.ca.Store(recordingConsumer(true)) + return func() chatAnswer { return rig.postRerank(t, "/v1/rerank", rerankBody("rrpub", "q", []string{"d1", "d2"})) } + }}, + } + for _, rt := range routes { + t.Run(rt.name+"/held", func(t *testing.T) { + store := newRecStore(nil) + a := rt.rig(t, store)() + if a.status != http.StatusBadRequest || !strings.Contains(string(a.body), "marker-571-rejected") { + t.Fatalf("client: %d %s — want the backend's 400 relayed (the test does not reach the relayed text)", a.status, a.body) + } + r := store.only(t) + if r.state != llmlog.RecordingDone || r.out.Status != http.StatusBadRequest || r.out.Code != oai.CodeUpstreamRejected { + t.Errorf("row: state %q status %d code %q — want done 400 upstream_rejected", r.state, r.out.Status, r.out.Code) + } + if string(r.response) != string(a.body) { + t.Errorf("row answer %q — want the body the client got %q", r.response, a.body) + } + }) + t.Run(rt.name+"/not_held", func(t *testing.T) { + store := newRecStore(nil) + post := rt.rig(t, store) + store.set(func(s *recStore) { s.finishErr = errors.New("database down") }) + a := post() + checkRecordingRefusal(t, a.status, a.header, a.body) + if strings.Contains(string(a.body), "marker-571-rejected") { + t.Errorf("the client got the backend's text that was not held: %s", a.body) + } + if r := store.only(t); r.state != llmlog.RecordingOpen { + t.Errorf("row state %q, want open (its outcome could not be held)", r.state) + } + }) + } +} diff --git a/go/internal/schemacontract/manifest.json b/go/internal/schemacontract/manifest.json index d92b1d8c4..9e2d6c8fa 100644 --- a/go/internal/schemacontract/manifest.json +++ b/go/internal/schemacontract/manifest.json @@ -3,7 +3,7 @@ "generated_against": { "migration_max": 197, "migration_count": 85, - "migration_chain_sha256": "2eba65c81991bb709597a4ac27591a014897f1c4e7ea1416347af4af115fbdf3", + "migration_chain_sha256": "a5dae7b8f260cd9e7fe03073cecf4aca2c92c4ac17745ce36756907868d49b2d", "pg_major": 18, "image": "pgvector-timescaledb:pg18" }, diff --git a/go/migrations/197_model_consumer_record_bodies.sql b/go/migrations/197_model_consumer_record_bodies.sql index e38f87e39..f07dc76fe 100644 --- a/go/migrations/197_model_consumer_record_bodies.sql +++ b/go/migrations/197_model_consumer_record_bodies.sql @@ -12,8 +12,8 @@ -- context_llm_recordings (4): the request body as the gateway read it, byte -- for byte, committed BEFORE the first backend attempt; a request that -- cannot be held is not served (503 recording_unavailable). A non-streamed --- answer is committed before it is written to the client; a stream's relayed --- lines when it ends. Whatever gateway.body_logging, the alias, the +-- answer is committed before it is written to the client (an answer that is +-- not a 2xx with its error body); a stream's relayed lines when it ends. Whatever gateway.body_logging, the alias, the -- consumer's prompt_sensitivity, the body scan or Ctx-Sensitivity say: no -- cut, no seal — a row can carry credentials in clear text, and no ctx -- surface reads its bodies (internal/llmlog/recordings.go). The gateway's From 262057248d60c001eee196e84ec806ac9922ae32 Mon Sep 17 00:00:00 2001 From: Jan-Stefan Janetzky Date: Fri, 27 Nov 2026 07:47:12 +0100 Subject: [PATCH 17/27] =?UTF-8?q?fix(gateway):=20a=20recorded=20answer=20t?= =?UTF-8?q?he=20client=20does=20not=20get=20is=20superseded=20in=20its=20r?= =?UTF-8?q?ow=20=E2=80=94=20a=20revocation=20during=20its=20commit,=20or?= =?UTF-8?q?=20a=20commit=20whose=20acknowledgement=20was=20lost?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Two ways left a recording row claiming a 200 and an answer the client never got. A request whose key was revoked (or whose consumer was deactivated, the model API switched off, the alias gone, the shutdown) while its answer was being committed still got the answer: nothing checked between the commit — up to the 5 s statement deadline — and the write. And an answer commit that went through but reported an error was refused with 503, while its row kept the 200 and the answer, since a done row took no later outcome. The routes (chat, embeddings, rerank) now check again between an answer's commit and its write (heldStillServes: the switch, the alias, the revocation, the shutdown) and answer the cause instead; a withheld answer — and a failed answer commit — has the request's final outcome supersede it in the row (RecordedOutcome.Supersedes: Finish writes over a done row). If that write fails too, the request counts as unfinished and its ERROR line says answer_withheld with the recording id. Also pinned: a refusal before the walk goes out as it is when its row cannot be written. Co-Authored-By: Claude Opus 5.5 --- docs/operations.md | 6 +- docs/security.md | 2 +- go/internal/llmlog/recordings.go | 12 +- .../llmlog/recordings_integration_test.go | 21 +++ go/internal/oai/chat.go | 10 ++ go/internal/oai/embeddings.go | 10 ++ go/internal/oai/record.go | 59 ++++++- go/internal/oai/record_route_test.go | 166 +++++++++++++++++- go/internal/oai/rerank.go | 8 + 9 files changed, 281 insertions(+), 13 deletions(-) diff --git a/docs/operations.md b/docs/operations.md index e4770e981..fa838380a 100644 --- a/docs/operations.md +++ b/docs/operations.md @@ -986,9 +986,9 @@ ctx manage model-consumer-update '' '{"id":"","record_bodies":true, **What a row holds.** `request_body` is the body as the gateway read it, byte for byte (bytea: invalid UTF-8 and NUL bytes included, no cut, no seal — a password, a token or a private key in a prompt is stored in clear text); `request_complete` says whether that is the whole body (a body cut short holds the part read), `declared_bytes` its `Content-Length`. `response_body` is the answer the client got: a non-streamed chat or rerank answer as written, a stream's relayed `data:` lines in order (without keepalives, the closing `[DONE]` or an error frame), and for every answer that is not a `2xx` — a refusal, an error, a backend's rejection whose text the gateway relays (`gateway.relay_upstream_4xx_messages`) — its error body as written; none for a successful embeddings answer (the vectors are not kept — the input is the record) and none for `503 recording_unavailable` (its bytes are fixed). `state` is `open` from the hold until the outcome is recorded, then `done` with `status` (the HTTP status the client got; `NULL` when the gateway wrote nothing — the client had gone), `code` (the gateway's code of a refusal or an error, where the refusing stage names one — the catch-alls of an unknown path and a wrong method leave it `NULL`), `finished_at`. `op`, `model` and `stream` are what the route read (`NULL` when no route parsed the request), `path` the request's path, `process_id` the ctxd process that admitted it. The row's `id` is the request's id: a chat answer's `id` is `chatcmpl-`, a rerank answer's `rerank-`, and the request's `context_llm_log` row carries it as `metadata.gw.recording_id` (with `metadata.gw.recorded: true`; that row carries no bodies under any `gateway.body_logging` value — the recording is their one place). -**Held before served.** The route commits the row — the whole request, state `open` — before the first backend attempt and before any queue wait; a request whose row cannot be committed is answered `503 recording_unavailable` (`Retry-After: 1`, `x-should-retry: true`) and no backend sees it: the database refuses the insert, or it does not answer within **5 s** (a fixed statement deadline), or the recording's memory account or its statement slots (below) have no room within `dispatch.external_max_wait` (20 s). The `503` reaches the client at once; the gateway then tries once more to leave the request's row (up to another 5 s, the client does not wait for it). A non-streamed answer is committed with the outcome before its first byte is written; if that fails, the client gets the same `503` instead of the answer (the backend ran: the meter books its usage; the client's retry is a second row). An answer that is not a `2xx` is held from the client until the row holds it with its bytes; if that row cannot be written after a backend was asked, the client gets the `503` in its place — a refusal before the walk (no backend asked) goes out as it is. A stream relays a line only after the recording kept it in memory; its lines are committed when it ends — what a stream sent cannot be taken back, so a stream whose end cannot be committed leaves its row `open` with its request and is counted in `stream_answers_unrecorded`. A request the gateway refuses after the door accepted the key — a body that does not parse, an unknown model, a limit, a body over `gateway.max_request_bytes` (never read: the row holds its declared size), an unknown path, a wrong method — gets its row at its end, `done`, with what was read of the body. Refusals before the door (`401`, a wrong key) are not the consumer's and leave nothing. A process that dies between the hold and the outcome leaves the row `open`: its request is there, its outcome is not known. +**Held before served.** The route commits the row — the whole request, state `open` — before the first backend attempt and before any queue wait; a request whose row cannot be committed is answered `503 recording_unavailable` (`Retry-After: 1`, `x-should-retry: true`) and no backend sees it: the database refuses the insert, or it does not answer within **5 s** (a fixed statement deadline), or the recording's memory account or its statement slots (below) have no room within `dispatch.external_max_wait` (20 s). The `503` reaches the client at once; the gateway then tries once more to leave the request's row (up to another 5 s, the client does not wait for it). A non-streamed answer is committed with the outcome before its first byte is written; if that fails, the client gets the same `503` instead of the answer (the backend ran: the meter books its usage; the client's retry is a second row). An answer that is not a `2xx` is held from the client until the row holds it with its bytes; if that row cannot be written after a backend was asked, the client gets the `503` in its place — a refusal before the walk (no backend asked) goes out as it is. A request that stops being served while its answer is being committed — its key revoked or its consumer deactivated, the model API switched off, the alias gone, the shutdown — gets the refusal it would have got before the commit (`401 invalid_api_key` for a revoked key), never the answer, and its row's outcome becomes that refusal; so does a `503` whose answer commit failed although it went through (its acknowledgement lost): the row never claims an answer the client did not get. A stream relays a line only after the recording kept it in memory; its lines are committed when it ends — what a stream sent cannot be taken back, so a stream whose end cannot be committed leaves its row `open` with its request and is counted in `stream_answers_unrecorded`. A request the gateway refuses after the door accepted the key — a body that does not parse, an unknown model, a limit, a body over `gateway.max_request_bytes` (never read: the row holds its declared size), an unknown path, a wrong method — gets its row at its end, `done`, with what was read of the body. Refusals before the door (`401`, a wrong key) are not the consumer's and leave nothing. A process that dies between the hold and the outcome leaves the row `open`: its request is there, its outcome is not known. -**Checking that nothing is missing.** `GET /api/status` (server-admin) carries `gateway.recording`: `process_id` and `since` (this process's start), `held_bytes` (the memory account's fill), and per recording consumer `admitted` (requests that passed the door as it), `in_flight`, `recorded` (requests whose row is in the table), `unrecordable` (requests for which no row could be written at all — an inference request is then refused with `recording_unavailable`, never served; see the model list below), `unfinished` (rows that stayed `open` because their outcome could not be written) and `stream_answers_unrecorded` (the streams among them that had sent lines). `admitted = in_flight + recorded + unrecordable` holds at every moment, and `recorded` equals the table's rows of that consumer and process: +**Checking that nothing is missing.** `GET /api/status` (server-admin) carries `gateway.recording`: `process_id` and `since` (this process's start), `held_bytes` (the memory account's fill), and per recording consumer `admitted` (requests that passed the door as it), `in_flight`, `recorded` (requests whose row is in the table), `unrecordable` (requests for which no row could be written at all — an inference request is then refused with `recording_unavailable`, never served; see the model list below), `unfinished` (requests whose final outcome could not be written: their row stayed `open` — or, for an answer committed and then withheld as above whose superseding outcome could not be written either, it keeps that answer and its `200`; the `ERROR` line below says `answer_withheld=true` and names the `recording_id`) and `stream_answers_unrecorded` (the streams among them that had sent lines). `admitted = in_flight + recorded + unrecordable` holds at every moment, and `recorded` equals the table's rows of that consumer and process: ```sql SELECT count(*) AS rows, @@ -1003,7 +1003,7 @@ SELECT count(*) AS WHERE consumer_id = '' AND process_id = ''; ``` -`answered_without_answer` is `0` by construction (a non-streamed chat or rerank answer is written only after its row holds it). The group's other routes — the model list `GET /v1/models` — get a row too, with their status and no body (`op` `NULL`); nothing of theirs goes to a backend, so they are not held first, and one whose row cannot be written counts as `unrecordable` although it was answered. For a time range instead of a process, filter on `created_at` (the rows of every process that ran then); the counts of processes that have ended are in their logs: every request that could not be recorded is an `ERROR` line (`a refused request of a recording consumer could not be recorded`, or `the outcome of a recorded request could not be recorded — its row stays open` with `recording_id` and `stream_answer_lost`). +`answered_without_answer` is `0` by construction (a non-streamed chat or rerank answer is written only after its row holds it). The group's other routes — the model list `GET /v1/models` — get a row too, with their status and no body (`op` `NULL`); nothing of theirs goes to a backend, so they are not held first, and one whose row cannot be written counts as `unrecordable` although it was answered. For a time range instead of a process, filter on `created_at` (the rows of every process that ran then); the counts of processes that have ended are in their logs: every request that could not be recorded is an `ERROR` line (`a refused request of a recording consumer could not be recorded`, or `the outcome of a recorded request could not be recorded — its row stays open` with `recording_id`, `stream_answer_lost` and `answer_withheld`). **Reading a consumer's requests out** (psql, in order): diff --git a/docs/security.md b/docs/security.md index 565b854ad..a30ca5103 100644 --- a/docs/security.md +++ b/docs/security.md @@ -167,7 +167,7 @@ Every refusal carries `x-should-retry: false`: the same request against the same What the gateway writes about a request, and what it never writes (design 06 §4.6): - **One body policy.** `gateway.body_logging` is the only switch for prompt and answer bodies of gateway rows in `context_llm_log` — of every consumer, a recording one (next point) included — global-only, so no tenant can raise it for itself. `none` (default) stores none; `errors` stores the serialized request and the answer on rows with an error only; `full` on every row, each capped at 64 KiB. Every row is then slimmed as for a tenant without developer mode: a credentials-class row stays sealed under every policy, whatever the tenant's `tenant.devmode` says — and so does a row whose sensitivity is empty or unknown (fail-closed, logged as a wiring defect). Embedded NUL bytes and invalid UTF-8 are cleaned before the write, so a crafted body cannot make the row — and its attribution — vanish. -- **The one exception: a recording consumer (migration 197, issue #571).** A model consumer with `record_bodies` on has every request it sends through the gateway held in `context_llm_recordings` — chat (a stream included), embeddings, rerank, and every request the gateway refuses after the door accepted its key: the body **as the gateway read it, byte for byte** (whatever `gateway.body_logging`, the alias, the consumer's `prompt_sensitivity`, the body scan or `Ctx-Sensitivity` say — no cut, no credentials seal), the answer the client got (a non-streamed chat or rerank answer; a stream's relayed lines; the error body of every answer that is not a `2xx`, a backend's relayed rejection included; no embedding vectors), the status and the gateway's code. **Such a row can carry credentials in clear text** — a password or key a client puts into a prompt is stored as sent. Only a server-admin can switch it on (also with self-service, and only with `confirm_record_bodies: true`); switching it off is open to the consumer's tenant-admin; both are audited. **No ctx surface reads the table's bodies:** no REST, MCP, CLI or web route, no export, no pipeline (distill, dream, digest) — `TestRecordingsReadersCensus` fails on any production statement that names the table outside its writer and the retention janitor; a server operator reads them in the database ([operations — Recording a consumer](operations.md#recording-a-consumer)). The consumer's `context_llm_log` rows carry **no bodies under any `gateway.body_logging` value** — the recording is the one place of its request and answer, so no reader of the LLM log (its list, detail and export) has them — and are marked `metadata.gw.recorded` with the `recording_id`; their other columns are those of every consumer's. **Held before served:** the request is committed to the table before the first backend attempt; a request that cannot be held — the database refuses it or does not answer within 5 s, or the recording's memory account has no room within the request's wait budget — is answered `503 recording_unavailable` (`x-should-retry: true`, `Retry-After: 1`) and reaches no backend; a non-streamed answer the table does not take is that `503` instead of the answer. **What the switch does not change:** the required sensitivity, the chain and its egress rule, the body scan and its `413`, the limits, the in-flight budget's bookings and the answer are the same with and without it — the one new refusal is `recording_unavailable`, and every database write of the recording is in the request's time; deactivating and reactivating the consumer (the switch stays as it was); every other consumer (no stage, no write, no wait — their requests pass the recording stage untouched); the retention — the bodies are NULLed after `scheduler.llmlog_retention_days` (90) like every body; and a database backup (`backup.sh`), which carries them like every other content of the database. +- **The one exception: a recording consumer (migration 197, issue #571).** A model consumer with `record_bodies` on has every request it sends through the gateway held in `context_llm_recordings` — chat (a stream included), embeddings, rerank, and every request the gateway refuses after the door accepted its key: the body **as the gateway read it, byte for byte** (whatever `gateway.body_logging`, the alias, the consumer's `prompt_sensitivity`, the body scan or `Ctx-Sensitivity` say — no cut, no credentials seal), the answer the client got (a non-streamed chat or rerank answer; a stream's relayed lines; the error body of every answer that is not a `2xx`, a backend's relayed rejection included; no embedding vectors), the status and the gateway's code. **Such a row can carry credentials in clear text** — a password or key a client puts into a prompt is stored as sent. Only a server-admin can switch it on (also with self-service, and only with `confirm_record_bodies: true`); switching it off is open to the consumer's tenant-admin; both are audited. **No ctx surface reads the table's bodies:** no REST, MCP, CLI or web route, no export, no pipeline (distill, dream, digest) — `TestRecordingsReadersCensus` fails on any production statement that names the table outside its writer and the retention janitor; a server operator reads them in the database ([operations — Recording a consumer](operations.md#recording-a-consumer)). The consumer's `context_llm_log` rows carry **no bodies under any `gateway.body_logging` value** — the recording is the one place of its request and answer, so no reader of the LLM log (its list, detail and export) has them — and are marked `metadata.gw.recorded` with the `recording_id`; their other columns are those of every consumer's. **Held before served:** the request is committed to the table before the first backend attempt; a request that cannot be held — the database refuses it or does not answer within 5 s, or the recording's memory account has no room within the request's wait budget — is answered `503 recording_unavailable` (`x-should-retry: true`, `Retry-After: 1`) and reaches no backend; a non-streamed answer the table does not take is that `503` instead of the answer, and a request that stops being served while its answer is committed (a key revoked, a consumer deactivated) gets the refusal, never the answer — its row then holds that refusal. **What the switch does not change:** the required sensitivity, the chain and its egress rule, the body scan and its `413`, the limits, the in-flight budget's bookings and the answer are the same with and without it — the one new refusal is `recording_unavailable`, and every database write of the recording is in the request's time; deactivating and reactivating the consumer (the switch stays as it was); every other consumer (no stage, no write, no wait — their requests pass the recording stage untouched); the retention — the bodies are NULLed after `scheduler.llmlog_retention_days` (90) like every body; and a database backup (`backup.sh`), which carries them like every other content of the database. - **Error redaction.** The `error` column of a gateway row holds only class, status and ctx code. The upstream response body (which can echo prompt fragments, and which tenant-admins would read in the LLM log list) never reaches it; class and code must have the shape of vocabulary words (lower snake case, at most 64 characters), anything else is stored as `[redacted]`; the writer takes the code from the gateway's own code vocabulary, never from the upstream answer. - **One identity.** A gateway row is attributed to the consumer (`consumer_id`); a knowledge key id that reached the row anyway is cleared with an ERROR line, and the database refuses any row carrying both. The model key id is kept in `metadata.gw.model_key_id` for key-leak forensics, never as a column. - **Access log.** A successful request is one `gateway request` line with ids, op, alias, status, token counts and timings (`gateway.access_log`, default on) — no consumer label, no content, never a key, its hint or a query string. Refusals are counted per (consumer, reason — a code of the gateway or door vocabulary, else `http_`) and logged as one `gateway rejections` WARN line per minute with the count, so a flood of `401`/`429` answers cannot rotate the error and security lines out of the 50 MB × 3 container log. The global request log stays silent for these requests. diff --git a/go/internal/llmlog/recordings.go b/go/internal/llmlog/recordings.go index 12d893e8d..870788066 100644 --- a/go/internal/llmlog/recordings.go +++ b/go/internal/llmlog/recordings.go @@ -85,6 +85,11 @@ type RecordedOutcome struct { Code string // Response is the answer as the client got it (nil: none recorded). Response []byte + // Supersedes: this outcome replaces one committed before — an answer + // whose commit went through (or may have: its acknowledgement was lost) + // and which the client then did not get (internal/oai record.go + // withhold). Finish writes it over a done row as over an open one. + Supersedes bool } // Recordings writes context_llm_recordings over Pool. @@ -150,15 +155,16 @@ func (r Recordings) Open(ctx context.Context, q RecordedRequest) error { // Finish ends the open row id with its outcome (state done); nil once the // update is committed. A row that is not open is an error: an outcome is -// written once. +// written once — unless it supersedes a withheld answer (o.Supersedes), +// which it replaces on the done row. func (r Recordings) Finish(ctx context.Context, id string, o RecordedOutcome) error { if r.Pool == nil { return errRecordingPool } tag, err := r.Pool.Exec(ctx, `UPDATE context_llm_recordings SET state = 'done', finished_at = now(), status = $2, code = $3, response_bytes = $4, response_body = $5 - WHERE id = $1::uuid AND state = 'open'`, - id, nullStatus(o.Status), nullText(o.Code), int64(len(o.Response)), bodyBytes(o.Response)) + WHERE id = $1::uuid AND (state = 'open' OR $6)`, + id, nullStatus(o.Status), nullText(o.Code), int64(len(o.Response)), bodyBytes(o.Response), o.Supersedes) if err != nil { return fmt.Errorf("llmlog: finish recording: %w", err) } diff --git a/go/internal/llmlog/recordings_integration_test.go b/go/internal/llmlog/recordings_integration_test.go index 1a952234e..0c5b83840 100644 --- a/go/internal/llmlog/recordings_integration_test.go +++ b/go/internal/llmlog/recordings_integration_test.go @@ -99,6 +99,27 @@ func TestRecordingsRoundTrip(t *testing.T) { if err := st.Finish(ctx, req.ID, llmlog.RecordedOutcome{Status: 503}); err == nil { t.Errorf("a second Finish of the same row succeeded; an outcome is written once") } + // An answer committed and then withheld from the client: the outcome + // the client got supersedes it on the done row — and on an open one. + if err := st.Finish(ctx, req.ID, llmlog.RecordedOutcome{Status: 401, Code: "invalid_api_key", Response: []byte("refusal"), Supersedes: true}); err != nil { + t.Fatalf("superseding finish: %v", err) + } + r = readRecording(t, ctx, q, req.ID) + if r.state != llmlog.RecordingDone || r.status == nil || *r.status != 401 || r.code == nil || *r.code != "invalid_api_key" || + string(r.response) != "refusal" || r.respBytes != int64(len("refusal")) || !bytes.Equal(r.body, body) { + t.Errorf("superseded row: state %q status %v code %v answer %q (%d bytes), request kept %v — want done 401 invalid_api_key with the refusal", + r.state, r.status, r.code, r.response, r.respBytes, bytes.Equal(r.body, body)) + } + open := llmlog.RecordedRequest{ID: recID(t), ConsumerID: gwiConsumer, Path: "/v1/chat/completions", Body: []byte("asked"), Complete: true} + if err := st.Open(ctx, open); err != nil { + t.Fatalf("open: %v", err) + } + if err := st.Finish(ctx, open.ID, llmlog.RecordedOutcome{Status: 503, Code: "recording_unavailable", Supersedes: true}); err != nil { + t.Fatalf("superseding finish of an open row: %v", err) + } + if r = readRecording(t, ctx, q, open.ID); r.state != llmlog.RecordingDone || r.status == nil || *r.status != 503 || r.response != nil { + t.Errorf("open row after a superseding finish: state %q status %v answer %v — want done 503 without an answer", r.state, r.status, r.response) + } // A request refused before its walk: done at once, with the part read. refused := llmlog.RecordedRequest{ID: recID(t), ConsumerID: gwiConsumer, Path: "/v1/chat/completions", Op: llmlog.GatewayOpChat, diff --git a/go/internal/oai/chat.go b/go/internal/oai/chat.go index 95285781d..2a1550880 100644 --- a/go/internal/oai/chat.go +++ b/go/internal/oai/chat.go @@ -1318,6 +1318,16 @@ func (c *chatCall) success(plan Plan, st *walkState) chatOutcome { c.refuseRecording() return chatOutcome{finish: llmlog.FinishError, redacted: &llmlog.RedactedErr{Class: "admission", Code: CodeRecordingUnavailable}} } + if c.recording != nil { + // The commit took its time: a request that stopped being served + // meanwhile does not get the answer it held (record.go). + if err := c.d.heldStillServes(c.ctx, c.target); err != nil { + c.recording.withhold() + c.cancel(err) + _, code := c.verdict() + return chatOutcome{finish: llmlog.FinishAborted, redacted: &llmlog.RedactedErr{Class: backends.ClassCanceled.String(), Code: code}} + } + } for k, v := range c.rateHeaders() { c.w.Header()[k] = v } diff --git a/go/internal/oai/embeddings.go b/go/internal/oai/embeddings.go index d71f3f858..4bc1bfc4a 100644 --- a/go/internal/oai/embeddings.go +++ b/go/internal/oai/embeddings.go @@ -1399,6 +1399,16 @@ func (c *embedCall) success(st *embedState) embedOutcome { refuseRecording(c.rec, c.w) return embedOutcome{finish: llmlog.FinishError, redacted: &llmlog.RedactedErr{Class: "admission", Code: CodeRecordingUnavailable}} } + if c.recording != nil { + // The commit took its time: a request that stopped being served + // meanwhile does not get the answer (record.go). + if err := c.d.heldStillServes(c.ctx, t); err != nil { + c.recording.withhold() + c.cancel(err) + _, code := c.verdict() + return embedOutcome{finish: llmlog.FinishAborted, redacted: &llmlog.RedactedErr{Class: backends.ClassCanceled.String(), Code: code}} + } + } // The meter's view of the request's op bucket, on the successful answer // only (design/06 §4.4; lead decision M2 (c)). if c.limit != nil { diff --git a/go/internal/oai/record.go b/go/internal/oai/record.go index b7ac7a43a..73a42eee5 100644 --- a/go/internal/oai/record.go +++ b/go/internal/oai/record.go @@ -42,7 +42,12 @@ import ( // rejection whose text the gateway relays — is held from the client by // the stage's writer until the request's outcome is committed with its // bytes (release); one whose row cannot take it after a backend was -// asked is 503 recording_unavailable in its place. A +// asked is 503 recording_unavailable in its place. A request that +// stops being served while its answer is committed (a revoked key, the +// model API switched off — heldStillServes) gets that refusal, never the +// answer, and its outcome supersedes the committed answer in the row; +// so does the 503 of an answer whose commit failed (it may have gone +// through). A // stream keeps every line it relays (captured before the relay takes it) // and commits them when it ends; what a stream already sent cannot be // taken back, so a stream whose end cannot be committed leaves its row @@ -283,6 +288,10 @@ type requestRecording struct { row, opened, ended, settled bool // unfinished: the outcome of an opened row could not be committed. unfinished bool + // withheld: an answer was committed — or may have been: its commit + // failed — and the client does not get it (withhold); the request's + // outcome supersedes it. + withheld bool // capture is a stream's relayed lines or a rerank answer; held is what // it takes of the account; streamed: a stream relayed at least one line. @@ -403,12 +412,50 @@ func (rr *requestRecording) answer(ctx context.Context, body []byte) bool { return false // the walk ran on an open row (ready); anything else is a defect } if err := rr.finish(context.WithoutCancel(ctx), llmlog.RecordedOutcome{Status: http.StatusOK, Response: body}); err != nil { + // The commit may have gone through all the same (its acknowledgement + // lost): the refusal's outcome supersedes whatever the row holds. + rr.withheld = true slog.Warn("gateway: an answer could not be recorded — refused", "consumer_id", rr.req.ConsumerID, "error", err) return false } return true } +// withhold marks a committed answer the client does not get — the request +// stopped being served between the answer's commit and its write +// (Deps.heldStillServes): the outcome the client gets supersedes it in the +// row (end), and a captured answer is no longer what the client gets. +// Nil-safe. +func (rr *requestRecording) withhold() { + if rr == nil { + return + } + rr.withheld = true + rr.dropCapture() +} + +// heldStillServes is the check between a held answer's commit and its write +// (D8 for the time the commit took; stillServes ran before it): the model +// API switched off, the alias gone (in memory; the grant is read again only +// when the alias registry moved since the entry, as a watcher tick does), +// the key revoked or its consumer deactivated (the door's registry ended +// the request with auth.ErrCredentialRevoked), the shutdown. A cause: the +// answer does not go out — the route answers the cause and withholds it. A +// request deadline that passed during the commit is none: the answer is +// ready (answer). +func (d Deps) heldStillServes(ctx context.Context, t watchTarget) error { + if _, err := d.recheck(ctx, t, t.gen, false); err != nil { + return err + } + if d.Lifecycle != nil && d.Lifecycle.Err() != nil { + return errShutdown + } + if cause := context.Cause(ctx); errors.Is(cause, auth.ErrCredentialRevoked) { + return cause + } + return nil +} + // finish commits o on the open row. The statement's copies of o.Response // wait for room for an answer of the request's own (a chat answer); for a // captured one (a stream's lines, a rerank answer) they are taken past the @@ -515,14 +562,14 @@ func (rr *requestRecording) noteStatus(code int) { // with its copies, since the request's in-flight reservation has ended. A // failure is counted, never retried later. func (rr *requestRecording) end(code string) { - if rr.ended { + if rr.ended && !rr.withheld { rr.settled = true rr.dropCapture() return } defer rr.dropCapture() ctx := context.Background() - o := llmlog.RecordedOutcome{Status: rr.writeStatus(), Code: code} + o := llmlog.RecordedOutcome{Status: rr.writeStatus(), Code: code, Supersedes: rr.withheld} if held := rr.heldAnswer(); held != nil { o.Response = held // what the client gets: the held answer, not a capture } else if len(rr.capture) > 0 { @@ -532,8 +579,12 @@ func (rr *requestRecording) end(code string) { rr.req.Body = nil // in the row since the open if err := rr.finish(ctx, o); err != nil { rr.unfinished = true + // answer_withheld: the row may hold an answer the client did not + // get (its commit went through before the request stopped being + // served, or its acknowledgement was lost) instead of staying open. slog.Error("gateway: the outcome of a recorded request could not be recorded — its row stays open", - "consumer_id", rr.req.ConsumerID, "recording_id", rr.req.ID, "stream_answer_lost", rr.streamed, "error", err) + "consumer_id", rr.req.ConsumerID, "recording_id", rr.req.ID, "stream_answer_lost", rr.streamed, + "answer_withheld", rr.withheld, "error", err) return } rr.settled = true diff --git a/go/internal/oai/record_route_test.go b/go/internal/oai/record_route_test.go index fc8a7bfce..c49df7bea 100644 --- a/go/internal/oai/record_route_test.go +++ b/go/internal/oai/record_route_test.go @@ -4,6 +4,7 @@ import ( "context" "encoding/json" "errors" + "io" "net/http" "net/http/httptest" "regexp" @@ -77,6 +78,13 @@ type recStore struct { inOpen, maxInOpen atomic.Int64 // finishFailures refuses that many Finish calls before it takes one. finishFailures int + // finishLost commits that many Finish calls and still returns an error + // (a commit whose acknowledgement was lost on the way back). + finishLost int + // finishGate, when set, holds every Finish until it is closed; inFinish + // counts the Finish calls waiting there. + finishGate chan struct{} + inFinish atomic.Int64 } func newRecStore(hits func() int64) *recStore { @@ -117,9 +125,22 @@ func (s *recStore) Open(ctx context.Context, q llmlog.RecordedRequest) error { return nil } -func (s *recStore) Finish(_ context.Context, id string, o llmlog.RecordedOutcome) error { +func (s *recStore) Finish(ctx context.Context, id string, o llmlog.RecordedOutcome) error { s.calls.Add(1) s.mu.Lock() + gate := s.finishGate + s.mu.Unlock() + if gate != nil { + s.inFinish.Add(1) + select { + case <-gate: + case <-ctx.Done(): + s.inFinish.Add(-1) + return ctx.Err() + } + s.inFinish.Add(-1) + } + s.mu.Lock() defer s.mu.Unlock() if s.finishErr != nil { return s.finishErr @@ -129,11 +150,15 @@ func (s *recStore) Finish(_ context.Context, id string, o llmlog.RecordedOutcome return errors.New("finish refused once") } r := s.rows[id] - if r == nil || r.state != llmlog.RecordingOpen { + if r == nil || (r.state != llmlog.RecordingOpen && !o.Supersedes) { return errors.New("no open row") } r.state, r.out, r.response = llmlog.RecordingDone, o, append([]byte(nil), o.Response...) s.order = append(s.order, "finish") + if s.finishLost > 0 { + s.finishLost-- + return errors.New("finish committed, its acknowledgement lost") + } return nil } @@ -883,3 +908,140 @@ func TestRecordingErrorAnswerHeldBeforeItIsWritten(t *testing.T) { }) } } + +// postVia posts body to path over srv (a real connection: the revoker's +// request contexts) and reads the whole answer. +func postVia(t *testing.T, srv *httptest.Server, path, body string) chatAnswer { + t.Helper() + req, _ := http.NewRequestWithContext(context.Background(), http.MethodPost, srv.URL+path, strings.NewReader(body)) + req.Header.Set("Content-Type", "application/json") + resp, err := srv.Client().Do(req) + if err != nil { + return chatAnswer{status: -1, body: []byte(err.Error())} + } + defer func() { _ = resp.Body.Close() }() + b, _ := io.ReadAll(resp.Body) + return chatAnswer{status: resp.StatusCode, header: resp.Header, body: b} +} + +// recRoutes are the three non-streamed routes of a recording consumer, each +// over its own engine and rig: rig builds them over store, path and body +// are the request; answered tells the route's answer from a refusal. +var recRoutes = []struct { + name, path string + rig func(t *testing.T, store *recStore) *chatRig + body string + answered func(b []byte) bool +}{ + {"chat", "/v1/chat/completions", func(t *testing.T, store *recStore) *chatRig { + u := newUpstream(t, recChatAnswer) + return newChatRig(t, []backends.Backend{u.row("spark", backends.TrustFull, 10)}, 4, 1, withRecordings(store)) + }, chatBody("pub"), func(b []byte) bool { return strings.Contains(string(b), "the answer") }}, + {"embeddings", "/v1/embeddings", func(t *testing.T, store *recStore) *chatRig { + e := newEmbedEngine(t, 8) + return newEmbedRig(t, []backends.Backend{e.row("spark-embed", backends.ProtocolOpenAI, 10)}, 4, 1, withRecordings(store)) + }, embedBody("emb1", []string{"a"}), func(b []byte) bool { return strings.Contains(string(b), `"embedding"`) }}, + {"rerank", "/v1/rerank", func(t *testing.T, store *recStore) *chatRig { + e := newRerankEngine(t) + return newRerankRig(t, []backends.Backend{e.row("spark-rerank", 10)}, 4, 1, withRecordings(store)) + }, rerankBody("rrpub", "q", []string{"d1", "d2"}), func(b []byte) bool { return strings.Contains(string(b), "relevance_score") }}, +} + +// TestRecordingAnswerWithheldWhenRevokedAfterItsHold: a request whose key +// stops authenticating while its answer is being held — between the commit +// of the answer and its write — gets the 401 the revocation answers, never +// the answer; its row ends with that 401 and its body, not with the answer +// it held. Chat, embeddings and rerank. +func TestRecordingAnswerWithheldWhenRevokedAfterItsHold(t *testing.T) { + for _, rt := range recRoutes { + t.Run(rt.name, func(t *testing.T) { + store := newRecStore(nil) + gate := make(chan struct{}) + var gateOnce sync.Once + defer gateOnce.Do(func() { close(gate) }) + store.set(func(s *recStore) { s.finishGate = gate }) + rig := rt.rig(t, store) + rig.ca.Store(recordingConsumer(true)) + rv := newRevoker() + srv := serveHTTP(t, rv.wrap(rig.router)) + done := make(chan chatAnswer, 1) + go func() { done <- postVia(t, srv, rt.path, rt.body) }() + if !waitFor(5*time.Second, func() bool { return store.inFinish.Load() == 1 }) { + t.Fatal("the answer's commit did not start") + } + if n := rv.revoke(); n != 1 { + t.Fatalf("revoked %d running requests, want 1", n) + } + gateOnce.Do(func() { close(gate) }) + var a chatAnswer + select { + case a = <-done: + case <-time.After(10 * time.Second): + t.Fatal("no answer after the revocation") + } + if a.status != http.StatusUnauthorized || !strings.Contains(string(a.body), `"code":"invalid_api_key"`) || rt.answered(a.body) { + t.Fatalf("answer %d %s — want 401 invalid_api_key, without the answer", a.status, a.body) + } + r := store.only(t) + if r.state != llmlog.RecordingDone || r.out.Status != http.StatusUnauthorized || r.out.Code != oai.CodeInvalidAPIKey || + string(r.response) != string(a.body) { + t.Errorf("row: state %q status %d code %q answer %q — want done 401 invalid_api_key with the client's %q", + r.state, r.out.Status, r.out.Code, r.response, a.body) + } + }) + } +} + +// TestRecordingLostAcknowledgementLeavesNoFalseAnswer: an answer whose +// commit went through but whose acknowledgement was lost is refused (the +// client gets 503 recording_unavailable and retries), and the row then says +// so — status 503, the code, no answer — instead of the 200 and the answer +// the client never got. Chat, embeddings and rerank. +func TestRecordingLostAcknowledgementLeavesNoFalseAnswer(t *testing.T) { + for _, rt := range recRoutes { + t.Run(rt.name, func(t *testing.T) { + store := newRecStore(nil) + store.set(func(s *recStore) { s.finishLost = 1 }) + rig := rt.rig(t, store) + ca := recordingConsumer(true) + ca.ConsumerID = uuid.NewString() + rig.ca.Store(ca) + srv := serveHTTP(t, rig.router) + a := postVia(t, srv, rt.path, rt.body) + checkRecordingRefusal(t, a.status, a.header, a.body) + if rt.answered(a.body) { + t.Errorf("the client got the answer: %s", a.body) + } + r := store.only(t) + if r.state != llmlog.RecordingDone || r.out.Status != http.StatusServiceUnavailable || + r.out.Code != oai.CodeRecordingUnavailable || len(r.response) != 0 { + t.Errorf("row: state %q status %d code %q answer %d bytes — want done 503 recording_unavailable without an answer", + r.state, r.out.Status, r.out.Code, len(r.response)) + } + if got := statsOf(ca.ConsumerID); got.Unfinished != 0 || got.Recorded != 1 { + t.Errorf("counts %+v — want recorded 1, unfinished 0 (the row holds the outcome)", got) + } + }) + } +} + +// TestRecordingRefusalGoesOutWhenItsRowFails: a refusal before the walk — +// nothing reached a backend — is held only until its row is attempted; when +// the row cannot be written the client still gets that refusal as it is +// (not 503 recording_unavailable), and the request counts as unrecordable. +func TestRecordingRefusalGoesOutWhenItsRowFails(t *testing.T) { + u := newUpstream(t, recChatAnswer) + store := newRecStore(nil) + rig := newChatRig(t, []backends.Backend{u.row("spark", backends.TrustFull, 10)}, 4, 1, withRecordings(store)) + ca := recordingConsumer(true) + ca.ConsumerID = uuid.NewString() + rig.ca.Store(ca) + store.set(func(s *recStore) { s.insertErr = errors.New("database down") }) + a := rig.post(t, `{"model":"no-such-model","messages":[{"role":"user","content":"hi"}]}`) + if code, _, _ := a.envelope(t); a.status != http.StatusNotFound || code != oai.CodeModelNotFound { + t.Errorf("client %d %q — want the refusal as it is, 404 model_not_found: %s", a.status, code, a.body) + } + if got := statsOf(ca.ConsumerID); got.Unrecordable != 1 || got.Recorded != 0 { + t.Errorf("counts %+v — want unrecordable 1, recorded 0", got) + } +} diff --git a/go/internal/oai/rerank.go b/go/internal/oai/rerank.go index 7cf299351..74c2cbb48 100644 --- a/go/internal/oai/rerank.go +++ b/go/internal/oai/rerank.go @@ -976,6 +976,14 @@ func (c *rerankCall) success(st *rerankState) embedOutcome { refuseRecording(c.rec, c.w) return embedOutcome{finish: llmlog.FinishError, redacted: &llmlog.RedactedErr{Class: "admission", Code: CodeRecordingUnavailable}} } + // The commit took its time: a request that stopped being served + // meanwhile does not get the answer it held. + if err := c.d.heldStillServes(c.ctx, t); err != nil { + c.recording.withhold() + c.cancel(err) + _, code := c.verdict() + return embedOutcome{finish: llmlog.FinishAborted, redacted: &llmlog.RedactedErr{Class: backends.ClassCanceled.String(), Code: code}} + } held = c.recording.capture } if c.limit != nil { From 214549f3bdac62641108826436a24d06c1cb78b8 Mon Sep 17 00:00:00 2001 From: Jan-Stefan Janetzky Date: Fri, 27 Nov 2026 07:49:15 +0100 Subject: [PATCH 18/27] fix(gateway): the recording's texts name the embedding vectors as the one answer not kept, recording_unavailable's two stages, and the way back of 197 starts by stopping 197 - The switch's confirmation text, the SPA's recording line, the docs, the migration's header and the code comments said every answer is held in full; an embeddings answer is held without its vectors (the input is the record), and each of them now says so. - recording_unavailable (docs/api.md): "no backend called" holds for a request that could not be held before its walk; when what a backend answered could not be held, the backend ran and a retry runs it again. - Migration 197's way back (docs/operations.md) starts with stopping every process of a release that embeds 197 and keeping it stopped: a running one fails at its door on the restored ctx_model_auth, and one that starts after the _migrations row is gone applies 197 again. The side-by-side advice is the rolling deploy's only. Co-Authored-By: Claude Opus 5.5 --- docs/api.md | 4 ++-- docs/operations.md | 2 +- go/internal/auth/consumer.go | 8 ++++---- go/internal/handler/model_consumers.go | 5 +++-- go/internal/handler/model_consumers_read.go | 7 ++++--- .../handler/model_consumers_record_integration_test.go | 5 +++-- go/internal/llmlog/gateway.go | 3 ++- go/internal/llmlog/recordings.go | 3 ++- go/internal/schemacontract/manifest.json | 2 +- go/migrations/197_model_consumer_record_bodies.sql | 3 ++- go/web/src/routes/gateway/format.ts | 2 +- 11 files changed, 25 insertions(+), 19 deletions(-) diff --git a/docs/api.md b/docs/api.md index 4adbebafb..4f8c3eab4 100644 --- a/docs/api.md +++ b/docs/api.md @@ -271,7 +271,7 @@ A **model consumer** is an external caller of the models ctx serves (`/v1`, not **Field rule — revoking is always allowed, granting needs a release.** On `model-consumer-update` each field is compared with the consumer as it stands (under its row lock, so a concurrent write is what the comparison sees): narrowing `allowed_cidrs` (a list whose every prefix lies inside a current one, or a list where there was none), `tenant_scope` → null, `all_models` → false, `allow_plaintext` → false, a higher `prompt_sensitivity`, a lower `fair_weight`, `admission_lane` `urgent` → `bulk`, deactivating (`active` false), `label` and `description` — always open to a tenant-admin. Removing an id from `models` is revoking too. Setting or changing `tenant_scope`, `all_models` true, adding an id to `models`, widening or removing `allowed_cidrs` and reactivating are **granting**: tenant-admin only with self-service. `kind = ctx-peer` (create), a lower `prompt_sensitivity`, `allow_plaintext = true`, a higher `fair_weight`, `admission_lane = urgent` and `record_bodies = true` stay **server-admin even with self-service**; on create they are measured against the defaults (`app`, `credentials`, `1`, `bulk`, no plaintext, no recording). `record_bodies` → `false` is revoking, open to a tenant-admin. **Peer row tier:** every granting change of a `ctx-peer` consumer — rotation, a granting update, reactivation — is server-admin only. `kind` is fixed at create; `tenant_id`, the peer binding and any key expiry cannot be updated — an unknown field is a `400`, `expires_at` included (a new expiry needs a new key: `model-key-rotate`). -**Recording** (`record_bodies`, migration 197, issue #571). With `record_bodies: true` every request the consumer sends through the gateway is held in `context_llm_recordings` **before it is served**: the body as the gateway read it, byte for byte — whatever `gateway.body_logging`, the alias, `prompt_sensitivity`, the body scan or `Ctx-Sensitivity` say, no cut, credentials in a prompt included —, then the answer the client got and the outcome ([telemetry](#telemetry--logging), [security](security.md#gateway-telemetry-v1-v2), [operations](operations.md#recording-a-consumer)). Switching it on (create, or update from `false`) needs `confirm_record_bodies: true`, else `400` with `record_bodies:true holds every request and answer of this consumer in full in context_llm_recordings — credentials in a prompt included, in clear text, readable in the database — requires confirm_record_bodies:true`; the tier check comes first, so a tenant-admin gets the shared `403 admin key required` with or without the confirmation. Sending the value a consumer already has is no change (no tier, no confirmation); `confirm_record_bodies` alone changes nothing; `null` is a `400`. Every change is an audited `update` row (`record_bodies` in `old_value`/`new_value`). A switch applies from the consumer's next request (the door reads it with the key, migration 197's `ctx_model_auth` column); a request already running keeps what it was admitted with. +**Recording** (`record_bodies`, migration 197, issue #571). With `record_bodies: true` every request the consumer sends through the gateway is held in `context_llm_recordings` **before it is served**: the body as the gateway read it, byte for byte — whatever `gateway.body_logging`, the alias, `prompt_sensitivity`, the body scan or `Ctx-Sensitivity` say, no cut, credentials in a prompt included —, then the answer the client got (an embeddings answer without its vectors: the input is the record) and the outcome ([telemetry](#telemetry--logging), [security](security.md#gateway-telemetry-v1-v2), [operations](operations.md#recording-a-consumer)). Switching it on (create, or update from `false`) needs `confirm_record_bodies: true`, else `400` with `record_bodies:true holds every request of this consumer in full in context_llm_recordings, with the answer it got (embedding vectors excepted) — credentials in a prompt included, in clear text, readable in the database — requires confirm_record_bodies:true`; the tier check comes first, so a tenant-admin gets the shared `403 admin key required` with or without the confirmation. Sending the value a consumer already has is no change (no tier, no confirmation); `confirm_record_bodies` alone changes nothing; `null` is a `400`. Every change is an audited `update` row (`record_bodies` in `old_value`/`new_value`). A switch applies from the consumer's next request (the door reads it with the key, migration 197's `ctx_model_auth` column); a request already running keeps what it was admitted with. **Model grants** (`models`, migration 164). `all_models: true` releases every model alias the consumer can see; otherwise only the aliases listed in `models` — by **id**, never by name: a deleted alias takes its grants with it, and an alias created later under the same name is granted to no one. `models` is a target set (duplicates and spellings are folded, the answer lists them sorted; on update `null` is a `400` and `[]` removes every grant; on create `null`, `[]` and an absent field all mean none); the server turns it into the grants to add and to remove, in the transaction of the update. Every id it **adds** must be one the consumer's own `tenant_scope` is offered — an enabled alias with a valid policy, `_global` or of that scope, and not a `_global` alias that a tenant alias of the same name (enabled or not) takes the place of; a consumer without `tenant_scope` is offered `_global` aliases only, and so is a `ctx-peer` consumer whatever its `tenant_scope` — a peer resolves model names against `_global` aliases only. The caller's own scope plays no part. Any other id — unknown, deleted, disabled, invalid, of another scope, shadowed — is `400` with `"param": "models"` and one text for all these reasons (a malformed id is a `400` at `models` as well); when the scope changes in the same update, the new scope decides. An id the consumer already holds is not judged again, so a grant stays when its alias is disabled later or a later `tenant_scope` change hides it — it then releases nothing (the request time checks visibility again). The list is judged against the server's in-memory alias catalog, which follows an alias write within moments; an alias created a moment ago may still be a `400`. Without the catalog (a wiring fault) a `models` write that adds an id is `503`; removing grants still works. Deleting an alias that an **active** consumer holds an explicit grant on is `409` with `"code": "model_granted"` and `"count"` — the number of such consumers, never who they are; `all_models` is no grant and does not count. Remove the alias from their `models`, or deactivate them, first; grants of inactive consumers go with the alias. A held grant that its consumer can no longer see — its alias was disabled, or a later `tenant_scope` change hid it — releases nothing but still counts for this `409` until it is removed from `models` (or the consumer is deactivated). The SPA's create dialog (`/gateway`, wave W05-06) is a client of exactly this rule: it offers the aliases of the chosen `tenant_scope` the way the server's offer does (enabled ones, a tenant alias in place of the `_global` one of the same name, shadowing by presence), sends the picked **ids** as `models` (or `all_models: true`), never sends `kind`, and shows a `400` at `models` in the dialog. @@ -655,7 +655,7 @@ External programs that hold a model key (`ctxm_…`, see [model consumers](#mode - **Statuses.** `401 invalid_api_key` (with `WWW-Authenticate: Bearer realm="ctx"`), `404 not_found`, `404 model_not_found` (one fixed body for a model that does not exist, belongs to another tenant, is not released to the key, is disabled or has a broken policy — no oracle: without `all_models` every name costs the same one grant probe, so the time does not tell the cases apart either), `405 method_not_allowed` (with `Allow`), `413 request_too_large`, `429 rate_limit_exceeded` (the door's failure lock, `Retry-After`), `503 proxy_misconfigured` (`X-Forwarded-For` without `CTX_TRUSTED_PROXY`, see [operations](operations.md#environment-variables)), `503 auth_overloaded` (`Retry-After: 1`) and `503 auth_unavailable` (the door's database step), `503 server_overloaded` with `Retry-After: 1` and `x-should-retry: true` when the in-flight budget (`gateway.inflight_budget`, 3 × the body plus a response reserve per request, and for an alias below `credentials` the sensitivity scan's 23 × the body + 128 KiB + 104 bytes per nesting level (up to 1 040 104 bytes at the decoder's depth limit) on top — for bodies up to the scan cap `gateway.scan_max_request_bytes`, a longer one is `413 request_too_large` before the scan; the JSON check's nesting state, up to 240 024 bytes at the decoder's depth limit, is booked before the check and takes the share's rest or grows it; the configuration refuses a budget that cannot hold one request at every cap) is exhausted — refused at once, never queued — and `503 internal_error` with `x-should-retry: false` for every fault inside ctx: a recovered panic, a failed grant read (one that does not answer within the door's 1-s deadline included), a wiring defect. A fault inside ctx is a `503`, not a `500`: a peer ctx falls over to its next backend on a `503` but stops its chain on a `500`. The only `500` the gateway will send is a relayed upstream `500` (`upstream_error`). - **Federation guard.** The group carries the federation loop guard and the ingress policy between the key door and the body cap (`EnabledGate → ModelAuth → LoopGuard → PeerIngress → body cap`), refusing in this envelope with the codes of [federation refusals](#federation-refusals-ctx-hop-ctx-path). `gateway.enabled` cannot be turned on while no model group with both stages is mounted: the settings write is a `409`, the boot refuses. - **Federation headers a client may send.** `Ctx-Sensitivity` (`public`, `internal`, `personal`, `credentials`) raises the sensitivity the serving chain must admit above the consumer's own level and never lowers it — from any consumer; an unknown value counts as `credentials`. `Ctx-Egress: local` (or an unreadable value) keeps the request on this instance's own engines: no other ctx instance, no row that answered as one, no external row; absent or `any`, at most one further hop to a row known as a ctx instance (provider class `ctx` or a learned instance — a ctx instance registered as `generic` is not known as one, see [security](security.md#federation-ingress-policy-peeringress)). A `ctx-peer` consumer that sends no `Ctx-Path` is always served as `local`. `Ctx-Max-Wait-Ms` can only shorten this instance's queue wait. `Ctx-Class` and `Ctx-Pipeline` take effect only from a `ctx-peer` consumer that also sends `Ctx-Path`; from an app they are ignored (no lane claim through a header). Prompts of a consumer below `credentials` are scanned for secrets over every string field of the body; a hit serves the request as `credentials` ([security](security.md#federation-ingress-policy-peeringress)). -- **Code vocabulary.** The full table of codes with their status and type is exported data (`oai.Codes()`, a copy): the statuses above plus `invalid_json`, `missing_required_parameter`, `invalid_type`, `unsupported_parameter`, `unsupported_value`, `model_not_supported`, `context_length_exceeded`, `upstream_rejected` (400), `permission_denied` (403), `server_busy`, `concurrency_limit_exceeded` (429 `rate_limit_error`), `insufficient_quota` (429 `insufficient_quota`), `service_unavailable`, `model_unavailable`, `no_eligible_backend`, `upstream_unavailable` (503), `upstream_error` (500), `upstream_timeout` (504) and the federation codes `federation_header_invalid`, `federation_hop_required` (400), `peer_instance_mismatch` (403), `federation_loop`, `federation_depth` (508). The three door codes `proxy_misconfigured`, `auth_overloaded`, `auth_unavailable` are `503 service_unavailable_error`, and so is `recording_unavailable` (`x-should-retry: true`, `Retry-After: 1`): a request of a [recording consumer](#model-consumer-administration) whose recording could not be committed — never served, no backend called. +- **Code vocabulary.** The full table of codes with their status and type is exported data (`oai.Codes()`, a copy): the statuses above plus `invalid_json`, `missing_required_parameter`, `invalid_type`, `unsupported_parameter`, `unsupported_value`, `model_not_supported`, `context_length_exceeded`, `upstream_rejected` (400), `permission_denied` (403), `server_busy`, `concurrency_limit_exceeded` (429 `rate_limit_error`), `insufficient_quota` (429 `insufficient_quota`), `service_unavailable`, `model_unavailable`, `no_eligible_backend`, `upstream_unavailable` (503), `upstream_error` (500), `upstream_timeout` (504) and the federation codes `federation_header_invalid`, `federation_hop_required` (400), `peer_instance_mismatch` (403), `federation_loop`, `federation_depth` (508). The three door codes `proxy_misconfigured`, `auth_overloaded`, `auth_unavailable` are `503 service_unavailable_error`, and so is `recording_unavailable` (`x-should-retry: true`, `Retry-After: 1`): a request of a [recording consumer](#model-consumer-administration) whose recording could not be committed. When the request itself could not be held — before the walk — it was never served and no backend was called; when what a backend answered could not be held — a non-streamed answer, or an error answer carrying the backend's text — the backend ran, and the client's retry runs it again. - **Conformance.** The envelope and the model list are checked against the official OpenAI SDKs — Go `openai-go/v3` in the regular test run, Python `openai` (`go test -tags=pyconformance ./internal/oai/`, needs `uv`; nightly in CI as `gateway-sdk-smoke`) — and against the `ErrorResponse`, `ListModelsResponse` and `Model` schemas of the OpenAI spec (vendored excerpts under `go/conformance/oai/testdata/`). The contract of the whole surface is `go/conformance/oai/contract.json`: every route of `/v1` and `/v2` with every answer form (chat also its stream chunk and error frame) and the pinned schema it validates against — the rerank answer against a ctx-owned schema (`ctx-rerank-response.json`), since OpenAI defines none — and every code of the vocabulary goes through the Go SDK as a valid `ErrorResponse` with its `x-should-retry`. The CI job `Conformance` runs exactly these checks on every pull request and is a required check; a route mounted without a contract, a form without a pinned schema or an answer without the envelope fails it. ### Admission diff --git a/docs/operations.md b/docs/operations.md index fa838380a..cdcc933ad 100644 --- a/docs/operations.md +++ b/docs/operations.md @@ -2389,7 +2389,7 @@ Issue #571. `context_model_consumers.record_bodies BOOLEAN NOT NULL DEFAULT fals **Locks.** `ADD COLUMN` with a constant default rewrites nothing: `ACCESS EXCLUSIVE` on `context_model_consumers` until the commit (the table holds at most `max_model_consumers`, 64 by default, rows per tenant) — milliseconds during which a `/v1` door check (`ctx_model_auth` reads the table) and every consumer write of another ctx process on the same database wait. `CREATE TRIGGER` takes `SHARE ROW EXCLUSIVE` on the same table inside that window; dropping and creating the function locks no table, a session calling it meanwhile uses the old definition until the commit; creating the new table locks nothing that exists. `lock_timeout 3s` fails the boot instead of queueing behind a long transaction; the next start retries. -**Rolling deploy and way back.** The release before (v5.89.0) runs unchanged on a database with 197 (executed: its auth, model-key door, consumer administration and `/v1` chat-row tests over a schema with 197): its door selects `ctx_model_auth`'s columns by name and does not see the new one, its consumer writes leave the column at its default, and it serves a recording consumer as before — **without recording it** (it knows neither the switch nor the table). Run the two side by side only while no consumer records, or accept that the older process's share of that consumer's requests is not held. Its schema-contract check reports the unknown migration as for every release ahead of it (`schema_contract: attention`; mode `enforce` refuses to start). The way back, in this order: `DROP TABLE context_llm_recordings;` (its rows go with it — read them out first); `DROP FUNCTION ctx_model_auth(TEXT, INET, BOOLEAN);` the `CREATE OR REPLACE FUNCTION ctx_model_auth` of migration 161 (section 8); the `CREATE OR REPLACE FUNCTION audit_state_model_consumer` of 161 (section 7); `DROP TRIGGER trg_model_consumers_audit_upd ON context_model_consumers;` and the `CREATE TRIGGER trg_model_consumers_audit_upd` of 161; `ALTER TABLE context_model_consumers DROP COLUMN record_bodies;` `DELETE FROM _migrations WHERE version = 197;` — `TestMigration197Idempotent` runs exactly these and compares the catalog with 196's. +**Rolling deploy and way back.** The release before (v5.89.0) runs unchanged on a database with 197 (executed: its auth, model-key door, consumer administration and `/v1` chat-row tests over a schema with 197): its door selects `ctx_model_auth`'s columns by name and does not see the new one, its consumer writes leave the column at its default, and it serves a recording consumer as before — **without recording it** (it knows neither the switch nor the table). Run the two side by side only while no consumer records, or accept that the older process's share of that consumer's requests is not held — that is the rolling deploy; it does not carry over to the way back. Its schema-contract check reports the unknown migration as for every release ahead of it (`schema_contract: attention`; mode `enforce` refuses to start). The way back: first stop every ctxd process of a release that embeds migration 197 and keep it stopped until the steps below are done and only the older release runs — a process of 197 that keeps running fails at its model-key door once `ctx_model_auth` has its 161 shape again, and one that starts after the `_migrations` row is gone applies 197 again and undoes the way back. Then, in this order: `DROP TABLE context_llm_recordings;` (its rows go with it — read them out first); `DROP FUNCTION ctx_model_auth(TEXT, INET, BOOLEAN);` the `CREATE OR REPLACE FUNCTION ctx_model_auth` of migration 161 (section 8); the `CREATE OR REPLACE FUNCTION audit_state_model_consumer` of 161 (section 7); `DROP TRIGGER trg_model_consumers_audit_upd ON context_model_consumers;` and the `CREATE TRIGGER trg_model_consumers_audit_upd` of 161; `ALTER TABLE context_model_consumers DROP COLUMN record_bodies;` `DELETE FROM _migrations WHERE version = 197;` — `TestMigration197Idempotent` runs exactly these and compares the catalog with 196's. ### `graph_overview.csr_loader`: the rebuild's input substrate diff --git a/go/internal/auth/consumer.go b/go/internal/auth/consumer.go index 14fae1800..a86f479e3 100644 --- a/go/internal/auth/consumer.go +++ b/go/internal/auth/consumer.go @@ -51,10 +51,10 @@ type ConsumerAuth struct { AdmissionLane string // 'urgent' | 'bulk' — the external lane ceiling (design/03) PeerInstanceID string // a ctx-peer's bound instance id; "" = not bound // RecordBodies is the consumer's recording switch (migration 197): every - // gateway row of the request keeps its request and answer in full - // (llmlog.GatewayRow.Recorded). It is read once at the door, like every - // other column: a switch applies from the next request on. It changes - // what the row carries and nothing on the request path. + // request is held in full in context_llm_recordings before it is served, + // with the answer it got, embedding vectors excepted (internal/oai + // record.go). It is read once at the door, like every other column: a + // switch applies from the next request on. RecordBodies bool } diff --git a/go/internal/handler/model_consumers.go b/go/internal/handler/model_consumers.go index 50c4cc4d8..13738a1e7 100644 --- a/go/internal/handler/model_consumers.go +++ b/go/internal/handler/model_consumers.go @@ -580,8 +580,9 @@ func (d *consumerCreateRequest) grant() consumerGrant { // confirm_record_bodies (the confirm_trust_elevation pattern): the switch // stores what the consumer sends in clear text, credentials in a prompt // included. -const recordConfirmRefusal = "record_bodies:true holds every request and answer of this consumer in full in context_llm_recordings — " + - "credentials in a prompt included, in clear text, readable in the database — requires confirm_record_bodies:true" +const recordConfirmRefusal = "record_bodies:true holds every request of this consumer in full in context_llm_recordings, with the answer it got " + + "(embedding vectors excepted) — credentials in a prompt included, in clear text, readable in the database — " + + "requires confirm_record_bodies:true" // errRecordConfirm is the refusal of recordConfirmRefusal under the consumer // lock (store.UpdateConsumerChecked); it surfaces as that 400. diff --git a/go/internal/handler/model_consumers_read.go b/go/internal/handler/model_consumers_read.go index cca8e52e4..90539b668 100644 --- a/go/internal/handler/model_consumers_read.go +++ b/go/internal/handler/model_consumers_read.go @@ -41,9 +41,10 @@ type consumerView struct { AdmissionLane string `json:"admission_lane"` AllowedCIDRs []string `json:"allowed_cidrs"` AllowPlaintext bool `json:"allow_plaintext"` - // RecordBodies: every gateway row of the consumer keeps its request and - // answer in full (migration 197) — shown to every reader of the - // consumer, its tenant-admins included. + // RecordBodies: every request of the consumer is held in full in + // context_llm_recordings with the answer it got, embedding vectors + // excepted (migration 197) — shown to every reader of the consumer, its + // tenant-admins included. RecordBodies bool `json:"record_bodies"` Active bool `json:"active"` Status string `json:"status"` diff --git a/go/internal/handler/model_consumers_record_integration_test.go b/go/internal/handler/model_consumers_record_integration_test.go index fd467b1e5..7c9b34dfb 100644 --- a/go/internal/handler/model_consumers_record_integration_test.go +++ b/go/internal/handler/model_consumers_record_integration_test.go @@ -47,8 +47,9 @@ func TestModelConsumerRecordSwitch(t *testing.T) { const adminRequired = "admin key required" // The wire text of the refusal (recordConfirmRefusal), spelled out so the // file compiles against the base. - const confirm = "record_bodies:true holds every request and answer of this consumer in full in context_llm_recordings — " + - "credentials in a prompt included, in clear text, readable in the database — requires confirm_record_bodies:true" + const confirm = "record_bodies:true holds every request of this consumer in full in context_llm_recordings, with the answer it got " + + "(embedding vectors excepted) — credentials in a prompt included, in clear text, readable in the database — " + + "requires confirm_record_bodies:true" recordOf := func(resp map[string]any) any { c, _ := resp["consumer"].(map[string]any) return c["record_bodies"] diff --git a/go/internal/llmlog/gateway.go b/go/internal/llmlog/gateway.go index 798b34232..9348017c8 100644 --- a/go/internal/llmlog/gateway.go +++ b/go/internal/llmlog/gateway.go @@ -374,7 +374,8 @@ type GatewayRow struct { // Recorded is the consumer's recording switch as the door read it // (auth.ConsumerAuth.RecordBodies, migration 197), RecordingID the // request's row in context_llm_recordings (recordings.go), which holds - // its request and answer whole. The row here is the row of every other + // its request whole and its answer (an embeddings answer without its + // vectors). The row here is the row of every other // consumer without its bodies — none under any body policy: the // recording is their one place — plus metadata.gw.recorded and // recording_id. diff --git a/go/internal/llmlog/recordings.go b/go/internal/llmlog/recordings.go index 870788066..9b9a191c8 100644 --- a/go/internal/llmlog/recordings.go +++ b/go/internal/llmlog/recordings.go @@ -13,7 +13,8 @@ import ( // record_bodies on has every request it sends through the gateway held in // context_llm_recordings: one row per request, keyed by the request's own // id, with the body as the gateway read it, byte for byte (bytea — no -// cleaning, no cut, no seal), the answer the client got, and the outcome. +// cleaning, no cut, no seal), the answer the client got (an embeddings +// answer without its vectors: the input is the record), and the outcome. // The gateway writes the row synchronously and in order (internal/oai // record.go): Open commits the request BEFORE the first backend attempt — // a request that cannot be held is not served —, Finish ends it with its diff --git a/go/internal/schemacontract/manifest.json b/go/internal/schemacontract/manifest.json index 9e2d6c8fa..5697fb933 100644 --- a/go/internal/schemacontract/manifest.json +++ b/go/internal/schemacontract/manifest.json @@ -3,7 +3,7 @@ "generated_against": { "migration_max": 197, "migration_count": 85, - "migration_chain_sha256": "a5dae7b8f260cd9e7fe03073cecf4aca2c92c4ac17745ce36756907868d49b2d", + "migration_chain_sha256": "6d1f1b2c6f2943ff5b03b948fe4c222cf33200f1555e6e27cb1e5ae0a44da540", "pg_major": 18, "image": "pgvector-timescaledb:pg18" }, diff --git a/go/migrations/197_model_consumer_record_bodies.sql b/go/migrations/197_model_consumer_record_bodies.sql index f07dc76fe..dc1bc5398 100644 --- a/go/migrations/197_model_consumer_record_bodies.sql +++ b/go/migrations/197_model_consumer_record_bodies.sql @@ -50,7 +50,8 @@ -- keyed by the request's own id (the uuid v7 the answer's id carries, -- "chatcmpl-"). state 'open' from the insert before the first -- backend attempt until the request ended; 'done' with the status the --- client got, the gateway's code and the answer. A row that stays 'open' +-- client got, the gateway's code and the answer (an embeddings answer +-- without its vectors: the input is the record). A row that stays 'open' -- is unfinished: the process ended (or the database failed) between -- holding the request and recording its outcome — its request is there, -- its outcome is not known; a stream row that stays 'open' may have diff --git a/go/web/src/routes/gateway/format.ts b/go/web/src/routes/gateway/format.ts index b2092abbe..dca38307f 100644 --- a/go/web/src/routes/gateway/format.ts +++ b/go/web/src/routes/gateway/format.ts @@ -24,7 +24,7 @@ export function consumerTone(status: string): 'ok' | 'warn' | 'off' { /** What the consumer view says while recording is on (record_bodies, issue #571) — the server's flag, shown to every reader. */ export const recordingText = - 'on — every request and answer of this consumer is held in full in context_llm_recordings, credentials in a prompt included; readable in the database only' + 'on — every request of this consumer is held in full in context_llm_recordings with the answer it got (embedding vectors excepted), credentials in a prompt included; readable in the database only' /** Badge tone of a key status: active ok, expiring/superseded (grace running) warn, dead off. */ export function keyTone(status: ModelKeyStatus | string): 'ok' | 'warn' | 'off' { From 4a08d298d15feaa6d9b4802e6dec8839943f510b Mon Sep 17 00:00:00 2001 From: Jan-Stefan Janetzky Date: Fri, 27 Nov 2026 08:16:53 +0100 Subject: [PATCH 19/27] fix(gateway): the check between a held answer's commit and its write holds past the request deadline, and a held answer replaced by 503 supersedes its row MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Found by a fresh reviewer of this round. The commit of an answer is not cut by the request deadline, so the check after it can run past that deadline — where the run's context keeps the deadline as its cause: a revocation was then not seen (the client got the answer), and a switched off model API, a gone alias or the shutdown wrote nothing (an empty 200). heldStillServes now reads the revocation on the request's own context, and refuseHeld writes the refusal for the cause directly. And a held error answer whose row commit failed is replaced by 503 recording_unavailable — flushed first, then written over the row with Supersedes, so a commit that went through without its acknowledgement leaves no error answer the client never got. Co-Authored-By: Claude Opus 5.5 --- docs/operations.md | 2 +- go/internal/oai/chat.go | 4 +- go/internal/oai/embeddings.go | 4 +- go/internal/oai/record.go | 98 ++++++++++++++----- go/internal/oai/record_route_test.go | 141 +++++++++++++++++++++++++-- go/internal/oai/rerank.go | 4 +- 6 files changed, 216 insertions(+), 37 deletions(-) diff --git a/docs/operations.md b/docs/operations.md index cdcc933ad..2fe704ab3 100644 --- a/docs/operations.md +++ b/docs/operations.md @@ -986,7 +986,7 @@ ctx manage model-consumer-update '' '{"id":"","record_bodies":true, **What a row holds.** `request_body` is the body as the gateway read it, byte for byte (bytea: invalid UTF-8 and NUL bytes included, no cut, no seal — a password, a token or a private key in a prompt is stored in clear text); `request_complete` says whether that is the whole body (a body cut short holds the part read), `declared_bytes` its `Content-Length`. `response_body` is the answer the client got: a non-streamed chat or rerank answer as written, a stream's relayed `data:` lines in order (without keepalives, the closing `[DONE]` or an error frame), and for every answer that is not a `2xx` — a refusal, an error, a backend's rejection whose text the gateway relays (`gateway.relay_upstream_4xx_messages`) — its error body as written; none for a successful embeddings answer (the vectors are not kept — the input is the record) and none for `503 recording_unavailable` (its bytes are fixed). `state` is `open` from the hold until the outcome is recorded, then `done` with `status` (the HTTP status the client got; `NULL` when the gateway wrote nothing — the client had gone), `code` (the gateway's code of a refusal or an error, where the refusing stage names one — the catch-alls of an unknown path and a wrong method leave it `NULL`), `finished_at`. `op`, `model` and `stream` are what the route read (`NULL` when no route parsed the request), `path` the request's path, `process_id` the ctxd process that admitted it. The row's `id` is the request's id: a chat answer's `id` is `chatcmpl-`, a rerank answer's `rerank-`, and the request's `context_llm_log` row carries it as `metadata.gw.recording_id` (with `metadata.gw.recorded: true`; that row carries no bodies under any `gateway.body_logging` value — the recording is their one place). -**Held before served.** The route commits the row — the whole request, state `open` — before the first backend attempt and before any queue wait; a request whose row cannot be committed is answered `503 recording_unavailable` (`Retry-After: 1`, `x-should-retry: true`) and no backend sees it: the database refuses the insert, or it does not answer within **5 s** (a fixed statement deadline), or the recording's memory account or its statement slots (below) have no room within `dispatch.external_max_wait` (20 s). The `503` reaches the client at once; the gateway then tries once more to leave the request's row (up to another 5 s, the client does not wait for it). A non-streamed answer is committed with the outcome before its first byte is written; if that fails, the client gets the same `503` instead of the answer (the backend ran: the meter books its usage; the client's retry is a second row). An answer that is not a `2xx` is held from the client until the row holds it with its bytes; if that row cannot be written after a backend was asked, the client gets the `503` in its place — a refusal before the walk (no backend asked) goes out as it is. A request that stops being served while its answer is being committed — its key revoked or its consumer deactivated, the model API switched off, the alias gone, the shutdown — gets the refusal it would have got before the commit (`401 invalid_api_key` for a revoked key), never the answer, and its row's outcome becomes that refusal; so does a `503` whose answer commit failed although it went through (its acknowledgement lost): the row never claims an answer the client did not get. A stream relays a line only after the recording kept it in memory; its lines are committed when it ends — what a stream sent cannot be taken back, so a stream whose end cannot be committed leaves its row `open` with its request and is counted in `stream_answers_unrecorded`. A request the gateway refuses after the door accepted the key — a body that does not parse, an unknown model, a limit, a body over `gateway.max_request_bytes` (never read: the row holds its declared size), an unknown path, a wrong method — gets its row at its end, `done`, with what was read of the body. Refusals before the door (`401`, a wrong key) are not the consumer's and leave nothing. A process that dies between the hold and the outcome leaves the row `open`: its request is there, its outcome is not known. +**Held before served.** The route commits the row — the whole request, state `open` — before the first backend attempt and before any queue wait; a request whose row cannot be committed is answered `503 recording_unavailable` (`Retry-After: 1`, `x-should-retry: true`) and no backend sees it: the database refuses the insert, or it does not answer within **5 s** (a fixed statement deadline), or the recording's memory account or its statement slots (below) have no room within `dispatch.external_max_wait` (20 s). The `503` reaches the client at once; the gateway then tries once more to leave the request's row (up to another 5 s, the client does not wait for it). A non-streamed answer is committed with the outcome before its first byte is written; if that fails, the client gets the same `503` instead of the answer (the backend ran: the meter books its usage; the client's retry is a second row). An answer that is not a `2xx` is held from the client until the row holds it with its bytes; if that row cannot be written once the request reached its walk, the client gets the `503` in its place, and the row is written with that `503` — a refusal before the walk (no backend asked) goes out as it is. A request that stops being served while its answer is being committed — its key revoked or its consumer deactivated, the model API switched off, the alias gone, the shutdown; also when its request deadline passed during the commit — gets the refusal it would have got before the commit (`401 invalid_api_key` for a revoked key), never the answer, and its row's outcome becomes that refusal; so does a `503` whose answer commit failed although it went through (its acknowledgement lost): the row never claims an answer the client did not get. A stream relays a line only after the recording kept it in memory; its lines are committed when it ends — what a stream sent cannot be taken back, so a stream whose end cannot be committed leaves its row `open` with its request and is counted in `stream_answers_unrecorded`. A request the gateway refuses after the door accepted the key — a body that does not parse, an unknown model, a limit, a body over `gateway.max_request_bytes` (never read: the row holds its declared size), an unknown path, a wrong method — gets its row at its end, `done`, with what was read of the body. Refusals before the door (`401`, a wrong key) are not the consumer's and leave nothing. A process that dies between the hold and the outcome leaves the row `open`: its request is there, its outcome is not known. **Checking that nothing is missing.** `GET /api/status` (server-admin) carries `gateway.recording`: `process_id` and `since` (this process's start), `held_bytes` (the memory account's fill), and per recording consumer `admitted` (requests that passed the door as it), `in_flight`, `recorded` (requests whose row is in the table), `unrecordable` (requests for which no row could be written at all — an inference request is then refused with `recording_unavailable`, never served; see the model list below), `unfinished` (requests whose final outcome could not be written: their row stayed `open` — or, for an answer committed and then withheld as above whose superseding outcome could not be written either, it keeps that answer and its `200`; the `ERROR` line below says `answer_withheld=true` and names the `recording_id`) and `stream_answers_unrecorded` (the streams among them that had sent lines). `admitted = in_flight + recorded + unrecordable` holds at every moment, and `recorded` equals the table's rows of that consumer and process: diff --git a/go/internal/oai/chat.go b/go/internal/oai/chat.go index 2a1550880..5e37bbd16 100644 --- a/go/internal/oai/chat.go +++ b/go/internal/oai/chat.go @@ -1321,10 +1321,10 @@ func (c *chatCall) success(plan Plan, st *walkState) chatOutcome { if c.recording != nil { // The commit took its time: a request that stopped being served // meanwhile does not get the answer it held (record.go). - if err := c.d.heldStillServes(c.ctx, c.target); err != nil { + if err := c.d.heldStillServes(c.ctx, c.client, c.target); err != nil { c.recording.withhold() c.cancel(err) - _, code := c.verdict() + code := refuseHeld(err, c.rec, c.w, c.r) return chatOutcome{finish: llmlog.FinishAborted, redacted: &llmlog.RedactedErr{Class: backends.ClassCanceled.String(), Code: code}} } } diff --git a/go/internal/oai/embeddings.go b/go/internal/oai/embeddings.go index 4bc1bfc4a..44ec36143 100644 --- a/go/internal/oai/embeddings.go +++ b/go/internal/oai/embeddings.go @@ -1402,10 +1402,10 @@ func (c *embedCall) success(st *embedState) embedOutcome { if c.recording != nil { // The commit took its time: a request that stopped being served // meanwhile does not get the answer (record.go). - if err := c.d.heldStillServes(c.ctx, t); err != nil { + if err := c.d.heldStillServes(c.ctx, c.client, t); err != nil { c.recording.withhold() c.cancel(err) - _, code := c.verdict() + code := refuseHeld(err, c.rec, c.w, c.r) return embedOutcome{finish: llmlog.FinishAborted, redacted: &llmlog.RedactedErr{Class: backends.ClassCanceled.String(), Code: code}} } } diff --git a/go/internal/oai/record.go b/go/internal/oai/record.go index 73a42eee5..4eff41a31 100644 --- a/go/internal/oai/record.go +++ b/go/internal/oai/record.go @@ -41,8 +41,9 @@ import ( // Every answer that is not a 2xx — a refusal, an error, a backend's // rejection whose text the gateway relays — is held from the client by // the stage's writer until the request's outcome is committed with its -// bytes (release); one whose row cannot take it after a backend was -// asked is 503 recording_unavailable in its place. A request that +// bytes (release); one whose row cannot take it once the row was opened +// (the request reached its walk) is 503 recording_unavailable in its +// place, and that 503 supersedes the row. A request that // stops being served while its answer is committed (a revoked key, the // model API switched off — heldStillServes) gets that refusal, never the // answer, and its outcome supersedes the committed answer in the row; @@ -438,24 +439,50 @@ func (rr *requestRecording) withhold() { // (D8 for the time the commit took; stillServes ran before it): the model // API switched off, the alias gone (in memory; the grant is read again only // when the alias registry moved since the entry, as a watcher tick does), -// the key revoked or its consumer deactivated (the door's registry ended -// the request with auth.ErrCredentialRevoked), the shutdown. A cause: the -// answer does not go out — the route answers the cause and withholds it. A -// request deadline that passed during the commit is none: the answer is -// ready (answer). -func (d Deps) heldStillServes(ctx context.Context, t watchTarget) error { +// the shutdown, the key revoked or its consumer deactivated — read on the +// request's own context client, which the door's registry ends with +// auth.ErrCredentialRevoked: the run's context ctx may have passed its +// deadline during the commit, and a context that ended keeps its first +// cause. A cause: the answer does not go out — the route answers it +// (refuseHeld) and withholds the answer. A deadline that passed during the +// commit is none: the answer is ready (answer). +func (d Deps) heldStillServes(ctx, client context.Context, t watchTarget) error { if _, err := d.recheck(ctx, t, t.gen, false); err != nil { return err } if d.Lifecycle != nil && d.Lifecycle.Err() != nil { return errShutdown } - if cause := context.Cause(ctx); errors.Is(cause, auth.ErrCredentialRevoked) { + if cause := context.Cause(client); errors.Is(cause, auth.ErrCredentialRevoked) { return cause } return nil } +// refuseHeld answers a request whose held answer heldStillServes stopped +// with the refusal the route's verdict gives that cause — written here, not +// through the verdict, which reads the run's context: past its deadline that +// context's cause is the deadline whatever ended the request since. It +// returns the refusal's code. +func refuseHeld(cause error, rec *AccessRecord, w http.ResponseWriter, r *http.Request) string { + switch { + case errors.Is(cause, errGatewayOff): + rec.Reason = CodeNotFound + NotFound(w, r) + return CodeNotFound + case errors.Is(cause, errModelGone): + refuseModelNotFound(w, r) + return CodeModelNotFound + case errors.Is(cause, errShutdown): + rec.Reason = CodeInternalError + WriteCode(w, CodeInternalError, shutdownMessage, true) + return CodeInternalError + } + rec.Reason = CodeInvalidAPIKey // auth.ErrCredentialRevoked + WriteInvalidAPIKey(w) + return CodeInvalidAPIKey +} + // finish commits o on the open row. The statement's copies of o.Response // wait for room for an answer of the request's own (a chat answer); for a // captured one (a stream's lines, a rerank answer) they are taken past the @@ -579,12 +606,9 @@ func (rr *requestRecording) end(code string) { rr.req.Body = nil // in the row since the open if err := rr.finish(ctx, o); err != nil { rr.unfinished = true - // answer_withheld: the row may hold an answer the client did not - // get (its commit went through before the request stopped being - // served, or its acknowledgement was lost) instead of staying open. - slog.Error("gateway: the outcome of a recorded request could not be recorded — its row stays open", - "consumer_id", rr.req.ConsumerID, "recording_id", rr.req.ID, "stream_answer_lost", rr.streamed, - "answer_withheld", rr.withheld, "error", err) + if !rr.holdingAnswer() { + rr.logUnfinished(err) + } // a held answer: release answers 503 in its place and supersedes the row (endStage) return } rr.settled = true @@ -604,6 +628,30 @@ func (rr *requestRecording) end(code string) { rr.row, rr.ended, rr.settled = true, true, true } +// logUnfinished is the ERROR of a request whose outcome could not be +// recorded: its row stays open — or, answer_withheld, it may keep an answer +// the client did not get (its commit went through before the request +// stopped being served, or its acknowledgement was lost). +func (rr *requestRecording) logUnfinished(err error) { + slog.Error("gateway: the outcome of a recorded request could not be recorded — its row stays open", + "consumer_id", rr.req.ConsumerID, "recording_id", rr.req.ID, "stream_answer_lost", rr.streamed, + "answer_withheld", rr.withheld, "error", err) +} + +// supersedeReplaced writes the outcome of a held answer that release +// replaced with 503 recording_unavailable — its row's commit failed, and it +// may have gone through all the same: that 503 supersedes whatever the row +// holds. A failure stays counted as unfinished. +func (rr *requestRecording) supersedeReplaced() { + rr.withheld = true + o := llmlog.RecordedOutcome{Status: http.StatusServiceUnavailable, Code: CodeRecordingUnavailable, Supersedes: true} + if err := rr.finish(context.Background(), o); err != nil { + rr.logUnfinished(err) + return + } + rr.unfinished, rr.settled = false, true +} + // dropCapture gives the captured answer back to the account. func (rr *requestRecording) dropCapture() { rr.acct.release(rr.held) @@ -630,8 +678,8 @@ func (rr *requestRecording) endStage(p any, w http.ResponseWriter) { _ = http.NewResponseController(w).Flush() } rr.end(code) - if p == nil { - rr.release(w) + if p == nil && rr.release(w) { + rr.supersedeReplaced() } recStats.done(rr.stats, rr.row, rr.unfinished, rr.unfinished && rr.streamed) } @@ -710,16 +758,18 @@ func (rr *requestRecording) dropHeld(status int) { // release writes the held answer once the request's outcome is decided: // as held when the row holds it (settled) or when the request never reached -// a backend (no open row: a refusal in the gateway's own words); otherwise — -// a backend was asked and the row could not take what the client would get — -// 503 recording_unavailable in its place, from the headers at the stage. -func (rr *requestRecording) release(w http.ResponseWriter) { +// its walk (no open row: a refusal in the gateway's own words, nothing a +// backend sent); otherwise — the row was opened and could not take what the +// client would get — 503 recording_unavailable in its place, from the +// headers at the stage, flushed before the row's superseding attempt; +// replaced reports that. +func (rr *requestRecording) release(w http.ResponseWriter) (replaced bool) { rr.statusMu.Lock() holding, code, body := rr.holding, rr.heldCode, rr.heldBody rr.holding, rr.heldBody, rr.passed = false, nil, true rr.statusMu.Unlock() if !holding { - return + return false } if !rr.settled && rr.opened { h := w.Header() @@ -728,12 +778,14 @@ func (rr *requestRecording) release(w http.ResponseWriter) { h[k] = v } refuseRecording(rr.access, w) - return + _ = http.NewResponseController(w).Flush() + return true } w.WriteHeader(code) if _, err := w.Write(body); err != nil { //nolint:gosec // G705: body is the route's own error envelope (WriteCode, refuseParam — encoding/json's escape), held and written unchanged: the bytes the unrecorded path writes slog.Warn("gateway: failed to write a held answer", "error", err, "recording_id", rr.req.ID) } + return false } // refuseRecording answers a request whose recording failed: 503 diff --git a/go/internal/oai/record_route_test.go b/go/internal/oai/record_route_test.go index c49df7bea..c48a5a68b 100644 --- a/go/internal/oai/record_route_test.go +++ b/go/internal/oai/record_route_test.go @@ -929,21 +929,21 @@ func postVia(t *testing.T, srv *httptest.Server, path, body string) chatAnswer { // are the request; answered tells the route's answer from a refusal. var recRoutes = []struct { name, path string - rig func(t *testing.T, store *recStore) *chatRig + rig func(t *testing.T, store *recStore, opts ...rigOption) *chatRig body string answered func(b []byte) bool }{ - {"chat", "/v1/chat/completions", func(t *testing.T, store *recStore) *chatRig { + {"chat", "/v1/chat/completions", func(t *testing.T, store *recStore, opts ...rigOption) *chatRig { u := newUpstream(t, recChatAnswer) - return newChatRig(t, []backends.Backend{u.row("spark", backends.TrustFull, 10)}, 4, 1, withRecordings(store)) + return newChatRig(t, []backends.Backend{u.row("spark", backends.TrustFull, 10)}, 4, 1, append(opts, withRecordings(store))...) }, chatBody("pub"), func(b []byte) bool { return strings.Contains(string(b), "the answer") }}, - {"embeddings", "/v1/embeddings", func(t *testing.T, store *recStore) *chatRig { + {"embeddings", "/v1/embeddings", func(t *testing.T, store *recStore, opts ...rigOption) *chatRig { e := newEmbedEngine(t, 8) - return newEmbedRig(t, []backends.Backend{e.row("spark-embed", backends.ProtocolOpenAI, 10)}, 4, 1, withRecordings(store)) + return newEmbedRig(t, []backends.Backend{e.row("spark-embed", backends.ProtocolOpenAI, 10)}, 4, 1, append(opts, withRecordings(store))...) }, embedBody("emb1", []string{"a"}), func(b []byte) bool { return strings.Contains(string(b), `"embedding"`) }}, - {"rerank", "/v1/rerank", func(t *testing.T, store *recStore) *chatRig { + {"rerank", "/v1/rerank", func(t *testing.T, store *recStore, opts ...rigOption) *chatRig { e := newRerankEngine(t) - return newRerankRig(t, []backends.Backend{e.row("spark-rerank", 10)}, 4, 1, withRecordings(store)) + return newRerankRig(t, []backends.Backend{e.row("spark-rerank", 10)}, 4, 1, append(opts, withRecordings(store))...) }, rerankBody("rrpub", "q", []string{"d1", "d2"}), func(b []byte) bool { return strings.Contains(string(b), "relevance_score") }}, } @@ -1045,3 +1045,130 @@ func TestRecordingRefusalGoesOutWhenItsRowFails(t *testing.T) { t.Errorf("counts %+v — want unrecordable 1, recorded 0", got) } } + +// TestRecordingHeldAnswerChecksPastTheDeadline: the request deadline may +// pass while an answer's commit waits (the commit is not cut by it); a +// request that stopped being served during that time — the model API +// switched off, the key revoked after the deadline or before it, the +// shutdown — still gets its refusal, never the answer and never an empty +// 200, and its row says what the client got. Chat, embeddings and rerank. +func TestRecordingHeldAnswerChecksPastTheDeadline(t *testing.T) { + want := map[string]struct { + status int + code string + }{ + "gateway_off": {http.StatusNotFound, oai.CodeNotFound}, + "revoked": {http.StatusUnauthorized, oai.CodeInvalidAPIKey}, + "revoked_before_deadline": {http.StatusUnauthorized, oai.CodeInvalidAPIKey}, + "shutdown": {http.StatusServiceUnavailable, oai.CodeInternalError}, + } + for _, rt := range recRoutes { + for _, mode := range []string{"gateway_off", "revoked", "revoked_before_deadline", "shutdown"} { + t.Run(rt.name+"/"+mode, func(t *testing.T) { + store := newRecStore(nil) + gate := make(chan struct{}) + var once sync.Once + defer once.Do(func() { close(gate) }) + store.set(func(s *recStore) { s.finishGate = gate }) + life, shutdown := context.WithCancel(context.Background()) + defer shutdown() + rig := rt.rig(t, store, func(r *chatRig) { r.deps.Lifecycle = life }) + rig.ca.Store(recordingConsumer(true)) + const deadline = 800 * time.Millisecond + rig.setSettings(func(s *oai.Settings) { s.RequestDeadline = deadline }) + rv := newRevoker() + srv := serveHTTP(t, rv.wrap(rig.router)) + done := make(chan chatAnswer, 1) + start := time.Now() + go func() { done <- postVia(t, srv, rt.path, rt.body) }() + if !waitFor(5*time.Second, func() bool { return store.inFinish.Load() == 1 }) { + t.Fatal("the answer's commit did not start") + } + if mode == "revoked_before_deadline" { + rv.revoke() + } + time.Sleep(time.Until(start.Add(deadline + 400*time.Millisecond))) + switch mode { + case "gateway_off": + rig.setSettings(func(s *oai.Settings) { s.Enabled = false }) + case "revoked": + if n := rv.revoke(); n != 1 { + t.Fatalf("revoked %d running requests, want 1", n) + } + case "shutdown": + shutdown() + } + once.Do(func() { close(gate) }) + var a chatAnswer + select { + case a = <-done: + case <-time.After(10 * time.Second): + t.Fatal("no answer") + } + w := want[mode] + if code, _, _ := a.envelope(t); a.status != w.status || code != w.code || rt.answered(a.body) { + t.Errorf("client %d %q (%d bytes) — want %d %q without the answer", a.status, code, len(a.body), w.status, w.code) + } + r := store.only(t) + if r.state != llmlog.RecordingDone || r.out.Status != a.status || r.out.Code != w.code || string(r.response) != string(a.body) { + t.Errorf("row: state %q status %d code %q answer %d bytes — want done %d %q with the client's %d bytes", + r.state, r.out.Status, r.out.Code, len(r.response), a.status, w.code, len(a.body)) + } + }) + } + } +} + +// TestRecordingHeldErrorLostAcknowledgement: an error answer held for its +// row whose commit went through but reported an error goes out as 503 +// recording_unavailable — and the row then says that, not the error answer +// the client never got. +func TestRecordingHeldErrorLostAcknowledgement(t *testing.T) { + u := newUpstream(t, recChatAnswer) + u.setRespond(func(w http.ResponseWriter, _ *http.Request) { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(http.StatusBadRequest) + _, _ = w.Write([]byte(`{"error":{"message":"` + recRejection + `","type":"invalid_request_error"}}`)) + }) + store := newRecStore(nil) + rig := newChatRig(t, []backends.Backend{u.row("spark", backends.TrustFull, 10)}, 4, 1, withRecordings(store)) + rig.setSettings(func(s *oai.Settings) { s.RelayUpstream4xxMessages = true }) + ca := recordingConsumer(true) + ca.ConsumerID = uuid.NewString() + rig.ca.Store(ca) + store.set(func(s *recStore) { s.finishLost = 1 }) + a := rig.post(t, chatBody("pub")) + checkRecordingRefusal(t, a.status, a.header, a.body) + r := store.only(t) + if r.state != llmlog.RecordingDone || r.out.Status != http.StatusServiceUnavailable || r.out.Code != oai.CodeRecordingUnavailable || + strings.Contains(string(r.response), "marker-571-rejected") { + t.Errorf("row: state %q status %d code %q answer %q — want done 503 recording_unavailable, not the error the client did not get", + r.state, r.out.Status, r.out.Code, r.response) + } + if got := statsOf(ca.ConsumerID); got.Unfinished != 0 || got.Recorded != 1 { + t.Errorf("counts %+v — want recorded 1, unfinished 0", got) + } +} + +// TestRecordingPanicAfterAHeldAnswer: a route that wrote an error answer — +// held for its row — and then panics: the client gets oai.Recover's 503, +// and the row says 503 internal_error, not the held answer. +func TestRecordingPanicAfterAHeldAnswer(t *testing.T) { + store := newRecStore(nil) + stage := oai.NewRecordingStage(store, func(context.Context) *auth.ConsumerAuth { return recordingConsumer(true) }, + func() oai.Settings { return chatSettings() }, func() time.Duration { return time.Second }) + rt := chi.NewRouter() + rt.Use(oai.Recover, stage.Handler) + rt.Post("/v1/chat/completions", func(w http.ResponseWriter, _ *http.Request) { + oai.WriteCode(w, oai.CodeUpstreamRejected, "a held answer", false) + panic("boom") + }) + w := httptest.NewRecorder() + rt.ServeHTTP(w, httptest.NewRequest(http.MethodPost, "/v1/chat/completions", strings.NewReader("{}"))) + r := store.only(t) + if w.Code != 503 || strings.Contains(w.Body.String(), "a held answer") || r.out.Status != 503 || r.out.Code != oai.CodeInternalError || + strings.Contains(string(r.response), "a held answer") { + t.Errorf("client %d %q, row status %d code %q answer %q — want 503 internal_error both, without the held answer", + w.Code, w.Body.String(), r.out.Status, r.out.Code, r.response) + } +} diff --git a/go/internal/oai/rerank.go b/go/internal/oai/rerank.go index 74c2cbb48..5ebb0b513 100644 --- a/go/internal/oai/rerank.go +++ b/go/internal/oai/rerank.go @@ -978,10 +978,10 @@ func (c *rerankCall) success(st *rerankState) embedOutcome { } // The commit took its time: a request that stopped being served // meanwhile does not get the answer it held. - if err := c.d.heldStillServes(c.ctx, t); err != nil { + if err := c.d.heldStillServes(c.ctx, c.client, t); err != nil { c.recording.withhold() c.cancel(err) - _, code := c.verdict() + code := refuseHeld(err, c.rec, c.w, c.r) return embedOutcome{finish: llmlog.FinishAborted, redacted: &llmlog.RedactedErr{Class: backends.ClassCanceled.String(), Code: code}} } held = c.recording.capture From efc5cb0335d6bc43071153ef71bb70d9403b8b12 Mon Sep 17 00:00:00 2001 From: Jan-Stefan Janetzky Date: Fri, 27 Nov 2026 09:29:09 +0100 Subject: [PATCH 20/27] =?UTF-8?q?fix(llmlog):=20the=20retention=20clears?= =?UTF-8?q?=20a=20refusal's=20answer=20whose=20request=20body=20was=20neve?= =?UTF-8?q?r=20read=20=E2=80=94=20request=5Fbody=20is=20NULL=20only=20once?= =?UTF-8?q?=20the=20retention=20cleared=20it?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A request refused before its body was read (an unknown path, a wrong method, a body over the cap) has its refusal's bytes as its answer and no request body; the janitor selected only rows with a request body, so that answer outlived the retention. Such a row now holds the empty bytea as its request body (request_complete false), and NULL means cleared: the janitor's partial index (request_body IS NOT NULL) holds every row that still carries a body, without naming response_body — the outcome's update changes that column and would otherwise never be HOT. Co-Authored-By: Claude Opus 5.5 --- docs/operations.md | 6 ++--- go/internal/llmlog/recordings.go | 26 +++++++++++++++---- .../llmlog/recordings_integration_test.go | 25 +++++++++++++----- go/internal/schemacontract/manifest.json | 2 +- .../197_model_consumer_record_bodies.sql | 7 ++++- 5 files changed, 50 insertions(+), 16 deletions(-) diff --git a/docs/operations.md b/docs/operations.md index 2fe704ab3..c07ec1f36 100644 --- a/docs/operations.md +++ b/docs/operations.md @@ -984,7 +984,7 @@ ctx manage model-consumer-update '' '{"id":"","record_bodies":true, (The consumer's `id` goes into `data`; `model-consumer-create` takes the same two fields.) From the consumer's next request on — a request already running keeps what it was admitted with — every request of it gets one row in `context_llm_recordings`; switching off is `"record_bodies": false`, which a tenant-admin of the consumer's tenant may do too. The consumer view (API, CLI `--json`, `/gateway` in the SPA) shows the switch to every reader; `GET /api/status` lists the recording consumers in `gateway.recording_consumers` and counts their requests in `gateway.recording` (server-admin). -**What a row holds.** `request_body` is the body as the gateway read it, byte for byte (bytea: invalid UTF-8 and NUL bytes included, no cut, no seal — a password, a token or a private key in a prompt is stored in clear text); `request_complete` says whether that is the whole body (a body cut short holds the part read), `declared_bytes` its `Content-Length`. `response_body` is the answer the client got: a non-streamed chat or rerank answer as written, a stream's relayed `data:` lines in order (without keepalives, the closing `[DONE]` or an error frame), and for every answer that is not a `2xx` — a refusal, an error, a backend's rejection whose text the gateway relays (`gateway.relay_upstream_4xx_messages`) — its error body as written; none for a successful embeddings answer (the vectors are not kept — the input is the record) and none for `503 recording_unavailable` (its bytes are fixed). `state` is `open` from the hold until the outcome is recorded, then `done` with `status` (the HTTP status the client got; `NULL` when the gateway wrote nothing — the client had gone), `code` (the gateway's code of a refusal or an error, where the refusing stage names one — the catch-alls of an unknown path and a wrong method leave it `NULL`), `finished_at`. `op`, `model` and `stream` are what the route read (`NULL` when no route parsed the request), `path` the request's path, `process_id` the ctxd process that admitted it. The row's `id` is the request's id: a chat answer's `id` is `chatcmpl-`, a rerank answer's `rerank-`, and the request's `context_llm_log` row carries it as `metadata.gw.recording_id` (with `metadata.gw.recorded: true`; that row carries no bodies under any `gateway.body_logging` value — the recording is their one place). +**What a row holds.** `request_body` is the body as the gateway read it, byte for byte (bytea: invalid UTF-8 and NUL bytes included, no cut, no seal — a password, a token or a private key in a prompt is stored in clear text); `request_complete` says whether that is the whole body (a body cut short holds the part read; a request refused before its body was read holds the empty body, `request_complete` false), `declared_bytes` its `Content-Length`; `request_body` is `NULL` only once the retention cleared the row. `response_body` is the answer the client got: a non-streamed chat or rerank answer as written, a stream's relayed `data:` lines in order (without keepalives, the closing `[DONE]` or an error frame), and for every answer that is not a `2xx` — a refusal, an error, a backend's rejection whose text the gateway relays (`gateway.relay_upstream_4xx_messages`) — its error body as written; none for a successful embeddings answer (the vectors are not kept — the input is the record) and none for `503 recording_unavailable` (its bytes are fixed). `state` is `open` from the hold until the outcome is recorded, then `done` with `status` (the HTTP status the client got; `NULL` when the gateway wrote nothing — the client had gone), `code` (the gateway's code of a refusal or an error, where the refusing stage names one — the catch-alls of an unknown path and a wrong method leave it `NULL`), `finished_at`. `op`, `model` and `stream` are what the route read (`NULL` when no route parsed the request), `path` the request's path, `process_id` the ctxd process that admitted it. The row's `id` is the request's id: a chat answer's `id` is `chatcmpl-`, a rerank answer's `rerank-`, and the request's `context_llm_log` row carries it as `metadata.gw.recording_id` (with `metadata.gw.recorded: true`; that row carries no bodies under any `gateway.body_logging` value — the recording is their one place). **Held before served.** The route commits the row — the whole request, state `open` — before the first backend attempt and before any queue wait; a request whose row cannot be committed is answered `503 recording_unavailable` (`Retry-After: 1`, `x-should-retry: true`) and no backend sees it: the database refuses the insert, or it does not answer within **5 s** (a fixed statement deadline), or the recording's memory account or its statement slots (below) have no room within `dispatch.external_max_wait` (20 s). The `503` reaches the client at once; the gateway then tries once more to leave the request's row (up to another 5 s, the client does not wait for it). A non-streamed answer is committed with the outcome before its first byte is written; if that fails, the client gets the same `503` instead of the answer (the backend ran: the meter books its usage; the client's retry is a second row). An answer that is not a `2xx` is held from the client until the row holds it with its bytes; if that row cannot be written once the request reached its walk, the client gets the `503` in its place, and the row is written with that `503` — a refusal before the walk (no backend asked) goes out as it is. A request that stops being served while its answer is being committed — its key revoked or its consumer deactivated, the model API switched off, the alias gone, the shutdown; also when its request deadline passed during the commit — gets the refusal it would have got before the commit (`401 invalid_api_key` for a revoked key), never the answer, and its row's outcome becomes that refusal; so does a `503` whose answer commit failed although it went through (its acknowledgement lost): the row never claims an answer the client did not get. A stream relays a line only after the recording kept it in memory; its lines are committed when it ends — what a stream sent cannot be taken back, so a stream whose end cannot be committed leaves its row `open` with its request and is counted in `stream_answers_unrecorded`. A request the gateway refuses after the door accepted the key — a body that does not parse, an unknown model, a limit, a body over `gateway.max_request_bytes` (never read: the row holds its declared size), an unknown path, a wrong method — gets its row at its end, `done`, with what was read of the body. Refusals before the door (`401`, a wrong key) are not the consumer's and leave nothing. A process that dies between the hold and the outcome leaves the row `open`: its request is there, its outcome is not known. @@ -998,7 +998,7 @@ SELECT count(*) AS AND response_bytes = 0 AND op IN ('chat', 'rerank') AND stream IS NOT TRUE) AS answered_without_answer, count(*) FILTER (WHERE state = 'done' AND (status IS NULL OR status >= 400)) AS refused, - count(*) FILTER (WHERE request_body IS NULL AND request_bytes > 0) AS past_retention + count(*) FILTER (WHERE request_body IS NULL) AS past_retention FROM context_llm_recordings WHERE consumer_id = '' AND process_id = ''; ``` @@ -1023,7 +1023,7 @@ SELECT created_at, id, path, op, model, stream, state, status, code, **Size.** A row holds at most `gateway.max_request_bytes` (8 MiB) of request; a non-streamed answer is capped by its read (`gateway.max_response_bytes`, 4 MiB); a stream's lines grow with the stream. A recording consumer at 30 requests a second writes about 2.6 M rows a day. The retention NULLs the bodies but deletes no row: each row leaves a skeleton of a few hundred bytes (measured 0.2–2 KB a row before a vacuum, depending on how many of the outcome updates stayed on their page) — delete old rows by hand (`DELETE FROM context_llm_recordings WHERE created_at < …`) if that matters. -**Retention.** Both bodies of a recording are NULLed after `scheduler.llmlog_retention_days` (90 days) by the same janitor that NULLs `context_llm_log`'s (`request_bytes`, `response_bytes`, the outcome and the row stay). Read them out before that if they are needed longer. +**Retention.** Both bodies of a recording are NULLed after `scheduler.llmlog_retention_days` (90 days) by the same janitor that NULLs `context_llm_log`'s (`request_bytes`, `response_bytes`, the outcome and the row stay) — a refusal's answer of a request whose body was never read included. Read them out before that if they are needed longer. ### Upgrading to 5.33.1: the image's `GOMEMLIMIT` is 768MiB diff --git a/go/internal/llmlog/recordings.go b/go/internal/llmlog/recordings.go index 9b9a191c8..c3c482ad4 100644 --- a/go/internal/llmlog/recordings.go +++ b/go/internal/llmlog/recordings.go @@ -121,7 +121,7 @@ func nullStatus(n int) *int16 { return &v } -// bodyBytes is b, NULL when empty: an empty body is no body. +// bodyBytes is b, NULL when empty: an empty answer is no answer. func bodyBytes(b []byte) []byte { if len(b) == 0 { return nil @@ -129,6 +129,18 @@ func bodyBytes(b []byte) []byte { return b } +// requestBody is b, the empty bytea when nothing was read — never NULL: a +// row's request_body is NULL only once the retention cleared it, so +// idx_llm_recordings_bodies (request_body IS NOT NULL) holds every row that +// still carries a body, a request refused before its body was read with its +// refusal's bytes included (evictRecordingBodies). +func requestBody(b []byte) []byte { + if b == nil { + return []byte{} + } + return b +} + func declared(n int64) *int64 { if n < 0 { return nil @@ -147,7 +159,7 @@ func (r Recordings) Open(ctx context.Context, q RecordedRequest) error { declared_bytes, request_bytes, request_complete, request_body, state) VALUES ($1::uuid, $2::uuid, $3::uuid, $4::uuid, $5, $6, $7, $8, $9, $10, $11, $12, $13, 'open')`, q.ID, ProcessID, q.ConsumerID, nullUUIDText(q.ModelKeyID), q.Path, nullText(q.Op), nullText(q.ClientRequestID), - nullText(q.Model), q.Stream, declared(q.Declared), int64(len(q.Body)), q.Complete, bodyBytes(q.Body)) + nullText(q.Model), q.Stream, declared(q.Declared), int64(len(q.Body)), q.Complete, requestBody(q.Body)) if err != nil { return fmt.Errorf("llmlog: open recording: %w", err) } @@ -194,7 +206,7 @@ func (r Recordings) Insert(ctx context.Context, q RecordedRequest, o RecordedOut response_bytes = EXCLUDED.response_bytes, response_body = EXCLUDED.response_body WHERE t.state = 'open'`, q.ID, ProcessID, q.ConsumerID, nullUUIDText(q.ModelKeyID), q.Path, nullText(q.Op), nullText(q.ClientRequestID), - nullText(q.Model), q.Stream, declared(q.Declared), int64(len(q.Body)), q.Complete, bodyBytes(q.Body), + nullText(q.Model), q.Stream, declared(q.Declared), int64(len(q.Body)), q.Complete, requestBody(q.Body), nullStatus(o.Status), nullText(o.Code), int64(len(o.Response)), bodyBytes(o.Response)) if err != nil { return fmt.Errorf("llmlog: insert recording: %w", err) @@ -203,8 +215,12 @@ func (r Recordings) Insert(ctx context.Context, q RecordedRequest, o RecordedOut } // evictRecordingBodies is EvictBodies' statement over the recordings: the two -// bodies of every row past the retention that still carries its request -// (idx_llm_recordings_bodies holds exactly those); the sizes stay. +// bodies of every row past the retention that the retention has not cleared +// yet — request_body is NULL only after it (requestBody), so a row with an +// answer and no request read is among them; idx_llm_recordings_bodies holds +// exactly those rows. The predicate names request_body alone on purpose: the +// outcome's update (Finish) changes response_body, and an index predicate +// over it would make every such update a non-HOT one. The sizes stay. const evictRecordingBodies = `UPDATE context_llm_recordings SET request_body = NULL, response_body = NULL WHERE created_at < now() - make_interval(days => $1) diff --git a/go/internal/llmlog/recordings_integration_test.go b/go/internal/llmlog/recordings_integration_test.go index 0c5b83840..0bd6fbbad 100644 --- a/go/internal/llmlog/recordings_integration_test.go +++ b/go/internal/llmlog/recordings_integration_test.go @@ -138,8 +138,9 @@ func TestRecordingsRoundTrip(t *testing.T) { if err := st.Insert(ctx, stage, llmlog.RecordedOutcome{Status: 404, Code: "not_found"}); err != nil { t.Fatalf("insert stage refusal: %v", err) } - if r = readRecording(t, ctx, q, stage.ID); r.body != nil || r.reqBytes != 0 || r.declared != nil || r.op != nil { - t.Errorf("stage refusal row: body %v bytes %d declared %v op %v, want none of them", r.body, r.reqBytes, r.declared, r.op) + if r = readRecording(t, ctx, q, stage.ID); r.body == nil || len(r.body) != 0 || r.reqBytes != 0 || r.declared != nil || r.op != nil { + t.Errorf("stage refusal row: body %v bytes %d declared %v op %v — want the empty body (NULL only past the retention), no size, no op", + r.body, r.reqBytes, r.declared, r.op) } // An Open the caller saw fail although it committed: Insert ends it and @@ -179,13 +180,25 @@ func TestRecordingsJanitor(t *testing.T) { t.Fatalf("finish: %v", err) } } - // The time shift is the fixture's only hand edit: rows are written by Open. - if _, err := pool.Exec(ctx, `UPDATE context_llm_recordings SET created_at = now() - interval '91 days' WHERE id = $1::uuid`, old); err != nil { + // A request refused before its body was read (an unknown path, a body + // over the cap): no request body, the refusal's bytes as its answer. + refusal := recID(t) + if err := st.Insert(ctx, llmlog.RecordedRequest{ID: refusal, ConsumerID: gwiConsumer, Path: "/v1/nowhere", Declared: -1}, + llmlog.RecordedOutcome{Status: 404, Code: "not_found", Response: []byte(`{"error":{"code":"not_found"}}`)}); err != nil { + t.Fatalf("insert: %v", err) + } + // The time shift is the fixture's only hand edit: rows are written by Open + // and Insert. + if _, err := pool.Exec(ctx, `UPDATE context_llm_recordings SET created_at = now() - interval '91 days' WHERE id = ANY($1::uuid[])`, + []string{old, refusal}); err != nil { t.Fatal(err) } n, err := llmlog.EvictBodies(ctx, pool, 90) - if err != nil || n != 1 { - t.Fatalf("evict: %d rows, %v — want the one recording past the retention", n, err) + if err != nil || n != 2 { + t.Fatalf("evict: %d rows, %v — want the two recordings past the retention (one with a request, one with an answer only)", n, err) + } + if r := readRecording(t, ctx, q, refusal); r.body != nil || r.response != nil || r.respBytes != int64(len(`{"error":{"code":"not_found"}}`)) { + t.Errorf("refusal past the retention: body %v answer %q (%d bytes) — want both NULL, the answer's size kept", r.body, r.response, r.respBytes) } if r := readRecording(t, ctx, q, old); r.body != nil || r.response != nil || r.reqBytes != 5 || r.respBytes != 6 || r.state != llmlog.RecordingDone { t.Errorf("past the retention: body %v answer %v sizes %d/%d state %q — want both NULL, sizes and outcome kept", r.body, r.response, r.reqBytes, r.respBytes, r.state) diff --git a/go/internal/schemacontract/manifest.json b/go/internal/schemacontract/manifest.json index 5697fb933..4cd6d1078 100644 --- a/go/internal/schemacontract/manifest.json +++ b/go/internal/schemacontract/manifest.json @@ -3,7 +3,7 @@ "generated_against": { "migration_max": 197, "migration_count": 85, - "migration_chain_sha256": "6d1f1b2c6f2943ff5b03b948fe4c222cf33200f1555e6e27cb1e5ae0a44da540", + "migration_chain_sha256": "ba7bd47e98be4683d68c4aca1ffbb681202a8d05876067a372a500ca87f20eeb", "pg_major": 18, "image": "pgvector-timescaledb:pg18" }, diff --git a/go/migrations/197_model_consumer_record_bodies.sql b/go/migrations/197_model_consumer_record_bodies.sql index dc1bc5398..4645a81fb 100644 --- a/go/migrations/197_model_consumer_record_bodies.sql +++ b/go/migrations/197_model_consumer_record_bodies.sql @@ -65,7 +65,12 @@ -- key to the consumer: a deleted consumer's recordings stay. The -- retention janitor (llmlog.EvictBodies) NULLs the two bodies after -- the LLM log's retention, as it does context_llm_log's; request_bytes --- and response_bytes keep their sizes. +-- and response_bytes keep their sizes. request_body is the empty bytea +-- when nothing was read and NULL only once the retention cleared it, so +-- idx_llm_recordings_bodies (request_body IS NOT NULL) holds every row +-- that still carries a body — a refusal's answer without a request +-- included — without naming response_body, which the outcome's update +-- changes (an index over it would make that update non-HOT). -- -- Cost and locks. ADD COLUMN with a constant default is a catalog change: -- ACCESS EXCLUSIVE on context_model_consumers until the commit — milliseconds; From 0771ec3b708ea0a9c734951011c622362051a3cd Mon Sep 17 00:00:00 2001 From: Jan-Stefan Janetzky Date: Fri, 27 Nov 2026 09:37:54 +0100 Subject: [PATCH 21/27] fix(gateway): a refused request's row is written while its in-flight reservation still books its body MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The in-flight budget stage runs inside the recording stage and releases a request's reservation when its route returns; the row of a request the route refused before its walk was written at the stage after that, so its body — up to gateway.max_request_bytes — waited for room in the recording account booked nowhere, and the released budget let more such requests in. The routes (chat, embeddings, rerank) now write that row before they return (endInRoute): its wait for room holds the reservation, a flood is held back by gateway.inflight_budget (503 server_overloaded, a row for each), and the body is let go after the attempt. Measured with 48 refused 1.5 MiB requests in a row and the account full, 64 MiB budget: before, 72.2 MiB live and 0 booked (48 waiting); after, 21.2 MiB live and 63 MiB booked (14 waiting, 34 turned away with their rows). Co-Authored-By: Claude Opus 5.5 --- docs/operations.md | 2 +- go/internal/oai/chat.go | 10 +++- go/internal/oai/embeddings.go | 7 ++- go/internal/oai/record.go | 47 ++++++++++++--- go/internal/oai/record_route_test.go | 90 ++++++++++++++++++++++++++++ go/internal/oai/rerank.go | 7 ++- 6 files changed, 149 insertions(+), 14 deletions(-) diff --git a/docs/operations.md b/docs/operations.md index c07ec1f36..4ff83c450 100644 --- a/docs/operations.md +++ b/docs/operations.md @@ -1019,7 +1019,7 @@ SELECT created_at, id, path, op, model, stream, state, status, code, **Cost on the request path.** Only for the recording consumer: two statements in the request's time (the insert before the walk, the outcome at the end — before the answer for a non-streamed answer), see the measurement in the pull request of issue #571 (p50/p99 of a small chat and a large embeddings request with and without recording). Every other consumer passes the recording stage untouched: no write, no wait, no allocation. -**Memory and the pool.** The request's own memory stays in `gateway.inflight_budget` with the same bookings as without recording. What the recording adds — the copies a statement makes of what it carries (pgx encodes a parameter into its own buffer and that into the connection's write buffer; measured 2.0–2.3 × the bytes, booked at 3 ×), a stream's kept lines (its buffer's capacity, up to twice the text), a rerank answer kept before it is written, and the body of a request refused before its walk while its row is written (its in-flight reservation has ended) — is held against **one process-wide account**: 128 MiB, or 4 × the larger of `gateway.max_request_bytes` and `gateway.max_response_bytes` when that is more, so the row of the largest refused request always fits. At most **4** recording statements run at once (fixed in the code, like the LLM-log writer's 4 inserts): a database that hangs binds 4 of the pool's connections, never the rest the other consumers and the knowledge API use. A statement waits for room and a slot — the hold up to `dispatch.external_max_wait`, an outcome up to its 5 s deadline — and the request is refused with `recording_unavailable` if none comes (backpressure); a stream's next line that does not fit ends the stream with `recording_unavailable` before that line is sent. The final statement of a captured answer (a stream's lines, a rerank answer) takes its copies even past the account's bound — it holds its capture already, and waiting for the room other captures hold could wait on itself —, so the account can be exceeded by at most 4 such statements' copies at once. At the defaults the process holds at most the 512 MiB budget + 128 MiB + its base (measured idle at 21–32 MiB) — inside the image's `GOMEMLIMIT` of 768 MiB — plus, while captured answers are written, the copies of at most 4 of them (3 × their size; streams of ordinary length: a few MiB) — inside the container's 1536 MiB. Nothing is dropped to stay in that bound: a request that does not fit waits or is refused. +**Memory and the pool.** The request's own memory stays in `gateway.inflight_budget` with the same bookings as without recording. What the recording adds — the copies a statement makes of what it carries (pgx encodes a parameter into its own buffer and that into the connection's write buffer; measured 2.0–2.3 × the bytes, booked at 3 ×), a stream's kept lines (its buffer's capacity, up to twice the text), a rerank answer kept before it is written, and the body of a request refused before its walk while its row is written — is held against **one process-wide account**: 128 MiB, or 4 × the larger of `gateway.max_request_bytes` and `gateway.max_response_bytes` when that is more, so the row of the largest refused request always fits. At most **4** recording statements run at once (fixed in the code, like the LLM-log writer's 4 inserts): a database that hangs binds 4 of the pool's connections, never the rest the other consumers and the knowledge API use. A statement waits for room and a slot — the hold up to `dispatch.external_max_wait`, an outcome up to its 5 s deadline — and the request is refused with `recording_unavailable` if none comes (backpressure); a stream's next line that does not fit ends the stream with `recording_unavailable` before that line is sent. The final statement of a captured answer (a stream's lines, a rerank answer) takes its copies even past the account's bound — it holds its capture already, and waiting for the room other captures hold could wait on itself —, so the account can be exceeded by at most 4 such statements' copies at once. At the defaults the process holds at most the 512 MiB budget + 128 MiB + its base (measured idle at 21–32 MiB) — inside the image's `GOMEMLIMIT` of 768 MiB — plus, while captured answers are written, the copies of at most 4 of them (3 × their size; streams of ordinary length: a few MiB) — inside the container's 1536 MiB. Nothing is dropped to stay in that bound: a request that does not fit waits or is refused. The row of a request refused before its walk is written before the request's in-flight reservation ends, so while it waits for room the body stays booked there too — a flood of such requests is held back by `gateway.inflight_budget` (`503 server_overloaded`, rows written for each), never held in memory booked nowhere. **Size.** A row holds at most `gateway.max_request_bytes` (8 MiB) of request; a non-streamed answer is capped by its read (`gateway.max_response_bytes`, 4 MiB); a stream's lines grow with the stream. A recording consumer at 30 requests a second writes about 2.6 M rows a day. The retention NULLs the bodies but deletes no row: each row leaves a skeleton of a few hundred bytes (measured 0.2–2 KB a row before a vacuum, depending on how many of the outcome updates stayed on their page) — delete old rows by hand (`DELETE FROM context_llm_recordings WHERE created_at < …`) if that matters. diff --git a/go/internal/oai/chat.go b/go/internal/oai/chat.go index 5e37bbd16..4bb7b56c5 100644 --- a/go/internal/oai/chat.go +++ b/go/internal/oai/chat.go @@ -102,8 +102,14 @@ func ChatCompletions(d Deps) http.Handler { } c := newChatCall(d, w, r, ca, entry) c.adoptRecording(rr) - defer c.close() - c.serve() + func() { + defer c.close() + c.serve() + }() + // A refused request's row while its in-flight reservation still + // books its body (record.go endInRoute); not on a panic — the stage + // ends that one. + rr.endInRoute(w) }) } diff --git a/go/internal/oai/embeddings.go b/go/internal/oai/embeddings.go index 44ec36143..87fdf6693 100644 --- a/go/internal/oai/embeddings.go +++ b/go/internal/oai/embeddings.go @@ -185,8 +185,11 @@ func Embeddings(d Deps) http.Handler { if rr != nil { c.id = rr.req.ID // the answer and the attempts name the recorded row } - defer c.close() - c.serve() + func() { + defer c.close() + c.serve() + }() + rr.endInRoute(w) // a refused request's row inside its in-flight reservation (record.go) }) } diff --git a/go/internal/oai/record.go b/go/internal/oai/record.go index 4eff41a31..1fc361f84 100644 --- a/go/internal/oai/record.go +++ b/go/internal/oai/record.go @@ -285,8 +285,9 @@ type requestRecording struct { // row: a row of the request is committed (open, or inserted at the // end); opened: it was opened before the walk; ended: its outcome is // committed (or known to be there); settled: the row holds the outcome - // the client gets (end). - row, opened, ended, settled bool + // the client gets (end); inserted: the row of a request refused before + // its walk was attempted (once: endInRoute or the stage). + row, opened, ended, settled, inserted bool // unfinished: the outcome of an opened row could not be committed. unfinished bool // withheld: an answer was committed — or may have been: its commit @@ -582,11 +583,12 @@ func (rr *requestRecording) noteStatus(code int) { rr.statusMu.Unlock() } -// end commits the request's outcome once it has ended (endStage): the open -// row ends with the status the client got, code and a stream's or a rerank -// answer's captured bytes; a request refused before its walk gets its row -// with what was read of the body — the body itself held against the account -// with its copies, since the request's in-flight reservation has ended. A +// end commits the request's outcome once it has ended (endInRoute, +// endStage): the open row ends with the status the client got, code and a +// stream's or a rerank answer's captured bytes; a request refused before its +// walk gets its row with what was read of the body — the body and the +// statement's copies held against the account, waiting for room while the +// request's in-flight reservation still books the body (endInRoute). A // failure is counted, never retried later. func (rr *requestRecording) end(code string) { if rr.ended && !rr.withheld { @@ -614,6 +616,10 @@ func (rr *requestRecording) end(code string) { rr.settled = true return } + if rr.inserted { + return // attempted in the route (endInRoute): its body is not held past the reservation + } + rr.inserted = true if rr.stage.store == nil { slog.Error("gateway: a recording consumer's request without a recording store (wiring defect) — not recorded", "consumer_id", rr.req.ConsumerID) @@ -652,6 +658,33 @@ func (rr *requestRecording) supersedeReplaced() { rr.unfinished, rr.settled = false, true } +// endInRoute writes the row of a request the route refused before its walk +// while the request's in-flight reservation still books the body the route +// read: the budget stage (InflightBudget) runs inside the recording stage +// and releases the reservation when the route returns, so a row written at +// the stage would hold the body booked nowhere while it waits for room in +// the recording account. Written here, that wait holds the reservation — it +// is backpressure on the in-flight budget —, and the body is let go after +// the attempt, written or not (a row that could not be written counts as +// unrecordable, as at the stage). A request that was opened, and every +// request a panic ends, ends at the stage. w is the route's writer: the +// 503 recording_unavailable goes out before the attempt, as at the stage. +// Nil-safe. +func (rr *requestRecording) endInRoute(w http.ResponseWriter) { + if rr == nil || rr.opened || rr.ended || rr.inserted { + return + } + code := "" + if rr.access != nil { + code = rr.access.Reason + } + if code == CodeRecordingUnavailable { + _ = http.NewResponseController(w).Flush() + } + rr.end(code) + rr.req.Body = nil +} + // dropCapture gives the captured answer back to the account. func (rr *requestRecording) dropCapture() { rr.acct.release(rr.held) diff --git a/go/internal/oai/record_route_test.go b/go/internal/oai/record_route_test.go index c48a5a68b..dea92cac5 100644 --- a/go/internal/oai/record_route_test.go +++ b/go/internal/oai/record_route_test.go @@ -7,7 +7,9 @@ import ( "io" "net/http" "net/http/httptest" + "os" "regexp" + "runtime" "strings" "sync" "sync/atomic" @@ -1172,3 +1174,91 @@ func TestRecordingPanicAfterAHeldAnswer(t *testing.T) { w.Code, w.Body.String(), r.out.Status, r.out.Code, r.response) } } + +// refusedBody is an unparsable chat request of n bytes: the route reads it +// whole and refuses it (invalid_json) before its walk. +func refusedBody(n int) string { + head := `{"model":"pub","messages":"` + return head + strings.Repeat("x", n-len(head)) +} + +// TestRecordingRefusedBodyStaysBooked: the body of a request refused before +// its walk stays booked while its row waits for room in the recording +// account — the request's in-flight reservation is held until the row is +// written, so the wait is backpressure on the in-flight budget, never a body +// booked nowhere — and the row gets the body once there is room. +func TestRecordingRefusedBodyStaysBooked(t *testing.T) { + u := newUpstream(t, recChatAnswer) + store := newRecStore(nil) + rig := newChatRig(t, []backends.Backend{u.row("spark", backends.TrustFull, 10)}, 4, 1, withRecordings(store)) + rig.ca.Store(recordingConsumer(true)) + body := refusedBody(1 << 20) + release := oai.FillRecordingAccount(oai.RecordingAccountLimit(chatSettings())) + var once sync.Once + defer once.Do(release) + done := make(chan chatAnswer, 1) + go func() { done <- rig.post(t, body) }() + // The route has read and refused the body; its row waits for room. + time.Sleep(500 * time.Millisecond) + booked := rig.budget.InUse() + once.Do(release) + a := <-done + if booked < int64(len(body)) { + t.Errorf("while the refused request's row waited for room, the in-flight budget booked %d bytes — want its reservation (≥ %d, the body)", booked, len(body)) + } + if code, _, _ := a.envelope(t); a.status != http.StatusBadRequest || code != "invalid_json" { + t.Errorf("client %d %q, want 400 invalid_json", a.status, code) + } + if r := store.only(t); string(r.body) != body || r.opened { + t.Errorf("row: %d bytes opened %v — want the whole refused body, never opened", len(r.body), r.opened) + } + if n := rig.budget.InUse(); n != 0 { + t.Errorf("the in-flight budget holds %d bytes after the request ended", n) + } +} + +// TestRecordingRefusedFloodProbe (opt-in, CTX_RECORD_PROBE=1) measures what a +// flood of refused 1.5 MiB requests of a recording consumer holds while their +// rows wait for room in the recording account: the live heap at the wait +// (after a collection), the in-flight budget's booking then, and how the +// requests were answered. +func TestRecordingRefusedFloodProbe(t *testing.T) { + if os.Getenv("CTX_RECORD_PROBE") != "1" { + t.Skip("opt-in probe (CTX_RECORD_PROBE=1)") + } + const n, size, budget = 48, 3 << 19, 64 << 20 // 48 requests of 1.5 MiB, a 64 MiB in-flight budget + u := newUpstream(t, recChatAnswer) + store := newRecStore(nil) + rig := newChatRig(t, []backends.Backend{u.row("spark", backends.TrustFull, 10)}, 4, 1, withRecordings(store)) + rig.setSettings(func(s *oai.Settings) { s.InflightBudget = budget }) + rig.ca.Store(recordingConsumer(true)) + body := refusedBody(size) + var base runtime.MemStats + runtime.GC() + runtime.ReadMemStats(&base) + release := oai.FillRecordingAccount(oai.RecordingAccountLimit(chatSettings())) + var wg sync.WaitGroup + var mu sync.Mutex + codes := map[int]int{} + for range n { + // One request after the other, as a client's steady stream: each + // finds the in-flight budget as the ones before it left it. + wg.Go(func() { + a := rig.post(t, body) + mu.Lock() + codes[a.status]++ + mu.Unlock() + }) + time.Sleep(25 * time.Millisecond) + } + time.Sleep(300 * time.Millisecond) // the last one has been read and refused or turned away; the rows wait + var at runtime.MemStats + runtime.GC() + runtime.ReadMemStats(&at) + booked := rig.budget.InUse() + release() + wg.Wait() + live := int64(at.HeapAlloc) - int64(base.HeapAlloc) + t.Logf("PROBE flood: %d requests of %d B, in-flight budget %d MiB: live heap at the wait %.1f MiB over the baseline, in-flight booked %.1f MiB, answers %v, rows %d", + n, size, budget>>20, float64(live)/(1<<20), float64(booked)/(1<<20), codes, len(store.rows)) +} diff --git a/go/internal/oai/rerank.go b/go/internal/oai/rerank.go index 5ebb0b513..15ab13da3 100644 --- a/go/internal/oai/rerank.go +++ b/go/internal/oai/rerank.go @@ -136,8 +136,11 @@ func Rerank(d Deps, dialect RerankDialect) http.Handler { if rr != nil { c.id = rr.req.ID // the answer ("rerank-") names the recorded row } - defer c.close() - c.serve() + func() { + defer c.close() + c.serve() + }() + rr.endInRoute(w) // a refused request's row inside its in-flight reservation (record.go) }) } From dada1c7c98b8d5f7d9c76117d771c9f40c11abe5 Mon Sep 17 00:00:00 2001 From: Jan-Stefan Janetzky Date: Fri, 27 Nov 2026 09:39:46 +0100 Subject: [PATCH 22/27] fix(gateway): a captured answer's forced copies are booked once its statement holds a slot MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The final statement of a captured answer (a rerank answer, a stream's lines) took its copies past the account's bound before it waited for a statement slot, so any number of such statements waiting for a slot held their copies, beyond the four the documentation bounds them to. They are now taken once the slot is held (taking does not wait, so no slot holder waits on the account). Four rerank answers waiting for a slot held 4 432 B of the account before (captures + 3 × the answer each), 1 108 B after (their captures). Co-Authored-By: Claude Opus 5.5 --- docs/operations.md | 2 +- go/internal/oai/record.go | 24 +++++++---- go/internal/oai/record_route_test.go | 62 ++++++++++++++++++++++++++++ 3 files changed, 78 insertions(+), 10 deletions(-) diff --git a/docs/operations.md b/docs/operations.md index 4ff83c450..3ca505eb4 100644 --- a/docs/operations.md +++ b/docs/operations.md @@ -1019,7 +1019,7 @@ SELECT created_at, id, path, op, model, stream, state, status, code, **Cost on the request path.** Only for the recording consumer: two statements in the request's time (the insert before the walk, the outcome at the end — before the answer for a non-streamed answer), see the measurement in the pull request of issue #571 (p50/p99 of a small chat and a large embeddings request with and without recording). Every other consumer passes the recording stage untouched: no write, no wait, no allocation. -**Memory and the pool.** The request's own memory stays in `gateway.inflight_budget` with the same bookings as without recording. What the recording adds — the copies a statement makes of what it carries (pgx encodes a parameter into its own buffer and that into the connection's write buffer; measured 2.0–2.3 × the bytes, booked at 3 ×), a stream's kept lines (its buffer's capacity, up to twice the text), a rerank answer kept before it is written, and the body of a request refused before its walk while its row is written — is held against **one process-wide account**: 128 MiB, or 4 × the larger of `gateway.max_request_bytes` and `gateway.max_response_bytes` when that is more, so the row of the largest refused request always fits. At most **4** recording statements run at once (fixed in the code, like the LLM-log writer's 4 inserts): a database that hangs binds 4 of the pool's connections, never the rest the other consumers and the knowledge API use. A statement waits for room and a slot — the hold up to `dispatch.external_max_wait`, an outcome up to its 5 s deadline — and the request is refused with `recording_unavailable` if none comes (backpressure); a stream's next line that does not fit ends the stream with `recording_unavailable` before that line is sent. The final statement of a captured answer (a stream's lines, a rerank answer) takes its copies even past the account's bound — it holds its capture already, and waiting for the room other captures hold could wait on itself —, so the account can be exceeded by at most 4 such statements' copies at once. At the defaults the process holds at most the 512 MiB budget + 128 MiB + its base (measured idle at 21–32 MiB) — inside the image's `GOMEMLIMIT` of 768 MiB — plus, while captured answers are written, the copies of at most 4 of them (3 × their size; streams of ordinary length: a few MiB) — inside the container's 1536 MiB. Nothing is dropped to stay in that bound: a request that does not fit waits or is refused. The row of a request refused before its walk is written before the request's in-flight reservation ends, so while it waits for room the body stays booked there too — a flood of such requests is held back by `gateway.inflight_budget` (`503 server_overloaded`, rows written for each), never held in memory booked nowhere. +**Memory and the pool.** The request's own memory stays in `gateway.inflight_budget` with the same bookings as without recording. What the recording adds — the copies a statement makes of what it carries (pgx encodes a parameter into its own buffer and that into the connection's write buffer; measured 2.0–2.3 × the bytes, booked at 3 ×), a stream's kept lines (its buffer's capacity, up to twice the text), a rerank answer kept before it is written, and the body of a request refused before its walk while its row is written — is held against **one process-wide account**: 128 MiB, or 4 × the larger of `gateway.max_request_bytes` and `gateway.max_response_bytes` when that is more, so the row of the largest refused request always fits. At most **4** recording statements run at once (fixed in the code, like the LLM-log writer's 4 inserts): a database that hangs binds 4 of the pool's connections, never the rest the other consumers and the knowledge API use. A statement waits for room and a slot — the hold up to `dispatch.external_max_wait`, an outcome up to its 5 s deadline — and the request is refused with `recording_unavailable` if none comes (backpressure); a stream's next line that does not fit ends the stream with `recording_unavailable` before that line is sent. The final statement of a captured answer (a stream's lines, a rerank answer) takes its copies even past the account's bound — it holds its capture already, and waiting for the room other captures hold could wait on itself —, and takes them only once it holds a statement slot, so the account can be exceeded by at most 4 such statements' copies at once. At the defaults the process holds at most the 512 MiB budget + 128 MiB + its base (measured idle at 21–32 MiB) — inside the image's `GOMEMLIMIT` of 768 MiB — plus, while captured answers are written, the copies of at most 4 of them (3 × their size; streams of ordinary length: a few MiB) — inside the container's 1536 MiB. Nothing is dropped to stay in that bound: a request that does not fit waits or is refused. The row of a request refused before its walk is written before the request's in-flight reservation ends, so while it waits for room the body stays booked there too — a flood of such requests is held back by `gateway.inflight_budget` (`503 server_overloaded`, rows written for each), never held in memory booked nowhere. **Size.** A row holds at most `gateway.max_request_bytes` (8 MiB) of request; a non-streamed answer is capped by its read (`gateway.max_response_bytes`, 4 MiB); a stream's lines grow with the stream. A recording consumer at 30 requests a second writes about 2.6 M rows a day. The retention NULLs the bodies but deletes no row: each row leaves a skeleton of a few hundred bytes (measured 0.2–2 KB a row before a vacuum, depending on how many of the outcome updates stayed on their page) — delete old rows by hand (`DELETE FROM context_llm_recordings WHERE created_at < …`) if that matters. diff --git a/go/internal/oai/record.go b/go/internal/oai/record.go index 1fc361f84..84a2ebeef 100644 --- a/go/internal/oai/record.go +++ b/go/internal/oai/record.go @@ -377,25 +377,31 @@ func (rr *requestRecording) open(ctx context.Context) bool { } // statement runs one recording statement: n bytes of the account first -// (waiting for room until wait ends; force: taken past the bound), then a -// slot (waiting until wait ends), then fn under recordWriteTimeout. In this -// order nobody waits while holding a slot — a slot holder only waits for the -// database. +// (waiting for room until wait ends), then a slot (waiting until wait ends), +// then fn under recordWriteTimeout. In this order nobody waits while holding +// a slot — a slot holder only waits for the database. force (a captured +// answer's final copies) takes its n bytes past the bound, and only once it +// holds a slot: taking does not wait, and the forced copies at any moment +// are those of at most maxRecordingStatements statements. func (rr *requestRecording) statement(ctx context.Context, wait time.Duration, n int64, force bool, fn func(context.Context) error) error { wctx, cancel := context.WithTimeout(ctx, wait) defer cancel() - if force { - rr.acct.take(n) - } else if err := rr.acct.acquire(wctx, n, recordAccountLimit(rr.stage.settings())); err != nil { - return fmt.Errorf("oai: no room to record: %w", err) + if !force { + if err := rr.acct.acquire(wctx, n, recordAccountLimit(rr.stage.settings())); err != nil { + return fmt.Errorf("oai: no room to record: %w", err) + } + defer rr.acct.release(n) } - defer rr.acct.release(n) select { case recordSlots <- struct{}{}: case <-wctx.Done(): return fmt.Errorf("oai: no recording slot: %w", wctx.Err()) } defer func() { <-recordSlots }() + if force { + rr.acct.take(n) + defer rr.acct.release(n) + } sctx, scancel := context.WithTimeout(ctx, recordWriteTimeout) defer scancel() return fn(sctx) diff --git a/go/internal/oai/record_route_test.go b/go/internal/oai/record_route_test.go index dea92cac5..290be3d9f 100644 --- a/go/internal/oai/record_route_test.go +++ b/go/internal/oai/record_route_test.go @@ -1262,3 +1262,65 @@ func TestRecordingRefusedFloodProbe(t *testing.T) { t.Logf("PROBE flood: %d requests of %d B, in-flight budget %d MiB: live heap at the wait %.1f MiB over the baseline, in-flight booked %.1f MiB, answers %v, rows %d", n, size, budget>>20, float64(live)/(1<<20), float64(booked)/(1<<20), codes, len(store.rows)) } + +// TestRecordingForcedCopiesWaitWithoutBooking: the final statement of a +// captured answer (a rerank answer, a stream's lines) books its copies past +// the account's bound — but only once it holds a statement slot: while it +// waits for one, the account holds its capture and nothing more, so the +// forced copies at any moment are those of at most four statements. +func TestRecordingForcedCopiesWaitWithoutBooking(t *testing.T) { + e := newRerankEngine(t) + store := newRecStore(nil) + rig := newRerankRig(t, []backends.Backend{e.row("spark-rerank", 10)}, 16, 1, withoutCensus, withRecordings(store)) + rig.ca.Store(recordingConsumer(true)) + body := rerankBody("rrpub", "q", []string{"d1", "d2"}) + warm := rig.postRerank(t, "/v1/rerank", body) + if warm.status != 200 { + t.Fatalf("warm-up: %d %s", warm.status, warm.body) + } + answer := int64(len(warm.body)) + // R1–R4 open and wait at the engine; S1–S4 then hold the four slots with + // their answers' commits; R1–R4's answers then wait for a slot. + engine := make(chan struct{}) + var engineOnce sync.Once + defer engineOnce.Do(func() { close(engine) }) + var calls atomic.Int64 + e.setRespond(func(_ http.ResponseWriter, r *http.Request, _ int64, _ rerankCall) bool { + if calls.Add(1) <= 4 { + select { + case <-engine: + case <-r.Context().Done(): + } + } + return false + }) + gate := make(chan struct{}) + var gateOnce sync.Once + defer gateOnce.Do(func() { close(gate) }) + var wg sync.WaitGroup + for range 4 { + wg.Go(func() { rig.postRerank(t, "/v1/rerank", body) }) + } + if !waitFor(3*time.Second, func() bool { return calls.Load() == 4 }) { + t.Fatal("R1–R4 did not reach the engine") + } + store.set(func(s *recStore) { s.finishGate = gate }) + for range 4 { + wg.Go(func() { rig.postRerank(t, "/v1/rerank", body) }) + } + if !waitFor(3*time.Second, func() bool { return store.inFinish.Load() == 4 }) { + t.Fatal("S1–S4 did not hold the slots with their commits") + } + before := oai.RecordingHeld() + engineOnce.Do(func() { close(engine) }) + time.Sleep(300 * time.Millisecond) // R1–R4 have their answers captured and wait for a slot + waiting := oai.RecordingHeld() - before + gateOnce.Do(func() { close(gate) }) + wg.Wait() + // Each waiter holds its capture (its buffer, at most twice the answer); + // its forced copies (3 × the answer) come with the slot. + if limit := 4 * 3 * answer; waiting >= limit { + t.Errorf("four answers waiting for a slot hold %d bytes of the account — want their captures only (< %d: no forced copies before the slot)", waiting, limit) + } + t.Logf("four waiting answers of %d B hold %d B", answer, waiting) +} From 1d4d698ff74781b483ae331effa7bca3ccf10c2b Mon Sep 17 00:00:00 2001 From: Jan-Stefan Janetzky Date: Fri, 27 Nov 2026 09:42:04 +0100 Subject: [PATCH 23/27] fix(gateway): an answer whose commit ended past the request's deadline is refused, not sent MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit docs/operations.md promised that a request whose deadline passed while its answer was committed gets the refusal, never the answer; heldStillServes let the ready answer go out (the commit itself is not cut by the deadline). It now refuses such an answer with 503 recording_unavailable — the hold took the request past its time, and the client may retry — after the revocation, switch, alias and shutdown checks, and the row's outcome becomes that refusal. The docs say which refusal each cause gets. Co-Authored-By: Claude Opus 5.5 --- docs/operations.md | 2 +- docs/security.md | 2 +- go/internal/oai/record.go | 18 +++++++++++++++--- go/internal/oai/record_route_test.go | 14 ++++++++++---- 4 files changed, 27 insertions(+), 9 deletions(-) diff --git a/docs/operations.md b/docs/operations.md index 3ca505eb4..1723291bb 100644 --- a/docs/operations.md +++ b/docs/operations.md @@ -986,7 +986,7 @@ ctx manage model-consumer-update '' '{"id":"","record_bodies":true, **What a row holds.** `request_body` is the body as the gateway read it, byte for byte (bytea: invalid UTF-8 and NUL bytes included, no cut, no seal — a password, a token or a private key in a prompt is stored in clear text); `request_complete` says whether that is the whole body (a body cut short holds the part read; a request refused before its body was read holds the empty body, `request_complete` false), `declared_bytes` its `Content-Length`; `request_body` is `NULL` only once the retention cleared the row. `response_body` is the answer the client got: a non-streamed chat or rerank answer as written, a stream's relayed `data:` lines in order (without keepalives, the closing `[DONE]` or an error frame), and for every answer that is not a `2xx` — a refusal, an error, a backend's rejection whose text the gateway relays (`gateway.relay_upstream_4xx_messages`) — its error body as written; none for a successful embeddings answer (the vectors are not kept — the input is the record) and none for `503 recording_unavailable` (its bytes are fixed). `state` is `open` from the hold until the outcome is recorded, then `done` with `status` (the HTTP status the client got; `NULL` when the gateway wrote nothing — the client had gone), `code` (the gateway's code of a refusal or an error, where the refusing stage names one — the catch-alls of an unknown path and a wrong method leave it `NULL`), `finished_at`. `op`, `model` and `stream` are what the route read (`NULL` when no route parsed the request), `path` the request's path, `process_id` the ctxd process that admitted it. The row's `id` is the request's id: a chat answer's `id` is `chatcmpl-`, a rerank answer's `rerank-`, and the request's `context_llm_log` row carries it as `metadata.gw.recording_id` (with `metadata.gw.recorded: true`; that row carries no bodies under any `gateway.body_logging` value — the recording is their one place). -**Held before served.** The route commits the row — the whole request, state `open` — before the first backend attempt and before any queue wait; a request whose row cannot be committed is answered `503 recording_unavailable` (`Retry-After: 1`, `x-should-retry: true`) and no backend sees it: the database refuses the insert, or it does not answer within **5 s** (a fixed statement deadline), or the recording's memory account or its statement slots (below) have no room within `dispatch.external_max_wait` (20 s). The `503` reaches the client at once; the gateway then tries once more to leave the request's row (up to another 5 s, the client does not wait for it). A non-streamed answer is committed with the outcome before its first byte is written; if that fails, the client gets the same `503` instead of the answer (the backend ran: the meter books its usage; the client's retry is a second row). An answer that is not a `2xx` is held from the client until the row holds it with its bytes; if that row cannot be written once the request reached its walk, the client gets the `503` in its place, and the row is written with that `503` — a refusal before the walk (no backend asked) goes out as it is. A request that stops being served while its answer is being committed — its key revoked or its consumer deactivated, the model API switched off, the alias gone, the shutdown; also when its request deadline passed during the commit — gets the refusal it would have got before the commit (`401 invalid_api_key` for a revoked key), never the answer, and its row's outcome becomes that refusal; so does a `503` whose answer commit failed although it went through (its acknowledgement lost): the row never claims an answer the client did not get. A stream relays a line only after the recording kept it in memory; its lines are committed when it ends — what a stream sent cannot be taken back, so a stream whose end cannot be committed leaves its row `open` with its request and is counted in `stream_answers_unrecorded`. A request the gateway refuses after the door accepted the key — a body that does not parse, an unknown model, a limit, a body over `gateway.max_request_bytes` (never read: the row holds its declared size), an unknown path, a wrong method — gets its row at its end, `done`, with what was read of the body. Refusals before the door (`401`, a wrong key) are not the consumer's and leave nothing. A process that dies between the hold and the outcome leaves the row `open`: its request is there, its outcome is not known. +**Held before served.** The route commits the row — the whole request, state `open` — before the first backend attempt and before any queue wait; a request whose row cannot be committed is answered `503 recording_unavailable` (`Retry-After: 1`, `x-should-retry: true`) and no backend sees it: the database refuses the insert, or it does not answer within **5 s** (a fixed statement deadline), or the recording's memory account or its statement slots (below) have no room within `dispatch.external_max_wait` (20 s). The `503` reaches the client at once; the gateway then tries once more to leave the request's row (up to another 5 s, the client does not wait for it). A non-streamed answer is committed with the outcome before its first byte is written; if that fails, the client gets the same `503` instead of the answer (the backend ran: the meter books its usage; the client's retry is a second row). An answer that is not a `2xx` is held from the client until the row holds it with its bytes; if that row cannot be written once the request reached its walk, the client gets the `503` in its place, and the row is written with that `503` — a refusal before the walk (no backend asked) goes out as it is. A request that stops being served while its answer is being committed — its key revoked or its consumer deactivated, the model API switched off, the alias gone, the shutdown, each seen also when the request's deadline passed during the commit — gets the refusal it would have got before the commit (`401 invalid_api_key` for a revoked key); one whose deadline alone passed during the commit (the commit is not cut by it) gets `503 recording_unavailable`; none of them gets the answer, and the row's outcome becomes that refusal; so does a `503` whose answer commit failed although it went through (its acknowledgement lost): the row never claims an answer the client did not get. A stream relays a line only after the recording kept it in memory; its lines are committed when it ends — what a stream sent cannot be taken back, so a stream whose end cannot be committed leaves its row `open` with its request and is counted in `stream_answers_unrecorded`. A request the gateway refuses after the door accepted the key — a body that does not parse, an unknown model, a limit, a body over `gateway.max_request_bytes` (never read: the row holds its declared size), an unknown path, a wrong method — gets its row at its end, `done`, with what was read of the body. Refusals before the door (`401`, a wrong key) are not the consumer's and leave nothing. A process that dies between the hold and the outcome leaves the row `open`: its request is there, its outcome is not known. **Checking that nothing is missing.** `GET /api/status` (server-admin) carries `gateway.recording`: `process_id` and `since` (this process's start), `held_bytes` (the memory account's fill), and per recording consumer `admitted` (requests that passed the door as it), `in_flight`, `recorded` (requests whose row is in the table), `unrecordable` (requests for which no row could be written at all — an inference request is then refused with `recording_unavailable`, never served; see the model list below), `unfinished` (requests whose final outcome could not be written: their row stayed `open` — or, for an answer committed and then withheld as above whose superseding outcome could not be written either, it keeps that answer and its `200`; the `ERROR` line below says `answer_withheld=true` and names the `recording_id`) and `stream_answers_unrecorded` (the streams among them that had sent lines). `admitted = in_flight + recorded + unrecordable` holds at every moment, and `recorded` equals the table's rows of that consumer and process: diff --git a/docs/security.md b/docs/security.md index a30ca5103..8a5679446 100644 --- a/docs/security.md +++ b/docs/security.md @@ -167,7 +167,7 @@ Every refusal carries `x-should-retry: false`: the same request against the same What the gateway writes about a request, and what it never writes (design 06 §4.6): - **One body policy.** `gateway.body_logging` is the only switch for prompt and answer bodies of gateway rows in `context_llm_log` — of every consumer, a recording one (next point) included — global-only, so no tenant can raise it for itself. `none` (default) stores none; `errors` stores the serialized request and the answer on rows with an error only; `full` on every row, each capped at 64 KiB. Every row is then slimmed as for a tenant without developer mode: a credentials-class row stays sealed under every policy, whatever the tenant's `tenant.devmode` says — and so does a row whose sensitivity is empty or unknown (fail-closed, logged as a wiring defect). Embedded NUL bytes and invalid UTF-8 are cleaned before the write, so a crafted body cannot make the row — and its attribution — vanish. -- **The one exception: a recording consumer (migration 197, issue #571).** A model consumer with `record_bodies` on has every request it sends through the gateway held in `context_llm_recordings` — chat (a stream included), embeddings, rerank, and every request the gateway refuses after the door accepted its key: the body **as the gateway read it, byte for byte** (whatever `gateway.body_logging`, the alias, the consumer's `prompt_sensitivity`, the body scan or `Ctx-Sensitivity` say — no cut, no credentials seal), the answer the client got (a non-streamed chat or rerank answer; a stream's relayed lines; the error body of every answer that is not a `2xx`, a backend's relayed rejection included; no embedding vectors), the status and the gateway's code. **Such a row can carry credentials in clear text** — a password or key a client puts into a prompt is stored as sent. Only a server-admin can switch it on (also with self-service, and only with `confirm_record_bodies: true`); switching it off is open to the consumer's tenant-admin; both are audited. **No ctx surface reads the table's bodies:** no REST, MCP, CLI or web route, no export, no pipeline (distill, dream, digest) — `TestRecordingsReadersCensus` fails on any production statement that names the table outside its writer and the retention janitor; a server operator reads them in the database ([operations — Recording a consumer](operations.md#recording-a-consumer)). The consumer's `context_llm_log` rows carry **no bodies under any `gateway.body_logging` value** — the recording is the one place of its request and answer, so no reader of the LLM log (its list, detail and export) has them — and are marked `metadata.gw.recorded` with the `recording_id`; their other columns are those of every consumer's. **Held before served:** the request is committed to the table before the first backend attempt; a request that cannot be held — the database refuses it or does not answer within 5 s, or the recording's memory account has no room within the request's wait budget — is answered `503 recording_unavailable` (`x-should-retry: true`, `Retry-After: 1`) and reaches no backend; a non-streamed answer the table does not take is that `503` instead of the answer, and a request that stops being served while its answer is committed (a key revoked, a consumer deactivated) gets the refusal, never the answer — its row then holds that refusal. **What the switch does not change:** the required sensitivity, the chain and its egress rule, the body scan and its `413`, the limits, the in-flight budget's bookings and the answer are the same with and without it — the one new refusal is `recording_unavailable`, and every database write of the recording is in the request's time; deactivating and reactivating the consumer (the switch stays as it was); every other consumer (no stage, no write, no wait — their requests pass the recording stage untouched); the retention — the bodies are NULLed after `scheduler.llmlog_retention_days` (90) like every body; and a database backup (`backup.sh`), which carries them like every other content of the database. +- **The one exception: a recording consumer (migration 197, issue #571).** A model consumer with `record_bodies` on has every request it sends through the gateway held in `context_llm_recordings` — chat (a stream included), embeddings, rerank, and every request the gateway refuses after the door accepted its key: the body **as the gateway read it, byte for byte** (whatever `gateway.body_logging`, the alias, the consumer's `prompt_sensitivity`, the body scan or `Ctx-Sensitivity` say — no cut, no credentials seal), the answer the client got (a non-streamed chat or rerank answer; a stream's relayed lines; the error body of every answer that is not a `2xx`, a backend's relayed rejection included; no embedding vectors), the status and the gateway's code. **Such a row can carry credentials in clear text** — a password or key a client puts into a prompt is stored as sent. Only a server-admin can switch it on (also with self-service, and only with `confirm_record_bodies: true`); switching it off is open to the consumer's tenant-admin; both are audited. **No ctx surface reads the table's bodies:** no REST, MCP, CLI or web route, no export, no pipeline (distill, dream, digest) — `TestRecordingsReadersCensus` fails on any production statement that names the table outside its writer and the retention janitor; a server operator reads them in the database ([operations — Recording a consumer](operations.md#recording-a-consumer)). The consumer's `context_llm_log` rows carry **no bodies under any `gateway.body_logging` value** — the recording is the one place of its request and answer, so no reader of the LLM log (its list, detail and export) has them — and are marked `metadata.gw.recorded` with the `recording_id`; their other columns are those of every consumer's. **Held before served:** the request is committed to the table before the first backend attempt; a request that cannot be held — the database refuses it or does not answer within 5 s, or the recording's memory account has no room within the request's wait budget — is answered `503 recording_unavailable` (`x-should-retry: true`, `Retry-After: 1`) and reaches no backend; a non-streamed answer the table does not take is that `503` instead of the answer, and a request that stops being served while its answer is committed (a key revoked, a consumer deactivated) — or whose deadline passes during the commit — gets the refusal, never the answer — its row then holds that refusal. **What the switch does not change:** the required sensitivity, the chain and its egress rule, the body scan and its `413`, the limits, the in-flight budget's bookings and the answer are the same with and without it — the one new refusal is `recording_unavailable`, and every database write of the recording is in the request's time; deactivating and reactivating the consumer (the switch stays as it was); every other consumer (no stage, no write, no wait — their requests pass the recording stage untouched); the retention — the bodies are NULLed after `scheduler.llmlog_retention_days` (90) like every body; and a database backup (`backup.sh`), which carries them like every other content of the database. - **Error redaction.** The `error` column of a gateway row holds only class, status and ctx code. The upstream response body (which can echo prompt fragments, and which tenant-admins would read in the LLM log list) never reaches it; class and code must have the shape of vocabulary words (lower snake case, at most 64 characters), anything else is stored as `[redacted]`; the writer takes the code from the gateway's own code vocabulary, never from the upstream answer. - **One identity.** A gateway row is attributed to the consumer (`consumer_id`); a knowledge key id that reached the row anyway is cleared with an ERROR line, and the database refuses any row carrying both. The model key id is kept in `metadata.gw.model_key_id` for key-leak forensics, never as a column. - **Access log.** A successful request is one `gateway request` line with ids, op, alias, status, token counts and timings (`gateway.access_log`, default on) — no consumer label, no content, never a key, its hint or a query string. Refusals are counted per (consumer, reason — a code of the gateway or door vocabulary, else `http_`) and logged as one `gateway rejections` WARN line per minute with the count, so a flood of `401`/`429` answers cannot rotate the error and security lines out of the 50 MB × 3 container log. The global request log stays silent for these requests. diff --git a/go/internal/oai/record.go b/go/internal/oai/record.go index 84a2ebeef..4acc1383d 100644 --- a/go/internal/oai/record.go +++ b/go/internal/oai/record.go @@ -116,6 +116,11 @@ func recordAccountLimit(s Settings) int64 { // stream's capture without room): verdict answers it. var errRecordingUnavailable = errors.New("oai: the request could not be recorded") +// errHeldPastDeadline is heldStillServes' cause for an answer whose commit +// ended after the request's deadline: refuseHeld answers it 503 +// recording_unavailable — the hold took the request past its time. +var errHeldPastDeadline = errors.New("oai: the answer's commit ended past the request's deadline") + // recordingAccount is the process-wide account of recorded bytes held // (statement copies, captured answers). acquire waits for room; release // wakes every waiter. @@ -450,9 +455,10 @@ func (rr *requestRecording) withhold() { // request's own context client, which the door's registry ends with // auth.ErrCredentialRevoked: the run's context ctx may have passed its // deadline during the commit, and a context that ended keeps its first -// cause. A cause: the answer does not go out — the route answers it -// (refuseHeld) and withholds the answer. A deadline that passed during the -// commit is none: the answer is ready (answer). +// cause —, and last the request's deadline itself: the commit is not cut by +// it (answer), but an answer whose commit ended past it is refused +// (errHeldPastDeadline), never sent. A cause: the answer does not go out — +// the route answers it (refuseHeld) and withholds the answer. func (d Deps) heldStillServes(ctx, client context.Context, t watchTarget) error { if _, err := d.recheck(ctx, t, t.gen, false); err != nil { return err @@ -463,6 +469,9 @@ func (d Deps) heldStillServes(ctx, client context.Context, t watchTarget) error if cause := context.Cause(client); errors.Is(cause, auth.ErrCredentialRevoked) { return cause } + if errors.Is(ctx.Err(), context.DeadlineExceeded) { + return errHeldPastDeadline + } return nil } @@ -484,6 +493,9 @@ func refuseHeld(cause error, rec *AccessRecord, w http.ResponseWriter, r *http.R rec.Reason = CodeInternalError WriteCode(w, CodeInternalError, shutdownMessage, true) return CodeInternalError + case errors.Is(cause, errHeldPastDeadline): + refuseRecording(rec, w) + return CodeRecordingUnavailable } rec.Reason = CodeInvalidAPIKey // auth.ErrCredentialRevoked WriteInvalidAPIKey(w) diff --git a/go/internal/oai/record_route_test.go b/go/internal/oai/record_route_test.go index 290be3d9f..b45f89f60 100644 --- a/go/internal/oai/record_route_test.go +++ b/go/internal/oai/record_route_test.go @@ -1052,8 +1052,9 @@ func TestRecordingRefusalGoesOutWhenItsRowFails(t *testing.T) { // pass while an answer's commit waits (the commit is not cut by it); a // request that stopped being served during that time — the model API // switched off, the key revoked after the deadline or before it, the -// shutdown — still gets its refusal, never the answer and never an empty -// 200, and its row says what the client got. Chat, embeddings and rerank. +// shutdown — still gets its refusal, and one whose deadline alone passed +// gets 503 recording_unavailable: never the answer and never an empty 200, +// and its row says what the client got. Chat, embeddings and rerank. func TestRecordingHeldAnswerChecksPastTheDeadline(t *testing.T) { want := map[string]struct { status int @@ -1063,9 +1064,10 @@ func TestRecordingHeldAnswerChecksPastTheDeadline(t *testing.T) { "revoked": {http.StatusUnauthorized, oai.CodeInvalidAPIKey}, "revoked_before_deadline": {http.StatusUnauthorized, oai.CodeInvalidAPIKey}, "shutdown": {http.StatusServiceUnavailable, oai.CodeInternalError}, + "deadline": {http.StatusServiceUnavailable, oai.CodeRecordingUnavailable}, } for _, rt := range recRoutes { - for _, mode := range []string{"gateway_off", "revoked", "revoked_before_deadline", "shutdown"} { + for _, mode := range []string{"gateway_off", "revoked", "revoked_before_deadline", "shutdown", "deadline"} { t.Run(rt.name+"/"+mode, func(t *testing.T) { store := newRecStore(nil) gate := make(chan struct{}) @@ -1112,7 +1114,11 @@ func TestRecordingHeldAnswerChecksPastTheDeadline(t *testing.T) { t.Errorf("client %d %q (%d bytes) — want %d %q without the answer", a.status, code, len(a.body), w.status, w.code) } r := store.only(t) - if r.state != llmlog.RecordingDone || r.out.Status != a.status || r.out.Code != w.code || string(r.response) != string(a.body) { + answer := string(a.body) + if w.code == oai.CodeRecordingUnavailable { + answer = "" // its bytes are fixed and go out unheld: the row keeps status and code (docs/operations.md) + } + if r.state != llmlog.RecordingDone || r.out.Status != a.status || r.out.Code != w.code || string(r.response) != answer { t.Errorf("row: state %q status %d code %q answer %d bytes — want done %d %q with the client's %d bytes", r.state, r.out.Status, r.out.Code, len(r.response), a.status, w.code, len(a.body)) } From a069bc9e2e1ddedfb3b72bbae029447b4636b12b Mon Sep 17 00:00:00 2001 From: Jan-Stefan Janetzky Date: Fri, 27 Nov 2026 09:44:19 +0100 Subject: [PATCH 24/27] fix(gateway): the row of a request a panic ended holds the 503 internal_error the client got MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A panic behind the recording stage is answered by oai.Recover outside it, after the stage has ended the row: the row held status and code but not the bytes, although every answer that is not a 2xx keeps its bytes. The stage now renders that answer — WriteInternal, the same fixed bytes Recover writes — into the row in place of a held answer, which it does not restore. Co-Authored-By: Claude Opus 5.5 --- docs/operations.md | 2 +- go/internal/oai/record.go | 51 ++++++++++++++++++++++++---- go/internal/oai/record_route_test.go | 12 ++++--- 3 files changed, 52 insertions(+), 13 deletions(-) diff --git a/docs/operations.md b/docs/operations.md index 1723291bb..10dbad865 100644 --- a/docs/operations.md +++ b/docs/operations.md @@ -984,7 +984,7 @@ ctx manage model-consumer-update '' '{"id":"","record_bodies":true, (The consumer's `id` goes into `data`; `model-consumer-create` takes the same two fields.) From the consumer's next request on — a request already running keeps what it was admitted with — every request of it gets one row in `context_llm_recordings`; switching off is `"record_bodies": false`, which a tenant-admin of the consumer's tenant may do too. The consumer view (API, CLI `--json`, `/gateway` in the SPA) shows the switch to every reader; `GET /api/status` lists the recording consumers in `gateway.recording_consumers` and counts their requests in `gateway.recording` (server-admin). -**What a row holds.** `request_body` is the body as the gateway read it, byte for byte (bytea: invalid UTF-8 and NUL bytes included, no cut, no seal — a password, a token or a private key in a prompt is stored in clear text); `request_complete` says whether that is the whole body (a body cut short holds the part read; a request refused before its body was read holds the empty body, `request_complete` false), `declared_bytes` its `Content-Length`; `request_body` is `NULL` only once the retention cleared the row. `response_body` is the answer the client got: a non-streamed chat or rerank answer as written, a stream's relayed `data:` lines in order (without keepalives, the closing `[DONE]` or an error frame), and for every answer that is not a `2xx` — a refusal, an error, a backend's rejection whose text the gateway relays (`gateway.relay_upstream_4xx_messages`) — its error body as written; none for a successful embeddings answer (the vectors are not kept — the input is the record) and none for `503 recording_unavailable` (its bytes are fixed). `state` is `open` from the hold until the outcome is recorded, then `done` with `status` (the HTTP status the client got; `NULL` when the gateway wrote nothing — the client had gone), `code` (the gateway's code of a refusal or an error, where the refusing stage names one — the catch-alls of an unknown path and a wrong method leave it `NULL`), `finished_at`. `op`, `model` and `stream` are what the route read (`NULL` when no route parsed the request), `path` the request's path, `process_id` the ctxd process that admitted it. The row's `id` is the request's id: a chat answer's `id` is `chatcmpl-`, a rerank answer's `rerank-`, and the request's `context_llm_log` row carries it as `metadata.gw.recording_id` (with `metadata.gw.recorded: true`; that row carries no bodies under any `gateway.body_logging` value — the recording is their one place). +**What a row holds.** `request_body` is the body as the gateway read it, byte for byte (bytea: invalid UTF-8 and NUL bytes included, no cut, no seal — a password, a token or a private key in a prompt is stored in clear text); `request_complete` says whether that is the whole body (a body cut short holds the part read; a request refused before its body was read holds the empty body, `request_complete` false), `declared_bytes` its `Content-Length`; `request_body` is `NULL` only once the retention cleared the row. `response_body` is the answer the client got: a non-streamed chat or rerank answer as written, a stream's relayed `data:` lines in order (without keepalives, the closing `[DONE]` or an error frame), and for every answer that is not a `2xx` — a refusal, an error, a backend's rejection whose text the gateway relays (`gateway.relay_upstream_4xx_messages`) — its error body as written (a request a panic ended: the `503 internal_error` the client got); none for a successful embeddings answer (the vectors are not kept — the input is the record) and none for `503 recording_unavailable` (its bytes are fixed). `state` is `open` from the hold until the outcome is recorded, then `done` with `status` (the HTTP status the client got; `NULL` when the gateway wrote nothing — the client had gone), `code` (the gateway's code of a refusal or an error, where the refusing stage names one — the catch-alls of an unknown path and a wrong method leave it `NULL`), `finished_at`. `op`, `model` and `stream` are what the route read (`NULL` when no route parsed the request), `path` the request's path, `process_id` the ctxd process that admitted it. The row's `id` is the request's id: a chat answer's `id` is `chatcmpl-`, a rerank answer's `rerank-`, and the request's `context_llm_log` row carries it as `metadata.gw.recording_id` (with `metadata.gw.recorded: true`; that row carries no bodies under any `gateway.body_logging` value — the recording is their one place). **Held before served.** The route commits the row — the whole request, state `open` — before the first backend attempt and before any queue wait; a request whose row cannot be committed is answered `503 recording_unavailable` (`Retry-After: 1`, `x-should-retry: true`) and no backend sees it: the database refuses the insert, or it does not answer within **5 s** (a fixed statement deadline), or the recording's memory account or its statement slots (below) have no room within `dispatch.external_max_wait` (20 s). The `503` reaches the client at once; the gateway then tries once more to leave the request's row (up to another 5 s, the client does not wait for it). A non-streamed answer is committed with the outcome before its first byte is written; if that fails, the client gets the same `503` instead of the answer (the backend ran: the meter books its usage; the client's retry is a second row). An answer that is not a `2xx` is held from the client until the row holds it with its bytes; if that row cannot be written once the request reached its walk, the client gets the `503` in its place, and the row is written with that `503` — a refusal before the walk (no backend asked) goes out as it is. A request that stops being served while its answer is being committed — its key revoked or its consumer deactivated, the model API switched off, the alias gone, the shutdown, each seen also when the request's deadline passed during the commit — gets the refusal it would have got before the commit (`401 invalid_api_key` for a revoked key); one whose deadline alone passed during the commit (the commit is not cut by it) gets `503 recording_unavailable`; none of them gets the answer, and the row's outcome becomes that refusal; so does a `503` whose answer commit failed although it went through (its acknowledgement lost): the row never claims an answer the client did not get. A stream relays a line only after the recording kept it in memory; its lines are committed when it ends — what a stream sent cannot be taken back, so a stream whose end cannot be committed leaves its row `open` with its request and is counted in `stream_answers_unrecorded`. A request the gateway refuses after the door accepted the key — a body that does not parse, an unknown model, a limit, a body over `gateway.max_request_bytes` (never read: the row holds its declared size), an unknown path, a wrong method — gets its row at its end, `done`, with what was read of the body. Refusals before the door (`401`, a wrong key) are not the consumer's and leave nothing. A process that dies between the hold and the outcome leaves the row `open`: its request is there, its outcome is not known. diff --git a/go/internal/oai/record.go b/go/internal/oai/record.go index 4acc1383d..b9c559c06 100644 --- a/go/internal/oai/record.go +++ b/go/internal/oai/record.go @@ -1,6 +1,7 @@ package oai import ( + "bytes" "context" "errors" "fmt" @@ -719,8 +720,9 @@ func (rr *requestRecording) endStage(p any, w http.ResponseWriter) { code = rr.access.Reason } if p != nil && !rr.answerPassed() { - // oai.Recover answers the panic: nothing of the route's went out. - rr.dropHeld(http.StatusServiceUnavailable) + // oai.Recover answers the panic: nothing of the route's went out, and + // its answer — the fixed bytes of WriteInternal — is the row's. + rr.holdInstead(renderAnswer(WriteInternal)) code = CodeInternalError } if p == nil && code == CodeRecordingUnavailable { @@ -798,15 +800,50 @@ func (rr *requestRecording) answerPassed() bool { return rr.passed } -// dropHeld forgets a held answer; the client gets status from elsewhere -// (oai.Recover's 503). -func (rr *requestRecording) dropHeld(status int) { +// holdInstead replaces a held answer — or nothing written — by a, the answer +// the client gets from elsewhere (oai.Recover's 503 after a panic): the row +// records a's status and bytes, and nothing of a goes out from here (release +// does not run on a panic). +func (rr *requestRecording) holdInstead(a *renderedAnswer) { rr.statusMu.Lock() - rr.holding, rr.heldCode, rr.heldBody = false, 0, nil - rr.status = status + rr.holding, rr.heldCode, rr.heldBody = true, a.code, a.body.Bytes() + rr.status = a.code rr.statusMu.Unlock() } +// renderedAnswer is an answer written into memory: the status, headers and +// bytes a writer function produces (WriteInternal for oai.Recover's answer). +type renderedAnswer struct { + header http.Header + code int + body bytes.Buffer +} + +// renderAnswer is what write writes. +func renderAnswer(write func(http.ResponseWriter)) *renderedAnswer { + a := &renderedAnswer{header: http.Header{}} + write(a) + if a.code == 0 { + a.code = http.StatusOK + } + return a +} + +func (a *renderedAnswer) Header() http.Header { return a.header } + +func (a *renderedAnswer) WriteHeader(code int) { + if a.code == 0 { + a.code = code + } +} + +func (a *renderedAnswer) Write(p []byte) (int, error) { + if a.code == 0 { + a.code = http.StatusOK + } + return a.body.Write(p) +} + // release writes the held answer once the request's outcome is decided: // as held when the row holds it (settled) or when the request never reached // its walk (no open row: a refusal in the gateway's own words, nothing a diff --git a/go/internal/oai/record_route_test.go b/go/internal/oai/record_route_test.go index b45f89f60..fbe130c25 100644 --- a/go/internal/oai/record_route_test.go +++ b/go/internal/oai/record_route_test.go @@ -601,8 +601,10 @@ func TestRecordingPanicLeavesTheRow(t *testing.T) { w := httptest.NewRecorder() rt.ServeHTTP(w, httptest.NewRequest(http.MethodPost, "/v1/chat/completions", strings.NewReader("{}"))) r := store.only(t) - if w.Code != 503 || r.out.Status != 503 || r.out.Code != oai.CodeInternalError { - t.Errorf("client %d, row status %d code %q — want 503 internal_error both", w.Code, r.out.Status, r.out.Code) + if w.Code != 503 || r.out.Status != 503 || r.out.Code != oai.CodeInternalError || string(r.response) != w.Body.String() || + !strings.Contains(w.Body.String(), `"code":"internal_error"`) { + t.Errorf("client %d %q, row status %d code %q answer %q — want 503 internal_error both, the row with the client's bytes", + w.Code, w.Body.String(), r.out.Status, r.out.Code, r.response) } } @@ -1174,9 +1176,9 @@ func TestRecordingPanicAfterAHeldAnswer(t *testing.T) { w := httptest.NewRecorder() rt.ServeHTTP(w, httptest.NewRequest(http.MethodPost, "/v1/chat/completions", strings.NewReader("{}"))) r := store.only(t) - if w.Code != 503 || strings.Contains(w.Body.String(), "a held answer") || r.out.Status != 503 || r.out.Code != oai.CodeInternalError || - strings.Contains(string(r.response), "a held answer") { - t.Errorf("client %d %q, row status %d code %q answer %q — want 503 internal_error both, without the held answer", + if w.Code != 503 || strings.Contains(w.Body.String(), "a held answer") || !strings.Contains(w.Body.String(), `"code":"internal_error"`) || + r.out.Status != 503 || r.out.Code != oai.CodeInternalError || string(r.response) != w.Body.String() { + t.Errorf("client %d %q, row status %d code %q answer %q — want 503 internal_error both, the row with the client's bytes, not the held answer", w.Code, w.Body.String(), r.out.Status, r.out.Code, r.response) } } From 0f4910c2066eb71f8b124fc9f01b48d503b3274a Mon Sep 17 00:00:00 2001 From: Jan-Stefan Janetzky Date: Fri, 27 Nov 2026 09:46:37 +0100 Subject: [PATCH 25/27] fix(gateway): a held error answer whose key is revoked after its commit goes out as 401 invalid_api_key, and that refusal supersedes its row MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit An error answer held for its row — possibly a backend's rejection text the gateway relays — was written after its commit without a second look: a key revoked while the row committed it still got it, and the row kept it. The stage's release now reads the revocation on the request's own context for a request that reached its walk; a revoked key gets 401 invalid_api_key (rendered, written and flushed), and that refusal with its bytes supersedes the row. Co-Authored-By: Claude Opus 5.5 --- docs/operations.md | 2 +- docs/security.md | 2 +- go/internal/oai/record.go | 64 +++++++++++++++++++--------- go/internal/oai/record_route_test.go | 45 +++++++++++++++++++ 4 files changed, 92 insertions(+), 21 deletions(-) diff --git a/docs/operations.md b/docs/operations.md index 10dbad865..b73c8a4e9 100644 --- a/docs/operations.md +++ b/docs/operations.md @@ -986,7 +986,7 @@ ctx manage model-consumer-update '' '{"id":"","record_bodies":true, **What a row holds.** `request_body` is the body as the gateway read it, byte for byte (bytea: invalid UTF-8 and NUL bytes included, no cut, no seal — a password, a token or a private key in a prompt is stored in clear text); `request_complete` says whether that is the whole body (a body cut short holds the part read; a request refused before its body was read holds the empty body, `request_complete` false), `declared_bytes` its `Content-Length`; `request_body` is `NULL` only once the retention cleared the row. `response_body` is the answer the client got: a non-streamed chat or rerank answer as written, a stream's relayed `data:` lines in order (without keepalives, the closing `[DONE]` or an error frame), and for every answer that is not a `2xx` — a refusal, an error, a backend's rejection whose text the gateway relays (`gateway.relay_upstream_4xx_messages`) — its error body as written (a request a panic ended: the `503 internal_error` the client got); none for a successful embeddings answer (the vectors are not kept — the input is the record) and none for `503 recording_unavailable` (its bytes are fixed). `state` is `open` from the hold until the outcome is recorded, then `done` with `status` (the HTTP status the client got; `NULL` when the gateway wrote nothing — the client had gone), `code` (the gateway's code of a refusal or an error, where the refusing stage names one — the catch-alls of an unknown path and a wrong method leave it `NULL`), `finished_at`. `op`, `model` and `stream` are what the route read (`NULL` when no route parsed the request), `path` the request's path, `process_id` the ctxd process that admitted it. The row's `id` is the request's id: a chat answer's `id` is `chatcmpl-`, a rerank answer's `rerank-`, and the request's `context_llm_log` row carries it as `metadata.gw.recording_id` (with `metadata.gw.recorded: true`; that row carries no bodies under any `gateway.body_logging` value — the recording is their one place). -**Held before served.** The route commits the row — the whole request, state `open` — before the first backend attempt and before any queue wait; a request whose row cannot be committed is answered `503 recording_unavailable` (`Retry-After: 1`, `x-should-retry: true`) and no backend sees it: the database refuses the insert, or it does not answer within **5 s** (a fixed statement deadline), or the recording's memory account or its statement slots (below) have no room within `dispatch.external_max_wait` (20 s). The `503` reaches the client at once; the gateway then tries once more to leave the request's row (up to another 5 s, the client does not wait for it). A non-streamed answer is committed with the outcome before its first byte is written; if that fails, the client gets the same `503` instead of the answer (the backend ran: the meter books its usage; the client's retry is a second row). An answer that is not a `2xx` is held from the client until the row holds it with its bytes; if that row cannot be written once the request reached its walk, the client gets the `503` in its place, and the row is written with that `503` — a refusal before the walk (no backend asked) goes out as it is. A request that stops being served while its answer is being committed — its key revoked or its consumer deactivated, the model API switched off, the alias gone, the shutdown, each seen also when the request's deadline passed during the commit — gets the refusal it would have got before the commit (`401 invalid_api_key` for a revoked key); one whose deadline alone passed during the commit (the commit is not cut by it) gets `503 recording_unavailable`; none of them gets the answer, and the row's outcome becomes that refusal; so does a `503` whose answer commit failed although it went through (its acknowledgement lost): the row never claims an answer the client did not get. A stream relays a line only after the recording kept it in memory; its lines are committed when it ends — what a stream sent cannot be taken back, so a stream whose end cannot be committed leaves its row `open` with its request and is counted in `stream_answers_unrecorded`. A request the gateway refuses after the door accepted the key — a body that does not parse, an unknown model, a limit, a body over `gateway.max_request_bytes` (never read: the row holds its declared size), an unknown path, a wrong method — gets its row at its end, `done`, with what was read of the body. Refusals before the door (`401`, a wrong key) are not the consumer's and leave nothing. A process that dies between the hold and the outcome leaves the row `open`: its request is there, its outcome is not known. +**Held before served.** The route commits the row — the whole request, state `open` — before the first backend attempt and before any queue wait; a request whose row cannot be committed is answered `503 recording_unavailable` (`Retry-After: 1`, `x-should-retry: true`) and no backend sees it: the database refuses the insert, or it does not answer within **5 s** (a fixed statement deadline), or the recording's memory account or its statement slots (below) have no room within `dispatch.external_max_wait` (20 s). The `503` reaches the client at once; the gateway then tries once more to leave the request's row (up to another 5 s, the client does not wait for it). A non-streamed answer is committed with the outcome before its first byte is written; if that fails, the client gets the same `503` instead of the answer (the backend ran: the meter books its usage; the client's retry is a second row). An answer that is not a `2xx` is held from the client until the row holds it with its bytes; if that row cannot be written once the request reached its walk, the client gets the `503` in its place, and the row is written with that `503` — a refusal before the walk (no backend asked) goes out as it is; when the key of a request that reached its walk is revoked between that commit and the write, the client gets `401 invalid_api_key` instead of the held answer, and that refusal supersedes the row. A request that stops being served while its answer is being committed — its key revoked or its consumer deactivated, the model API switched off, the alias gone, the shutdown, each seen also when the request's deadline passed during the commit — gets the refusal it would have got before the commit (`401 invalid_api_key` for a revoked key); one whose deadline alone passed during the commit (the commit is not cut by it) gets `503 recording_unavailable`; none of them gets the answer, and the row's outcome becomes that refusal; so does a `503` whose answer commit failed although it went through (its acknowledgement lost): the row never claims an answer the client did not get. A stream relays a line only after the recording kept it in memory; its lines are committed when it ends — what a stream sent cannot be taken back, so a stream whose end cannot be committed leaves its row `open` with its request and is counted in `stream_answers_unrecorded`. A request the gateway refuses after the door accepted the key — a body that does not parse, an unknown model, a limit, a body over `gateway.max_request_bytes` (never read: the row holds its declared size), an unknown path, a wrong method — gets its row at its end, `done`, with what was read of the body. Refusals before the door (`401`, a wrong key) are not the consumer's and leave nothing. A process that dies between the hold and the outcome leaves the row `open`: its request is there, its outcome is not known. **Checking that nothing is missing.** `GET /api/status` (server-admin) carries `gateway.recording`: `process_id` and `since` (this process's start), `held_bytes` (the memory account's fill), and per recording consumer `admitted` (requests that passed the door as it), `in_flight`, `recorded` (requests whose row is in the table), `unrecordable` (requests for which no row could be written at all — an inference request is then refused with `recording_unavailable`, never served; see the model list below), `unfinished` (requests whose final outcome could not be written: their row stayed `open` — or, for an answer committed and then withheld as above whose superseding outcome could not be written either, it keeps that answer and its `200`; the `ERROR` line below says `answer_withheld=true` and names the `recording_id`) and `stream_answers_unrecorded` (the streams among them that had sent lines). `admitted = in_flight + recorded + unrecordable` holds at every moment, and `recorded` equals the table's rows of that consumer and process: diff --git a/docs/security.md b/docs/security.md index 8a5679446..e4e23c2aa 100644 --- a/docs/security.md +++ b/docs/security.md @@ -167,7 +167,7 @@ Every refusal carries `x-should-retry: false`: the same request against the same What the gateway writes about a request, and what it never writes (design 06 §4.6): - **One body policy.** `gateway.body_logging` is the only switch for prompt and answer bodies of gateway rows in `context_llm_log` — of every consumer, a recording one (next point) included — global-only, so no tenant can raise it for itself. `none` (default) stores none; `errors` stores the serialized request and the answer on rows with an error only; `full` on every row, each capped at 64 KiB. Every row is then slimmed as for a tenant without developer mode: a credentials-class row stays sealed under every policy, whatever the tenant's `tenant.devmode` says — and so does a row whose sensitivity is empty or unknown (fail-closed, logged as a wiring defect). Embedded NUL bytes and invalid UTF-8 are cleaned before the write, so a crafted body cannot make the row — and its attribution — vanish. -- **The one exception: a recording consumer (migration 197, issue #571).** A model consumer with `record_bodies` on has every request it sends through the gateway held in `context_llm_recordings` — chat (a stream included), embeddings, rerank, and every request the gateway refuses after the door accepted its key: the body **as the gateway read it, byte for byte** (whatever `gateway.body_logging`, the alias, the consumer's `prompt_sensitivity`, the body scan or `Ctx-Sensitivity` say — no cut, no credentials seal), the answer the client got (a non-streamed chat or rerank answer; a stream's relayed lines; the error body of every answer that is not a `2xx`, a backend's relayed rejection included; no embedding vectors), the status and the gateway's code. **Such a row can carry credentials in clear text** — a password or key a client puts into a prompt is stored as sent. Only a server-admin can switch it on (also with self-service, and only with `confirm_record_bodies: true`); switching it off is open to the consumer's tenant-admin; both are audited. **No ctx surface reads the table's bodies:** no REST, MCP, CLI or web route, no export, no pipeline (distill, dream, digest) — `TestRecordingsReadersCensus` fails on any production statement that names the table outside its writer and the retention janitor; a server operator reads them in the database ([operations — Recording a consumer](operations.md#recording-a-consumer)). The consumer's `context_llm_log` rows carry **no bodies under any `gateway.body_logging` value** — the recording is the one place of its request and answer, so no reader of the LLM log (its list, detail and export) has them — and are marked `metadata.gw.recorded` with the `recording_id`; their other columns are those of every consumer's. **Held before served:** the request is committed to the table before the first backend attempt; a request that cannot be held — the database refuses it or does not answer within 5 s, or the recording's memory account has no room within the request's wait budget — is answered `503 recording_unavailable` (`x-should-retry: true`, `Retry-After: 1`) and reaches no backend; a non-streamed answer the table does not take is that `503` instead of the answer, and a request that stops being served while its answer is committed (a key revoked, a consumer deactivated) — or whose deadline passes during the commit — gets the refusal, never the answer — its row then holds that refusal. **What the switch does not change:** the required sensitivity, the chain and its egress rule, the body scan and its `413`, the limits, the in-flight budget's bookings and the answer are the same with and without it — the one new refusal is `recording_unavailable`, and every database write of the recording is in the request's time; deactivating and reactivating the consumer (the switch stays as it was); every other consumer (no stage, no write, no wait — their requests pass the recording stage untouched); the retention — the bodies are NULLed after `scheduler.llmlog_retention_days` (90) like every body; and a database backup (`backup.sh`), which carries them like every other content of the database. +- **The one exception: a recording consumer (migration 197, issue #571).** A model consumer with `record_bodies` on has every request it sends through the gateway held in `context_llm_recordings` — chat (a stream included), embeddings, rerank, and every request the gateway refuses after the door accepted its key: the body **as the gateway read it, byte for byte** (whatever `gateway.body_logging`, the alias, the consumer's `prompt_sensitivity`, the body scan or `Ctx-Sensitivity` say — no cut, no credentials seal), the answer the client got (a non-streamed chat or rerank answer; a stream's relayed lines; the error body of every answer that is not a `2xx`, a backend's relayed rejection included; no embedding vectors), the status and the gateway's code. **Such a row can carry credentials in clear text** — a password or key a client puts into a prompt is stored as sent. Only a server-admin can switch it on (also with self-service, and only with `confirm_record_bodies: true`); switching it off is open to the consumer's tenant-admin; both are audited. **No ctx surface reads the table's bodies:** no REST, MCP, CLI or web route, no export, no pipeline (distill, dream, digest) — `TestRecordingsReadersCensus` fails on any production statement that names the table outside its writer and the retention janitor; a server operator reads them in the database ([operations — Recording a consumer](operations.md#recording-a-consumer)). The consumer's `context_llm_log` rows carry **no bodies under any `gateway.body_logging` value** — the recording is the one place of its request and answer, so no reader of the LLM log (its list, detail and export) has them — and are marked `metadata.gw.recorded` with the `recording_id`; their other columns are those of every consumer's. **Held before served:** the request is committed to the table before the first backend attempt; a request that cannot be held — the database refuses it or does not answer within 5 s, or the recording's memory account has no room within the request's wait budget — is answered `503 recording_unavailable` (`x-should-retry: true`, `Retry-After: 1`) and reaches no backend; a non-streamed answer the table does not take is that `503` instead of the answer, and a request that stops being served while its answer is committed (a key revoked, a consumer deactivated) — or whose deadline passes during the commit — gets the refusal, never the answer (an error answer held for its row likewise, when the key is revoked before it goes out) — its row then holds that refusal. **What the switch does not change:** the required sensitivity, the chain and its egress rule, the body scan and its `413`, the limits, the in-flight budget's bookings and the answer are the same with and without it — the one new refusal is `recording_unavailable`, and every database write of the recording is in the request's time; deactivating and reactivating the consumer (the switch stays as it was); every other consumer (no stage, no write, no wait — their requests pass the recording stage untouched); the retention — the bodies are NULLed after `scheduler.llmlog_retention_days` (90) like every body; and a database backup (`backup.sh`), which carries them like every other content of the database. - **Error redaction.** The `error` column of a gateway row holds only class, status and ctx code. The upstream response body (which can echo prompt fragments, and which tenant-admins would read in the LLM log list) never reaches it; class and code must have the shape of vocabulary words (lower snake case, at most 64 characters), anything else is stored as `[redacted]`; the writer takes the code from the gateway's own code vocabulary, never from the upstream answer. - **One identity.** A gateway row is attributed to the consumer (`consumer_id`); a knowledge key id that reached the row anyway is cleared with an ERROR line, and the database refuses any row carrying both. The model key id is kept in `metadata.gw.model_key_id` for key-leak forensics, never as a column. - **Access log.** A successful request is one `gateway request` line with ids, op, alias, status, token counts and timings (`gateway.access_log`, default on) — no consumer label, no content, never a key, its hint or a query string. Refusals are counted per (consumer, reason — a code of the gateway or door vocabulary, else `http_`) and logged as one `gateway rejections` WARN line per minute with the count, so a flood of `401`/`429` answers cannot rotate the error and security lines out of the 50 MB × 3 container log. The global request log stays silent for these requests. diff --git a/go/internal/oai/record.go b/go/internal/oai/record.go index b9c559c06..81b0fa943 100644 --- a/go/internal/oai/record.go +++ b/go/internal/oai/record.go @@ -255,7 +255,7 @@ func (s *RecordingStage) begin(ca *auth.ConsumerAuth, r *http.Request) *requestR if err != nil { id = uuid.New() } - rr := &requestRecording{stage: s, acct: recAccount, access: AccessRecordFrom(r.Context()), req: llmlog.RecordedRequest{ + rr := &requestRecording{stage: s, acct: recAccount, access: AccessRecordFrom(r.Context()), client: r.Context(), req: llmlog.RecordedRequest{ ID: id.String(), ConsumerID: ca.ConsumerID, ModelKeyID: ca.ModelKeyID, Path: r.URL.Path, ClientRequestID: clientRequestID(r), Declared: r.ContentLength, }} @@ -273,6 +273,9 @@ type requestRecording struct { stage *RecordingStage acct *recordingAccount access *AccessRecord // the access log's record: the refusal's code + // client is the request's own context at the stage, which the door's + // registry ends with auth.ErrCredentialRevoked (release). + client context.Context req llmlog.RecordedRequest stats *recordingConsumerStats @@ -663,13 +666,14 @@ func (rr *requestRecording) logUnfinished(err error) { "answer_withheld", rr.withheld, "error", err) } -// supersedeReplaced writes the outcome of a held answer that release -// replaced with 503 recording_unavailable — its row's commit failed, and it -// may have gone through all the same: that 503 supersedes whatever the row -// holds. A failure stays counted as unfinished. -func (rr *requestRecording) supersedeReplaced() { +// supersedeReplaced writes the outcome o of a held answer that release +// replaced — with 503 recording_unavailable when its row's commit failed +// (it may have gone through all the same), with the 401 of a key revoked +// after the commit —: o supersedes whatever the row holds. A failure stays +// counted as unfinished. +func (rr *requestRecording) supersedeReplaced(o llmlog.RecordedOutcome) { rr.withheld = true - o := llmlog.RecordedOutcome{Status: http.StatusServiceUnavailable, Code: CodeRecordingUnavailable, Supersedes: true} + o.Supersedes = true if err := rr.finish(context.Background(), o); err != nil { rr.logUnfinished(err) return @@ -731,8 +735,10 @@ func (rr *requestRecording) endStage(p any, w http.ResponseWriter) { _ = http.NewResponseController(w).Flush() } rr.end(code) - if p == nil && rr.release(w) { - rr.supersedeReplaced() + if p == nil { + if o := rr.release(w); o != nil { + rr.supersedeReplaced(*o) + } } recStats.done(rr.stats, rr.row, rr.unfinished, rr.unfinished && rr.streamed) } @@ -847,33 +853,53 @@ func (a *renderedAnswer) Write(p []byte) (int, error) { // release writes the held answer once the request's outcome is decided: // as held when the row holds it (settled) or when the request never reached // its walk (no open row: a refusal in the gateway's own words, nothing a -// backend sent); otherwise — the row was opened and could not take what the -// client would get — 503 recording_unavailable in its place, from the -// headers at the stage, flushed before the row's superseding attempt; -// replaced reports that. -func (rr *requestRecording) release(w http.ResponseWriter) (replaced bool) { +// backend sent). Otherwise something else goes out in its place, from the +// headers at the stage and flushed before the row's superseding attempt, +// and release returns that outcome for the row (endStage supersedes it): +// 503 recording_unavailable when the row was opened and could not take what +// the client would get; the 401 invalid_api_key of a key that stopped +// authenticating between the commit of an opened request's held answer and +// this write (read on the request's own context, as heldStillServes does) — +// the held answer can carry a backend's text, and a revoked key gets +// nothing of it. +func (rr *requestRecording) release(w http.ResponseWriter) *llmlog.RecordedOutcome { rr.statusMu.Lock() holding, code, body := rr.holding, rr.heldCode, rr.heldBody rr.holding, rr.heldBody, rr.passed = false, nil, true rr.statusMu.Unlock() if !holding { - return false + return nil } - if !rr.settled && rr.opened { + if rr.opened && (!rr.settled || errors.Is(context.Cause(rr.client), auth.ErrCredentialRevoked)) { h := w.Header() clear(h) for k, v := range rr.entry { h[k] = v } - refuseRecording(rr.access, w) + if !rr.settled { + refuseRecording(rr.access, w) + _ = http.NewResponseController(w).Flush() + return &llmlog.RecordedOutcome{Status: http.StatusServiceUnavailable, Code: CodeRecordingUnavailable} + } + a := renderAnswer(WriteInvalidAPIKey) + if rr.access != nil { + rr.access.Reason = CodeInvalidAPIKey + } + for k, v := range a.header { + h[k] = v + } + w.WriteHeader(a.code) + if _, err := w.Write(a.body.Bytes()); err != nil { + slog.Warn("gateway: failed to write the refusal of a revoked key", "error", err, "recording_id", rr.req.ID) + } _ = http.NewResponseController(w).Flush() - return true + return &llmlog.RecordedOutcome{Status: a.code, Code: CodeInvalidAPIKey, Response: a.body.Bytes()} } w.WriteHeader(code) if _, err := w.Write(body); err != nil { //nolint:gosec // G705: body is the route's own error envelope (WriteCode, refuseParam — encoding/json's escape), held and written unchanged: the bytes the unrecorded path writes slog.Warn("gateway: failed to write a held answer", "error", err, "recording_id", rr.req.ID) } - return false + return nil } // refuseRecording answers a request whose recording failed: 503 diff --git a/go/internal/oai/record_route_test.go b/go/internal/oai/record_route_test.go index fbe130c25..b0c22e2a1 100644 --- a/go/internal/oai/record_route_test.go +++ b/go/internal/oai/record_route_test.go @@ -1332,3 +1332,48 @@ func TestRecordingForcedCopiesWaitWithoutBooking(t *testing.T) { } t.Logf("four waiting answers of %d B hold %d B", answer, waiting) } + +// TestRecordingHeldErrorWithheldWhenRevoked: a held error answer — here a +// backend's rejection text the gateway relays — whose key is revoked while +// its row commits it does not go out: the client gets 401 invalid_api_key, +// and the row's outcome becomes that refusal with its bytes. +func TestRecordingHeldErrorWithheldWhenRevoked(t *testing.T) { + u := newUpstream(t, recChatAnswer) + u.setRespond(func(w http.ResponseWriter, _ *http.Request) { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(http.StatusBadRequest) + _, _ = w.Write([]byte(`{"error":{"message":"` + recRejection + `","type":"invalid_request_error"}}`)) + }) + store := newRecStore(nil) + rig := newChatRig(t, []backends.Backend{u.row("spark", backends.TrustFull, 10)}, 4, 1, withRecordings(store)) + rig.setSettings(func(s *oai.Settings) { s.RelayUpstream4xxMessages = true }) + rig.ca.Store(recordingConsumer(true)) + gate := make(chan struct{}) + var once sync.Once + defer once.Do(func() { close(gate) }) + store.set(func(s *recStore) { s.finishGate = gate }) + rv := newRevoker() + srv := serveHTTP(t, rv.wrap(rig.router)) + done := make(chan chatAnswer, 1) + go func() { done <- postVia(t, srv, "/v1/chat/completions", chatBody("pub")) }() + if !waitFor(5*time.Second, func() bool { return store.inFinish.Load() == 1 }) { + t.Fatal("the held error's commit did not start") + } + if n := rv.revoke(); n != 1 { + t.Fatalf("revoked %d running requests, want 1", n) + } + once.Do(func() { close(gate) }) + var a chatAnswer + select { + case a = <-done: + case <-time.After(10 * time.Second): + t.Fatal("no answer after the revocation") + } + if code, _, _ := a.envelope(t); a.status != http.StatusUnauthorized || code != oai.CodeInvalidAPIKey || strings.Contains(string(a.body), "marker-571-rejected") { + t.Fatalf("answer %d %q %s — want 401 invalid_api_key, without the backend's text", a.status, code, a.body) + } + r := store.only(t) + if r.state != llmlog.RecordingDone || r.out.Status != http.StatusUnauthorized || r.out.Code != oai.CodeInvalidAPIKey || string(r.response) != string(a.body) { + t.Errorf("row: state %q status %d code %q answer %q — want done 401 invalid_api_key with the client's %q", r.state, r.out.Status, r.out.Code, r.response, a.body) + } +} From 1414216d090f775d81db4ce191d2615e3087aeba Mon Sep 17 00:00:00 2001 From: Jan-Stefan Janetzky Date: Fri, 27 Nov 2026 09:49:31 +0100 Subject: [PATCH 26/27] test(gateway): the recording store double refuses a canceled statement, and the LLM-log row test has its positive control for the answer MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The double's Finish committed whatever context it was given — after its gate, Go's select picks either of two ready cases, and without a gate it never looked: a superseding write on the revoked request's context passed the held-error revocation test 8 times in 20 as a mutant; with the check under the store's lock it fails 20 of 20. TestRecordedLLMLogRowCarriesNoBodies now requires the unrecorded chat row to carry its answer, and the stream, embeddings and rerank rows to carry none — the exclusion explicit per route. Co-Authored-By: Claude Opus 5.5 --- go/internal/oai/record_route_test.go | 22 +++++++++++++++++----- 1 file changed, 17 insertions(+), 5 deletions(-) diff --git a/go/internal/oai/record_route_test.go b/go/internal/oai/record_route_test.go index b0c22e2a1..7e8198291 100644 --- a/go/internal/oai/record_route_test.go +++ b/go/internal/oai/record_route_test.go @@ -144,6 +144,11 @@ func (s *recStore) Finish(ctx context.Context, id string, o llmlog.RecordedOutco } s.mu.Lock() defer s.mu.Unlock() + if err := ctx.Err(); err != nil { + // A canceled statement commits nothing — whatever the gate's select + // picked when both were ready. + return err + } if s.finishErr != nil { return s.finishErr } @@ -756,7 +761,10 @@ func TestRecordingStatementSlots(t *testing.T) { // of the same request without the switch carries both; the recorded row is // marked with its recording id. Chat, a stream, embeddings and rerank. func TestRecordedLLMLogRowCarriesNoBodies(t *testing.T) { - check := func(t *testing.T, rig *chatRig, store *recStore) { + // loggedAnswer: the route hands its answer to the LLM-log row (a + // non-streamed chat answer); the stream, embeddings and rerank rows carry + // a request only — the positive control is explicit per route. + check := func(t *testing.T, rig *chatRig, store *recStore, loggedAnswer bool) { t.Helper() rows := rig.rows.all() if len(rows) != 2 { @@ -767,6 +775,10 @@ func TestRecordedLLMLogRowCarriesNoBodies(t *testing.T) { t.Fatalf("the unrecorded row carries no request under body_logging=full (handed %d bytes, sensitivity %q) — the test does not reach the body policy", len(rows[0].Request), off.RequiredSensitivity) } + if (off.ResponseContent != "") != loggedAnswer { + t.Fatalf("the unrecorded row's answer: %d bytes, want an answer %v for this route — the positive control does not hold", + len(off.ResponseContent), loggedAnswer) + } if on.RequestSystem != "" || on.RequestUser != "" || on.ResponseContent != "" { t.Errorf("the recorded llmlog row carries bodies (request %d, response %d bytes) — want none, the recording holds them", len(on.RequestUser), len(on.ResponseContent)) @@ -787,7 +799,7 @@ func TestRecordedLLMLogRowCarriesNoBodies(t *testing.T) { t.Fatalf("switch %v: %d %s", on, a.status, a.body) } } - check(t, rig, store) + check(t, rig, store, true) }) t.Run("stream", func(t *testing.T) { u := newUpstream(t, "") @@ -802,7 +814,7 @@ func TestRecordedLLMLogRowCarriesNoBodies(t *testing.T) { t.Fatalf("switch %v: stream %d %q", on, a.status, a.raw) } } - check(t, rig, store) + check(t, rig, store, false) }) t.Run("embeddings", func(t *testing.T) { e := newEmbedEngine(t, 8) @@ -819,7 +831,7 @@ func TestRecordedLLMLogRowCarriesNoBodies(t *testing.T) { t.Fatalf("switch %v: %d %s", on, a.status, a.body) } } - check(t, rig, store) + check(t, rig, store, false) }) t.Run("rerank", func(t *testing.T) { e := newRerankEngine(t) @@ -832,7 +844,7 @@ func TestRecordedLLMLogRowCarriesNoBodies(t *testing.T) { t.Fatalf("switch %v: %d %s", on, a.status, a.body) } } - check(t, rig, store) + check(t, rig, store, false) }) } From f002ea0a61748eb344e9c9564b4f3f27c3ee690e Mon Sep 17 00:00:00 2001 From: Jan-Stefan Janetzky Date: Fri, 27 Nov 2026 09:49:56 +0100 Subject: [PATCH 27/27] docs(gateway): recorded is a process count a deleted row does not lower, and security.md names the one case a superseding refusal cannot be written MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - docs/operations.md: GET /api/status's recording counts are this process's since `since`, in its memory; a row deleted by hand does not lower `recorded`, so it equals the table's rows only while none was deleted (the status counter's comment says the same). - docs/security.md: the promise that a withheld answer's row holds the refusal now names its one exception, as operations.md does — when the superseding write fails too, the row keeps the answer and its 200, the request counts as unfinished and its ERROR line names the recording. Co-Authored-By: Claude Opus 5.5 --- docs/operations.md | 2 +- docs/security.md | 2 +- go/internal/oai/record.go | 9 +++++---- 3 files changed, 7 insertions(+), 6 deletions(-) diff --git a/docs/operations.md b/docs/operations.md index b73c8a4e9..c6ce23488 100644 --- a/docs/operations.md +++ b/docs/operations.md @@ -988,7 +988,7 @@ ctx manage model-consumer-update '' '{"id":"","record_bodies":true, **Held before served.** The route commits the row — the whole request, state `open` — before the first backend attempt and before any queue wait; a request whose row cannot be committed is answered `503 recording_unavailable` (`Retry-After: 1`, `x-should-retry: true`) and no backend sees it: the database refuses the insert, or it does not answer within **5 s** (a fixed statement deadline), or the recording's memory account or its statement slots (below) have no room within `dispatch.external_max_wait` (20 s). The `503` reaches the client at once; the gateway then tries once more to leave the request's row (up to another 5 s, the client does not wait for it). A non-streamed answer is committed with the outcome before its first byte is written; if that fails, the client gets the same `503` instead of the answer (the backend ran: the meter books its usage; the client's retry is a second row). An answer that is not a `2xx` is held from the client until the row holds it with its bytes; if that row cannot be written once the request reached its walk, the client gets the `503` in its place, and the row is written with that `503` — a refusal before the walk (no backend asked) goes out as it is; when the key of a request that reached its walk is revoked between that commit and the write, the client gets `401 invalid_api_key` instead of the held answer, and that refusal supersedes the row. A request that stops being served while its answer is being committed — its key revoked or its consumer deactivated, the model API switched off, the alias gone, the shutdown, each seen also when the request's deadline passed during the commit — gets the refusal it would have got before the commit (`401 invalid_api_key` for a revoked key); one whose deadline alone passed during the commit (the commit is not cut by it) gets `503 recording_unavailable`; none of them gets the answer, and the row's outcome becomes that refusal; so does a `503` whose answer commit failed although it went through (its acknowledgement lost): the row never claims an answer the client did not get. A stream relays a line only after the recording kept it in memory; its lines are committed when it ends — what a stream sent cannot be taken back, so a stream whose end cannot be committed leaves its row `open` with its request and is counted in `stream_answers_unrecorded`. A request the gateway refuses after the door accepted the key — a body that does not parse, an unknown model, a limit, a body over `gateway.max_request_bytes` (never read: the row holds its declared size), an unknown path, a wrong method — gets its row at its end, `done`, with what was read of the body. Refusals before the door (`401`, a wrong key) are not the consumer's and leave nothing. A process that dies between the hold and the outcome leaves the row `open`: its request is there, its outcome is not known. -**Checking that nothing is missing.** `GET /api/status` (server-admin) carries `gateway.recording`: `process_id` and `since` (this process's start), `held_bytes` (the memory account's fill), and per recording consumer `admitted` (requests that passed the door as it), `in_flight`, `recorded` (requests whose row is in the table), `unrecordable` (requests for which no row could be written at all — an inference request is then refused with `recording_unavailable`, never served; see the model list below), `unfinished` (requests whose final outcome could not be written: their row stayed `open` — or, for an answer committed and then withheld as above whose superseding outcome could not be written either, it keeps that answer and its `200`; the `ERROR` line below says `answer_withheld=true` and names the `recording_id`) and `stream_answers_unrecorded` (the streams among them that had sent lines). `admitted = in_flight + recorded + unrecordable` holds at every moment, and `recorded` equals the table's rows of that consumer and process: +**Checking that nothing is missing.** `GET /api/status` (server-admin) carries `gateway.recording`: `process_id` and `since` (this process's start), `held_bytes` (the memory account's fill), and per recording consumer `admitted` (requests that passed the door as it), `in_flight`, `recorded` (requests whose row is in the table), `unrecordable` (requests for which no row could be written at all — an inference request is then refused with `recording_unavailable`, never served; see the model list below), `unfinished` (requests whose final outcome could not be written: their row stayed `open` — or, for an answer committed and then withheld as above whose superseding outcome could not be written either, it keeps that answer and its `200`; the `ERROR` line below says `answer_withheld=true` and names the `recording_id`) and `stream_answers_unrecorded` (the streams among them that had sent lines). `admitted = in_flight + recorded + unrecordable` holds at every moment. The counts are this process's since `since`, kept in its memory — a row deleted from the table does not lower `recorded` —, so `recorded` equals the table's rows of that consumer and process as long as none of them was deleted by hand (see Size below): ```sql SELECT count(*) AS rows, diff --git a/docs/security.md b/docs/security.md index e4e23c2aa..e304e9eca 100644 --- a/docs/security.md +++ b/docs/security.md @@ -167,7 +167,7 @@ Every refusal carries `x-should-retry: false`: the same request against the same What the gateway writes about a request, and what it never writes (design 06 §4.6): - **One body policy.** `gateway.body_logging` is the only switch for prompt and answer bodies of gateway rows in `context_llm_log` — of every consumer, a recording one (next point) included — global-only, so no tenant can raise it for itself. `none` (default) stores none; `errors` stores the serialized request and the answer on rows with an error only; `full` on every row, each capped at 64 KiB. Every row is then slimmed as for a tenant without developer mode: a credentials-class row stays sealed under every policy, whatever the tenant's `tenant.devmode` says — and so does a row whose sensitivity is empty or unknown (fail-closed, logged as a wiring defect). Embedded NUL bytes and invalid UTF-8 are cleaned before the write, so a crafted body cannot make the row — and its attribution — vanish. -- **The one exception: a recording consumer (migration 197, issue #571).** A model consumer with `record_bodies` on has every request it sends through the gateway held in `context_llm_recordings` — chat (a stream included), embeddings, rerank, and every request the gateway refuses after the door accepted its key: the body **as the gateway read it, byte for byte** (whatever `gateway.body_logging`, the alias, the consumer's `prompt_sensitivity`, the body scan or `Ctx-Sensitivity` say — no cut, no credentials seal), the answer the client got (a non-streamed chat or rerank answer; a stream's relayed lines; the error body of every answer that is not a `2xx`, a backend's relayed rejection included; no embedding vectors), the status and the gateway's code. **Such a row can carry credentials in clear text** — a password or key a client puts into a prompt is stored as sent. Only a server-admin can switch it on (also with self-service, and only with `confirm_record_bodies: true`); switching it off is open to the consumer's tenant-admin; both are audited. **No ctx surface reads the table's bodies:** no REST, MCP, CLI or web route, no export, no pipeline (distill, dream, digest) — `TestRecordingsReadersCensus` fails on any production statement that names the table outside its writer and the retention janitor; a server operator reads them in the database ([operations — Recording a consumer](operations.md#recording-a-consumer)). The consumer's `context_llm_log` rows carry **no bodies under any `gateway.body_logging` value** — the recording is the one place of its request and answer, so no reader of the LLM log (its list, detail and export) has them — and are marked `metadata.gw.recorded` with the `recording_id`; their other columns are those of every consumer's. **Held before served:** the request is committed to the table before the first backend attempt; a request that cannot be held — the database refuses it or does not answer within 5 s, or the recording's memory account has no room within the request's wait budget — is answered `503 recording_unavailable` (`x-should-retry: true`, `Retry-After: 1`) and reaches no backend; a non-streamed answer the table does not take is that `503` instead of the answer, and a request that stops being served while its answer is committed (a key revoked, a consumer deactivated) — or whose deadline passes during the commit — gets the refusal, never the answer (an error answer held for its row likewise, when the key is revoked before it goes out) — its row then holds that refusal. **What the switch does not change:** the required sensitivity, the chain and its egress rule, the body scan and its `413`, the limits, the in-flight budget's bookings and the answer are the same with and without it — the one new refusal is `recording_unavailable`, and every database write of the recording is in the request's time; deactivating and reactivating the consumer (the switch stays as it was); every other consumer (no stage, no write, no wait — their requests pass the recording stage untouched); the retention — the bodies are NULLed after `scheduler.llmlog_retention_days` (90) like every body; and a database backup (`backup.sh`), which carries them like every other content of the database. +- **The one exception: a recording consumer (migration 197, issue #571).** A model consumer with `record_bodies` on has every request it sends through the gateway held in `context_llm_recordings` — chat (a stream included), embeddings, rerank, and every request the gateway refuses after the door accepted its key: the body **as the gateway read it, byte for byte** (whatever `gateway.body_logging`, the alias, the consumer's `prompt_sensitivity`, the body scan or `Ctx-Sensitivity` say — no cut, no credentials seal), the answer the client got (a non-streamed chat or rerank answer; a stream's relayed lines; the error body of every answer that is not a `2xx`, a backend's relayed rejection included; no embedding vectors), the status and the gateway's code. **Such a row can carry credentials in clear text** — a password or key a client puts into a prompt is stored as sent. Only a server-admin can switch it on (also with self-service, and only with `confirm_record_bodies: true`); switching it off is open to the consumer's tenant-admin; both are audited. **No ctx surface reads the table's bodies:** no REST, MCP, CLI or web route, no export, no pipeline (distill, dream, digest) — `TestRecordingsReadersCensus` fails on any production statement that names the table outside its writer and the retention janitor; a server operator reads them in the database ([operations — Recording a consumer](operations.md#recording-a-consumer)). The consumer's `context_llm_log` rows carry **no bodies under any `gateway.body_logging` value** — the recording is the one place of its request and answer, so no reader of the LLM log (its list, detail and export) has them — and are marked `metadata.gw.recorded` with the `recording_id`; their other columns are those of every consumer's. **Held before served:** the request is committed to the table before the first backend attempt; a request that cannot be held — the database refuses it or does not answer within 5 s, or the recording's memory account has no room within the request's wait budget — is answered `503 recording_unavailable` (`x-should-retry: true`, `Retry-After: 1`) and reaches no backend; a non-streamed answer the table does not take is that `503` instead of the answer, and a request that stops being served while its answer is committed (a key revoked, a consumer deactivated) — or whose deadline passes during the commit — gets the refusal, never the answer (an error answer held for its row likewise, when the key is revoked before it goes out) — its row then holds that refusal. One case is left: when the answer's commit went through and the write of the superseding refusal fails as well, the row keeps the answer and its `200`, so a row's `200` alone does not prove the client got the answer; such a request counts as `unfinished` and its `ERROR` line names the recording ([operations — Recording a consumer](operations.md#recording-a-consumer)). **What the switch does not change:** the required sensitivity, the chain and its egress rule, the body scan and its `413`, the limits, the in-flight budget's bookings and the answer are the same with and without it — the one new refusal is `recording_unavailable`, and every database write of the recording is in the request's time; deactivating and reactivating the consumer (the switch stays as it was); every other consumer (no stage, no write, no wait — their requests pass the recording stage untouched); the retention — the bodies are NULLed after `scheduler.llmlog_retention_days` (90) like every body; and a database backup (`backup.sh`), which carries them like every other content of the database. - **Error redaction.** The `error` column of a gateway row holds only class, status and ctx code. The upstream response body (which can echo prompt fragments, and which tenant-admins would read in the LLM log list) never reaches it; class and code must have the shape of vocabulary words (lower snake case, at most 64 characters), anything else is stored as `[redacted]`; the writer takes the code from the gateway's own code vocabulary, never from the upstream answer. - **One identity.** A gateway row is attributed to the consumer (`consumer_id`); a knowledge key id that reached the row anyway is cleared with an ERROR line, and the database refuses any row carrying both. The model key id is kept in `metadata.gw.model_key_id` for key-leak forensics, never as a column. - **Access log.** A successful request is one `gateway request` line with ids, op, alias, status, token counts and timings (`gateway.access_log`, default on) — no consumer label, no content, never a key, its hint or a query string. Refusals are counted per (consumer, reason — a code of the gateway or door vocabulary, else `http_`) and logged as one `gateway rejections` WARN line per minute with the count, so a flood of `401`/`429` answers cannot rotate the error and security lines out of the 50 MB × 3 container log. The global request log stays silent for these requests. diff --git a/go/internal/oai/record.go b/go/internal/oai/record.go index 81b0fa943..029db8b22 100644 --- a/go/internal/oai/record.go +++ b/go/internal/oai/record.go @@ -1005,10 +1005,11 @@ func (s *recordingStats) done(c *recordingConsumerStats, row, unfinished, stream // (gateway.recording.consumers). type RecordingConsumer struct { ConsumerID string `json:"consumer_id"` - // Admitted requests passed the door as this consumer; each is in - // flight, recorded (its row is in context_llm_recordings) or - // unrecordable (no row could be written: an inference request was - // refused, not served; a model list may have been answered). + // Admitted requests passed the door as this consumer since Since; each + // is in flight, recorded (its row was written to context_llm_recordings + // — a count in this process's memory, which a deleted row does not + // lower) or unrecordable (no row could be written: an inference request + // was refused, not served; a model list may have been answered). Admitted int64 `json:"admitted"` InFlight int64 `json:"in_flight"` Recorded int64 `json:"recorded"`