diff --git a/promptbook/prompts.json b/promptbook/prompts.json index 97a3b7d..7ff1daf 100644 --- a/promptbook/prompts.json +++ b/promptbook/prompts.json @@ -1102,6 +1102,26 @@ ], "formatNotes": "All three. Point the tool at the model client, prompt templates, the gateway route config, the cache store client, and the eval fixtures. Copilot: llm-caching path instructions plus those files in agent mode (or save the prompt as `.github/prompts/add-llm-gateway-caching.prompt.md`). Claude Code: the llm-gateway-caching-guardrails skill plus the route config and key builder. Codex: the AGENTS.md LLM caching section, then the diff. Leave price tables, routing fallback, PII redaction, structured output validation, and eval gate wiring to their own skills.", "body": "Task: Add safe caching to the LLM routes I specify. Start with provider prompt caching, then an opt-in exact response cache, and add a semantic cache only on routes that qualify. No cache may serve one caller's answer to another, serve a stale answer after a model, prompt, or data change, or serve the answer to a different question. Finish with a minimal diff, config, and tests.\n\nContext placeholders (fill from the repo or ask only if missing):\n- Gateway or service and module: {{APP_NAME}} at {{APP_PATH}}\n- Stack: {{STACK}} (Spring Boot version; Spring AI | LangChain4j | plain HTTP client | API Management or proxy policy)\n- Providers and targets: {{PROVIDERS}} (Azure OpenAI, OpenAI, Anthropic, Amazon Bedrock, OpenRouter, other OpenAI-compatible) and how each turns on prompt caching\n- Routes: {{ROUTES}} (route → deterministic? → user-specific? → RAG? → wrong-answer cost)\n- Cache store: {{STORE}} (Redis or Azure Managed Redis with vector search, pgvector, Azure AI Search, other) and whether it reports similarity or distance\n- Embedding model for semantic lookups: {{EMBEDDING_MODEL}} (or \"none yet\")\n- Tenancy and auth scope: {{TENANCY}} (where tenant and permission scope come from in the authenticated context)\n- Data rules: {{DATA_RULES}} (classification, retention, residency, erasure requirements)\n- Observability: {{OBSERVABILITY}} (Micrometer | OpenTelemetry | both) and the cost ledger that prices tokens\n- Eval gate: {{EVAL_GATE}} (existing eval CI job and fixture path, or \"none\")\n\nRequirements:\n\n1. Inventory\n - Table: route | model | deterministic? | user-specific? | RAG (corpus version source)? | estimated repeat rate | wrong-answer cost | proposed tier (none | prompt cache | exact | semantic) | reason\n - Flag any existing cache whose key is the user message alone, any global semantic index, missing TTLs, and thresholds with no labeled data behind them\n\n2. Provider prompt caching\n - Reorder each prompt: system instructions, tool definitions, schemas, examples, and long reference text first; user message, retrieved chunks, timestamps, and IDs last\n - Make the static prefix byte-stable (deterministic key order for tool and schema JSON, stable tool order)\n - Turn on caching per target from capability config: automatic where the provider does it, explicit markers (for example `cache_control` or cache checkpoints) where required. Keep minimum lengths, lifetimes, and write premiums in config with a checked-on date and doc link\n - Mark only prefixes that repeat within the lifetime when writes cost extra\n - Record cached-read and cache-write token counts from every response and hand them to the cost ledger. Do not hard-code prices here\n\n3. Exact response cache (opt-in per route, default off)\n - Key: SHA-256 of a canonical serialization of tenant, auth scope (when the answer depends on it), route, resolved model and version (not an alias), prompt template version, tool definitions version, normalized redacted messages, generation parameters (temperature, top_p, max_tokens, response format and schema version, tool choice, seed), and corpus or index version plus retrieved chunk IDs for RAG. Prefix with a cache format version. No raw prompt in the key\n - Store only complete responses: normal stop reason, schema-valid where a schema applies, not refused, filtered, or truncated, no tool calls, no streaming partials\n - Store the redacted body, key fields as metadata, model, prompt version, created time, TTL, and originating request ID. Encrypt at rest per {{DATA_RULES}}. Every entry has a TTL; short for user-specific content\n - Skip routes whose answer depends on time or live data the key does not capture\n\n4. Semantic cache (only for routes the inventory marks semantic)\n - Hard partition on tenant, auth scope, route, resolved model, prompt and tool versions, schema version, embedding model and version, and corpus version. Similarity search runs only inside that partition, and the partition is re-verified on the returned entry\n - Embed the normalized, redacted question plus any context that changes the answer. Routes where unembedded context changes the answer are not eligible. Skip multi-turn requests past a configured message count\n - Requests carrying IDs, amounts, dates, or code skip the semantic tier\n - Build a labeled pair file per route from redacted real traffic: pairs that should share an answer and near-miss pairs that must not (different action words, negations, different IDs or amounts). Choose the threshold from the route's allowed false-hit rate. Write in config whether the store measures similarity (higher is closer) or distance (lower is closer)\n - Stricter threshold or no semantic tier for money, policy, eligibility, health, security, or account-specific answers\n - Timeouts on the embedding call and vector query; on timeout or error, call the model\n\n5. Invalidation and control\n - Version bumps (model, prompt, tools, schema, embedding model, corpus) change the key or partition, so old entries are unreachable and expire by TTL\n - Source tags on RAG entries; a data-change event invalidates tagged entries\n - Erasure: deleting a user or tenant removes every entry in that partition\n - Per-route, per-tier kill switch in config and a purge command for a partition\n\n6. Response semantics and security\n - `X-Cache: HIT-EXACT | HIT-SEMANTIC | MISS | BYPASS` and the entry's creation time on responses\n - Trusted internal callers may bypass. End users cannot force writes into shared partitions. Anonymous or untrusted traffic never writes to a shared partition\n - Hits still pass caller-dependent output checks (authorization on referenced records, redaction for the current audience)\n - Partition values come from the authenticated context, never from request fields\n - Hits are recorded with zero model tokens; semantic lookups record embedding cost\n\n7. Metrics and logs ({{OBSERVABILITY}})\n - `llm_cache_requests_total` labels: `route`, `tier`, `result` (`hit`, `miss`, `bypass`, `ineligible`, `error`)\n - `llm_cache_semantic_score` histogram per route\n - `llm_prompt_cache_tokens_total` labels: `route`, `provider`, `kind` (`read`, `write`)\n - `llm_cache_false_hit_total` labels: `route`, `tier`, fed by feedback, quick re-asks, or audit\n - Logs: request ID, route, tier, result, score, matched entry's request ID. No prompt or answer text, and no tenant names in labels\n\n8. Tests and CI ({{EVAL_GATE}})\n - Changing any key component produces a miss; the same request from two tenants or two auth scopes never shares an entry\n - Refused, truncated, filtered, schema-invalid, tool-call, and partial responses are never stored; ineligible routes never read or write\n - Near-miss pair file per semantic route runs in CI with the configured embedding model and threshold. Fail on any must-not-match hit or a false-hit rate above the route limit. Report into the existing eval gate; do not build a second one\n - Version bump makes old entries unreachable; erasure leaves zero entries\n - Cache store down or slow: requests still succeed through the model within the route deadline\n - Rendered prompt prefix is byte-identical across two requests with different user messages\n - Synthetic or redacted fixtures only\n\n9. Verification\n - Updated inventory table with the chosen tier per route\n - Key and partition field list, TTLs, thresholds with measure direction, and the labeled-set results per semantic route\n - Before and after: cached-token share, hit rate per tier, and p95 latency on misses\n\nConstraints:\n- Minimal diff. Reuse the existing Redis or vector store client and cache config style; no second cache library.\n- Caching is off by default for every route until config opts it in.\n- Do not lower a threshold, widen a partition, or skip an eligibility check to make a test pass.\n- Leave price tables, routing and fallback, PII redaction rules, structured output validation, retrieval quality, and eval gate wiring to their existing skills. Call their hooks where caching sits next to them.\n- Copilot, Claude Code, and Codex: concrete diffs, the inventory table, and a checklist. Do not paste this prompt into AGENTS.md.\n\nOutput format:\n1. Inventory table and the tier chosen per route\n2. Prompt reordering diff and prompt-cache config per target\n3. Exact cache diff (key builder, eligibility, storage, header)\n4. Semantic cache diff and labeled-set results, if any route qualifies\n5. Invalidation, kill switch, metrics, and tests added with what each asserts\n\nStart from {{APP_PATH}}. Ship prompt caching and the exact cache with their tests before turning on any semantic route.\n" + }, + { + "id": "harden-llm-streaming-responses", + "title": "Harden Streaming (SSE) Responses on LLM Routes", + "whenToUse": "Fix LLM streaming that buffers into one late burst, keeps billing after the user leaves, or hides failures as finished answers — event contract with terminal frames, before-first-byte checks and fallback, no retry after content, end-to-end cancellation, three deadlines plus heartbeats, ingress and compression settings, output-check modes, tool-call assembly, final or estimated usage, metrics, shutdown drain, and fake-upstream tests.", + "tools": [ + "copilot", + "claude-code", + "codex" + ], + "tags": [ + "llm", + "streaming", + "sse", + "gateway", + "spring-boot", + "cancellation" + ], + "formatNotes": "All three. Point the tool at the stream relay or chat controller, the model client, the streaming Ingress or edge config, application config, and the test folder. Copilot: llm-streaming path instructions plus those files in agent mode (or save the prompt as `.github/prompts/harden-llm-streaming-responses.prompt.md`). Claude Code: the llm-streaming-response-guardrails skill plus the relay and Ingress files. Codex: the AGENTS.md LLM streaming section, then the diff. Leave routing policy, price tables, redaction rules, schema validation, and caching to their own skills.", + "body": "Task: Make streaming (SSE) responses on the LLM routes I specify reliable and cheap. Callers must see tokens as they are generated, a client that leaves must stop the upstream model call, a failure must never look like a successful answer, and every stream must be accounted for in usage. Finish with a minimal diff, config, and tests.\n\nContext placeholders (fill from the repo or ask only if missing):\n- Gateway or service and module: {{APP_NAME}} at {{APP_PATH}}\n- Stack: {{STACK}} (Spring Boot version; WebFlux | Spring MVC with SseEmitter | Spring AI | LangChain4j | plain WebClient/HttpClient)\n- Providers and targets: {{PROVIDERS}} (Azure OpenAI, OpenAI, Anthropic, Amazon Bedrock, OpenRouter, other OpenAI-compatible) and each one's stream format and usage option\n- Streaming routes: {{ROUTES}} (route → client type → output checks needed → observed TTFT p99 → max duration)\n- Wire format to clients: {{WIRE_FORMAT}} (OpenAI-compatible chat chunks | provider-native | custom events)\n- Edge path: {{EDGE}} (ingress-nginx | Gateway API implementation | Application Gateway | API Management | mesh | CDN) and the manifest location\n- Output checks on streams: {{OUTPUT_CHECKS}} (PII redaction, policy filter, schema validation, none)\n- Observability and cost: {{OBSERVABILITY}} (Micrometer | OpenTelemetry | both) and the cost ledger that prices tokens\n\nRequirements:\n\n1. Inventory\n - Table: route | stack (WebFlux or MVC) | providers | forwards incrementally? | cancels upstream on disconnect? | terminal frame on every exit? | retries after first byte? | output-check mode | usage source\n - Flag any route that collects the whole upstream response before forwarding, drains the upstream after the client leaves, or closes without a finish reason or error frame\n\n2. Event contract\n - Headers: `Content-Type: text/event-stream`, `Cache-Control: no-cache`, `X-Accel-Buffering: no`, request ID header; no `Content-Length`, no compression\n - Order: content chunks, finish-reason chunk, usage chunk (empty `choices`), `data: [DONE]`\n - Every exit path (clean stop, upstream error, deadline, policy block, shutdown) ends with a finish reason or an in-band error frame such as `{\"error\":{\"type\":...,\"code\":...,\"message\":...,\"request_id\":...}}` followed by `[DONE]`. No stack traces, keys, or raw upstream bodies\n\n3. Before the first byte\n - Auth, authorization, budget check, validation, input redaction, and target selection run before any bytes are written\n - Wait for the first upstream chunk before committing the 200; upstream errors and connect timeouts here return a normal HTTP error and may use routing fallback\n - Race that wait against client disconnect; on disconnect cancel upstream and record `client_cancelled`\n - Per-route time-to-first-token deadline in config\n\n4. After the first byte\n - No retry and no fallback once content was sent; send an error frame and end\n - Client disconnects never count as provider failures and never trip circuit breakers\n\n5. Cancellation\n - Propagate cancellation from the inbound request to the upstream call. WebFlux: build the response `Flux` from the upstream body so cancel disposes the connection. MVC: `SseEmitter` `onCompletion`/`onTimeout`/`onError` cancel the upstream subscription, and a send `IOException` is a disconnect\n - Close the upstream connection, never drain it\n - Outcomes: `completed`, `client_cancelled`, `upstream_error`, `deadline_exceeded`, `policy_blocked`, `shutdown`\n\n6. Deadlines, heartbeats, buffers\n - Three timers per route in config: time to first token, inter-chunk idle, total stream. Choose values from observed data and write the source next to each value\n - SSE comment heartbeat (`: ping`) at an interval shorter than the smallest idle timeout on the path; heartbeats do not reset the inter-chunk idle timer\n - Bounded per-stream buffer; a slow reader that fills it gets an error frame. No full-text accumulation for logging\n\n7. Edge and server settings ({{EDGE}}, streaming paths only)\n - ingress-nginx: separate Ingress for streaming paths with `proxy-buffering: \"off\"` and `proxy-read-timeout` / `proxy-send-timeout` above the total stream deadline. Other edges: the equivalent buffering and timeout settings from their docs\n - Exclude `text/event-stream` from Spring and proxy compression\n - MVC: `spring.mvc.async.request-timeout` at least the total stream deadline. Note if a platform-thread pool limits concurrent streams\n\n8. Output checks on streams ({{OUTPUT_CHECKS}})\n - Declare per route: pass-through (audit on final text), windowed (hold back a trailing window at least as long as the longest redaction pattern), or buffered (release nothing until checks pass; heartbeats only)\n - Mid-stream policy block ends with a `policy_blocked` error frame\n - Routes that need schema-valid JSON do not stream raw partial JSON to clients that cannot handle it\n\n9. Tool calls\n - Assemble fragmented tool-call arguments per index; parse and validate only after the tool-call finish reason; never execute from a partial string\n\n10. Usage, metrics, logs ({{OBSERVABILITY}})\n - Request usage on streams where the provider makes it optional (for example `stream_options: {\"include_usage\": true}`)\n - Early end without a usage event: estimate output tokens from the text received with the ledger's tokenizer, mark `usage_source=estimated`, never record zero. Pass counts to the cost ledger; do not price here\n - Metrics: `llm_stream_requests_total` (`route`, `target`, `outcome`), `llm_stream_ttft_seconds`, `llm_stream_duration_seconds`, `llm_stream_inter_chunk_gap_seconds`, `llm_stream_active`, `llm_stream_tokens_after_cancel_total`\n - Logs: request ID, route, target, outcome, TTFT, duration, chunk count, tokens and source, early-end reason. No prompt or completion text\n\n11. Shutdown\n - On SIGTERM fail readiness, drain active streams up to a configured limit, then end the rest with a `shutdown` error frame and `[DONE]`. `terminationGracePeriodSeconds` covers preStop plus drain\n\n12. Tests (fake streaming upstream: WireMock, MockWebServer, or a Netty stub; no real provider calls)\n - Contract and headers; cancel mid-stream closes upstream within a bound; cancel before first token cancels upstream\n - Error before first byte returns an HTTP error and allows fallback; error after first byte sends an error frame and calls no second target\n - Idle stall hits `deadline_exceeded`; quiet upstream produces heartbeats\n - Early end records estimated usage; secret split across chunks is redacted in windowed mode\n - Fragmented tool-call arguments parse only after the finish reason; shutdown sends a `shutdown` frame\n - A smoke script against the deployed edge with a slow fake stream shows chunks arriving incrementally\n\nConstraints:\n- Minimal diff. Reuse the existing HTTP client, Reactor or MVC style, and metrics registry; no new streaming framework.\n- Do not change non-streaming routes or global ingress settings.\n- Do not lengthen a deadline, drop a terminal frame, or disable a test to make CI pass.\n- Leave routing and fallback policy, price tables, redaction rules, schema validation, caching, and eval gates to their existing skills; call their hooks.\n- Copilot, Claude Code, and Codex: concrete diffs, the inventory table, and a checklist. Do not paste this prompt into AGENTS.md.\n\nOutput format:\n1. Inventory table with the gaps found\n2. Stream relay diff (contract, terminal frames, before-first-byte logic, cancellation)\n3. Deadlines, heartbeat, buffer, and output-check mode config\n4. Edge, compression, and shutdown changes\n5. Usage and metrics changes, and the tests added with what each asserts\n\nStart from {{APP_PATH}}. Fix cancellation and terminal frames first, then deadlines and the edge, then usage and output checks.\n" } ] } diff --git a/skillbook/skills.json b/skillbook/skills.json index e67e943..36296b5 100644 --- a/skillbook/skills.json +++ b/skillbook/skills.json @@ -1100,6 +1100,26 @@ ], "formatNotes": "All three. Copilot: path-scoped `.github/instructions/llm-caching.instructions.md` with applyTo for `**/gateway/**`, `**/cache/**`, `**/llm/**`, and `**/prompts/**`. Optional on-demand procedure at `.github/skills/llm-gateway-caching-guardrails/SKILL.md`. Claude Code: `.claude/skills/llm-gateway-caching-guardrails/SKILL.md` plus a CLAUDE.md fact that response caching is opt-in per route and semantic lookups never cross tenant, scope, model, prompt, or corpus partitions. Codex: a short \"LLM caching\" brief in root `AGENTS.md` (cache config location, key builder class, eligible routes, near-miss test command) while the procedure stays in SKILL.md. Pair with llm-cost-latency-budget-guardrails for pricing cached tokens and hits, llm-gateway-routing-fallback-guardrails for capability flags, llm-pii-redaction-guardrails for what is stored and embedded, llm-structured-output-guardrails for validating a response before it may be cached, rag-retrieval-eval-guardrails for corpus versions, llm-eval-ci-regression-gate for the near-miss gate, and spring-boot-cache-redis-guardrails for plain Redis hygiene. This skill owns the cache tiers, keys, partitions, eligibility, thresholds, and invalidation.", "body": "# Skill: LLM Gateway Caching Guardrails\n\n## Goal\n\nAn LLM gateway or a Java/Spring Boot service reuses work it has already paid for without ever serving one caller's answer to another, serving a stale answer after the model, prompt, or data changed, or serving the answer to a different question that happened to sound similar.\n\nThis skill owns three caches and the rules that keep them honest:\n\n1. **Provider prompt caching** (prefix caching done by the provider). Cheap input tokens on repeated prefixes. No answer is reused.\n2. **Exact response cache** in the gateway. The same normalized request returns the stored response.\n3. **Semantic response cache** in the gateway. A request that is close enough in embedding space returns a stored response.\n\nThey carry very different risk. Roll them out in that order and stop at the level that pays for itself.\n\nToken budgets and price tables stay in **llm-cost-latency-budget-guardrails**; this skill only reports cache savings into them. Target selection, fallback, and capability flags stay in **llm-gateway-routing-fallback-guardrails**. Redaction before anything is stored or embedded stays in **llm-pii-redaction-guardrails**. Schema validation of a response before it may be cached stays in **llm-structured-output-guardrails**. Retrieval quality and corpus versions stay in **rag-retrieval-eval-guardrails**. The CI gate that reads the false-hit rate stays in **llm-eval-ci-regression-gate**. Plain Spring Cache and Redis hygiene (serializers, TTLs, eviction, key prefixes) stays in **spring-boot-cache-redis-guardrails**.\n\nA cache hit is the gateway answering on the model's behalf. Treat it with the same care as a model response.\n\n## When to apply\n\n- Adding prompt caching, a response cache, or a semantic cache to a gateway, Spring AI or LangChain4j app, or an API Management / proxy policy\n- Long, stable system prompts, tool lists, or reference documents sent on every request\n- FAQ-style or classification traffic with many repeated questions\n- A review that finds a cache key built from the user message alone, a single global semantic index, no TTL, or a similarity threshold copied from a blog post\n- Cost reports where cached tokens or cache hits are not visible\n\n## Level 1: provider prompt caching\n\nPrefix caching lowers input cost and time to first token on repeated prefixes. It never returns a stored answer, so it is the safe first step.\n\n- **Order the prompt for it.** Static content first: system instructions, tool definitions, schemas, few-shot examples, long reference text. Per-request content last: user message, retrieved chunks, timestamps, request IDs. One volatile line at the top (a date, a user name) breaks the prefix for everything after it.\n- **Keep the prefix byte-stable.** Deterministic JSON key order for tool and schema definitions, no reordered tool lists, no whitespace changes between releases. A prompt template change is a new prompt version and is expected to miss once.\n- **Turn it on per provider from capability config.** Some providers cache automatically above a minimum prefix length; others need explicit markers (for example Anthropic `cache_control` breakpoints, or Bedrock cache checkpoints). Minimum lengths, lifetimes, write premiums, and read discounts differ by provider and model and change often. Keep them in config with a \"checked on\" date and the doc link, not in code or comments.\n- **Write premiums are real.** Where a cache write costs more than a normal input token, only mark prefixes that repeat within the lifetime. A marker on a prompt that never repeats costs more, not less. Longer lifetimes cost more to write; pick them from measured reuse, not by default.\n- **Read the usage fields.** Record cached-read and cache-write token counts from every response (provider names differ, for example `cached_tokens`, `cache_read_input_tokens`, `cache_creation_input_tokens`) and pass them to the cost ledger in **llm-cost-latency-budget-guardrails**, which prices them. A prefix that should hit but reports zero cached tokens is a bug to investigate (volatile prefix, below the minimum, expired, or the router dropped the marker).\n- **Isolation.** Provider prompt caches are scoped by the provider (typically per organization or workspace). Check the provider's documented scope before routing several customers' traffic through one key, and use any per-customer cache key the provider offers for accounting.\n\n## Level 2: exact response cache\n\nReturn the stored response only when the request is the same request.\n\n**Cache key.** A SHA-256 over a canonical serialization of everything that changes the answer:\n\n- tenant, and the caller's authorization scope (role set, data-access groups, row filter version) when the answer depends on what the caller may see\n- route and target model (resolved deployment and version, not an alias)\n- prompt template ID and version, and tool definitions version\n- the full message list after redaction, normalized (Unicode NFC, trimmed whitespace) but not paraphrased\n- generation parameters that matter: `temperature`, `top_p`, `max_tokens`, response format and schema version, tool choice, seed\n- retrieval corpus or index version for RAG routes, plus the IDs of the retrieved chunks when retrieval runs before the lookup\n\nPrefix the stored key with a cache version (`llmc:v3:`) so a format change is a clean break. Never store the raw prompt in the key.\n\n**What may be cached:**\n\n- Only routes that opt in, in config, with a reason. Default is off.\n- Only successful, complete responses: normal stop reason, schema-valid where a schema applies, not refused, not filtered, not truncated.\n- Not responses that contain tool calls or that led to side effects. Not streaming partials.\n- Not responses whose answer depends on time, on live data the key does not capture, or on the individual user's history, unless the key carries that dependency.\n- Deterministic or near-deterministic routes (low temperature, classification, extraction). Creative routes gain little and surprise users when the \"random\" answer repeats.\n\n**Storage.** Store the redacted response body, the key fields as metadata (not the prompt), model, prompt version, created time, TTL, and the request ID that produced it. Encrypt at rest as the data classification requires. Every entry has a TTL. Keep it short for anything user-specific and longer only for generic content.\n\n## Level 3: semantic response cache\n\nA semantic cache answers a different request with a stored response because two embeddings were close. That is a correctness decision, not an optimization. Add it only after Level 2 is live and measured.\n\n**Hard partition first, similarity second.** The vector search runs only inside a partition that matches exactly on: tenant, authorization scope, route, target model and version, prompt template version, tool definitions version, embedding model and version, response schema version, and corpus or index version for RAG. Similarity never crosses those boundaries. Two users with different permissions do not share an entry even for the identical question.\n\n**What gets embedded.** The normalized, redacted user question, plus any context that changes the answer. If the system prompt, retrieved context, or conversation history changes the answer and is not in the embedding or the partition, the route is not eligible. Multi-turn conversations are usually not eligible past the first turn; cap by message count or skip.\n\n**Threshold.**\n\n- There is no universal number. It depends on the embedding model, the domain, the language, and the cost of a wrong answer. Published values from one setup do not transfer.\n- Know which direction your store measures. Some return a similarity (higher is closer), others a distance (lower is closer), and some policies call a distance a \"score\". Write the direction next to the value in config and test it with a known pair.\n- Build a labeled set of question pairs from real (redacted) traffic: pairs that should share an answer and near-miss pairs that must not (\"reset my password\" vs \"reset my API key\", \"cancel\" vs \"pause\", \"monthly\" vs \"annual\", negations, different IDs or amounts). Pick the threshold from the false-hit rate the route can tolerate, then check the hit rate.\n- Set a stricter threshold, or disable the semantic tier, for routes where a wrong answer is expensive: money, policy, eligibility, health, security, or anything with an account-specific value.\n- Requests carrying identifiers, amounts, dates, or code skip the semantic tier and go to Level 2 only. A one-character difference in an ID is a different question.\n\n**Guarded serve.** On a candidate hit, also check: entry not expired or invalidated, same partition (re-verify, do not trust the index filter alone), and the stored entry passed the same validation as a fresh response. Optionally run a cheap verifier (a small model or rules) on borderline scores, or use near hits only as a hint, never as the answer.\n\n**Latency.** Every semantic lookup pays for an embedding and a vector query. Put a timeout on both; on timeout or cache error, go to the model. Measure that the hit rate pays for the extra latency on misses.\n\n## Invalidation\n\n- **By version, not by hunting.** A new model version, prompt template, tool definition, schema, embedding model, or corpus version changes the partition or the key, so old entries are never read again and expire by TTL.\n- **By event.** When source data changes (a policy page, a product price, a document deleted), invalidate entries tagged with that source. Store source tags on RAG entries for this.\n- **By request.** A user deletion or data-erasure request removes every entry in that user's or tenant's partition. Test it.\n- **Kill switch.** One config flag per route and tier turns caching off without a deploy, and a purge command clears a partition.\n\n## Response semantics\n\n- Mark cached responses to the caller: a header such as `X-Cache: HIT-EXACT | HIT-SEMANTIC | MISS | BYPASS`, and the original creation time. Do not pretend a cached answer is fresh.\n- Honor a bypass from trusted callers (`Cache-Control: no-cache` from an internal client, or a per-route flag). Do not let an end user force a write into a shared partition.\n- A cache hit still goes through output guardrails that depend on the current caller (authorization re-check on referenced records, redaction for the current audience).\n- Usage and billing: a hit consumes no model tokens. Record it as a hit with zero model cost and the embedding cost for semantic lookups, so cost reports stay true.\n\n## Security\n\n- **Poisoning.** A shared partition can be poisoned by one caller who gets a bad or injected answer stored. Do not write to shared partitions from untrusted or anonymous traffic, store only responses that passed every output check, and prefer pre-seeded, reviewed entries for shared FAQ caches.\n- **Leakage.** No cross-tenant or cross-scope reads, ever. The partition key comes from the authenticated context, not from request fields.\n- **Data at rest.** The cache is a copy of prompts and answers. It follows the same retention, residency, and encryption rules as the conversation logs. Redact before embedding and before storing (**llm-pii-redaction-guardrails**).\n- **Timing.** Hit-vs-miss latency reveals whether someone asked a similar question. In a shared partition that is acceptable only for public content.\n\n## Metrics\n\n- `llm_cache_requests_total`: labels `route`, `tier` (`exact`, `semantic`), `result` (`hit`, `miss`, `bypass`, `ineligible`, `error`)\n- `llm_cache_semantic_score`: histogram of best candidate scores for hits and misses, per route\n- `llm_prompt_cache_tokens_total`: labels `route`, `provider`, `kind` (`read`, `write`)\n- `llm_cache_false_hit_total`: from user feedback, re-asks within a short window, or offline audit; labels `route`, `tier`\n- `llm_cache_saved_cost`: computed by the cost ledger, not here\n\nNo prompt text, answer text, or tenant name in labels. Log the request ID, route, tier, result, score, and the matched entry's request ID.\n\n## Tests and CI\n\n- **Key tests.** Changing each key component (tenant, scope, model, prompt version, schema version, temperature, corpus version) produces a miss. Identical requests from two tenants never share an entry.\n- **Eligibility.** Refused, truncated, filtered, schema-invalid, tool-call, and streaming-partial responses are never stored. Ineligible routes never read or write.\n- **Semantic near-miss set.** A labeled pair file per semantic route runs in CI against the chosen embedding model and threshold. The build fails when any must-not-match pair would hit, or when the false-hit rate on the labeled set exceeds the route's limit. Wire it into the existing eval gate in **llm-eval-ci-regression-gate**.\n- **Invalidation.** Bumping a prompt version or corpus version makes old entries unreachable; an erasure request leaves zero entries in the partition.\n- **Failure.** Cache store down or slow: requests succeed through the model within the route deadline.\n- **Prompt caching.** A fixture asserts that the rendered prompt's static prefix is byte-identical across two requests with different user messages.\n\n## Workflow\n\n1. Inventory routes: route | deterministic? | user-specific? | RAG? | repeat rate | wrong-answer cost | proposed tier.\n2. Reorder prompts for prefix caching and record cached tokens. Ship and measure.\n3. Add the exact cache to eligible routes with the full key, eligibility rules, TTLs, and the `X-Cache` header.\n4. Only for routes with high repeat rates and tolerable wrong-answer cost, build the labeled pair set, choose a threshold, and add the semantic tier with hard partitions.\n5. Add invalidation by version, source tag, and erasure, plus the kill switch.\n6. Add metrics and CI tests. Review false hits weekly for the first month after enabling a semantic route.\n\n## Tool-specific notes\n\n- **GitHub Copilot:** path-scoped `.github/instructions/llm-caching.instructions.md` with `applyTo` for `**/gateway/**`, `**/cache/**`, `**/llm/**`, and `**/prompts/**`. Put \"partition before similarity\", the eligibility list, and \"version bump invalidates\" at the top. Optional procedure in `.github/skills/llm-gateway-caching-guardrails/SKILL.md`.\n- **Claude Code:** `.claude/skills/llm-gateway-caching-guardrails/SKILL.md` holds the procedure. Add one `CLAUDE.md` fact: \"LLM response caching is opt-in per route. Keys include tenant, auth scope, model version, prompt version, and corpus version. Semantic cache never crosses those partitions.\"\n- **Codex:** root `AGENTS.md` gets a short brief: where cache config lives, the key builder class, eligible routes, and the near-miss test command. The procedure stays in `SKILL.md`.\n\n## Anti-patterns\n\n- A cache key built from the user message alone, or one global semantic index for all tenants\n- Similarity threshold copied from another system, or similarity and distance confused\n- Caching refused, truncated, filtered, schema-invalid, or tool-call responses\n- No TTL, or invalidation by \"flush everything\" only\n- Timestamps or request IDs at the top of the prompt, killing prefix caching\n- Cache markers on prompts that never repeat, paying write premiums for nothing\n- Semantic cache on account-specific, money, or policy answers\n- Shared partitions written by anonymous traffic\n- Raw prompts or answers in keys, labels, or logs\n- Cached answers served without telling the caller\n\n## Done when\n\n- [ ] Every route has a documented tier (none, prompt cache only, exact, semantic) and a reason\n- [ ] Prompts put static content first; cached-read and write tokens are recorded and priced by the cost ledger\n- [ ] Exact cache keys include tenant, auth scope, resolved model, prompt and tool versions, normalized redacted messages, generation parameters, and corpus version\n- [ ] Only complete, valid, non-tool, non-refused responses are stored, with a TTL and redacted content\n- [ ] Semantic lookups run inside exact-match partitions, with a per-route threshold chosen from a labeled near-miss set and the measure direction documented\n- [ ] Version bumps, source-tag events, and erasure requests invalidate entries; a kill switch exists per route and tier\n- [ ] Responses carry a cache status header; hits are recorded with zero model cost\n- [ ] Key, eligibility, near-miss, invalidation, and outage tests run in CI\n\n## Copy-ready SKILL.md stub\n\n```markdown\n---\nname: llm-gateway-caching-guardrails\ndescription: Use when adding or reviewing provider prompt caching, an exact response cache, or a semantic cache in an LLM gateway or Java/Spring service. Covers prompt ordering for prefix caching and recording cached tokens, cache keys that include tenant, auth scope, resolved model, prompt and tool versions, generation parameters and corpus version, which responses may be stored, hard partitions before any similarity search, per-route thresholds from a labeled near-miss set, invalidation by version, source tag and erasure, cache status headers, poisoning and leakage controls, metrics, and CI tests.\n---\n\nFollow LLM Gateway Caching Guardrails: roll out provider prompt caching first (static content first, record cached tokens), then an opt-in exact response cache, and a semantic cache only where repeat rate is high and a wrong answer is cheap. Keys and partitions include tenant, authorization scope, resolved model, prompt and tool versions, schema version, generation parameters, embedding model, and corpus version; similarity never crosses them. Store only complete, valid, non-tool, non-refused, redacted responses with a TTL. Choose each semantic threshold from a labeled near-miss set and document whether the store measures similarity or distance. Invalidate by version bump, source tag, and erasure request, keep a kill switch, mark hits to the caller, and test keys, eligibility, near misses, invalidation, and cache outages in CI.\n```\n" + }, + { + "id": "llm-streaming-response-guardrails", + "title": "LLM Streaming Response Guardrails", + "whenToUse": "Adding or reviewing streaming (SSE) responses in an LLM gateway or Java/Spring Boot service — an explicit event contract with a terminal frame on every exit, auth and target selection before the first byte, no retry after content is sent, upstream cancellation on client disconnect (including before the first token), time-to-first-token, idle and total deadlines with heartbeats, ingress buffering and compression off on streaming paths, windowed or buffered output checks, final or estimated usage, shutdown drain, and fake-upstream tests.", + "tools": [ + "copilot", + "claude-code", + "codex" + ], + "tags": [ + "llm", + "streaming", + "sse", + "gateway", + "spring-boot", + "cancellation" + ], + "formatNotes": "All three. Copilot: path-scoped `.github/instructions/llm-streaming.instructions.md` with applyTo for `**/gateway/**`, `**/stream/**`, `**/llm/**`, and `**/k8s/**`. Optional on-demand procedure at `.github/skills/llm-streaming-response-guardrails/SKILL.md`. Claude Code: `.claude/skills/llm-streaming-response-guardrails/SKILL.md` plus a CLAUDE.md fact that streams never retry after the first byte, always cancel upstream on disconnect, and always end with a finish or error frame plus [DONE]. Codex: a short \"LLM streaming\" brief in root `AGENTS.md` (stream relay location, fake-upstream test command, streaming Ingress file) while the procedure stays in SKILL.md. Pair with llm-gateway-routing-fallback-guardrails for fallback before the first byte, llm-cost-latency-budget-guardrails for pricing final or estimated usage, llm-pii-redaction-guardrails for windowed redaction rules, llm-structured-output-guardrails for JSON routes, and k8s-probes-graceful-shutdown-guardrails for pod drain basics. This skill owns the stream contract, cancellation, deadlines, buffering, mid-stream errors, and partial usage.", + "body": "# Skill: LLM Streaming Response Guardrails\n\n## Goal\n\nAn LLM gateway or Java/Spring Boot service streams tokens to callers over Server-Sent Events (SSE) without paying for tokens nobody reads, without turning a broken stream into a \"successful\" response, and without proxies silently buffering the stream into one late burst.\n\nStreaming changes four things compared with a plain request/response call:\n\n1. **The response starts before it is finished.** Status code and headers are sent with the first byte, so a failure after that point cannot become a 5xx. It must be an in-band error event.\n2. **The caller can leave at any time.** A closed tab or a dropped mobile connection must cancel the upstream model call, including while waiting for the first token.\n3. **Every hop can buffer or time out.** Ingress, load balancer, service mesh, compression filters, and the client library each have their own buffering and idle timeout.\n4. **Usage arrives last, if at all.** Token counts, finish reason, and cost are known only when the stream ends cleanly.\n\nRouting, fallback, and capability flags stay in **llm-gateway-routing-fallback-guardrails**. Token budgets and price tables stay in **llm-cost-latency-budget-guardrails**. Redaction rules stay in **llm-pii-redaction-guardrails**. Schema validation stays in **llm-structured-output-guardrails**. Response caches stay in **llm-gateway-caching-guardrails**. Pod shutdown basics stay in **k8s-probes-graceful-shutdown-guardrails**. This skill owns the stream itself: the event contract, cancellation, deadlines, heartbeats, buffering, mid-stream errors, partial usage, and tests.\n\n## When to apply\n\n- Adding `stream: true` support to a gateway route, a Spring AI / LangChain4j chat endpoint, or a proxy in front of Azure OpenAI, OpenAI, Anthropic, Amazon Bedrock, OpenRouter, or another OpenAI-compatible provider\n- Users report \"nothing for 30 seconds, then everything at once\", streams that die at a round number of seconds, or a stop button that does not stop billing\n- Cost reports show output tokens for requests the client abandoned\n- A review finds the gateway collects the whole stream before forwarding, or retries a stream after content was already sent\n\n## The event contract\n\nPick one wire format per route and document it. Normalizing every provider to the OpenAI-compatible chat chunk shape is common for gateways; translating is fine, inventing a new shape per provider is not.\n\n- `Content-Type: text/event-stream`, `Cache-Control: no-cache`, `X-Accel-Buffering: no`. No `Content-Length`. No gzip or br on the stream path.\n- Each event is `data: \\n\\n`. Optional `event:` names for error and heartbeat frames if the client library supports them.\n- Order: content chunks, then a chunk with `finish_reason`, then a usage chunk (empty `choices`), then the terminal `data: [DONE]`. Clients that use the OpenAI SDK skip empty-`choices` chunks safely; hand-written parsers must too.\n- **Every exit path ends the stream explicitly**: clean stop, upstream error, deadline, policy block, or gateway shutdown. A stream that closes without a finish reason or a terminal error frame is treated as incomplete by the gateway and by its clients.\n- An error after the first byte is an in-band frame, for example `data: {\"error\":{\"type\":\"upstream_error\",\"code\":\"stream_interrupted\",\"message\":\"...\",\"request_id\":\"...\"}}`, followed by `[DONE]`. No stack traces, provider keys, or raw upstream bodies in the message.\n- Put the request ID in a response header and in the error frame so a support ticket can find the trace.\n\n## Before the first byte\n\nEverything that can fail cleanly should fail before streaming starts, so the caller still gets a real HTTP status:\n\n- Authentication, authorization, token-budget check, request validation, input redaction, and target selection run first.\n- Open the upstream stream and wait for the provider's first event (or first content chunk) before committing the 200. A provider 4xx/5xx or connect timeout at this point is still a normal error response, and routing fallback may try the next target.\n- **Race that wait against client disconnect.** A long time to first token (reasoning models, long prompts) is exactly when callers give up. If the client leaves before the first chunk, cancel the upstream call and record the request as cancelled.\n- Apply a time-to-first-token deadline per route. On expiry, cancel upstream and fall back or fail with a normal status.\n\n## After the first byte: no retries, no fallback\n\nOnce content has reached the client, the gateway cannot transparently switch targets: the next model would repeat or contradict what the user already saw.\n\n- Do not retry or fail over a stream mid-response. Send an error frame and end the stream. Let the client decide whether to re-ask.\n- The only exception is a route that buffers on purpose (see \"Guarded streaming\") and has not yet released any content.\n- Mark the attempt as failed for circuit breakers only when the upstream failed. A client disconnect is not a provider failure and must never trip a breaker.\n\n## Cancellation\n\n- Pass cancellation from the inbound request to the upstream call end to end. In Spring WebFlux, return a `Flux>` built from the upstream `WebClient` body so subscriber cancellation disposes the upstream connection. With Spring MVC `SseEmitter`, register `onCompletion`, `onTimeout`, and `onError` callbacks that cancel the upstream subscription, and treat an `IOException` on send as a disconnect.\n- Close the upstream connection; do not drain it. Draining keeps the provider generating and billing.\n- Verify through every hop. Some ingress and mesh setups keep the upstream connection to the pod open after the browser leaves; a heartbeat write is often the first point where the server learns the client is gone. Test disconnect detection through the real ingress, not only locally.\n- Map outcomes clearly: `completed`, `client_cancelled` (log as 499-style, not an error), `upstream_error`, `deadline_exceeded`, `policy_blocked`, `shutdown`.\n\n## Deadlines and heartbeats\n\nThree separate timers, all in config per route:\n\n| Timer | Purpose | Typical starting point (tune from data) |\n|---|---|---|\n| Time to first token | Give up on a target that never starts | Based on the model's observed p99 TTFT |\n| Inter-chunk idle | Abort a stalled stream that never closes | Longer than the slowest normal gap between chunks |\n| Total stream | Hard cap on one response | From the route's `max_tokens` and observed output rate |\n\n- Send an SSE comment heartbeat (`: ping\\n\\n`) when no event has been written for an interval shorter than the **smallest** idle timeout on the path (ingress, load balancer, corporate proxies). Heartbeats keep the connection alive and surface disconnects; they do not reset the gateway's own inter-chunk idle timer, which watches upstream progress.\n- Keep every proxy's read timeout above the heartbeat interval and at least as long as the total stream deadline.\n\n## Buffering and infrastructure\n\n- **ingress-nginx:** on the streaming path set `nginx.ingress.kubernetes.io/proxy-buffering: \"off\"` and raise `proxy-read-timeout` and `proxy-send-timeout` above the total stream deadline. Keep the streaming path in its own Ingress object so these annotations do not leak to the rest of the host. Send `X-Accel-Buffering: no` from the app as a second line of defence.\n- **Gateway API, Application Gateway, API Management, service meshes, CDNs:** each has its own buffering and timeout knobs. Check the implementation's docs and test with a deliberately slow stream.\n- **Compression:** exclude `text/event-stream` from response compression filters (Spring `server.compression.mime-types` must not include it), and from any proxy gzip.\n- **Servlet stack:** an async request timeout (`spring.mvc.async.request-timeout`) shorter than the stream deadline will cut streams. Prefer WebFlux or virtual threads for many long-lived streams; a platform-thread-per-stream servlet pool runs out under load.\n- **Backpressure:** the gateway holds at most a small bounded buffer per stream. If the client reads too slowly and the buffer fills, end the stream with an error frame rather than growing memory. Never accumulate the full response text in memory just to log it.\n\n## Guarded streaming (output checks while streaming)\n\nOutput checks such as PII redaction, policy filters, and schema validation are harder on a stream because the text is released piece by piece.\n\n- Decide per route: **pass-through** (checks run on the final text for audit only), **windowed** (hold back a small trailing window so a pattern split across chunks can still be redacted before release), or **buffered** (no content released until checks pass; the stream only carries heartbeats until then).\n- Redaction that must never leak needs windowed or buffered mode. The window must be at least as long as the longest pattern the redactor matches.\n- Routes that need a schema-valid JSON result should not stream raw partial JSON to clients that cannot handle it; stream progress events, or buffer and validate per **llm-structured-output-guardrails**.\n- A policy block mid-stream ends the stream with a `policy_blocked` error frame. The client must drop or mark the partial text already shown.\n\n## Tool calls in streams\n\n- Tool-call arguments arrive as fragments across chunks. Assemble them per tool-call index and parse only after the finish reason is `tool_calls` (or the provider's equivalent).\n- Never execute a tool from a partial argument string. Validate the assembled arguments as untrusted input.\n\n## Usage, cost, and logs\n\n- Ask providers for usage on streams where it is optional (for example `stream_options: {\"include_usage\": true}` on OpenAI-compatible APIs) and read the final usage event.\n- When the stream ends early (client cancel, deadline, upstream error), usage may be missing. Record output tokens as **estimated** from the text actually received (with the tokenizer the cost ledger uses) and flag the entry `usage_source=estimated`. Never record zero just because the usage event did not arrive.\n- Hand the final or estimated counts to the cost ledger in **llm-cost-latency-budget-guardrails**; this skill does not price tokens.\n- Record per stream: request ID, route, target, outcome, time to first token, total duration, chunk count, output tokens and source, and the reason for any early end. No prompt or completion text in metrics or default logs.\n\n## Metrics\n\n- `llm_stream_requests_total`: labels `route`, `target`, `outcome` (`completed`, `client_cancelled`, `upstream_error`, `deadline_exceeded`, `policy_blocked`, `shutdown`)\n- `llm_stream_ttft_seconds` histogram: labels `route`, `target`\n- `llm_stream_duration_seconds` histogram: labels `route`, `outcome`\n- `llm_stream_inter_chunk_gap_seconds` histogram: labels `route`, `target`\n- `llm_stream_active` gauge per pod\n- `llm_stream_tokens_after_cancel_total`: output tokens the provider reported or the gateway received after the client left. Should trend to zero.\n\n## Shutdown and rollouts\n\n- On SIGTERM, stop accepting new streams (readiness fails), let active streams finish up to a drain limit, then end the rest with a `shutdown` error frame and `[DONE]`. Never let the pod disappear mid-stream with a reset connection.\n- Set `terminationGracePeriodSeconds` above the drain limit plus the preStop delay. Clients should expect `shutdown` frames during deploys and re-ask.\n\n## Tests and CI\n\nUse a fake upstream (WireMock, MockWebServer, or a small Netty stub) that streams scripted chunks with controlled delays. No real provider calls in CI.\n\n- **Contract:** a normal stream yields content chunks, a finish reason, a usage event, then `[DONE]`; headers include `text/event-stream`, `no-cache`, `X-Accel-Buffering: no`, and no compression.\n- **Cancel mid-stream:** the client disconnects after N chunks; assert the fake upstream sees its connection closed within a bound and no further chunks are requested.\n- **Cancel before first token:** the fake upstream delays its first chunk; the client leaves; assert upstream cancellation and a `client_cancelled` outcome.\n- **Upstream error after first byte:** assert an in-band error frame and `[DONE]`, no retry, no second target called.\n- **Upstream error before first byte:** assert normal HTTP error status and that routing fallback is allowed.\n- **Idle stall:** upstream stops sending without closing; assert the inter-chunk deadline ends the stream with `deadline_exceeded`.\n- **Heartbeat:** a quiet upstream produces comment heartbeats at the configured interval.\n- **Missing usage:** stream ends early; assert an estimated usage entry is recorded, not zero.\n- **Windowed redaction:** a secret split across two chunks is redacted before release.\n- **Tool calls:** fragmented arguments are assembled and parsed only after the finish reason.\n- **Shutdown:** an active stream during shutdown ends with a `shutdown` frame.\n- A smoke test against the deployed ingress with a slow stream confirms chunks arrive incrementally (measure time between first and last received chunk).\n\n## Workflow\n\n1. Inventory streaming routes: route | client type | providers | output checks needed | TTFT p99 | max duration.\n2. Fix the event contract and headers, and make every exit path send a terminal frame.\n3. Wire cancellation end to end, including the time-to-first-token wait.\n4. Add the three deadlines, heartbeats, and bounded buffers.\n5. Fix ingress, proxy, and compression settings on the streaming path only.\n6. Choose pass-through, windowed, or buffered per route for output checks.\n7. Record final or estimated usage and the metrics above.\n8. Add the fake-upstream tests and the ingress smoke test.\n\n## Tool-specific notes\n\n- **GitHub Copilot:** path-scoped `.github/instructions/llm-streaming.instructions.md` with `applyTo` for `**/gateway/**`, `**/stream/**`, `**/llm/**`, and `**/k8s/**`. Put \"no retry after first byte\", \"cancel upstream on disconnect\", and \"every exit path ends with a terminal frame\" at the top. Optional procedure at `.github/skills/llm-streaming-response-guardrails/SKILL.md`.\n- **Claude Code:** `.claude/skills/llm-streaming-response-guardrails/SKILL.md` holds the procedure. Add one `CLAUDE.md` fact: \"Streams never retry after the first byte, always cancel upstream on client disconnect, and always end with a finish or error frame plus [DONE].\"\n- **Codex:** root `AGENTS.md` gets a short brief: where the stream relay lives, the fake-upstream test command, and the ingress file for streaming paths. The procedure stays in `SKILL.md`.\n\n## Anti-patterns\n\n- Collecting the whole upstream response before forwarding, or logging the full text by keeping it in memory\n- Draining the upstream after the client left, or no cancellation during the time-to-first-token wait\n- Retrying or failing over after content was sent\n- A broken stream that just closes, so clients and cost reports treat it as success\n- Default ingress buffering and a 60-second read timeout on a streaming path\n- gzip on `text/event-stream`\n- Recording zero output tokens when the usage event never arrived\n- Client disconnects counted as provider failures that open circuit breakers\n- Executing tool calls from partial argument fragments\n- Pods killed mid-stream during rollouts with no shutdown frame\n\n## Done when\n\n- [ ] Each streaming route has a documented event contract, and every exit path ends with a finish reason or error frame plus `[DONE]`\n- [ ] Auth, budget, validation, and target selection finish before the first byte; upstream errors before the first byte return a real HTTP status\n- [ ] No retry or fallback after the first byte\n- [ ] Client disconnect cancels the upstream call mid-stream and before the first token, verified through the real ingress\n- [ ] Time-to-first-token, inter-chunk idle, and total deadlines plus heartbeats are configured per route\n- [ ] Buffering and compression are off and timeouts raised on streaming paths only\n- [ ] Output checks run in a declared mode (pass-through, windowed, or buffered) per route\n- [ ] Final or estimated usage is recorded for every stream; stream metrics exist with no prompt text in labels\n- [ ] Fake-upstream tests cover contract, cancel, errors, stall, heartbeat, missing usage, redaction window, tool calls, and shutdown\n\n## Copy-ready SKILL.md stub\n\n```markdown\n---\nname: llm-streaming-response-guardrails\ndescription: Use when adding or reviewing streaming (SSE) responses in an LLM gateway or Java/Spring service. Covers the event contract and terminal frames, doing auth, budget and target selection before the first byte, no retry or fallback after content is sent, cancelling the upstream call on client disconnect including before the first token, time-to-first-token, idle and total deadlines with heartbeats, ingress and compression settings, bounded buffers, windowed or buffered output checks, tool-call fragment assembly, final or estimated usage, stream metrics, shutdown drain, and fake-upstream tests.\n---\n\nFollow LLM Streaming Response Guardrails: finish auth, budget, validation, and target selection before the first byte, and wait for the first upstream chunk while watching for client disconnect. After the first byte never retry or fail over; end failures with an in-band error frame and [DONE]. Cancel the upstream call whenever the client leaves and close it instead of draining. Configure time-to-first-token, inter-chunk idle, and total deadlines plus SSE heartbeats shorter than the smallest proxy idle timeout. Turn off buffering and compression and raise timeouts on streaming paths only. Pick pass-through, windowed, or buffered output checks per route, assemble tool-call arguments before parsing, record final or estimated usage for every stream, drain streams on shutdown, and test it all against a fake streaming upstream.\n```\n" } ] }