Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 20 additions & 0 deletions promptbook/prompts.json
Original file line number Diff line number Diff line change
Expand Up @@ -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"
}
]
}
Loading
Loading