Technical article Fail-closed · HTTP 503 Pre-MVP · ADR 0028
How to handle detector timeouts without silently trusting content
When an inspection call times out, hits pool backpressure, or meets
an open circuit breaker, the untrusted document or tool output has
not been cleared — inspection did not complete. Swallowing that
error in a catch block silently feeds uninspected text
into your model prompt. ANANZI returns explicit
HTTP 503 (error="detector_failed") rather
than no_findings, and your application decides how to
omit, quarantine, or escalate the text. Detection, not prevention.
Scope notice: Serving clearance remains refused under ADR 0028
(#117) and policy thresholds remain open (#142). On the default
unconfigured pre-MVP build (MODEL_* unset),
prompt_injection runs
UnloadedPromptInjection and fails closed
(HTTP 503, error="detector_failed"), while
deterministic secrets (secrets-rules
version mvp-0) runs live. Optional
source="tool_description" inspection (ADR 0025 / #230)
and research-stage jailbreak checks are Experimental, not launch
checks. The published latency figure is a target, not an SLA (ADR 0039).
Why fail-open timeout handlers silently trust untrusted text
Retrieval pipelines and agent loops often wrap external security
checks in a defensive try / catch so an upstream outage
cannot crash a user request. The subtle failure happens on the line
after catch: if execution falls through to prompt
assembly, every network timeout, saturated worker pool, or open
circuit breaker becomes equivalent to “clean input” — precisely when
an attacker or a degraded runtime is most likely to trigger slow or
failing requests.
- Separate completion from findings (ADR 0005):
Only
HTTP 200with a validClassifyResponsemeans every requested check ran to completion. Even then,decision: "no_findings"means completed checks did not flag the submitted string — neversafe,allow, orblock. ANANZI never maps an incomplete detector onto an empty finding list and never invents syntheticreviewfindings when inspection did not run. - Zero partial findings on multi-check calls: A
request asking for
checks: ["prompt_injection", "secrets"]fails atomically withHTTP 503(error: "detector_failed") and returns zero partial findings wheneverprompt_injectioncannot complete. By contrast,checks: ["secrets"]alone runs deterministicSecretsScanner(secrets-rulesversionmvp-0) without touching inference. - Released usage reservations (ADR 0009):
POST /v1/inspectreserves monthly units before dispatching detectors and immediately callsusage::releaseon any detector error, setting theusage_eventsrow tostatus: "released"so failed inspections never debit your monthly unit allowance.
// Anti-pattern — NEVER map timeouts or HTTP 503 onto no_findings / trusted
try {
const res = await client.inspect(
{ content: chunkText, source: "retrieved_document", checks: ["prompt_injection"] },
{ idempotencyKey: chunkKey },
);
if (res.decision === "review") return holdForReview(chunkText, res.findings);
} catch {
// BUG: 503 detector_failed or network timeout falls through as if clean!
}
return includeInPrompt(chunkText);
// Fail-closed caller pattern — hold content closed on EVERY non-200 or transport error
try {
const res = await client.inspect(
{ content: chunkText, source: "retrieved_document", checks: ["prompt_injection"] },
{ idempotencyKey: chunkKey }, // stable per logical chunk; reuse on bounded retry
);
if (res.decision === "review") {
return holdForReview(chunkText, res.findings);
}
// decision === "no_findings": completed checks did not flag (not a safety guarantee)
return includeInPromptWithHostControls(chunkText);
} catch (err) {
const retryable =
err instanceof AnanziError
? err.status === 503 || (err.status === 429 && err.body?.error === "rate_limited")
: true; // client transport timeout or abort
return handleUnavailableInspection(chunkText, { err, retryable });
}
Inside ANANZI’s bounded pool and circuit-breaker failure path (ADR 0034)
When a SHA-256-verified ONNX model and tokenizer bundle is
configured at server startup (ADR 0033
and
ADR 0034
/ #143), PromptInjectionDetector executes CPU-only ONNX
Runtime sessions inside a bounded BlockingPool and
SessionPool wrapped by a process-local, three-state
CircuitBreakerEngine:
- Bounded
BlockingPooland permit retention: Concurrenttokio::task::spawn_blockingtasks are capped atMODEL_SESSION_POOL_SIZE(default1, API maximum4CPU sessions), with optional async queue depthMODEL_MAX_IN_FLIGHT - MODEL_SESSION_POOL_SIZE(default0), async queue waitMODEL_QUEUE_TIMEOUT_MS(0.5-second default when queueing is enabled), and per-call execution boundMODEL_INFERENCE_TIMEOUT_MS(2-second default). Startup validates that queue plus execution bounds stay strictly inside the3-second HTTPtimeout_requestceiling so the handler normally releases the usage hold and returns JSONErrorBodybefore middleware timeout; the middleware can still answer 408 first, and the ledger expiry rule then covers any remaining reservation. A RAIIPermitGuardmoves into the blocking closure so cancelled or timed-out requests never release a worker slot until the OS thread actually exits. - Zombie-timeout tracking for wedged workers: Under
healthy burst load, an unavailable pool slot or expired queue wait
returns
InferenceError::Saturated.BlockingPoolalso tracks timed-out tasks still running in FFI (timed_out_in_flight): when every concurrent execution slot is occupied by wedged timed-out workers, subsequent callers receiveInferenceError::TimedOutinstead ofSaturatedso the circuit breaker still trips open even whensession_pool_sizeis smaller thanfailure_threshold. - Failure classification in
Closed:CircuitBreakerEngineruns independently per process (no Redis). Consecutive engine or timeout failures (TimedOut,ExecutionFailed,Unavailable,LoadFailed,ChecksumMismatch,InvalidConfig) tripClosedtoOpenatMODEL_BREAKER_FAILURE_THRESHOLD(default5), while anyOkresets the failure streak. Normal backpressure (Saturated) and per-inputTokenizationFailederrors do not tripClosed, preventing brief traffic bursts or malformed single-tenant inputs from causing a process-wide cooldown outage. - Fast-fail
Open, single-probeHalfOpen, and generation fencing: DuringMODEL_BREAKER_OPEN_MS(30-second default cooldown), calls fail fast withInferenceError::CircuitOpenwithout enteringspawn_blocking. Once cooldown elapses,HalfOpenadmits a single recovery probe (HalfOpenProbeGuardclearsprobe_in_flightif cancelled) while concurrent callers still receiveCircuitOpen. InHalfOpen,TokenizationFailedreleases the probe slot without re-opening, any other probe failure re-opensOpenimmediately, andMODEL_BREAKER_SUCCESS_THRESHOLD(default1) consecutive probe successes return the breaker toClosed. A monotonicgenerationcounter fences stale completions from earlier epochs. - Frozen v1 wire contract (ADR 0014): Saturation,
timeouts, unloaded models, and open breakers all map to
HTTP 503anderror: "detector_failed"without changingopenapi/openapi.jsonor echoing submitted prompt text.
POST /v1/inspect HTTP/1.1
Authorization: Bearer <ANANZI_API_KEY>
Idempotency-Key: article-timeout-rag-1
Content-Type: application/json
{
"content": "Quarterly vendor FAQ: contact billing-ops@example.com for invoice copies.",
"source": "retrieved_document",
"checks": ["prompt_injection", "secrets"]
}
# Case A — Unloaded model (default pre-MVP build), execution timeout, or runtime failure:
# HTTP 503 Service Unavailable (usage hold released; zero partial findings)
{
"request_id": "req_…",
"error": "detector_failed",
"message": "check failed to complete: prompt_injection"
}
# Case B — Healthy pool at capacity or async queue wait expired:
# HTTP 503 Service Unavailable (does NOT trip Closed circuit breaker)
{
"request_id": "req_…",
"error": "detector_failed",
"message": "check failed to complete: prompt_injection (inference saturated)"
}
# Case C — Circuit breaker Open (or HalfOpen probe already in flight):
# HTTP 503 Service Unavailable (fails fast before spawn_blocking)
{
"request_id": "req_…",
"error": "detector_failed",
"message": "check failed to complete: prompt_injection (circuit breaker open)"
}
Readiness probes (degraded vs. not_ready) and caller fallback patterns
Container platforms use GET /health/ready to decide
when to restart a replica. In crates/inference,
SessionLease marks both Ok and normal
Err runs completed so ONNX sessions return cleanly to
SessionPool; only an unwinding panic inside FFI drops
the lease uncompleted, permanently marks the pool poisoned
(!engine.is_healthy()), and flips
/health/ready to HTTP 503
(status: "not_ready",
inference: "unhealthy") so the platform replaces the
wedged container. Transient Open and
HalfOpen circuit-breaker states instead report
HTTP 200 with status: "degraded" — never
falsely claiming "loaded" before a probe succeeds, and
avoiding cold restarts that would disrupt healthy
secrets, API-key, usage, and billing routes on a
single-replica service:
# 1. Default pre-MVP boot (MODEL_* unset — secrets-rules live, prompt_injection fails closed)
# HTTP 200 OK
{ "status": "ready", "inference": "not_loaded", "detector": "secrets-rules" }
# 2. Verified model loaded & circuit breaker Closed
# HTTP 200 OK
{ "status": "ready", "inference": "loaded", "detector": "<MODEL_ID>" }
# 3. Transient circuit-breaker cooldown or single-probe recovery (no container restart)
# HTTP 200 OK
{ "status": "degraded", "inference": "circuit_open", "detector": "<MODEL_ID>" }
{ "status": "degraded", "inference": "half_open", "detector": "<MODEL_ID>" }
# 4. Permanently poisoned ONNX session pool (triggers container restart)
# HTTP 503 Service Unavailable
{ "status": "not_ready", "inference": "unhealthy", "detector": "<MODEL_ID>" }
When wiring POST /v1/inspect into your own retrieval or
agent runtime, follow four fail-closed rules:
- Hold content closed on every non-200 status or client timeout, and branch on status plus
ErrorBody.error:ErrorBody.messageis diagnostic text for humans, not a frozen client contract. Treat503 detector_failed,429 rate_limited,429 quota_exceeded,409 idempotency_in_progress, untyped middleware or proxy timeouts (err.body === nullinAnanziError), and client network aborts as uninspected text. - Pick an explicit degraded-mode policy per workflow:
In RAG pipelines (
source="retrieved_document"), omit uninspected chunks from LLM context or render source links without model synthesis. In agent loops (source="tool_output"), pause for human confirmation or abort the untrusted step while keeping deterministic tool allowlists and argument schemas enforced in host code. - Decouple deterministic
secretsscanning when appropriate: Because multi-check calls fail with zero partial findings whenprompt_injectionis unavailable, sendchecks: ["secrets"]separately if credential-pattern checks (secrets-rulesversionmvp-0) must continue while holding uninspected prompt-injection text closed. - Reuse a stable
Idempotency-Keyper logical item with bounded, jittered backoff: Pass an explicitidempotencyKeyper logical chunk (omitting it in@ananzi/sdk-tsmints a new UUID per call) and reuse that key when retrying after the prior attempt finishes. Reusing the key replays without a second unit charge if a client timeout raced a server commit (ADR 0009) and re-reserves areleasedrow in place without burning an extra slot only within the 60-second window of your organization’susage_eventsattempt cap (ADR 0011 rule 3; after the window a retry counts as a new attempt; concurrent retries while an attempt is stillreservedreturn409 idempotency_in_progress). Avoid tight retry loops during cooldown, as each fail-fast rejection still executes a reserve/release database pair (ADR 0034). Runnable TypeScript (@ananzi/sdk-ts) and Python (ananzi) demos live in examples/ on GitHub (in-repo packages, not registry-published).
Brand limits, model provenance, and the latency target
- Detection, not prevention: ANANZI returns
revieworno_findingson completed checks. Your application owns timeout budgets, chunk omission, fallback UX, tool authorization, and runtime enforcement. - Static, versioned stack — no continuous learning:
ANANZI serves static, versioned detectors
(
secrets-rulesversionmvp-0and pinned ONNXmodel_version) and does not continuously learn from customer traffic or update weights on live requests. (“The web that learns” is long-term brand direction, not current runtime behavior.) Submitted inspection text and findings are not retained as customer data; see Privacy. - Experimental checks and model provenance: Serving
clearance remains refused under
ADR 0028
(#117), policy thresholds remain open (#142), and no model weights
are stored in Git or baked into the container image. Two
Apache-2.0 classifier candidates, one CC-BY-NC-4.0 research-only
comparator (
sdmlai/cyber-jev), and one conditional entry (meta-llama/Llama-Prompt-Guard-2-22M, #321; not yet on the evaluation set, license unread, no weights downloaded, decision pending in #320) are recorded in models/candidates.md and models/manifests/ for evaluation against the independent hand-authored corpus (eval/corpus/, provenanceananzi-authored-2026-11). Optionalsource="tool_description"inspection (ADR 0025 / #230; see Scanning agent tool descriptions) is Experimental text-only plumbing rather than a launch check, and jailbreak classification remains research-only. - Latency is a target, not an SLA: ANANZI publishes a
prompt_injectionlatency target of p50 at most 100 ms and p95 at most 500 ms (warm, one request in flight, on a local Apple M2 container basis, tokenization and inference only; ADR 0039). It is unmeasured at 512 tokens, has no p99 or cold-start target, and is not a guarantee. The published limits (512-token model context, with longer text truncated and reported inprompt_injection_truncated, 4,096-bytecontent, 32 KiB HTTP body,3-second request timeout,2-second default inference execution bound and0.5-second default queue wait; ADR 0040) were chosen, not measured, and act as fail-closed safety guards rather than latency SLAs. The30-second default circuit-breaker cooldown is likewise a guard.
Sources and further reading
External security and resilience references:
- OWASP Top 10 for LLM Applications — LLM01 Prompt Injection
- UK NCSC — Mistaking AI prompt injection could lead to large-scale breaches
- Martin Fowler — CircuitBreaker (pattern popularized in Michael Nygard’s Release It!)
- Tokio — task::spawn_blocking execution and cancellation behavior
ANANZI architecture decisions, error schema, and SDK demos:
- ADR 0005 — Detector completion failure must not become no_findings
- ADR 0014 — Freeze the versioned public inspect API
- ADR 0033 — Real prompt-injection detector wired through InferenceEngine
- ADR 0034 — Bounded spawn_blocking inference pool and process-local circuit breaker
- docs/errors.md — ErrorBody, HTTP statuses, and transport limits
- examples/ — TypeScript and Python SDK inspect demos
Article: scanning agent tool descriptions · RAG use case · Agents use case · prompt_injection product page · secrets product page · Security · Privacy · Local docs live in apps/docs (Starlight). Deploy is tracked separately.