diff --git a/promptbook/prompts.json b/promptbook/prompts.json index 7ff1daf..0ad018a 100644 --- a/promptbook/prompts.json +++ b/promptbook/prompts.json @@ -1122,6 +1122,26 @@ ], "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" + }, + { + "id": "harden-rag-ingestion-pipeline", + "title": "Harden a RAG Ingestion Pipeline and Index Lifecycle", + "whenToUse": "Fix a RAG index that quotes deleted or superseded documents, leaks content after a permission change, or needs downtime to change embedding models — chunk identity and manifest, cursor-after-success sync, chunk-set replacement, tombstones and erasure through every cache, reconciliation, per-chunk ACL filters that fail closed, one embedding version per index, scripted alias-based blue/green re-index, freshness metrics, and lifecycle tests.", + "tools": [ + "copilot", + "claude-code", + "codex" + ], + "tags": [ + "llm", + "rag", + "ingestion", + "vector-search", + "data-platform", + "access-control" + ], + "formatNotes": "All three. Point the tool at the connectors, chunker, embedding client, index client and schema, the retrieval query builder, scheduler config, and the test folder. Copilot: rag-ingestion path instructions plus those files in agent mode (or save the prompt as `.github/prompts/harden-rag-ingestion-pipeline.prompt.md`). Claude Code: the rag-ingestion-index-lifecycle-guardrails skill plus the connector and index files. Codex: the AGENTS.md RAG ingestion section, then the diff. Leave retrieval quality metrics, query-time injection defences, redaction rules, cache internals, and pricing to their own skills.", + "body": "Task: Make the RAG ingestion pipeline and search index I specify a faithful, permission-correct copy of its sources. Updated documents must leave no stale chunks, deleted or erased documents must disappear from retrieval and every cache, permission changes must reach the index quickly, and an embedding model or chunking change must ship as a reversible blue/green re-index. Finish with a minimal diff, config, and tests.\n\nContext placeholders (fill from the repo or ask only if missing):\n- Pipeline and module: {{APP_NAME}} at {{APP_PATH}}\n- Stack: {{STACK}} (Spring Boot version; Spring AI | LangChain4j | Spring Batch | Spark/Databricks job | custom workers)\n- Sources: {{SOURCES}} (SharePoint, Confluence, Git, blob storage, database, ticketing) and each one's change feed, delete detection, and ACL model\n- Index store: {{STORE}} (Azure AI Search | pgvector | OpenSearch/Elasticsearch | Qdrant | other) and whether it supports aliases and filtered vector search\n- Embedding model: {{EMBEDDING_MODEL}} (name, version, dimensions) and any planned change\n- Identity: {{IDENTITY}} (Entra ID or other; where user and group object IDs come from at ingestion and at query time)\n- Data rules: {{DATA_RULES}} (classification, retention, residency, erasure requirements)\n- Answer caches: {{CACHES}} (exact or semantic caches that store answers citing this index, or \"none\")\n- Observability: {{OBSERVABILITY}} (Micrometer | OpenTelemetry | both) and the cost ledger for embedding spend\n- Retrieval eval: {{EVAL}} (existing golden set and CI job, or \"none\")\n\nRequirements:\n\n1. Inventory\n - Table: source | change feed or polling | delete detection | ACL source and format | index or alias name | embedding model and dims | chunker version | upsert-only? | cursor saved after success? | freshness today\n - Flag upsert-only writes, missing delete paths, ACLs not stored on chunks, hard-coded index names, mixed embedding versions, and cursors saved before writes\n\n2. Identity and manifest\n - Stable document ID from the source system; deterministic chunk IDs (doc ID + sequence or position hash)\n - Chunk fields: doc ID, source, source URI, content version, ACL version, chunker version, embedding model and version, dims, ingested and source-modified times, classification, principal IDs\n - A manifest table per document: current content and ACL versions, emitted chunk IDs, last success, last error\n\n3. Sync loop\n - Change feed or modified-since polling per source; cursor stored with the batch outcome and advanced only after index writes succeed\n - Classify changes: content (re-chunk, re-embed changed chunks), ACL only (metadata update), delete (tombstone). ACL and delete events take a fast path\n - Hash-skip unchanged documents and chunks; cache embeddings by chunk hash and model version\n - Replace chunk sets: write the new set, then delete that document's chunks not in it\n - Idempotent, order-safe workers: an older version never overwrites a newer one, and nothing recreates a tombstoned document\n - Batch calls, back off on 429/503, check per-item status on bulk responses, dead-letter by doc ID without content\n\n4. Deletes and erasure\n - Tombstone first; retrieval excludes tombstoned IDs at once; physical cleanup follows\n - Cleanup reaches chunks, vectors, keyword entries, staging and extracted text, embedding cache, answer caches in {{CACHES}}, eval fixtures, and backups per {{DATA_RULES}}\n - Configure the connector's own delete detection where it needs it (soft-delete flag or deletion policy)\n - Scheduled reconciliation: source IDs vs manifest vs index; remove orphans, re-queue version mismatches\n\n5. Permissions\n - Principal IDs (user, group, tenant) on every chunk as filterable fields\n - One query-filter builder that takes the caller's authenticated identity and applies the filter inside the vector or hybrid query, never after top-k\n - ACL changes update all chunks of the document and invalidate caches keyed by the old scope\n - Missing or unreadable ACL means not retrievable (fail closed). Document the group-resolution cache window and nested-group handling\n - Tenant filter mandatory on every query; separate index per tenant where {{DATA_RULES}} require it\n\n6. Embedding versioning and blue/green re-index\n - One embedding model version and dimension per index, recorded on the index or in a registry; the query embedder reads it from there and fails startup on mismatch\n - Applications read and write through an alias (or a config-switched table for pgvector); no index names in app code\n - Script: create new index, backfill from source or manifest text, dual-write changes, deletes, and ACL updates during backfill, verify counts per source, zero chunks without ACLs, tombstones absent, and {{EVAL}} passing, switch the alias in one call (respect documented propagation delay), keep the old index read-only for a rollback window, then retire it\n - pgvector: `CREATE INDEX CONCURRENTLY` and a validity check before switching\n - Answer caches partitioned by index or embedding version, or purged on switch\n\n7. Ingestion-time safety\n - Redact secrets and sensitive personal data before chunking and embedding (reuse the existing redaction hook)\n - Provenance and source trust level on each chunk; allow-listed sources only; instruction-like content flagged for review\n - Connectors use managed or workload identity with read-only scopes\n\n8. Freshness and metrics ({{OBSERVABILITY}})\n - SLOs per source for content, ACL, and delete visibility\n - `rag_ingest_documents_total` (`source`, `action`), `rag_ingest_lag_seconds` (`source`, `change_type`), `rag_index_chunks` (`index`, `source`), `rag_reconcile_drift_total` (`source`, `kind`), `rag_embedding_tokens_total` (`source`, `embedding_model`), `rag_ingest_cursor_age_seconds` (`source`)\n - Alerts on cursor age, ACL and delete lag over SLO, any `missing_acl` drift. No document text, titles, or user names in labels; logs carry IDs and versions\n\n9. Tests (synthetic corpus; Testcontainers for the store where possible)\n - Re-ingest is idempotent; shrinking a document leaves exactly the new chunk count\n - Delete hides immediately and cleans up later; a late update does not resurrect it; out-of-order versions resolve correctly\n - Revoked principal sees nothing, granted principal sees the document, chunk without ACL never returns\n - Failed write leaves the cursor unchanged\n - Query-model vs index-model mismatch fails startup or health check\n - Blue/green run on a fixture corpus switches, passes checks, and rolls back\n - Erasure leaves zero chunks, vectors, cache entries, and staging files\n\n10. Verification\n - Updated inventory table, drift found by the first reconciliation run, freshness per source before and after, and the re-index runbook\n\nConstraints:\n- Minimal diff. Reuse the existing store client, scheduler, messaging, and metrics registry; no new ingestion framework.\n- Do not weaken an ACL filter, skip a tombstone, or delete a test to make CI pass.\n- Never copy real customer documents into fixtures.\n- Leave retrieval quality metrics, query-time prompt-injection defences, redaction rules, cache internals, and pricing 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. Identity, manifest, and sync loop diff\n3. Delete, erasure, reconciliation, and ACL diff\n4. Alias, embedding version check, and blue/green re-index script\n5. Metrics, alerts, and the tests added with what each asserts\n\nStart from {{APP_PATH}}. Fix deletes, ACLs, and orphan chunks first, then the cursor and reconciliation, then the alias and re-index path.\n" } ] } diff --git a/skillbook/skills.json b/skillbook/skills.json index 36296b5..b7522b7 100644 --- a/skillbook/skills.json +++ b/skillbook/skills.json @@ -1120,6 +1120,26 @@ ], "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" + }, + { + "id": "rag-ingestion-index-lifecycle-guardrails", + "title": "RAG Ingestion and Index Lifecycle Guardrails", + "whenToUse": "Building or reviewing a RAG ingestion pipeline or vector/hybrid index (Azure AI Search, pgvector, OpenSearch, Qdrant) — stable document and chunk IDs with a per-document manifest, change-feed sync that saves cursors only after writes succeed, replacing chunk sets instead of upsert-only, tombstones and deletes that reach every derived copy and cache, reconciliation, ACL principals on every chunk with fail-closed query filters and a fast path for permission changes, one embedding model version per index, alias-based blue/green re-indexing with dual writes and rollback, freshness SLOs, and lifecycle tests.", + "tools": [ + "copilot", + "claude-code", + "codex" + ], + "tags": [ + "llm", + "rag", + "ingestion", + "vector-search", + "data-platform", + "access-control" + ], + "formatNotes": "All three. Copilot: path-scoped `.github/instructions/rag-ingestion.instructions.md` with applyTo for `**/ingest/**`, `**/indexer/**`, `**/rag/**`, `**/search/**`, and `**/db/migration/**`. Optional on-demand procedure at `.github/skills/rag-ingestion-index-lifecycle-guardrails/SKILL.md`. Claude Code: `.claude/skills/rag-ingestion-index-lifecycle-guardrails/SKILL.md` plus a CLAUDE.md fact that the index is queried through an alias bound to one embedding model version, every chunk carries versions and ACL principals, and deletes go through tombstones. Codex: a short \"RAG ingestion\" brief in root `AGENTS.md` (connector and manifest location, alias name, re-index script, ingestion test command); the procedure can live in `.agents/skills/rag-ingestion-index-lifecycle-guardrails/SKILL.md`. Pair with rag-retrieval-eval-guardrails for the eval that gates an alias switch, llm-app-prompt-injection-guardrails for treating retrieved text as untrusted, llm-pii-redaction-guardrails for redaction before embedding, llm-gateway-caching-guardrails for answer-cache invalidation, llm-cost-latency-budget-guardrails for pricing embedding tokens, and transactional-outbox-guardrails for reliable change events. This skill owns document and chunk identity, the sync loop, deletes, ACL propagation, embedding versioning, blue/green re-indexing, freshness, and reconciliation.", + "body": "# Skill: RAG Ingestion and Index Lifecycle Guardrails\n\n## Goal\n\nA RAG pipeline in a Java/Spring Boot or data-platform stack keeps its search index an honest copy of the source systems: every answer cites content that still exists, that the caller may still read, and that was embedded with the same model the query uses. Updates, deletions, permission changes, and model upgrades reach the index on a measured clock, and none of them depends on someone remembering to run a script.\n\nMost RAG incidents in production are not retrieval-quality problems. They are lifecycle problems:\n\n1. **Orphans.** A document shrank from 12 chunks to 8, the pipeline upserted 8, and 4 stale chunks still answer questions.\n2. **Ghosts.** A document was deleted or erased at the source, but its chunks, vectors, and cached answers live on.\n3. **Stale permissions.** The text did not change, so nothing was re-indexed, but a group was removed from the document's ACL last week.\n4. **Mixed vector spaces.** Half the index was re-embedded with a new model, or queries use a different model than the index.\n5. **Silent drift.** A connector cursor moved forward after a failed batch, and nobody noticed the gap.\n\nRetrieval quality, golden sets, and recall metrics stay in **rag-retrieval-eval-guardrails**. Query-time handling of retrieved text as untrusted input stays in **llm-app-prompt-injection-guardrails**. What gets redacted before embedding stays in **llm-pii-redaction-guardrails**. Semantic cache invalidation mechanics stay in **llm-gateway-caching-guardrails**. Embedding spend and price tables stay in **llm-cost-latency-budget-guardrails**. Change-event delivery basics stay in **transactional-outbox-guardrails** and **spring-kafka-consumer-reliability-guardrails** / **azure-service-bus-consumer-reliability-guardrails**. This skill owns document and chunk identity, the sync loop, deletes and tombstones, ACL propagation, embedding versioning, blue/green re-indexing, freshness, and reconciliation.\n\n## When to apply\n\n- Building or reviewing an ingestion pipeline that feeds Azure AI Search, pgvector, Elasticsearch/OpenSearch, Qdrant, or another vector or hybrid index from SharePoint, Confluence, Git, a database, blob storage, or a ticketing system\n- Changing the embedding model, its version or dimensions, the chunking strategy, or the index schema\n- A user or auditor reports that the assistant quotes a deleted or superseded document, or shows content a user should not see\n- Adding a data-erasure or retention requirement that must reach the index\n- A review finds upsert-only writes, no delete path, ACLs stored only at document level outside the index, or index names hard-coded in application config\n\n## Identity: documents, chunks, versions\n\n- **Stable document ID** from the source system (`source` + source-native ID), never from file path or title alone. Renames and moves keep the ID.\n- **Deterministic chunk IDs**: `doc_id` + chunk sequence (or a hash of the chunk's position and content). The same input always yields the same IDs, so re-runs are idempotent.\n- On every chunk store: `doc_id`, `source`, `source_uri`, `content_version` (source etag, revision, or content hash), `acl_version`, `chunker_version`, `embedding_model` and version, `embedding_dim`, `ingested_at`, `source_modified_at`, and data classification.\n- Keep a **manifest** per document outside the index (a table is fine): current content version, ACL version, the set of chunk IDs it emitted, last success time, last error. The manifest is the source of truth for what the index should contain.\n\n## The sync loop\n\n- Prefer change feeds (CDC, webhooks, delta queries, change tracking) over full crawls; fall back to modified-since polling where that is all the source offers.\n- **Advance the cursor only after the writes it covers succeeded.** A cursor saved before the index write is how gaps happen. Store the cursor and the batch outcome together.\n- Classify every change: **content** (re-parse, re-chunk, re-embed changed chunks), **permissions only** (metadata update, no re-embedding), **delete** (tombstone, then remove). Permission and delete events take a fast path that skips the parse and embed queue.\n- **Skip unchanged work by hash.** Compare the content hash before parsing, and the chunk hash before embedding. Identical text is never embedded twice; cache embeddings by `(chunk_hash, embedding_model_version)`.\n- **Replace, do not just upsert.** On a content change, write the new chunk set, then delete every chunk of that `doc_id` that is not in the new set (or swap the whole set where the store supports it). Upsert-only leaves orphans.\n- Idempotent workers: a replayed event produces the same index state. Out-of-order events are resolved by `content_version` or source modified time; an older version never overwrites a newer one, and nothing recreates a tombstoned document.\n- Rate limits and partial failures: batch embedding and index calls, back off on 429/503, check per-document status on bulk responses (some stores return mixed results with a 2xx), and send repeated failures to a dead-letter list with the document ID, not the content.\n\n## Deletes, tombstones, and erasure\n\n- A source delete writes a **tombstone** (doc ID, deletion version, time, reason) before any cleanup. Queries exclude tombstoned doc IDs immediately; physical deletion of chunks and vectors follows.\n- Deletion reaches every derived copy: chunks, vectors, keyword index entries, extracted-text and blob staging, embedding cache, semantic and exact answer caches that cited the document, eval fixtures built from it, and index backups or snapshots per the retention policy.\n- Some indexers and connectors do not see source deletions on their own (for example, they need a soft-delete flag or a deletion-detection policy configured from the first run). Check the connector's docs; do not assume.\n- Erasure requests (user or tenant) are a test case, not a hope: after the run, a query for the erased content returns nothing and the manifest shows zero chunks.\n- Run a periodic **reconciliation**: list source IDs, compare with the manifest and the index, delete chunks whose source no longer exists, re-queue documents whose version differs. Reconciliation is the safety net for missed events.\n\n## Permissions (ACL) propagation\n\n- Resolve each document's readers at ingestion into principal IDs (user and group object IDs, tenant ID) and store them on **every chunk** as filterable fields. Use IDs, not display names or emails.\n- At query time, the retrieval call applies a mandatory filter built from the caller's authenticated identity, inside the vector or hybrid query (pre-filter or filtered ANN), not by dropping results after top-k. The filter-building code lives in one place and is covered by tests.\n- Track `acl_version` separately from `content_version`. A permission change triggers a metadata-only update for all chunks of that document and invalidates caches keyed by the old scope.\n- **Fail closed.** A chunk with missing or unparseable ACL fields is not retrievable. A source whose ACL cannot be read is not indexed, or is indexed into an admin-only partition.\n- Large group memberships: resolve the caller's groups from the identity provider with a short cache, and cap or flatten nested groups deliberately; document the staleness window.\n- Multi-tenant: tenant ID is a mandatory filter on every query at minimum; prefer a separate index or collection per tenant where the blast radius or data rules demand it.\n\n## Embedding and index versioning\n\n- Vectors from different embedding models (or different versions or dimensions of one model) live in different spaces. **One index, one embedding model version.** The query is embedded with that same model, read from the index's own metadata or the alias config, not from a separate setting that can drift.\n- Record the model name, version, and dimensions on the index (or in an index registry table) and on each chunk.\n- Changes that force a rebuild: embedding model or dimensions, chunking strategy, analyzer or field type changes, vector algorithm settings that the store cannot change in place. Treat each as a migration.\n\n## Blue/green re-indexing\n\n1. Applications query and write through an **alias** (Azure AI Search index alias, Elasticsearch/OpenSearch alias, Qdrant collection alias) or, for pgvector, a config-switched table or column. Index names never appear in application code.\n2. Create the new index (`docs_v7`) beside the live one (`docs_v6`) with the new schema or model.\n3. Backfill from the source or from the manifest's stored chunk text (not from the old index's vectors). While backfilling, **dual-write** new changes, deletes, and ACL updates to both indexes, or replay the change log from the backfill start point.\n4. Verify: document and chunk counts per source match the manifest, no chunk lacks ACL fields, tombstoned IDs are absent, and the retrieval eval in **rag-retrieval-eval-guardrails** passes on the new index.\n5. Switch the alias in one call. Respect any propagation delay the store documents before deleting or writing only to the old index.\n6. Keep the old index read-only for a rollback window, then delete it and its secrets, snapshots, and caches. Rollback is an alias switch back, so keep dual writes until the window closes.\n7. Invalidate answer caches partitioned by the old index or embedding version (or let the version change the cache partition).\n\nFor pgvector, build the new HNSW or IVFFlat index with `CREATE INDEX CONCURRENTLY` so writes are not blocked, and check that the index is valid before switching.\n\n## Freshness and observability\n\n- Freshness SLOs per source, measured end to end from the source change time to \"visible in retrieval\": content, permissions (tighter), and deletes (tightest).\n- Metrics:\n - `rag_ingest_documents_total`: labels `source`, `action` (`added`, `updated`, `acl_updated`, `deleted`, `skipped_unchanged`, `failed`)\n - `rag_ingest_lag_seconds` histogram: labels `source`, `change_type` (`content`, `acl`, `delete`)\n - `rag_index_chunks` gauge: labels `index`, `source`\n - `rag_reconcile_drift_total`: labels `source`, `kind` (`orphan_chunk`, `missing_doc`, `version_mismatch`, `missing_acl`)\n - `rag_embedding_tokens_total`: labels `source`, `embedding_model` (priced by the cost ledger, not here)\n - `rag_ingest_cursor_age_seconds`: labels `source`\n- Alert on cursor age, delete and ACL lag over SLO, non-zero `missing_acl`, and drift above a small threshold. No document text, titles, or user names in metric labels; logs carry doc IDs and versions, not content.\n\n## Ingestion-time safety\n\n- Redact secrets and sensitive personal data before chunking and embedding, per **llm-pii-redaction-guardrails**. Text that reached the index and the embedding provider is hard to recall.\n- Record source trust level and provenance (`source`, `source_uri`, author or system of record) on each chunk so query-time code can label retrieved text as untrusted data and cite it.\n- Ingestion is a write path into prompts. Only allow-listed sources and locations are crawled; a new source needs review. Flag documents with instruction-like content for review rather than silently dropping them; query-time defences stay in **llm-app-prompt-injection-guardrails**.\n- Connector credentials use managed or workload identity with read-only scopes per source.\n\n## Tests and CI\n\n- **Idempotency:** ingesting the same batch twice yields identical chunk IDs and counts.\n- **Shrink:** a document that goes from N to M < N chunks leaves exactly M chunks.\n- **Delete:** a deleted document is absent from retrieval immediately (tombstone) and physically after cleanup; a late update event does not recreate it.\n- **Out of order:** an older version arriving after a newer one does not overwrite it.\n- **ACL:** a revoked principal cannot retrieve any chunk after the ACL update, a newly granted one can, and a chunk with missing ACL fields is never returned.\n- **Cursor:** a failed index write leaves the cursor unchanged and the batch is retried.\n- **Embedding mismatch:** startup or a health check fails if the query embedding model differs from the index's recorded model or dimensions.\n- **Re-index:** a scripted blue/green run on a small fixture corpus switches the alias, passes count and ACL checks, and rolls back cleanly.\n- **Erasure:** the erasure job leaves zero chunks, vectors, cache entries, and staging files for the subject.\n- Use a small synthetic corpus and a local store (Testcontainers for PostgreSQL with pgvector, OpenSearch, or Qdrant). No real customer documents in fixtures.\n\n## Workflow\n\n1. Inventory: source | change feed type | delete detection | ACL source | index and alias | embedding model and dims | chunker version | freshness today.\n2. Add stable document and chunk IDs, chunk metadata, and the manifest.\n3. Fix the sync loop: cursor after success, replace instead of upsert, hash-skip, idempotent workers.\n4. Add tombstones, delete propagation to every derived copy, and reconciliation.\n5. Store ACLs per chunk, enforce the query filter in one place, add the fast path for ACL changes, and fail closed.\n6. Put an alias in front of the index, record the embedding version, and script the blue/green re-index.\n7. Add freshness metrics, alerts, and the tests above.\n\n## Tool-specific notes\n\n- **GitHub Copilot:** path-scoped `.github/instructions/rag-ingestion.instructions.md` with `applyTo` for `**/ingest/**`, `**/indexer/**`, `**/rag/**`, `**/search/**`, and `**/db/migration/**`. Put \"replace, never upsert-only\", \"cursor after success\", and \"ACL on every chunk, fail closed\" at the top. Optional procedure at `.github/skills/rag-ingestion-index-lifecycle-guardrails/SKILL.md`.\n- **Claude Code:** `.claude/skills/rag-ingestion-index-lifecycle-guardrails/SKILL.md` holds the procedure. Add one `CLAUDE.md` fact: \"The RAG index is queried through an alias with one embedding model version; every chunk carries doc ID, versions, and ACL principals; deletes go through tombstones.\"\n- **Codex:** root `AGENTS.md` gets a short brief: where connectors and the manifest live, the alias name, the re-index script, and the ingestion test command. The procedure can live in `.agents/skills/rag-ingestion-index-lifecycle-guardrails/SKILL.md`.\n\n## Anti-patterns\n\n- Upsert-only ingestion with no delete of chunks that disappeared\n- Cursor or checkpoint saved before the index write succeeded\n- Deletions handled only by a full rebuild \"every so often\"\n- ACLs checked in application code after top-k, or stored only on the document outside the index\n- Missing ACL treated as public\n- Mixing two embedding models or dimensions in one index, or a query model configured separately from the index\n- Index names hard-coded in application config, so a rebuild means downtime\n- Re-embedding from vectors or extracted text of unknown version instead of the source or manifest\n- Answer caches that survive a delete, an ACL change, or an index switch\n- Real customer documents in test fixtures, or document text in metric labels\n\n## Done when\n\n- [ ] Every chunk carries doc ID, source URI, content and ACL versions, chunker and embedding versions, and principal IDs\n- [ ] A manifest records the chunk set per document; ingestion replaces chunk sets and leaves no orphans\n- [ ] Cursors advance only after successful writes; workers are idempotent and order-safe\n- [ ] Deletes and erasure use tombstones and reach chunks, vectors, staging, embedding cache, answer caches, and fixtures; reconciliation runs on a schedule\n- [ ] ACL changes take a fast path, retrieval filters by principals inside the query, and missing ACLs fail closed\n- [ ] The index is accessed through an alias with one recorded embedding model version, and the query uses that model\n- [ ] Blue/green re-index is scripted with dual writes, count and ACL checks, the retrieval eval, an alias switch, and a rollback window\n- [ ] Freshness SLOs, lag and drift metrics, and alerts exist; the lifecycle tests run in CI\n\n## Copy-ready SKILL.md stub\n\n```markdown\n---\nname: rag-ingestion-index-lifecycle-guardrails\ndescription: Use when building or reviewing a RAG ingestion pipeline or vector/hybrid index (Azure AI Search, pgvector, OpenSearch, Qdrant) fed from document or data sources. Covers stable document and chunk IDs, a per-document manifest, change-feed sync with cursors saved only after success, replacing chunk sets instead of upsert-only, tombstones and delete propagation to every derived copy including caches, reconciliation, ACL principals on every chunk with fail-closed query filters and a fast path for permission changes, one embedding model version per index, alias-based blue/green re-indexing with dual writes and rollback, freshness metrics, and lifecycle tests.\n---\n\nFollow RAG Ingestion and Index Lifecycle Guardrails: give every document a stable source ID and every chunk a deterministic ID plus content, ACL, chunker, and embedding versions and principal IDs. Keep a manifest of each document's chunk set. Sync from change feeds and advance cursors only after writes succeed; replace chunk sets so no orphans remain, and skip unchanged text by hash. Tombstone deletes first, then remove chunks, vectors, staging files, embedding cache entries, and answer caches, and reconcile against the source on a schedule. Filter retrieval by the caller's principals inside the query, fast-path ACL changes, and fail closed on missing ACLs. Query through an alias bound to one embedding model version, re-index blue/green with dual writes, checks, the retrieval eval, and a rollback window, and measure content, ACL, and delete freshness.\n```\n" } ] }