Skip to content

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 200 with a valid ClassifyResponse means every requested check ran to completion. Even then, decision: "no_findings" means completed checks did not flag the submitted string — never safe, allow, or block. ANANZI never maps an incomplete detector onto an empty finding list and never invents synthetic review findings when inspection did not run.
  • Zero partial findings on multi-check calls: A request asking for checks: ["prompt_injection", "secrets"] fails atomically with HTTP 503 (error: "detector_failed") and returns zero partial findings whenever prompt_injection cannot complete. By contrast, checks: ["secrets"] alone runs deterministic SecretsScanner (secrets-rules version mvp-0) without touching inference.
  • Released usage reservations (ADR 0009): POST /v1/inspect reserves monthly units before dispatching detectors and immediately calls usage::release on any detector error, setting the usage_events row to status: "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 BlockingPool and permit retention: Concurrent tokio::task::spawn_blocking tasks are capped at MODEL_SESSION_POOL_SIZE (default 1, API maximum 4 CPU sessions), with optional async queue depth MODEL_MAX_IN_FLIGHT - MODEL_SESSION_POOL_SIZE (default 0), async queue wait MODEL_QUEUE_TIMEOUT_MS (0.5-second default when queueing is enabled), and per-call execution bound MODEL_INFERENCE_TIMEOUT_MS (2-second default). Startup validates that queue plus execution bounds stay strictly inside the 3-second HTTP timeout_request ceiling so the handler normally releases the usage hold and returns JSON ErrorBody before middleware timeout; the middleware can still answer 408 first, and the ledger expiry rule then covers any remaining reservation. A RAII PermitGuard moves 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. BlockingPool also 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 receive InferenceError::TimedOut instead of Saturated so the circuit breaker still trips open even when session_pool_size is smaller than failure_threshold.
  • Failure classification in Closed: CircuitBreakerEngine runs independently per process (no Redis). Consecutive engine or timeout failures (TimedOut, ExecutionFailed, Unavailable, LoadFailed, ChecksumMismatch, InvalidConfig) trip Closed to Open at MODEL_BREAKER_FAILURE_THRESHOLD (default 5), while any Ok resets the failure streak. Normal backpressure (Saturated) and per-input TokenizationFailed errors do not trip Closed, preventing brief traffic bursts or malformed single-tenant inputs from causing a process-wide cooldown outage.
  • Fast-fail Open, single-probe HalfOpen, and generation fencing: During MODEL_BREAKER_OPEN_MS (30-second default cooldown), calls fail fast with InferenceError::CircuitOpen without entering spawn_blocking. Once cooldown elapses, HalfOpen admits a single recovery probe (HalfOpenProbeGuard clears probe_in_flight if cancelled) while concurrent callers still receive CircuitOpen. In HalfOpen, TokenizationFailed releases the probe slot without re-opening, any other probe failure re-opens Open immediately, and MODEL_BREAKER_SUCCESS_THRESHOLD (default 1) consecutive probe successes return the breaker to Closed. A monotonic generation counter fences stale completions from earlier epochs.
  • Frozen v1 wire contract (ADR 0014): Saturation, timeouts, unloaded models, and open breakers all map to HTTP 503 and error: "detector_failed" without changing openapi/openapi.json or 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:

  1. Hold content closed on every non-200 status or client timeout, and branch on status plus ErrorBody.error: ErrorBody.message is diagnostic text for humans, not a frozen client contract. Treat 503 detector_failed, 429 rate_limited, 429 quota_exceeded, 409 idempotency_in_progress, untyped middleware or proxy timeouts (err.body === null in AnanziError), and client network aborts as uninspected text.
  2. 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.
  3. Decouple deterministic secrets scanning when appropriate: Because multi-check calls fail with zero partial findings when prompt_injection is unavailable, send checks: ["secrets"] separately if credential-pattern checks (secrets-rules version mvp-0) must continue while holding uninspected prompt-injection text closed.
  4. Reuse a stable Idempotency-Key per logical item with bounded, jittered backoff: Pass an explicit idempotencyKey per logical chunk (omitting it in @ananzi/sdk-ts mints 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 a released row in place without burning an extra slot only within the 60-second window of your organization’s usage_events attempt cap (ADR 0011 rule 3; after the window a retry counts as a new attempt; concurrent retries while an attempt is still reserved return 409 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 review or no_findings on 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-rules version mvp-0 and pinned ONNX model_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/, provenance ananzi-authored-2026-11). Optional source="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_injection latency 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 in prompt_injection_truncated, 4,096-byte content, 32 KiB HTTP body, 3-second request timeout, 2-second default inference execution bound and 0.5-second default queue wait; ADR 0040) were chosen, not measured, and act as fail-closed safety guards rather than latency SLAs. The 30-second default circuit-breaker cooldown is likewise a guard.

Sources and further reading

External security and resilience references:

ANANZI architecture decisions, error schema, and SDK 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.