From 9ec4b93095a65b63d2e414f84f51e11f9163862f Mon Sep 17 00:00:00 2001 From: Ramkumar Ethiraj <64294490+rmkr-dev@users.noreply.github.com> Date: Sat, 7 Nov 2026 05:21:41 +0000 Subject: [PATCH 1/2] Add LLM gateway routing and fallback guardrails skill --- skillbook/skills.json | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/skillbook/skills.json b/skillbook/skills.json index 27acea6..8c6aad8 100644 --- a/skillbook/skills.json +++ b/skillbook/skills.json @@ -1020,6 +1020,26 @@ ], "formatNotes": "All three. Copilot: path-scoped `.github/instructions/azure-service-bus-consumer.instructions.md` with applyTo for `**/*Listener*.java`, `**/*Consumer*.java`, `**/*ServiceBus*Config*.java`, `**/application*.{yml,yaml,properties}`, and Service Bus IaC (`**/*servicebus*.bicep`, `**/servicebus*.json`). Optional `.github/skills/azure-service-bus-consumer-reliability-guardrails/SKILL.md`. Claude Code: `.claude/skills/azure-service-bus-consumer-reliability-guardrails/SKILL.md` plus a CLAUDE.md fact that every Service Bus message may arrive twice and nothing is completed before the side effect is durable. Codex: a Service Bus consumer section in root `AGENTS.md` or nested `src/main/java/**/messaging/AGENTS.md`. Pair with transactional-outbox-guardrails for publishing (this skill owns consuming), spring-kafka-consumer-reliability-guardrails as the Kafka contrast (offsets and DLTs vs settlement and the system DLQ), k8s-probes-graceful-shutdown-guardrails for the shutdown timeout chain, azure-key-vault-app-integration for connection strings or certificates, spring-boot-testcontainers for the emulator harness, and hikari-connection-pool-guardrails for concurrency vs pool size. This skill owns consumer delivery semantics, settlement, DLQ, and lock handling — not outbox publishing.", "body": "# Skill: Azure Service Bus Consumer Reliability Guardrails (Spring Boot)\n\n## Goal\nMake Spring Boot consumers of Azure Service Bus safe to run as several replicas. Under PeekLock the broker delivers at least once: a crash, an abandon, or a lost lock all show up as another delivery. Complete a message only after the side effect is durable, abandon what can succeed on a later try, and dead-letter what never will. Locks, prefetch, and concurrency stay inside what the handler can finish. The dead-letter queue has an owner, and duplicates are stopped in the handler.\n\nThis skill owns consumer delivery, settlement, the dead-letter queue, and lock handling. Publishing, the outbox relay, and broker-side duplicate detection on send stay in **transactional-outbox-guardrails**. Settlement here (complete, abandon, dead-letter) is the Service Bus counterpart of a Kafka offset commit, and the system dead-letter sub-queue is the counterpart of a dead-letter topic, with different mechanics (see **spring-kafka-consumer-reliability-guardrails**).\n\n## When to apply\n- A new queue or subscription listener, or a review of a `ServiceBusProcessorClient`, a Spring Cloud Azure processor, or a Spring Cloud Stream Service Bus binding\n- Incidents: double charges, lost messages, a growing dead-letter queue, `MessageLockLost`, or a consumer that looks healthy while the active count climbs\n- Choosing sessions for per-key order versus competing consumers for throughput\n- AKS rollouts where the pod grace period is shorter than in-flight work\n- Anyone reaching for `ReceiveAndDelete`, `replicas: 1`, or a catch-all that completes\n\n## Baseline rules\n1. **PeekLock for anything with a side effect.** `PEEK_LOCK` locks the message and leaves it on the entity until you settle it. `RECEIVE_AND_DELETE` removes it the moment the client receives it: a crash, a timeout, or a failed commit, and the work is gone. Use receive-and-delete only for data you can drop (a sample, a heartbeat). Spring Cloud Azure: `spring.cloud.azure.servicebus.processor.receive-mode=peek_lock`. The Stream binder default is already `spring.cloud.stream.servicebus.bindings..consumer.receive-mode=peek_lock`; leave it there. On the Java builder, `receiveMode(ServiceBusReceiveMode.PEEK_LOCK)`. If the app still uses the JMS starter, the same rule applies: acknowledge only after commit, and avoid a mode that settles on receive.\n\n2. **Settle only after the side effect is durable.** Complete removes the message. Abandon releases it now and increments the delivery count so another competing consumer can try. Dead-letter moves it to the system DLQ with a short `DeadLetterReason` and `DeadLetterErrorDescription` an operator can act on: a stable code, not the payload and not personal data. The order is: do the work in one transaction, commit, then complete. Completing and then writing loses the message when the write fails. Abandon (or let the exception propagate while auto-complete is on) for recoverable failures: timeouts, deadlocks, 503s, a full pool. Dead-letter on the first attempt when another try cannot help: schema mismatch, validation, a business rule that fails forever. Defer is not a retry mechanism. A deferred message leaves the normal receive path and comes back only if you stored its sequence number.\n\n3. **Auto-complete is a contract.** The processor completes when the callback returns and abandons when it throws. On the Stream binder `auto-complete` defaults to true. That is safe only when the durable write finished before the return and failures are not swallowed. The moment the handler calls `complete`, `abandon`, or `deadLetter` itself, turn auto-complete off: `spring.cloud.azure.servicebus.processor.auto-complete=false`, or `consumer.auto-complete=false` on the binding (the binder then passes a `Checkpointer`), or `disableAutoComplete()` on `ServiceBusProcessorClientBuilder`. Manual complete while auto-complete is still on settles twice. Catching `Exception`, logging, and returning completes a failed message. Let recoverable exceptions propagate, or abandon explicitly.\n\n4. **MaxDeliveryCount and a DLQ you own.** The entity max delivery count (default 10) is the broker's backstop. Abandon, and a lock that expires because the handler was too slow, both count toward it. Past the limit, Service Bus dead-letters the message with reason `MaxDeliveryCountExceeded`. Expired messages land in the DLQ only when the entity dead-letters on message expiration (`TTLExpiredException`); otherwise they disappear. Read `getDeadLetterReason()` and `getDeadLetterErrorDescription()` before any replay. A poison message you can already classify should be dead-lettered by the handler with your own reason, so the queue does not fill with an opaque max-delivery reason. Own the `$deadletterqueue` sub-queue: a separate processor whose `sub-queue` is the dead-letter sub-queue (SDK `SubQueue.DEAD_LETTER_QUEUE`), or an operator tool. It records reason, message id, and delivery count, and it pages someone. It does not auto-replay. Replay is a deliberate resend after the bug is fixed. If the entity has duplicate detection, resending the same `MessageId` inside the detection window is dropped, and completing the DLQ copy then loses the message. Keep the original id in an application property the inbox already keys on, and send the replay under a new `MessageId`.\n\n5. **Lock duration versus processing time.** The queue or subscription lock duration defaults to one minute and cannot exceed five minutes. Each renewal extends the lock by that same duration, and the last successful renewal still holds for one lock duration after the renewal task stops. `maxAutoLockRenewDuration` (property `max-auto-lock-renew-duration`, binder default five minutes) is how long the client keeps renewing. `Duration.ZERO` turns renewal off. Receive-and-delete has no lock to renew. Size the pair from measured p99: the entity lock above a normal attempt, the renewal budget above p99 plus downstream waits, with headroom. A dead pod holds the message until the current lock lapses, so a five-minute lock is not a substitute for renewal. On `ServiceBusFailureReason.MESSAGE_LOCK_LOST` or `SESSION_LOCK_LOST`, stop the handler and do not complete, abandon, or dead-letter. The broker has released the message or will redeliver it. If the database commit happened before the loss, the next delivery has to be a no-op (rule 7). A dropped link or a service update can surface as lock-lost without incrementing the delivery count. An expired lock from a slow handler does increment it. In both cases, stop settling.\n\n6. **Prefetch and concurrency stay inside the lock.** Prefetch (default 0) pulls messages onto the client before a handler wants them, and those messages are locked while they sit in the local buffer. A large prefetch plus a slow handler expires locks, bumps the delivery count, and can dead-letter work that was only waiting locally. Keep prefetch at 0 for database or HTTP handlers. If you raise it, cap it at a small multiple of `max-concurrent-calls`, and only after the lock-lost rate stays flat. `max-concurrent-calls` defaults to 1 on the binder; with sessions it applies per session. Concurrent calls times replicas times connections per call has to fit the Hikari pool (see **hikari-connection-pool-guardrails**). Raising concurrency to hide a slow query holds more locks and more connections. Manual settlement plus a measured prefetch is the safer pair; a fat prefetch with auto-complete races the local buffer.\n\n7. **Handlers are idempotent under redelivery.** Abandon, lock expiry, a crash between commit and complete, and a DLQ replay all deliver again. Broker duplicate detection is a send-side `MessageId` window. It does not suppress consumer redelivery, and it cannot be enabled after the entity exists. Dedupe in the consumer: an inbox row unique on `(consumer, message_id)` inserted in the same transaction as the side effect, an upsert on a natural business key, or an application property the producer set (an event id). Prefer that producer id over the broker sequence number, because a replay is a new sequence. `MessageId` is the right inbox key when the outbox sets it. On conflict, complete and return. When the handler also emits events, write an outbox row in that same transaction instead of calling the sender inline.\n\n```sql\ncreate table inbox_message (\n consumer varchar(64) not null,\n message_id varchar(128) not null,\n processed_at timestamptz not null default now(),\n primary key (consumer, message_id)\n);\n-- same transaction as the side effect:\ninsert into inbox_message (consumer, message_id) values (:consumer, :id)\non conflict do nothing; -- 0 rows: already done, complete and skip\n```\n\n8. **Sessions when order matters; competing consumers otherwise.** Several processor instances on one queue or subscription are competing consumers. There is no Kafka-style partition ownership: more replicas increase throughput until the entity or the database saturates, and they do not remove duplicates. `replicas: 1` is not a correctness fix. Per-key FIFO needs sessions. The queue or subscription is created with sessions required (that flag cannot be flipped later), every message carries a `SessionId` for the entity whose order matters, and only one consumer holds a given session. `max-concurrent-sessions` bounds how many sessions one pod works. Set `session-idle-timeout` above a normal handler so a quiet gap does not drop the session lock while the message lock is still held. On a partitioned entity the partition key and the session id have to match; publishers that follow the outbox skill set both. A missing `SessionId` on a session entity is poison, not a retry.\n\n9. **Prefer the processor over a hand-rolled receive loop.** `ServiceBusProcessorClient` (or a session processor) is the push path: it pumps, renews, and invokes your callback. A `ServiceBusReceiverClient` loop is pull, so you own receive, renewal, settlement, and shutdown, and those bugs show up under load. Use one style per entity. Spring Cloud Azure knobs live under `spring.cloud.azure.servicebus.processor`: `receive-mode`, `auto-complete`, `prefetch-count`, `max-concurrent-calls`, `max-concurrent-sessions`, `max-auto-lock-renew-duration`, `session-enabled`, `subscription-name` for a topic, and `sub-queue` for the DLQ reader. The Stream binder mirrors them at `spring.cloud.stream.servicebus.bindings..consumer.*`. Authenticate with the namespace plus a `TokenCredential` (workload identity on AKS). A connection string, if one still exists, comes from Key Vault or a secret mount (see **azure-key-vault-app-integration**), never from Git or a ConfigMap.\n\n```yaml\nspring:\n cloud:\n azure:\n servicebus:\n namespace: ${SERVICEBUS_NAMESPACE}\n processor:\n receive-mode: peek_lock\n auto-complete: false\n prefetch-count: 0\n max-concurrent-calls: 4\n max-auto-lock-renew-duration: 2m\n```\n\n```java\nvoid onMessage(ServiceBusReceivedMessageContext ctx) {\n var message = ctx.getMessage();\n try {\n // Commits the inbox row and the side effect together. False means already processed.\n if (!inbox.claimAndHandle(message)) {\n ctx.complete();\n return;\n }\n ctx.complete();\n } catch (PoisonMessageException ex) {\n var options = new DeadLetterOptions()\n .setDeadLetterReason(\"validation-failed\")\n .setDeadLetterErrorDescription(ex.getCode());\n ctx.deadLetter(options);\n } catch (ServiceBusException ex) {\n if (ex.getReason() == ServiceBusFailureReason.MESSAGE_LOCK_LOST\n || ex.getReason() == ServiceBusFailureReason.SESSION_LOCK_LOST) {\n return; // lock is gone; do not settle\n }\n throw ex;\n } catch (RuntimeException ex) {\n ctx.abandon(); // transaction rolled back; another delivery may succeed\n }\n}\n```\n\n10. **Shutdown stops receiving, then finishes in-flight work inside the lock.** On context close, stop the processor so it takes no new message, then wait for callbacks that already hold a lock. That wait (`spring.lifecycle.timeout-per-shutdown-phase` and the processor close timeout) has to be shorter than `terminationGracePeriodSeconds` minus the preStop sleep (see **k8s-probes-graceful-shutdown-guardrails**). If the lock drops during the wait, do not complete. Readiness may go false when the processor is stopped. Liveness must not depend on the namespace being reachable, or a broker blip restarts every pod. A manual receiver exits its loop on the shutdown signal and settles only what it still holds a lock for.\n\n11. **Watch the queue, not just the process.** Azure Monitor already exposes active message count, dead-lettered message count, incoming, complete, abandon, and dead-letter counts, plus throttling. Add Micrometer timers for handler latency and counters for settlement outcome, lock-lost, and inbox hits. Tags stay bounded: entity, subscription, outcome. No message id, session id, or payload as a tag. Alert when the dead-letter count is rising, and when the active count stays high while the complete rate is flat (pods up, work not moving). Log message id, delivery count, entity, and outcome. Do not log the body. Tag and dashboard conventions: **spring-boot-micrometer-prometheus-guardrails**.\n\n12. **Test the three paths that fail in production.** The same message delivered twice produces one side effect and a second complete. A poison payload is dead-lettered with your reason and is not completed. A lock-lost error mid-handler does not settle, and a later delivery after a commit is an inbox no-op. Drive those with a fake `ServiceBusReceivedMessageContext` so the test asserts which settlement ran. Add one integration test on the Service Bus emulator (Testcontainers or the emulator container; see **spring-boot-testcontainers**) for peek-lock complete, abandon then redelivery, and a message that lands on the dead-letter sub-queue. Do not point tests at a shared namespace. Use Awaitility, not fixed sleeps. The emulator is not the Premium tier: confirm sessions, duplicate detection, and partitioning on a real namespace before you depend on them.\n\n## Workflow\n1. Inventory: queue versus topic plus subscription, receive mode, auto-complete, who settles, lock duration, max delivery count, prefetch, max concurrent calls, sessions, replicas, side effects, and where the dedupe key lives.\n2. Settlement: PeekLock, complete only after commit, abandon versus dead-letter written down per exception, auto-complete off when the handler settles itself.\n3. Idempotency: inbox or natural key in the same transaction as the side effect. Confirm duplicate detection is not standing in for that inbox.\n4. DLQ: a deliberate max delivery count, a reader for `$deadletterqueue`, and a replay note that reads `DeadLetterReason` and avoids resending the same `MessageId` inside the duplicate-detection window.\n5. Sizing: lock duration, `max-auto-lock-renew-duration`, prefetch, and concurrency against p99 and the connection pool. Sessions only where per-key order is required.\n6. Shutdown and metrics: the grace-period chain, alerts on DLQ growth and stuck active messages, lock-lost and abandon rates.\n7. Tests for the rule 12 matrix. PR notes name the dedupe key, the exception-to-settlement table, the DLQ owner, and the lock budget.\n\n## Tool-specific notes\n### GitHub Copilot\n- Path-scoped `.github/instructions/azure-service-bus-consumer.instructions.md` with `applyTo` for `**/*Listener*.java`, `**/*Consumer*.java`, `**/*ServiceBus*Config*.java`, `**/application*.{yml,yaml,properties}`, and Service Bus IaC (`**/*servicebus*.bicep`, `**/servicebus*.json`).\n- Always-on line in `.github/copilot-instructions.md`: \"Service Bus consumers are at-least-once: PeekLock, idempotent handlers, complete only after the side effect commits, abandon or dead-letter on failure, never ReceiveAndDelete for work you cannot lose.\"\n- Optional `.github/skills/azure-service-bus-consumer-reliability-guardrails/SKILL.md` for agent mode.\n\n### Claude Code\n- Procedure in `.claude/skills/azure-service-bus-consumer-reliability-guardrails/SKILL.md`.\n- CLAUDE.md fact: \"Every Service Bus message may arrive twice. Never complete before the side effect is durable, and never settle after MessageLockLost.\"\n- Before claiming done, show the settlement table, the DLQ owner, the lock-budget numbers, and the passing duplicate, dead-letter, and lock-lost tests.\n\n### Codex\n- Service Bus consumer section in root `AGENTS.md`, or nested `src/main/java/**/messaging/AGENTS.md` (or linked `docs/agents/azure-service-bus-consumer.md`).\n- State: PeekLock, the auto-complete policy, the dedupe key and inbox table, abandon versus dead-letter lists, the DLQ path and replay rule, the lock and prefetch budget, sessions versus competing consumers, shutdown timeouts, and banned patterns (ReceiveAndDelete for side effects, complete-then-process, catch-and-complete, unbounded prefetch, `replicas: 1` as a dedupe fix).\n\n## Anti-patterns\n- `RECEIVE_AND_DELETE` for a write, a charge, an email, or anything else you cannot lose\n- Completing, or returning under auto-complete, and then doing the work\n- Catching `Exception`, logging it, and completing or returning normally\n- Auto-complete left on while the handler also calls `complete`\n- Prefetch in the hundreds on a handler that takes seconds, or prefetch raised with no look at the lock-lost rate\n- No reader, owner, or alert on the dead-letter sub-queue, or a job that replays the DLQ in a loop\n- Resending a DLQ message with the same `MessageId` while duplicate detection still covers that id\n- `replicas: 1`, or a single-pod hostname check, as the fix for duplicates\n- Treating broker duplicate detection as consumer idempotency\n- Sessions required on the entity while publishers omit `SessionId`, or sessions turned on when the only goal was throughput\n- Lock duration set to five minutes and renewal left untouched while p99 is longer, or renewal disabled while the handler regularly outlives the lock\n- Message bodies in logs, or message ids on metric tags\n\n## Done when\n- [ ] Receive mode is PeekLock for every handler with a side effect\n- [ ] Complete runs only after the side effect commits; recoverable failures abandon; poison failures dead-letter with a reason and a description\n- [ ] Auto-complete is off if the handler settles itself, and no catch-all completes a failure\n- [ ] Every handler has a dedupe key enforced by an inbox, an upsert, or a natural key in the same transaction\n- [ ] Max delivery count is a choice; the `$deadletterqueue` sub-queue has an owner, an alert, and a replay note that reads `DeadLetterReason` first\n- [ ] Lock duration and `max-auto-lock-renew-duration` cover p99 with headroom; `MessageLockLost` stops the handler without a settlement\n- [ ] Prefetch and `max-concurrent-calls` are sized so locks are not held past processing capacity, and concurrency fits the pool\n- [ ] Sessions are on only where per-key order is required; otherwise competing consumers, not `replicas: 1`\n- [ ] Shutdown stops receive, finishes in-flight work inside the grace period, and does not complete after lock loss\n- [ ] Active count, DLQ depth, lock-lost, abandon, and latency are visible, with alerts on DLQ growth and stuck active messages\n- [ ] Tests cover duplicate delivery, the dead-letter path, and the lock-lost path\n\n## Copy-ready SKILL.md stub\n```markdown\n---\nname: azure-service-bus-consumer-reliability-guardrails\ndescription: Use when writing or reviewing Spring Boot consumers of Azure Service Bus — PeekLock settlement, complete-after-commit, abandon versus dead-letter, MaxDeliveryCount and the system DLQ, lock renewal, prefetch and concurrency, idempotent handlers, sessions versus competing consumers, shutdown, and DLQ metrics.\n---\n\nFollow Azure Service Bus Consumer Reliability Guardrails: PeekLock for any side effect, complete only after the side effect commits, abandon recoverable failures, and dead-letter poison messages with a reason. Keep an owner on the dead-letter sub-queue who reads DeadLetterReason before replay. Handlers are idempotent (inbox or natural key) because delivery is at-least-once; duplicate detection does not replace that. Size lock duration, max-auto-lock-renew-duration, prefetch, and max-concurrent-calls so locks are not held longer than the work, and stop without settling on MessageLockLost. Use sessions only for per-key order; otherwise competing consumers. Stop receiving on shutdown, finish in-flight work inside the pod grace period, and alert on DLQ growth and stuck active messages.\n```" + }, + { + "id": "llm-gateway-routing-fallback-guardrails", + "title": "LLM Gateway Routing and Fallback Guardrails", + "whenToUse": "Routing or reviewing a Java/Spring or provider-agnostic LLM gateway that serves chat, completions, or embeddings through an alias across Azure OpenAI, Amazon Bedrock, OpenRouter, Together, Modal, or other OpenAI-compatible backends — ordered or weighted targets, sticky versus per-request selection, health-aware skipping, which failures fall through versus fail fast, the per-target fallbackOnBadRequest switch (default off), surfacing a final 400, 413, or 422 and returning 502 that lists every attempt when the final target fails another way, streaming rules that forbid a mid-stream provider switch, adapter boundaries, per-attempt metrics under one correlation id, and two-stub tests that lock the walk.", + "tools": [ + "copilot", + "claude-code", + "codex" + ], + "tags": [ + "llm", + "gateway", + "routing", + "fallback", + "spring-boot", + "reliability" + ], + "formatNotes": "All three. Copilot: path-scoped `.github/instructions/llm-gateway-routing.instructions.md` with applyTo for `**/llm/gateway/**`, `**/*Router*.java`, `**/*Gateway*.java`, `**/*Routing*.java`, `**/*Adapter*.java`, `**/*Provider*.java`, and `**/application*.{yml,yaml,properties}`. Optional on-demand procedure at `.github/skills/llm-gateway-routing-fallback-guardrails/SKILL.md`. Claude Code: `.claude/skills/llm-gateway-routing-fallback-guardrails/SKILL.md` plus a CLAUDE.md fact that aliases walk ordered targets, a caller 4xx stops the walk unless that target sets fallbackOnBadRequest, and a committed stream never changes provider. Codex: a short \"LLM gateway routing\" brief in root `AGENTS.md` (the rule, the table path, the two-stub test command) while the procedure stays in SKILL.md. Pair with llm-cost-latency-budget-guardrails for pricing each attempt, llm-app-prompt-injection-guardrails for untrusted content and upstream redaction, llm-eval-ci-regression-gate, llm-eval-agent-workflow, and rag-retrieval-eval-guardrails for eval, spring-boot-http-client-guardrails for client timeouts and pools, spring-boot-resilience4j for the breaker primitive, api-rate-limiting-guardrails for inbound quotas, and api-idempotency-key-guardrails for the public Idempotency-Key. This skill owns outbound routing, fallback classes, the final status (surface a final 400, 413, or 422; otherwise 502 listing every attempt), streaming commit, and adapter boundaries.", + "body": "# Skill: LLM Gateway Routing and Fallback Guardrails\n\n## Goal\n\nMake multi-provider chat, completions, and similar calls fail over on purpose. Callers name an alias such as `chat-default`. The gateway resolves it to ordered targets (provider, model or deployment, region), walks them under the caller deadline, and reports an honest status when the walk fails. Timeouts, 429s, 5xx, and connection errors move to the next healthy target. A 400, 413, or 422 stops the walk unless that target sets fallbackOnBadRequest. After the first streamed token, the gateway stays on that target. When the final target returns 400, 413, or 422, the caller sees that status. When the final target fails another way, the caller sees 502 and the body lists every attempt.\n\nThis skill owns the routing table, primary versus fallback selection, which failure classes fall through, the per-target `fallbackOnBadRequest` switch, streaming commit rules, the adapter boundary, and the tests that prove multi-target behavior. Pricing, token caps, and reserve-then-reconcile budgets stay in **llm-cost-latency-budget-guardrails**. Prompt-injection boundaries stay in **llm-app-prompt-injection-guardrails**. Eval gates stay in **llm-eval-ci-regression-gate**, **llm-eval-agent-workflow**, and **rag-retrieval-eval-guardrails**. Breaker primitives stay in **spring-boot-resilience4j**. Client timeouts, pools, and TLS stay in **spring-boot-http-client-guardrails**. Inbound quotas stay in **api-rate-limiting-guardrails**. An `Idempotency-Key` on the public POST stays in **api-idempotency-key-guardrails**.\n\n## When to apply\n\n- A second provider or region for chat, completions, embeddings, or a similar method (Azure OpenAI, Amazon Bedrock, OpenRouter, Together, Modal, or another OpenAI-compatible backend)\n- Replacing a hard-coded model name with an alias the gateway owns\n- An outage where one region's 500s took the product down, or a rejected request came back as 502 and clients retried for hours\n- A content-filter or schema 400 that a product owner wants to replay on another model\n- A stream that mixes two models' tokens, or hangs after the first provider dies mid-response\n- Review of router, gateway, or adapter code before a new alias is enabled\n\n## The rule\n\nThe caller names an alias. The gateway walks that alias's eligible targets once, and starts the next attempt only when the failure is retryable and no response bytes have been committed. A 400, 413, or 422 stops the walk unless the target that produced it has `fallbackOnBadRequest: true`. The switch defaults to false. When the final target returns 400, 413, or 422, surface that status. When the final target fails another way — a 5xx after an earlier 400, an auth failure, a timeout, a 429, or a connection error — return 502 and list every attempt. Do not answer that mixed walk with 503, timeouts with a blanket 504, or auth exhaustion with 503.\n\n## Routing model\n\nAn alias is the only model name callers and config are allowed to use. Provider model ids and Azure deployment names live in the routing table.\n\n| Field | Meaning |\n|---|---|\n| `id` | Stable name in metrics and logs (`azure-east-chat`, `bedrock-backup`) |\n| `provider` | Adapter key: `azure-openai`, `bedrock`, `openrouter`, `together`, `modal`, or `openai-compatible` |\n| `model` | Provider model id, or an Azure deployment name. The adapter knows which the wire protocol wants |\n| `region` | Region or endpoint name. A URL with a credential in it is a startup error |\n| `secretRef` | Env var or Key Vault secret. The table stores the reference, never the value |\n| `priority` | Lower runs first. Also the fallback order after a weighted primary is chosen |\n| `weight` | Used only when the alias strategy is `weighted` |\n| `fallbackOnBadRequest` | Default `false`. Applies to this target only |\n| `capabilities` | Subset of `stream`, `tools`, `json_schema`, `vision`, `embeddings`. Missing capability skips the target before HTTP |\n| `minAttemptBudget` | Shortest remaining deadline still worth starting (connect plus a useful read) |\n\n**Priority.** Sort eligible targets by `priority`. First is primary; the rest fall back in that order.\n\n**Weighted.** Pick the primary by weight, then fall back in priority order. Selection is a pure function of the alias, the eligible set, and a stable key (request id or the sticky key), so a test can pin it and a caller retry prefers the same primary. The walk does not re-roll after the first failure.\n\n**Sticky.** `sticky: none` (the default) resolves health on every call — the right mode for stateless completions and embeddings. `sticky: session` pins a conversation id to the target that last succeeded for that key, for a documented window (the conversation lifetime, or about 30 minutes idle). Failures are not pinned. Sticky does not override health, residency, or capabilities; an ineligible pin is skipped and a later success updates it.\n\nEligible means enabled, breaker closed (or this call is the half-open probe), capabilities cover the request, region is on the alias residency allowlist, and remaining deadline is at least `minAttemptBudget`. Attempt cap equals that list. Do not revisit a target already tried for this request.\n\nThe adapter's HTTP client does not retry this POST. The walk is the retry; stacking both multiplies paid calls and burns the deadline. Apply an `Idempotency-Key`, when the public API has one, before the walk so a caller retry that already streamed tokens replays the stored outcome.\n\n```yaml\nllm:\n gateway:\n aliases:\n chat-default:\n strategy: priority # priority | weighted\n sticky: none # none | session\n deadline: 10s\n residency: [eastus, us-east-1]\n targets:\n - id: azure-east-chat\n provider: azure-openai\n deployment: chat-primary\n region: eastus\n secretRef: kv:llm-azure-east\n priority: 1\n fallbackOnBadRequest: false\n minAttemptBudget: 800ms\n capabilities: [stream, tools, json_schema]\n - id: bedrock-backup\n provider: bedrock\n model: chat-backup\n region: us-east-1\n secretRef: kv:llm-bedrock\n priority: 2\n fallbackOnBadRequest: false\n minAttemptBudget: 800ms\n capabilities: [stream, tools]\n```\n\nEmbeddings and similar methods share this table, these failure classes, and the final-status function. They usually use `sticky: none` and have no stream commit point. Give each method a small adapter method (`complete`, `stream`, `embed`) and one shared policy. A second copy of the status rules will drift.\n\n## Failure classes\n\nAdapters map vendor payloads into these classes. The router switches on the class, not on a provider error string.\n\n| Class | Typical signals | Next target? | Affects health? |\n|---|---|---|---|\n| Timeout | Connect timeout, read timeout, deadline hit during the attempt | Yes | Yes |\n| Rate limit | HTTP 429, or a slow-down code mapped to 429 | Yes, when `Retry-After` does not fit the remaining deadline. On the last target, wait once if the delay fits, then stop | Short cooldown only. A 429 does not open a long breaker |\n| Upstream 5xx | 500, 502, 503, 504 | Yes | Yes |\n| Connection | Reset, DNS, TLS handshake, empty response | Yes | Yes |\n| Client rejection | 400, 413, 422, including a content-filter or schema failure mapped onto those statuses | Only when this target's `fallbackOnBadRequest` is true | No. A rejected request is not an unhealthy model |\n| Auth or config | 401, 403, or a 404 that means the deployment or model id is missing | Yes. Another target may be configured. This is not the bad-request switch | Yes. Alert, and keep the target out until the credential or deployment name is fixed |\n| Caller cancelled | Client closed the connection | No. Cancel the upstream and stop | No |\n\nTurn `fallbackOnBadRequest` on only when a 400 from that model is model-specific (unsupported parameter, stricter content filter) and the next target may see the same canonical request. Leave it false for an oversized body, a bad schema, or a malformed message list: those fail on every provider, and replaying them spends budget while hiding a client bug. The flag does not retry the same target and does not apply to 401 or 403.\n\nSkip a target that lacks tools, JSON schema, or vision with reason `capability_skip` before any HTTP call. If that empties the list, return 422 `no_capable_target` with an empty attempt list — the gateway's status, because no upstream saw the call.\n\nCount only the health column toward the breaker the service already runs. A burst of 400s leaves it closed. An open breaker skips the target with reason `unhealthy`, except the half-open probe.\n\n## When every target fails\n\n`fallbackOnBadRequest` defaults to false and covers only 400, 413, and 422. The caller status depends on what the final target did, not on passing through whichever status arrived last.\n\n1. No attempt was made. Return 422 `no_capable_target` when capabilities emptied the list. Return 503 `no_eligible_target` when every target was unhealthy, disabled, or out of deadline. Both responses carry an empty attempt list. Use them only when nothing was called: a 422 the final target actually returned is that status, not `no_capable_target`, and a target that was called and then failed another way is 502, not `no_eligible_target`.\n2. The final target returned 400, 413, or 422. Surface that status. Do not wrap it in 502. An earlier 503 followed by a final 422 is still 422.\n3. The final target failed another way: timeout, 429, upstream 5xx (500, 502, 503, or 504), connection error, or auth or config (401, 403, or a deployment 404). Return 502. The body lists every attempt in order, including an earlier 400 that fell through and the last 503, each auth status, and each timeout. Record `Retry-After` on a 429 attempt when the upstream sent one; the caller status is still 502. Do not return the last 503, a blanket 504, or 503 for auth exhaustion. A caller-facing 401 would blame the caller for the gateway's provider key or deployment name, so those statuses stay inside the attempt list.\n\nThe 502 body is problem+json: stable code `upstream_failed`, the alias, and `attempts` (target id, failure class, and HTTP status when the target returned one). A surfaced 400, 413, or 422 uses the client-rejection code and that HTTP status. Do not copy the upstream error document. Those documents often echo the prompt.\n\n## Streaming\n\nThe commit point is the first model-output byte flushed to the caller. Flush nothing before that token, so a connect or wait failure can still fall through. Skip early heartbeats; a flushed heartbeat is a commit.\n\nBefore the commit point, a retryable failure starts the next target, and the caller sees one stream. Do not buffer a full generation to preserve a later fallback.\n\nAfter the commit point the status is already 200 and the caller holds one model's tokens. Cancel the upstream. Emit one terminal error a client can tell from a normal stop — for SSE, `event: error` with `{ \"code\": \"stream_interrupted\", \"alias\": \"\", \"attempt\": }` — then close. Do not open the next provider or append another model's tokens. The error frame is how a closed 200 says the answer stopped early.\n\nBuffer non-streaming calls until the attempt settles, so fallback and final-status rules still apply. If the caller disconnects, cancel the upstream and stop the walk.\n\n## Adapter boundary\n\nThe router depends on one interface. Each provider is an implementation. The router does not import a vendor SDK and does not branch on provider name.\n\n```text\ninterface LlmProviderAdapter {\n String provider();\n Capabilities capabilities(Target target);\n AttemptResult complete(CanonicalRequest request, Target target, Deadline deadline);\n void stream(CanonicalRequest request, Target target, Deadline deadline, StreamSink sink);\n}\n```\n\n`AttemptResult` carries the failure class, HTTP status when one exists, an allowlisted provider code, token counts when usage was reported, and latency. It carries neither the raw prompt nor the raw error document.\n\nThe canonical request is messages, tools, response format, sampling parameters, max output tokens, and the stream flag. Azure OpenAI, OpenRouter, Together, Modal, and other OpenAI-compatible backends share one HTTP adapter. Config supplies base URL, header style (`api-key` or `Authorization: Bearer`), API version, and deployment-versus-model path. Amazon Bedrock is its own adapter: signing and the Converse or invoke body are a different schema. A new provider is a new class plus a table row.\n\nResolve `secretRef` from the environment or Key Vault (**azure-key-vault-app-integration**). Send credentials in headers. Reject a base URL that already contains a key.\n\nConnect and read timeouts fit the deadline passed into the adapter, using the client builder, pool, and TLS rules from **spring-boot-http-client-guardrails**. Skip a target with reason `deadline` when remaining budget is below `minAttemptBudget`. The read timeout is that remainder, not the happy-path SLO.\n\n## Budgets and latency\n\nThe alias deadline is the hard stop behind the latency SLO (for example a 10s deadline behind an 8s p95). Subtract time already spent before each attempt. Record attempt latency, and time to first token on streams, as histograms with the labels below. Hand every attempt — success, transport failure, and a 400 taken because the switch is on — to the cost and budget hook before the next target starts, so a walk cannot outrun a budget checked only on the first call. This module does not own the price table, max-token caps, or the ledger.\n\n## Observability\n\nEach attempt is a child span of the gateway request. Every attempt log carries the inbound correlation id.\n\nRecord alias, target id, provider, model or deployment, region, attempt index, failure class, HTTP status, reason, latency, whether the stream had committed, and token counts when the provider sent them. Reasons are a fixed set: `timeout`, `rate_limit`, `upstream_5xx`, `connection`, `bad_request`, `auth_config`, `capability_skip`, `unhealthy`, `deadline`, `cancelled`, `stream_committed`.\n\n- `llm_gateway_attempt_seconds` — histogram. Labels: `alias`, `provider`, `outcome`.\n- `llm_gateway_attempts_total` — counter. Labels: `alias`, `provider`, `model`, `outcome`, `failure_class`.\n- `llm_gateway_fallback_total` — counter. Labels: `alias`, `reason`.\n- `llm_gateway_response_total` — counter. Labels: `alias`, `status_class` (`2xx`, `4xx`, `5xx`).\n\n`model` is the configured id. Request ids, user ids, prompt hashes, and provider messages are not labels. Alert on a rising fallback rate, any `auth_config`, and `no_eligible_target`.\n\n## Safety\n\nDefault logs and traces hold routing metadata only. A debug switch that prints prompts or completions stays off in shared environments. Redaction of secrets and personal data in the prompt is upstream of this router: **llm-app-prompt-injection-guardrails** for untrusted content and output sinks, **spring-boot-structured-logging-guardrails** for the log pipeline. Body logging is not a fallback debugging tool.\n\nTargets are an allowlist. The inbound body cannot name a provider URL, a region, or a credential. Residency is a hard filter. `fallbackOnBadRequest` can move a request one provider's content filter rejected onto a provider with a different filter. Write that decision next to the flag. The default stays off.\n\n## Tests\n\nUse a pure walk test with a fake adapter, plus two HTTP stubs (WireMock, MockWebServer, or a Testcontainers mock). No cloud account.\n\n| Case | Setup | What passes |\n|---|---|---|\n| Happy primary | Primary 200 | Secondary unused. Caller 200. One attempt |\n| Fallback on 503 | Primary 503, secondary 200 | Caller 200. Order primary then secondary. Reason `upstream_5xx` |\n| No fallback on 400 | Primary 400, switch false | Caller 400. Secondary unused. Breaker failure count unchanged |\n| Switch on | Primary 400, switch true, secondary 200 | Caller 200. Both called. Reason `bad_request` |\n| Last 4xx kept | Primary 503, secondary 422, switch false | Caller 422, client-rejection code |\n| 429 then 400 | Primary 429, secondary 400, switch false | Caller 400 |\n| Switch then 5xx | Primary 400 switch on, secondary 503 | Caller 502. Body lists the 400 and the 503 |\n| All timeouts | Both time out | Caller 502. Body lists both timeouts. Both called |\n| Auth exhausted | Primary 401, secondary 403 | Caller 502. Body lists both auth statuses |\n| Capability skip | Needs tools; primary has none; secondary 200 | Primary stub unused. Reason `capability_skip` |\n| None capable | No target supports tools | Caller 422 `no_capable_target`. Both stubs unused |\n| Stream before commit | Primary resets before any token | Caller sees only the secondary stream |\n| Stream after commit | Primary flushes two tokens, then resets | Those tokens plus `stream_interrupted`. Secondary unused |\n| Correlation | Two attempts | Same correlation id on both spans and logs |\n| Sticky | Two calls, same session, primary healthy | Same target id |\n| Deadline skip | Budget below `minAttemptBudget` | Target not called. Reason `deadline` |\n| Single pass | Both return 503 | Caller 502 listing both 503s. Each stub received one request |\n\nAssert the problem body does not contain the prompt fixture.\n\n## Workflow\n\n1. Inventory aliases, call sites that still pass a raw model name, providers, and any retry already on the HTTP client or a breaker.\n2. Add the canonical request, `AttemptResult`, and `LlmProviderAdapter`. Wrap today's client as a one-target adapter. A final 400, 413, or 422 stays that status; any other final failure is 502 listing the attempt.\n3. Move model choice into the table. If the service is live, ship one target per alias and log the id the walk would have picked.\n4. Add adapter classification and the walk. Leave every `fallbackOnBadRequest` false.\n5. Add the commit rule and `stream_interrupted` before a second streaming target is enabled.\n6. Add per-attempt metrics and the shared correlation id. Confirm a 400 does not move the breaker.\n7. Add the decision tests and the two-stub tests.\n8. Add the spare target on one alias. Watch fallback rate, status class, and auth failures for a bounded window.\n9. Turn the bad-request switch on only for a named target, with the reason in the config change.\n\n## Tool-specific notes\n\n- **GitHub Copilot:** path-scoped `.github/instructions/llm-gateway-routing.instructions.md` with `applyTo` for `**/llm/gateway/**`, `**/*Router*.java`, `**/*Gateway*.java`, `**/*Routing*.java`, `**/*Adapter*.java`, `**/*Provider*.java`, and `**/application*.{yml,yaml,properties}`. Put The rule, the failure-class table, and the final-status steps at the top. Keep the longer procedure in an optional `.github/skills/llm-gateway-routing-fallback-guardrails/SKILL.md`. Ask for the alias inventory before editing the walk.\n- **Claude Code:** `.claude/skills/llm-gateway-routing-fallback-guardrails/SKILL.md` holds the procedure. Add one `CLAUDE.md` fact: \"The LLM gateway resolves aliases to ordered targets, falls through only on retryable failures before any streamed token, leaves fallbackOnBadRequest off unless a target opts in, surfaces a final 400, 413, or 422, and returns 502 listing every attempt when the final target fails another way.\"\n- **Codex:** root `AGENTS.md` stays a short brief — The rule, the routing-table path, and the two-stub test command. The procedure lives in `SKILL.md`, or in a nested `AGENTS.md` beside the gateway module if the repo already uses nested briefs. Do not paste this whole skill into `AGENTS.md`.\n\n## Anti-patterns\n\n- Callers pass provider model ids and the gateway forwards them\n- A final 400, 413, or 422 is rewritten as 502, so the client retries a rejected request\n- An earlier 400 followed by a last 503 is returned as 503, or as that last upstream status, instead of 502 listing both attempts\n- Timeouts are answered with a blanket 504, or auth exhaustion with 503, instead of 502 listing every attempt\n- `fallbackOnBadRequest: true` on every target, so every malformed body is replayed everywhere\n- HTTP 400 and 422 increment the breaker, and one bad client opens the model for everyone\n- The HTTP client retries the POST and the gateway also walks fallbacks\n- The next provider opens after tokens were already flushed\n- A truncated stream is stored as success because the status was 200\n- One class full of `if (provider.equals(\"bedrock\"))` owns both routing and vendor payloads\n- API keys, or URLs that contain keys, sit in the routing YAML\n- Attempt logs or span attributes contain prompt or completion text\n- A health check sends a real user prompt to keep a target warm\n- Fallback picks a region outside the alias's residency allowlist\n- The target list cycles until the deadline expires\n\n## Checklist\n\n- [ ] Every caller-facing model name is an alias; each target names provider, model or deployment, region, and a secret reference\n- [ ] Strategy and sticky mode are set per alias, and the primary is not re-rolled during the walk\n- [ ] The walk is one pass, and the HTTP client does not also retry that attempt\n- [ ] Timeouts, 429, 5xx, and connection errors fall through. 400, 413, and 422 fall through only when that target's switch is true\n- [ ] 401, 403, and deployment-not-found continue the walk and mark the target unhealthy. When one of them is the final failure, the caller gets 502 listing every attempt, not 503\n- [ ] Client 4xx does not open the breaker\n- [ ] A final 400, 413, or 422 is surfaced as that status. Any other final failure is 502 whose body lists every attempt, including an earlier 400 then a last 503, auth failures, and timeouts\n- [ ] Streams fall through only before the first flushed token. A mid-stream failure cancels the upstream and emits `stream_interrupted`\n- [ ] Each provider implements `LlmProviderAdapter`. Bedrock is not forced through the OpenAI-compatible adapter\n- [ ] Attempt spans share a correlation id and record provider, model, status, latency, tokens when known, and a reason from the fixed set\n- [ ] Default logs and traces omit raw prompts and completions\n- [ ] Two-stub tests cover fallback order, a 400 with the switch off, a preserved final 422, a 400 then 503 returned as 502 listing both attempts, timeouts and auth exhaustion returned as 502, and no mid-stream switch\n- [ ] Each attempt is visible to the cost and budget hook. This module does not own prices or inbound quotas\n\n## Copy-ready SKILL.md stub\n\n```markdown\n---\nname: llm-gateway-routing-fallback-guardrails\ndescription: Use when a Java or Spring LLM gateway routes chat or completions across Azure OpenAI, Bedrock, OpenRouter, Together, Modal, or other backends — alias to ordered targets, health-aware priority or weighted selection, fallback on timeout 429 5xx and connection errors, per-target fallbackOnBadRequest defaulting off for 400/413/422, a final 400/413/422 surfaced as that status and 502 listing every attempt when the final target fails another way, no mid-stream provider switch, one adapter per provider, per-attempt metrics, and two-stub tests.\n---\n\nFollow LLM Gateway Routing and Fallback Guardrails: callers name an alias, and the gateway walks that alias's eligible targets once. Fall through on timeout, 429, 5xx, connection errors, and auth or deployment-config failures. A 400, 413, or 422 stops the walk unless that target sets fallbackOnBadRequest, which defaults to false. Do not switch providers after the first streamed token; cancel and emit stream_interrupted. When the final target returns 400, 413, or 422, surface that status. When it fails another way, including an earlier 400 then a last 503, an auth failure, or a timeout, return 502 and list every attempt. Do not use 503 for that mixed walk or for auth exhaustion, and do not use a blanket 504 for timeouts. Keep provider SDKs behind adapters, keep secrets out of the routing table, log attempt metadata under one correlation id, and prove the walk with two provider stubs.\n```" } ] } From 0a203ca06c5c57fc69fedf6b6f558a9544416e14 Mon Sep 17 00:00:00 2001 From: Ramkumar Ethiraj <64294490+rmkr-dev@users.noreply.github.com> Date: Sat, 7 Nov 2026 05:21:42 +0000 Subject: [PATCH 2/2] Add prompt for multi-provider routing and fallback on an LLM gateway --- promptbook/prompts.json | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/promptbook/prompts.json b/promptbook/prompts.json index 5fbfea3..c4b1bbf 100644 --- a/promptbook/prompts.json +++ b/promptbook/prompts.json @@ -1022,6 +1022,26 @@ ], "formatNotes": "All three. Point the tool at `application.yml`/`application.properties` (`spring.cloud.azure.servicebus.*` or `spring.cloud.stream.servicebus.*`), the processor or listener classes, settlement code, any inbox migration, and the Bicep or ARM that creates the queue or subscription (lock duration, max delivery count, sessions, duplicate detection). Keep test harness conventions aligned with spring-boot-testcontainers. Copilot: azure-service-bus-consumer path instructions plus those files in agent mode. Claude Code: the azure-service-bus-consumer-reliability-guardrails skill plus the listener, config, and entity files. Codex: AGENTS.md Service Bus consumer section, then the diff.", "body": "Task: Harden the Azure Service Bus consumer(s) I specify so they are safe in production. Use PeekLock, make each handler idempotent under at-least-once delivery, and complete only after the side effect is durable. Abandon recoverable failures, dead-letter poison messages with a reason, and keep an owner on the dead-letter queue. Size locks, prefetch, and concurrency to real processing time, and make shutdown stop receiving without completing after a lost lock. Finish with a minimal diff I can open as a PR, plus tests for redelivery, dead-letter, and lock-lost.\n\nContext placeholders (fill from the repo or ask only if missing):\n- Service root / module: {{APP_PATH}}\n- Spring Boot / Spring Cloud Azure (or Stream binder) version: {{BOOT_VERSION}} (e.g. Boot 3.4 / Spring Cloud Azure 5.18 | unknown)\n- Listeners in scope: {{LISTENERS}} (bean or binding name → queue or topic, processor | manual receiver | JMS)\n- Entity: {{ENTITY}} (queue name, or topic + subscription; sessions on or off; partitioned or not)\n- Lock duration and renewal: {{LOCK_DURATION}} (entity lock, max-auto-lock-renew-duration, or \"unknown\")\n- Max delivery count: {{MAX_DELIVERY}} (entity setting, default 10 if unset)\n- Prefetch and concurrency: {{SIZING}} (prefetch-count, max-concurrent-calls, max-concurrent-sessions, replica / HPA range)\n- Side effects per handler: {{SIDE_EFFECTS}} (db-write | http-call | publish | email | none)\n- Dedupe key available: {{DEDUPE_KEY}} (MessageId | application property | business key | none | unknown)\n- Ordering requirement: {{ORDERING}} (per-key FIFO required | order irrelevant)\n- Client stack: {{CLIENT}} (Spring Cloud Azure processor | Spring Cloud Stream Service Bus binder | azure-messaging-servicebus processor | manual receiver)\n- Broker extras: {{BROKER}} (duplicate detection window | dead-letter on expiration | none | unknown)\n- Pain points: {{PAIN}} (duplicates | lost-messages | dlq-growth | lock-lost | stuck-active | none)\n\nRequirements:\n\n1. Inventory\n - Read {{APP_PATH}} build file, `application*.yml|properties` (`spring.cloud.azure.servicebus.*` and `spring.cloud.stream.servicebus.*`), every processor, `@ServiceBusListener` or binder consumer, and any hand-rolled `ServiceBusReceiverClient` loop\n - Record per listener: receive mode, auto-complete, who calls complete / abandon / deadLetter, prefetch, max concurrent calls, sessions, lock renewal, and what each side effect does\n - Find catch-all handlers that log and return, completes that run before the database commit, and any `ReceiveAndDelete`\n - Note IaC for {{ENTITY}}: lock duration, max delivery count, sessions required, duplicate detection, dead-letter on expiration. Note metrics, alerts, and where the namespace credential or connection string comes from\n\n2. Findings (rank by risk: non-idempotent side effects > ReceiveAndDelete or complete-before-commit or catch-and-complete > poison messages with no reason > unowned DLQ or blind replay > lock budget or prefetch > sessions versus ordering > shutdown > observability and tests > secrets in config)\n - Side effects with no dedupe key or inbox, so a redelivery double-charges, double-inserts, or double-sends\n - `RECEIVE_AND_DELETE` on work that cannot be lost, or complete (including auto-complete) before the side effect is durable\n - `catch (Exception)` that completes or returns normally, so a failure is settled as success\n - Manual `complete` while `auto-complete` is still true\n - No handler dead-letter for poison input, so messages sit until `MaxDeliveryCountExceeded` with no useful reason\n - No reader, owner, or alert on the `$deadletterqueue` sub-queue, or a replay that resends the same `MessageId` inside {{BROKER}} duplicate detection\n - `max-auto-lock-renew-duration` and {{LOCK_DURATION}} shorter than p99, or prefetch large enough that messages expire in the client buffer\n - Sessions missing where {{ORDERING}} is per-key FIFO, or sessions enabled while publishers omit `SessionId`\n - `replicas: 1` (or a hostname check) used as the duplicate fix\n - Shutdown timeout longer than the pod grace period, or a complete attempted after `MessageLockLost`\n - Connection strings in Git, ConfigMaps, or code; message bodies in logs or metric tags\n\n3. Fix — settlement\n - Set receive mode to PeekLock on every listener in {{LISTENERS}} that has a side effect. Leave receive-and-delete only where the team has written down that loss is acceptable\n - For {{CLIENT}}, turn `auto-complete` off if the handler settles itself (`processor.auto-complete=false`, binding `consumer.auto-complete=false` plus the `Checkpointer`, or `disableAutoComplete()`). If auto-complete stays on, the method must commit before it returns and must not swallow exceptions\n - Complete only after the side-effect transaction commits. Abandon on recoverable failures. Dead-letter poison failures with `DeadLetterReason` and a short `DeadLetterErrorDescription` (a code, not the payload)\n - On `MESSAGE_LOCK_LOST` or `SESSION_LOCK_LOST`, return without complete, abandon, or dead-letter\n\n4. Fix — idempotency\n - For each handler in {{SIDE_EFFECTS}}, use {{DEDUPE_KEY}} (or propose one). Add an inbox table with a unique `(consumer, message_id)` constraint, written in the same database transaction as the side effect, or an upsert on the business key\n - A conflict means the work is already durable: complete and skip\n - Route outbound events through an outbox in that same transaction. Do not treat broker duplicate detection as the consumer lock; it only collapses duplicate sends\n\n5. Fix — retry and DLQ\n - Keep {{MAX_DELIVERY}} as the backstop for abandons and expired locks. Dead-letter classified poison on the first attempt so the reason is yours, not only `MaxDeliveryCountExceeded`\n - Add a DLQ reader (processor `sub-queue` = dead-letter sub-queue, SDK `SubQueue.DEAD_LETTER_QUEUE`) that records reason, message id, and delivery count. It alerts; it does not auto-replay\n - Document replay: read `DeadLetterReason` first. If {{BROKER}} has duplicate detection, resend under a new `MessageId` and keep the original id in an application property the inbox already uses\n\n6. Fix — sizing\n - From {{LOCK_DURATION}} and measured p99, set the entity lock above a normal attempt (it cannot exceed five minutes) and `max-auto-lock-renew-duration` above p99 plus downstream waits. Do not park the lock at five minutes to avoid renewal\n - Set `prefetch-count` to 0 for slow handlers, or a small multiple of `max-concurrent-calls` once lock-lost stays flat\n - Set `max-concurrent-calls` so {{SIZING}} replicas times in-flight handlers fit CPU and the connection pool. With sessions, that limit is per session; set `max-concurrent-sessions` and a `session-idle-timeout` above a normal handler\n - Enable sessions only when {{ORDERING}} is per-key FIFO. Otherwise competing consumers on {{ENTITY}}. Remove any `replicas: 1` workaround\n\n7. Fix — shutdown, metrics, credentials\n - Stop the processor before waiting for in-flight callbacks. Keep `spring.lifecycle.timeout-per-shutdown-phase` and the client close timeout under `terminationGracePeriodSeconds` minus preStop. Do not complete after the lock is lost\n - Export handler latency and counters for complete, abandon, dead-letter, lock-lost, and dedupe hits, with tags limited to entity, subscription, and outcome. Note the Azure Monitor alerts to add: dead-letter count rising, active count high while complete rate is flat\n - Namespace plus workload-identity or another `TokenCredential`. Any remaining connection string comes from Key Vault or a secret, referenced by placeholder. Log message id, delivery count, and outcome, never the body\n\n8. Tests\n - Unit tests with a fake settlement context: same message twice → one side effect and a second complete; poison → `deadLetter` with the expected reason and no complete; lock-lost mid-handler → no settlement; a commit followed by lock-lost → the next delivery is an inbox no-op\n - One integration test on the Service Bus emulator via Testcontainers (or the emulator container) for peek-lock complete, abandon then redelivery, and a message on the dead-letter sub-queue. No shared namespace. Awaitility, no fixed sleeps\n - Call out emulator gaps (sessions, duplicate detection, partitioning) instead of pretending the emulator is Premium\n\n9. Verification and the PR diff\n - Settlement table: exception or outcome → complete / abandon / dead-letter / stop\n - Entity table: {{ENTITY}} lock duration, max delivery count, sessions, duplicate detection, DLQ owner\n - Lock budget: p99, entity lock, renewal duration, prefetch, concurrency times replicas\n - Metrics and alerts list, and confirmation that no connection string or body appears in config, logs, or tags\n - The diff stays minimal: extend the existing processor or binding, the inbox migration, and the tests. No second client stack and no new messaging framework\n\nConstraints:\n- Minimal diff. Do not replace a working processor with a hand-rolled receive loop, or a receive loop with a new framework, unless the current loop cannot settle safely.\n- Do not invent namespace names, entity names, lock durations, or delivery counts. Use placeholders when {{LOCK_DURATION}} or {{MAX_DELIVERY}} is unknown, and list what to measure.\n- Do not claim exactly-once. Duplicate detection and an inbox are different tools; the handler still has to be idempotent.\n- Do not fix duplicates with `replicas: 1`.\n- Optimize for GitHub Copilot, Claude Code, and Codex: concrete diffs and a checklist.\n- Leave entity changes and alert rules as follow-up notes unless the repo already manages that IaC.\n\nOutput format:\n1. Findings table: severity | location | issue | fix\n2. Patch (receive mode and auto-complete, settlement changes, inbox migration, DLQ reader or runbook note, sizing, shutdown, metrics)\n3. Tests added and their results\n4. Settlement table, entity table, lock-budget math, and follow-ups (alerts, replay runbook, emulator gaps)\n\nStart from {{APP_PATH}}. Fix non-idempotent side effects and complete-before-commit before tuning prefetch or metrics." + }, + { + "id": "add-llm-gateway-routing-fallback", + "title": "Add Multi-Provider Routing and Fallback to an LLM Gateway", + "whenToUse": "Add or repair multi-provider routing in an LLM gateway: inventory aliases and adapters, install a priority or weighted target list with health and residency filters, fall through only on retryable failures, keep fallbackOnBadRequest off unless a target opts in, surface a final 400, 413, or 422, and return 502 listing every attempt when the final target fails another way (an earlier 400 then a last 503, auth failures, or a timeout) instead of 503 or a blanket 504, forbid mid-stream provider switches, and deliver the routing diff, two-stub tests, and rollout notes.", + "tools": [ + "copilot", + "claude-code", + "codex" + ], + "tags": [ + "llm", + "gateway", + "routing", + "fallback", + "spring-boot", + "reliability" + ], + "formatNotes": "All three. Point the tool at the gateway module, router and adapter classes (`**/*Router*.java`, `**/*Gateway*.java`, `**/*Adapter*.java`, `**/llm/gateway/**`), the routing config, and the existing HTTP client and breaker setup. Copilot: llm-gateway-routing path instructions plus those files in agent mode (or save the prompt as `.github/prompts/add-llm-gateway-routing-fallback.prompt.md`). Claude Code: the llm-gateway-routing-fallback-guardrails skill plus the router, adapter, and config files. Codex: the AGENTS.md LLM gateway routing section, then the diff. Leave cost tables, inbound rate limits, idempotency storage, and prompt-injection filters to their own skills.", + "body": "Task: Add multi-provider routing and fallback to the LLM gateway I specify. Callers should name an alias. The gateway walks that alias's ordered targets, falls through only on retryable failures before any response bytes are committed, keeps per-target fallbackOnBadRequest off unless a target opts in. When the final target returns 400, 413, or 422, return that status. When the final target fails another way, return 502 and list every attempt, including an earlier 400 then a last 503, auth failures, and timeouts. Do not use 503 for that mixed walk or for auth exhaustion, and do not use 504 for timeouts. Finish with an inventory, a config and code diff, two-provider tests, and rollout notes.\n\nContext placeholders (fill from the repo or ask only if missing):\n- Gateway name and module: {{GATEWAY_NAME}} at {{APP_PATH}}\n- Stack: {{STACK}} (Spring Boot version; Spring AI | LangChain4j | plain HTTP adapters | mixed)\n- Providers: {{PROVIDERS}} (e.g. Azure OpenAI deployments, Amazon Bedrock, OpenRouter, Together, Modal, other OpenAI-compatible base URLs)\n- Aliases: {{ALIASES}} (alias → current model or deployment, and the intended primary then fallbacks)\n- Strategy and stickiness: {{STRATEGY}} (priority | weighted) and {{STICKY}} (none | session, plus the session key and window)\n- Streaming: {{STREAMING}} (yes | no | mixed per alias)\n- Latency SLO and hard deadline: {{SLO}} (e.g. p95 8s, deadline 10s per alias)\n- Residency allowlist: {{RESIDENCY}} (regions each alias may call, or \"unrestricted\")\n- Observability stack: {{OBSERVABILITY}} (Micrometer/Prometheus | OpenTelemetry | both; correlation-id header name)\n- Bad-request fallback: {{BAD_REQUEST_FALLBACK}} (which target ids may set fallbackOnBadRequest, or \"none\")\n- Pain: {{PAIN}} (single-region outage | 400s returned as 502 | mid-stream model switch | no metrics | none)\n\nRequirements:\n\n1. Inventory\n - Read {{APP_PATH}}: routing or model config, gateway filter or controller, each provider client, retry and breaker config, and call sites that pass a raw model id\n - Table: alias or call site | provider | model or deployment | region | streaming | retry today | breaker today | secret source\n - Flag raw model ids outside the table, retries on the HTTP client and inside the gateway, 400s counted as breaker failures, and logs that store prompts or completions\n\n2. Routing table and selection\n - One alias per caller-facing model name. Each target has id, provider, model or deployment, region, secretRef, priority or weight, capabilities, minAttemptBudget, and fallbackOnBadRequest (default false)\n - {{STRATEGY}} for primary selection. Fallback order is fixed at the start of the request. Weighted choice is a pure function of the eligible set and a stable key\n - {{STICKY}}: per request, or pin the target that last succeeded for the session key. A failed target is not pinned. Sticky does not override health, {{RESIDENCY}}, or capabilities\n - Skip ineligible targets before HTTP: disabled, open breaker (except the half-open probe), missing capability, region outside {{RESIDENCY}}, remaining deadline below minAttemptBudget\n - One pass. Attempt cap equals the eligible list. Turn off HTTP-client retries for this POST so only the walk retries\n\n3. Failure classes\n - Adapters map vendor errors to timeout, rate_limit, upstream_5xx, connection, client_rejection (400/413/422), auth_config (401/403/deployment 404), or cancelled\n - Fall through on timeout, 429 (honor Retry-After only when it fits the remaining deadline; wait at most once on the last target), 5xx, connection, and auth_config\n - Client rejection falls through only when that target's fallbackOnBadRequest is true. {{BAD_REQUEST_FALLBACK}} is the only place the flag may be true\n - Client rejection does not increment breaker failures. Auth_config and upstream 5xx do. A 429 applies a short cooldown, not a long open\n - Capability gaps skip the target with reason capability_skip and never become a synthetic upstream 400\n\n4. Status when every target fails\n - fallbackOnBadRequest defaults off and covers only 400, 413, and 422\n - No attempt: 422 no_capable_target, or 503 no_eligible_target when the cause is health or deadline. Empty attempt list. These are not a failed upstream call\n - Final target returned 400, 413, or 422: surface that status. A 503 followed by a final 422 stays 422. Do not wrap it in 502\n - Final target failed another way (timeout, 429, 5xx, connection, or auth/config): return 502. The body lists every attempt in order, including an earlier 400 and the last 503, each auth status (401, 403, deployment 404), and each timeout. Do not return 503 for that mixed walk, 503 for auth exhaustion, or a blanket 504 for timeouts\n - Problem+json for the 502 carries code upstream_failed, alias, and attempts (target id, failure class, HTTP status when one exists). A surfaced 400, 413, or 422 carries the client-rejection code and that HTTP status. Do not copy the upstream error document\n\n5. Streaming ({{STREAMING}})\n - Flush no model bytes to the caller until the first token, so a pre-commit failure can still fall through\n - After the first flushed token, cancel the upstream, emit a terminal error (SSE event: error with code stream_interrupted, alias, and attempt), and do not call the next provider\n - On caller disconnect, cancel the upstream and stop the walk\n - Non-streaming calls stay buffered until the attempt settles so the status rules in section 4 still apply\n\n6. Adapters, secrets, deadlines\n - One LlmProviderAdapter per provider family. OpenAI-compatible backends (Azure OpenAI, OpenRouter, Together, Modal, and similar) may share one HTTP adapter parameterized by base URL, header style, API version, and deployment-versus-model path. Bedrock is its own adapter\n - The router has no vendor SDK imports and no provider-name branches\n - secretRef only in config. Load values from env or Key Vault. Fail startup when a base URL contains a key\n - Per-attempt read timeout is the remaining {{SLO}} deadline. Skip a target that cannot fit minAttemptBudget\n\n7. Budgets and observability ({{OBSERVABILITY}})\n - Child span per attempt under the inbound trace. One correlation id on every attempt log\n - Metrics: attempt latency histogram, attempt counter, fallback counter, response status-class counter. Labels stay within alias, provider, configured model, outcome, failure_class, reason, status_class\n - Pass every attempt, including failures, to the existing cost and budget hook before the next target starts. Do not add a price table or a quota ledger in this change\n - Alert notes (as code or as rollout notes): fallback-rate climb, any auth_config, no_eligible_target\n\n8. Safety\n - Attempt logs and spans omit raw prompts and completions. Leave a debug switch off in production config\n - Do not add a redaction engine or a prompt-injection filter here. Note the upstream component that should own redaction\n - Targets stay an allowlist. Ignore provider, region, and credential fields on the inbound body\n\n9. Tests\n - Pure walk tests on a fake adapter, plus two HTTP stubs (WireMock, MockWebServer, or Testcontainers) and no live cloud account\n - Cover: fallback order on 503 then 200; 400 with the switch off leaves the second stub at zero requests; 400 with the switch on reaches the second target; a final 422 after a 503 stays 422; 429 then 400 returns 400; 400 with the switch on then 503 returns 502 listing both attempts; both timeouts return 502 listing both attempts; 401 then 403 returns 502 listing both auth statuses; both 503s return 502 listing both attempts; tools request skips a target that lacks tools; stream reset before the first token uses the second provider; two flushed tokens then a reset emit stream_interrupted and do not call the second provider; one pass means one request per stub; correlation id matches across attempts\n - Assert the problem body does not contain the prompt fixture\n\n10. Rollout\n - Ship the table with the current single target first if {{GATEWAY_NAME}} is already in production, and log the target the walk would pick\n - Enable the second target on one alias. Watch fallback rate, 4xx versus 5xx, and auth_config for a bounded window before widening\n - Rollback is removing the spare target from the alias, or disabling it, without a code revert\n - Call out any alias where {{BAD_REQUEST_FALLBACK}} is on, and why a 400 from that model is model-specific\n\nConstraints:\n- Minimal diff. Match the module's config style and test style. No new resilience library when one is already on the classpath.\n- No secrets, live endpoints, or key-bearing URLs in git or in test fixtures.\n- Do not weaken deadlines to make tests pass. Drive timeouts with the stub.\n- Leave price tables, inbound rate limits, Idempotency-Key storage, HTTP pool sizing, and prompt-injection filters to their existing skills. Wire hooks where this walk depends on them.\n- Copilot, Claude Code, and Codex: concrete diffs, the inventory table, and a checklist. Do not paste this prompt into AGENTS.md.\n\nOutput format:\n1. Inventory table and flagged call sites\n2. Config and code diff (routing table, router walk, adapter interface, status mapping, streaming commit, metrics)\n3. Tests added and what each asserts\n4. Rollout notes: enable order, dashboards, rollback, and any fallbackOnBadRequest exceptions\n\nStart from {{APP_PATH}}. Classify failures, surface a final 400, 413, or 422, and return 502 listing every attempt when the final target fails another way, before adding a second provider or a weighted policy." } ] }