diff --git a/promptbook/prompts.json b/promptbook/prompts.json index 0ad018a..497dc9f 100644 --- a/promptbook/prompts.json +++ b/promptbook/prompts.json @@ -1142,6 +1142,26 @@ ], "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" + }, + { + "id": "add-llm-tracing-and-genai-metrics", + "title": "Add LLM Tracing and GenAI Metrics Without Leaking Prompts", + "whenToUse": "Wire or fix OpenTelemetry for an LLM service or gateway — inventory of spans and leaks, per-attempt CLIENT spans for retries and fallbacks, tool and agent spans, GenAI attributes and metrics from a pinned conventions version, content capture off by default with redacted opt-in, provider usage instead of estimates, bounded metric labels, W3C propagation across streaming and async, Collector tail sampling and attribute backstop, and in-memory exporter tests.", + "tools": [ + "copilot", + "claude-code", + "codex" + ], + "tags": [ + "llm", + "observability", + "opentelemetry", + "tracing", + "spring-boot", + "privacy" + ], + "formatNotes": "All three. Point the tool at the provider clients, routing and retry code, streaming handler, Observation or tracer config, logback config, Collector config, and the test folder. Copilot: llm-tracing path instructions plus those files in agent mode (or save the prompt as `.github/prompts/add-llm-tracing-and-genai-metrics.prompt.md`). Claude Code: the llm-tracing-observability-guardrails skill plus those files. Codex: the AGENTS.md LLM tracing section, then the diff. Leave budgets, Collector cluster setup, redaction rules, streaming deadlines, and eval scoring to their own skills.", + "body": "Task: Add or fix OpenTelemetry tracing and metrics for the LLM service or gateway I specify so that one inbound request produces one readable trace with model attempts, retrieval, tools, and guardrail checks, using the GenAI semantic conventions, with no prompt or completion text in telemetry by default. Finish with a minimal diff, config, and tests.\n\nContext placeholders (fill from the repo or ask only if missing):\n- Service: {{APP_NAME}} at {{APP_PATH}}\n- Stack: {{STACK}} (Spring Boot version; Spring AI | LangChain4j | hand-rolled HTTP clients; WebFlux or MVC; virtual threads?)\n- Instrumentation today: {{INSTRUMENTATION}} (OpenTelemetry Java agent | Micrometer Tracing with OTel bridge | vendor SDK | none)\n- Providers and routes: {{PROVIDERS}} (Azure OpenAI, OpenAI-compatible routers, Bedrock, others; retry and fallback logic location)\n- Backend: {{BACKEND}} (OTel Collector then Datadog | Azure Monitor | Tempo/Grafana | other)\n- Conventions version: {{SEMCONV_VERSION}} (pin one; note the instrumentation library's GenAI stability setting if it has one)\n- Data rules: {{DATA_RULES}} (what may never leave the service; telemetry retention; redaction hook to reuse)\n- Async paths: {{ASYNC}} (streaming/SSE, reactive, @Async, queues)\n\nRequirements:\n\n1. Inventory\n - Table: operation (inbound endpoint, chat, embeddings, retrieval, tool, agent loop, guardrail) | span today? | parent correct? | attributes today | content captured? | metrics today | labels | propagation across async?\n - Flag new traces per upstream call, missing retry/fallback attempts, prompts or completions in spans or logs, user/conversation IDs as metric labels, estimated usage where the provider returned real usage, and vendor-specific names where GenAI names exist\n\n2. Span tree\n - SERVER span for the inbound request; CLIENT span per model attempt named `{operation} {model}`; retrieval span; `execute_tool {tool}` INTERNAL spans; `invoke_agent {agent}` around agent loops; INTERNAL spans or events for guardrail checks\n - Attempt number and routing or fallback reason on each attempt span; span status ERROR with `error.type` only for real failures; refusals recorded as finish reasons\n\n3. Attributes\n - GenAI attributes from {{SEMCONV_VERSION}}: operation name, provider name, request and response model, request parameters actually sent, response ID, finish reasons, input and output token usage from the provider usage block, tool name and call ID, agent name, conversation ID (span only), server address and port\n - All GenAI names in one constants class; gateway-specific facts (route, tenant, deployment, cache hit, budget decision, fallback reason) under `llm.gateway.*`\n - Mark estimated usage explicitly when a stream ends without a usage block\n\n4. Content capture\n - Off by default for input and output messages, system instructions, tool definitions, tool arguments and results, and retrieved text, in spans, events, and logs\n - Disable framework prompt and completion logging and HTTP wire logging; record shape instead (message count, token counts, chunk IDs and scores)\n - Optional opt-in: named flag per environment or tenant, time-boxed, passed through the existing redaction hook, preferably exported to a separate store referenced by ID\n\n5. Metrics\n - GenAI token usage histogram with token type, and the duration histograms the pinned version defines (per-operation in newer versions); time to first token and time per output token for streaming\n - Labels limited to operation, provider, request and response model, route, outcome or `error.type`, token type; bounded tenant only if small\n - If using Micrometer Observation, map exported names to the conventions with an observation convention class\n\n6. Propagation\n - W3C trace context continued from the caller and sent to providers; preserved across {{ASYNC}}; injected into message headers for queues\n - Baggage restricted to non-sensitive low-cardinality keys; untrusted inbound baggage stripped before provider calls\n - `trace_id` and `span_id` in log MDC\n\n7. Sampling and export\n - SDK head sampling plus Collector tail sampling keeping errors, fallbacks, guardrail blocks, and requests above the latency SLO\n - OTLP to the Collector; Collector attribute-delete processor for content keys as a backstop; resource attributes for service name, version, environment, namespace, and pod\n - Exporter failure never fails a request; bounded queue with a dropped-spans counter\n\n8. Tests\n - In-memory span exporter with a stubbed provider: span tree per request including retry and fallback attempts; required attributes; no content, keys, or Authorization headers anywhere; opt-in path emits redacted content only when enabled; inbound traceparent continued and outbound carries it; context survives streaming and async paths; forbidden metric labels absent\n - A test that pins the attribute names in the constants class\n\n9. Verification\n - One example trace (attribute keys only, no content) before and after, the updated inventory table, and the dashboard or monitor queries that need renaming\n\nConstraints:\n- Minimal diff. Reuse the existing tracer, Observation registry, and Collector; no new vendor SDK.\n- Do not loosen redaction or delete tests to make CI pass. Do not put real prompts or customer data in fixtures.\n- Leave budgets and price tables, Collector cluster setup, log formatting, redaction rules, streaming deadlines, and eval scoring 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. Span tree and attribute diff (constants class included)\n3. Content capture settings and redaction hook wiring\n4. Metrics, propagation, sampling, and Collector config diff\n5. Tests added and what each asserts\n\nStart from {{APP_PATH}}. Remove content leaks first, then fix trace continuity and per-attempt spans, then names, metrics, and sampling.\n" } ] } diff --git a/skillbook/skills.json b/skillbook/skills.json index b7522b7..165691b 100644 --- a/skillbook/skills.json +++ b/skillbook/skills.json @@ -1140,6 +1140,26 @@ ], "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" + }, + { + "id": "llm-tracing-observability-guardrails", + "title": "LLM Tracing and Observability Guardrails", + "whenToUse": "Adding or reviewing OpenTelemetry tracing in an LLM gateway, RAG service, agent runtime, or MCP tool server on Java/Spring Boot — one trace per inbound request with a CLIENT span per model attempt so retries and fallbacks show, execute_tool and invoke_agent spans, GenAI semantic convention attributes and metrics from a pinned version kept in one constants class, prompt and completion capture off by default with redacted time-boxed opt-in, provider-reported token usage, low-cardinality labels, W3C propagation across async and streaming paths, tail sampling for errors and fallbacks, and telemetry tests.", + "tools": [ + "copilot", + "claude-code", + "codex" + ], + "tags": [ + "llm", + "observability", + "opentelemetry", + "tracing", + "spring-boot", + "privacy" + ], + "formatNotes": "All three. Copilot: path-scoped `.github/instructions/llm-tracing.instructions.md` with applyTo for `**/gateway/**`, `**/llm/**`, `**/ai/**`, `**/observability/**`, and `**/otel-collector*.yaml`. Optional on-demand procedure at `.github/skills/llm-tracing-observability-guardrails/SKILL.md`. Claude Code: `.claude/skills/llm-tracing-observability-guardrails/SKILL.md` plus a CLAUDE.md fact that GenAI attribute names live in one constants class and prompt or completion text never goes into telemetry by default. Codex: a short \"LLM tracing\" brief in root `AGENTS.md` (constants class path, Collector config path, telemetry test command); the procedure can live in `.agents/skills/llm-tracing-observability-guardrails/SKILL.md`. Pair with otel-aks-observability for the Collector on AKS, llm-cost-latency-budget-guardrails for budgets and prices, llm-pii-redaction-guardrails for the redaction hook used by opt-in capture, llm-streaming-response-guardrails for first-token timing, llm-gateway-routing-fallback-guardrails for attempt and fallback semantics, and spring-boot-structured-logging-guardrails for trace IDs in logs. This skill owns the span tree, GenAI names, content capture policy, propagation, sampling, and telemetry tests.", + "body": "# Skill: LLM Tracing and Observability Guardrails\n\n## Goal\n\nEvery LLM call, retrieval, tool call, and agent step in a Java/Spring Boot service or gateway shows up as one connected OpenTelemetry trace that an on-call engineer can read without seeing anyone's prompt. Spans and metrics use the OpenTelemetry GenAI semantic conventions, so Datadog, Azure Monitor, Grafana Tempo, or any OTLP backend understands them. Prompt and completion text stays out of telemetry unless a named, time-boxed, redacted opt-in turns it on.\n\nTypical failures this skill prevents:\n\n1. **Broken traces.** The gateway starts a new trace for each upstream call, so a slow answer cannot be tied to the request, the retrieval, or the retry that caused it.\n2. **Prompts in telemetry.** A framework logs full prompts and completions into span attributes or logs by default, and customer data now sits in a vendor backend with a different retention policy.\n3. **Cardinality blow-ups.** User IDs, conversation IDs, or prompt hashes used as metric labels.\n4. **Wrong numbers.** Token counts estimated when the provider returned usage, retries counted as separate user requests, streaming latency measured to the first byte of headers instead of the first token.\n5. **Silent renames.** GenAI conventions are still in Development status, attribute names change between versions, and dashboards quietly go empty after a library upgrade.\n\nToken budgets and price tables stay in **llm-cost-latency-budget-guardrails**. General AKS OpenTelemetry Collector setup stays in **otel-aks-observability**. Micrometer registry and Prometheus wiring stay in **spring-boot-micrometer-prometheus-guardrails**. Log format and MDC stay in **spring-boot-structured-logging-guardrails**. What counts as sensitive and how to redact it stays in **llm-pii-redaction-guardrails**. Streaming deadlines and terminal frames stay in **llm-streaming-response-guardrails**. Eval scoring stays in **llm-eval-ci-regression-gate** and **rag-retrieval-eval-guardrails**. This skill owns the span tree, GenAI attribute and metric names, content capture policy, context propagation, sampling, and the telemetry tests.\n\n## When to apply\n\n- Adding or reviewing tracing in an LLM gateway, RAG service, agent runtime, or MCP tool server\n- Adopting Spring AI or LangChain4j observability, or the OpenTelemetry Java agent, on a service that calls models\n- Moving LLM telemetry from a vendor-specific SDK to OTLP\n- A review finds prompts or completions in spans or logs, user IDs in metric labels, or one trace per upstream call\n- Upgrading OpenTelemetry instrumentation or the semantic conventions version\n\n## Span tree\n\nOne inbound request is one trace. A typical gateway or RAG request looks like this:\n\n```\nPOST /v1/chat/completions SERVER (http.route, tenant, gateway route)\n├── retrieval / vector search CLIENT (index alias, top_k, result count)\n├── chat {model} CLIENT attempt 1 → primary deployment (error.type=429)\n├── chat {model} CLIENT attempt 2 → fallback deployment (ok)\n│ └── execute_tool {tool} INTERNAL (tool name, call id, outcome)\n└── eval hook / guardrail checks INTERNAL (check name, verdict)\n```\n\n- One client span per **attempt**, so retries and fallbacks are visible; mark the attempt number and the routing reason. Usage metrics count once per billable attempt.\n- Agents: `invoke_agent {agent}` wraps the loop; each model turn is a `chat` span and each tool run an `execute_tool` span beneath it.\n- Span kind CLIENT for remote model calls, INTERNAL for in-process tools and checks. Span status ERROR only for real failures, with `error.type` set (HTTP status class, timeout, provider error code). A content-filter refusal is a result, not a span error; record it as a finish reason.\n\n## Attributes (GenAI semantic conventions)\n\nUse the attribute names from the pinned semantic conventions version, for example:\n\n- `gen_ai.operation.name` (`chat`, `embeddings`, `execute_tool`, `invoke_agent`)\n- `gen_ai.provider.name`, `gen_ai.request.model`, `gen_ai.response.model`\n- `gen_ai.request.max_tokens`, `gen_ai.request.temperature`, and other request parameters you actually send\n- `gen_ai.response.id`, `gen_ai.response.finish_reasons`\n- `gen_ai.usage.input_tokens`, `gen_ai.usage.output_tokens` from the provider's usage block, not an estimate; mark estimates explicitly when a stream ends without usage\n- `gen_ai.tool.name`, `gen_ai.tool.call.id`, `gen_ai.agent.name`, `gen_ai.conversation.id` (span attribute only, never a metric label)\n- `server.address`, `server.port`, `error.type`\n\nRules:\n\n- **Pin the conventions version** and keep every GenAI attribute name in one constants class or config. A rename is then one diff, plus a dashboard update in the same PR. If the instrumentation library supports a stability opt-in setting for GenAI conventions, set it explicitly instead of taking the default.\n- Gateway-specific facts (route name, tenant, deployment, fallback reason, cache hit, budget decision) go in a short custom namespace such as `llm.gateway.*`, never squatted under `gen_ai.*`.\n- Never put API keys, bearer tokens, full URLs with query strings, or raw headers on spans.\n\n## Content capture policy\n\n- **Off by default.** No `gen_ai.input.messages`, `gen_ai.output.messages`, `gen_ai.system_instructions`, tool arguments, tool results, or retrieved chunk text in spans, span events, or logs.\n- Turn off framework defaults that log prompts or completions (Spring AI, LangChain4j, HTTP client wire logging) and assert that in a test.\n- Opt-in only per environment or per tenant, behind a named flag, time-boxed, and routed through the redaction hook before export. Prefer exporting content to a separate store with its own retention and access control, referenced from the span by an ID.\n- Record content **shape** instead: message count, input and output token counts, tool count, chunk IDs and scores (IDs, not text), output schema validation result.\n\n## Metrics\n\n- Use the GenAI metric names from the pinned version: token usage histogram (`gen_ai.client.token.usage` with `gen_ai.token.type`) and the duration histograms for inference, embeddings, tool and agent operations. Newer versions split the generic operation duration into per-operation metrics; follow whichever the pinned version defines.\n- For streaming, record time to first token and time per output token separately from total duration.\n- Labels: operation, provider, request model, response model, route, outcome or `error.type`, token type. Never user ID, conversation ID, prompt hash, or response ID. Keep tenant as a label only when the tenant count is small and bounded.\n- Micrometer Observation is fine: one Observation per operation produces both the span and the timer. Check the exported names match the conventions, or add a convention class that maps them.\n\n## Context propagation\n\n- W3C `traceparent` and `tracestate` in and out. The gateway continues the caller's trace and propagates to the provider call.\n- Context survives async hops: reactive pipelines, virtual threads, `@Async` executors, streaming callbacks, and message queues (inject into message headers and link consumer spans).\n- Baggage carries only non-sensitive, low-cardinality keys (tenant, route); strip inbound baggage you do not trust before it reaches the provider.\n- Logs carry `trace_id` and `span_id` via MDC so a log line jumps to its trace.\n\n## Sampling and export\n\n- Head sampling in the SDK at a modest rate, plus tail sampling in the Collector that keeps every error, every fallback, every guardrail block, and slow requests above the latency SLO.\n- Export over OTLP to the Collector, not straight from the app to a vendor; the Collector owns batching, retries, attribute deletion as a last line of defence, and routing.\n- Exporter failure never fails a request; bounded queues, drop with a counter.\n- Use resource attributes for `service.name`, `service.version`, `deployment.environment.name`, and the Kubernetes namespace and pod.\n\n## Linking quality signals\n\n- Eval and guardrail verdicts (prompt-injection check, PII redaction count, schema validation, groundedness score) are attributes or child spans on the same trace, so a bad answer can be traced back to the retrieval and the model attempt.\n- Offline eval runs set their own `service.name` and a run ID resource attribute so they never pollute production dashboards.\n\n## Tests\n\n- In-memory span exporter (OpenTelemetry SDK testing) with a stubbed provider (WireMock or MockWebServer):\n - one inbound request yields one trace with the expected span tree, including one span per retry and fallback attempt\n - required GenAI attributes present with values from the provider's usage and response\n - no message content, tool arguments, API keys, or Authorization headers in any attribute, event, or captured log line\n - content capture opt-in produces redacted content only when the flag is on\n - inbound `traceparent` is continued; outbound request carries it; context survives the streaming and async paths\n - metric labels contain none of the forbidden high-cardinality keys\n- A test that fails when an attribute name changes without the constants class and dashboards being updated.\n\n## Review checklist\n\n- [ ] One trace per inbound request; one client span per model attempt; tool and agent spans nested correctly\n- [ ] GenAI attribute and metric names from a pinned conventions version, defined in one place\n- [ ] Prompt, completion, tool argument, and retrieved text capture off by default and asserted in tests\n- [ ] Usage from the provider's usage block; estimates marked\n- [ ] No user, conversation, or response IDs as metric labels\n- [ ] W3C propagation across HTTP, async, streaming, and messaging\n- [ ] Tail sampling keeps errors, fallbacks, guardrail blocks, and slow requests\n- [ ] Export via OTLP to the Collector; exporter failures never fail requests\n\n## Copy-paste brief for instruction files\n\n```\nLLM tracing: one trace per inbound request, one CLIENT span per model attempt (retries and fallbacks visible), execute_tool and invoke_agent spans nested under it. Use OpenTelemetry GenAI attribute and metric names from the pinned conventions version, defined in one constants class; gateway facts go under llm.gateway.*. Never record prompts, completions, system instructions, tool arguments or results, retrieved text, keys, or auth headers by default; opt-in capture is flagged, time-boxed, and redacted. Usage comes from the provider's usage block. No user, conversation, or response IDs as metric labels. Propagate W3C trace context across HTTP, async, streaming, and queues. Export OTLP to the Collector with tail sampling that keeps errors, fallbacks, guardrail blocks, and slow requests. Tests assert the span tree, attributes, propagation, and the absence of content.\n```\n" } ] }