Core Concepts

The Match Cascade

In ordinary MOCK HTTP serving, the proxy selects among eligible stored responses, configured stateful behavior and prepared generated responses. Routing, admission, faults and episode rules can answer or refuse before that selection. Inspect the serving source separately from any background model work.

Separate the serving answer from generation

Ordinary HTTP generated-response serving reads prepared content from cache. A missing eligible cache entry can enqueue background generation without supplying the current response. Another admitted prepared source may still answer; otherwise the configured miss response is returned.

The worker uses a bounded queue. Enqueue, generation and cache admission can fail or be refused, so a miss does not promise a hit on the next request. Eligible smart-swap answers can also trigger background comparison and generation; model work is not confined to requests that exhaust the serving sources.

What to inspect

Record which source answered, whether background work was admitted and whether a later request actually used an eligible prepared response. These are distinct findings. They do not establish latency, complete coverage or the correctness of the client's result.

Generation depends on enabled features and request eligibility. See the inference-server reference for the inference-server details.

Eligible ordinary HTTP sources, in order

These rows describe ordinary MOCK HTTP source selection where each source is eligible, after earlier routing, admission and fault handling. A source can be skipped or refused. Representative serving markers use an X-Ghost-* header and counted in the ghost_requests_total{match_type} metric.

Session-verbatim

Eligible active session

X-Ghost-Mock: session-verbatim

The active-session memory store retains admitted response bodies and session headers for replay to callers. An eligible body-matching session response is checked before the loaded exact library. This memory store is distinct from durable replay copies; a session hit does not establish retained-library coverage.

Exact library entry

Loaded response

X-Ghost-Mock: true

Lookup matches service, method, path/query and request body against the loaded library. Selected fields are served subject to applicable header and response behavior. Library entries may come from recordings or imports; the marker identifies the serving source, not proof of an upstream capture.

Resource and chart behavior

Existing scoped state

X-Ghost-Resource: true

A GET can read an existing service/episode-scoped resource by collection and ID. PATCH with an action, or POST to its action path, can advance a bound chart. Unhandled actions fall through or reject according to chart policy. Earlier recorded matches can answer before mutable state. Ordinary POST replay does not create arbitrary resources; episode creation is a separate opt-in.

Smart-swap

Effective smart_swap feature

X-Ghost-SwapMatch: true

A structurally matching recorded entry can supply a response for changed path parameters when the effective smart_swap capability permits it. Check the returned identity and relevant fields with a meaningful changed-request control. The structural answer can also trigger background model work.

Eligible generated cache

Enabled and admitted

X-Ghost-Generated: true

After smart swap, eligible cached responses can serve subject to authority, confidence and media checks. Cache identity includes method, URI, service, request body and adapter binding. Episode requests skip this volatile cache. A miss can enqueue background generation without supplying the current response.

Prepared generalized response

Separately admitted

X-Ghost-Generalized: true

A pinned generalized-response store can answer after the earlier eligible sources and before the final miss. Its admission is separate from the volatile generated cache; it is not an automatic authoring or coverage guarantee.

If no eligible source answers, X-Ghost-Miss: true marks the configured unmatched status and body, with match_type="miss". The default is 404 with a generic no-mock-found body. X-Gostly-Miss-Reason says why, and the default body (not a custom one) gains the same value as miss_reason: pending (a generation is queued; retry after Retry-After), no_generation_in_mode (an episode, or a plan without generation), media_unknown (nothing shows the route answers text), breaker_open (generation is paused), degraded (the last answer was dropped as degraded), below_threshold or unrecordable (a binary route). Inspect the uncovered request before deciding whether to record or seed more coverage.

Background generation and cache limits

The ordinary HTTP serving path reads prepared responses; generation work is requested through a bounded background queue. A submitted job and a later eligible cache hit are separate outcomes.

On the request

After smart swap, the eligible cache lookup includes method, URI, service, request body and adapter binding. A missing entry can request background work and continue toward another admitted prepared source or the configured miss. This does not reorder earlier serving sources.

Bounded queue

Enqueue is non-blocking. INFERENCE_PREWARM_QUEUE_CAPACITY defaults to 1024; when full, new jobs are dropped with a metric increment. Duplicate in-flight keys coalesce. Coalescing uses the full request key, including the body and adapter binding.

Background worker

The worker makes the inference HTTP call and records success/failure against the circuit breaker. Admitted output can populate the TTL- and LRU-bounded memory cache. Failure, rejection, expiry, eviction or dropped work can leave a later request without a usable entry.

The cache is ephemeral by design

The volatile generated-response cache lives in memory and does not persist across agent restarts. Its identity includes service and adapter binding as well as request inputs. A cold start has no promise of an immediate usable response; the separately admitted pinned store is a different source.

Full Compose routes response generation from ghost-inference to local ghost-llamacpp. Generated responses are cached; LoRA adapters are model files loaded by the backend. Live-mock training requires processing markers and other eligibility checks, not proof of complete sensitive-data removal. Separately configured API convention analysis can use OpenAI, Azure OpenAI or Bedrock; those providers are distinct from the local response-generation path.

For what a caller sees when testing a trained adapter (the first miss, smart swap, text types and dropped output), see Sending a request the adapter can answer.

Background shadow comparison

Smart swap serves before the AI cache. With AI enabled on Pro or Team, eligible smart-swap responses outside deterministic episodes also queue a background comparison against the AI cache. If that cache entry is absent, the worker can request generation for a later request. This work does not replace the smart-swap response already served.

GOSTLY_CASCADE_SHADOW defaults on. Passing 0, false or off to the proxy container disables this comparison and its generation requests for smart-swap matches; it does not disable ordinary AI-cache miss generation or change serving order. See configuration for Compose environment wiring.

What the cascade can serve — and what it can't

The cascade records and replays HTTP and HTTPS — HTTP/1.1 and HTTP/2 over TLS. Plain HTTP is served on :8080; the TLS-MITM listener binds on :8443 only when ENABLE_TLS_INTERCEPTION is set (tri-state: default off; true/lax; or strict). With interception on, GET /ca.crt serves the MITM CA for the per-OS trust-install step (it returns a 503 while interception is off).

Scope boundaries (honest about what's not replayed)

WebSocket frame capture is off by default. When explicitly enabled, it follows the service's traffic capture switch and retains frames for observability only; frames are not replayed through the cascade and their bodies are not scrubbed. See the TLS guide for configuration and capture limits. Webhook capture follows its own per-service switch; webhook replay is operator-triggered through the control-plane API, not auto-fired by the agent. There is no gRPC, async-messaging, or database mocking today — those are on the roadmap.

Two product behaviours are worth distinguishing from the cascade itself. Drift watches recorded responses against live traffic and emits drift events plus a 0–100 freshness score with a sparkline trend, so you know when a mock has gone stale. AI mock-repair turns drift into operator proposals you approve or reject; it is off by default (ENABLE_AI_MOCK_REPAIR) and never edits a mock without approval. Neither sits on the request hot path.

The cascade runs in MOCK mode — the other three modes

Ordinary source selection above applies in MOCK mode. A service override takes precedence over global mode; a global switch does not clear those overrides. The operating states are:

LEARN

Forwards eligible traffic to the configured upstream and captures supported exchanges. Capture is conditional and bounded; an upstream response does not establish durable coverage.

MOCK

Selects eligible loaded responses and configured behavior. An ordinary HTTP miss uses the configured local status/body rather than automatically fetching upstream. Admission, faults and episode rules can answer or refuse earlier.

PASSTHROUGH

Forwards eligible traffic without building the ordinary recorded library. Use it when the test requires current upstream behavior.

TRANSITIONING

An internal state during library processing. Its ordinary HTTP branch returns 503 with Retry-After: 5. Wait for completion and confirm service mode before accepting a replay result.

You don't have to record from scratch to fill the library. Cold-start seeding accepts a HAR, Postman collection, or OpenAPI spec via the dashboard's drag-and-drop, which posts to POST /v1/seed/{har,postman,openapi}. Seeded entries feed the same cascade as recorded traffic.

# Request global MOCK; confirm applied mode and service overrides
curl -X POST http://localhost:8000/v1/mode \
  -H "X-API-Key: $GHOST_API_KEY" \
  -H 'Content-Type: application/json' \
  -d '{"mode": "MOCK"}'

The POST accepts LEARN, MOCK or PASSTHROUGH, not TRANSITIONING. Authenticated GET /v1/mode reads the configured agent's global health mode, not every service's effective mode. Check overrides in service configuration as well as the applied global mode.

Startup uses a valid saved mode before a valid INITIAL_MODE, then falls back to LEARN. Generated Compose uses /data/mode.txt. Concrete global-mode writes are best-effort; TRANSITIONING is not saved. A successful POST does not guarantee the mode file was durably written, so check again after restart when persistence matters.

Observing which tier answered

The agent exposes Prometheus metrics on /metrics. Inspect the match_type distribution for the traffic you actually sampled. These are illustrative series names:

# Per-tier request counts (one increment per match-path outcome)
ghost_requests_total{match_type="session_verbatim"}
ghost_requests_total{match_type="exact"}
ghost_requests_total{match_type="resource_store"}
ghost_requests_total{match_type="smart_swap"}
ghost_requests_total{match_type="generated_cached"}
ghost_requests_total{match_type="miss"}

# Library + I/O health
ghost_mock_library_size
ghost_io_errors_total{operation="..."}

# HTTP rate + latency, and the TLS-MITM subsystem
axum_http_requests_total
axum_http_requests_duration_seconds
gostly_tls_listener_state{state="..."}

Compare the observed source mix with the requests your test intended to cover. A rising miss count is a reason to inspect changed requests, routing and retained coverage before deciding to record or seed more. No source distribution alone establishes application correctness.

Provenance headers

Every response the proxy produces for a routed request says which layer produced it: in MOCK, PASSTHROUGH and LEARN, and on the 503 a service returns while TRANSITIONING. Two headers carry it.

X-Gostly-Behavior is one structured header (an RFC 8941 dictionary). Every value is a plain token or a boolean, and the header is at most 512 bytes.

X-Gostly-Behavior: svc=svc_4be1, src=exact, fault=?0, rule=service, timeout=inherit
MemberWhat it tells you
svcThe service the request was routed to. Absent when no service matched.
srcWhat produced the response: upstream (forwarded in PASSTHROUGH or LEARN), session-verbatim, exact, smart-swap, resource, statechart, environment, recorded-retrieval (stored response reused through the AI cache), generated (output classified as generated), generalized, miss, fault (an injected chaos error), or agent (the proxy answered itself, with a reason).
fault?1 when chaos replaced the response with an injected error, ?0 otherwise.
ruleThe chaos rule that applied: service for the service-level config, or endpoint-<n> for the n-th endpoint rule counted from 0, followed by its path pattern unless the pattern holds characters a header token cannot carry (such as {, ? or a space) or is very long. Absent when no chaos rule applied. Positions change when rules are reordered.
timeoutinherit: the proxy applied no deadline of its own to the request.

Server-Timing splits the response time into three entries, so a slow response explains itself in browser devtools and in APM tools that read the header.

Server-Timing: gostly-source;dur=3, gostly-recorded;dur=212, gostly-latency;dur=120
  • gostly-source is the rest of the proxy's time on the request, mostly the matching tier or the upstream.
  • gostly-recorded is latency replayed from the recording.
  • gostly-latency is latency injected by the service's chaos config.

An upstream's own Server-Timing entries are kept; the proxy adds its entries as a separate field.

Turning them off

Both headers are on by default. A service whose clients sign or pin response headers can turn them off with provenance_headers: false on the service (PUT /v1/services/{id}); its responses then carry neither header, except that an error the proxy returns itself because the request to the upstream failed (for example a refused connection, a TLS failure or a timeout) still says so (X-Gostly-Behavior: src=agent, reason=<failure>). Responses in a deterministic episode run do not carry them either: the episode journal records the same attribution.

In MOCK mode the proxy also adds an X-Ghost-* header naming the tier, and an injected chaos error carries X-Ghost-Chaos in MOCK and PASSTHROUGH.

AnswerHeaderWhat it tells you
Stored / replayedX-Ghost-Mock: session-verbatimX-Ghost-Mock: trueX-Ghost-SwapMatch: trueIdentifies a stored or session replay source. Loaded library entries can be recorded or imported; this marker alone does not prove an upstream capture. SwapMatch means a structurally matching entry answered.
RebuiltX-Ghost-Resource: trueX-Ghost-Transition: <state>A resource-store read or configured chart transition answered. A transition's value names the new state; the marker alone does not show how the resource was created.
Generated / generalized markersX-Ghost-Generated: trueX-Ghost-Generalized: trueIdentifies generated-classified or separately admitted generalized output. Confidence does not establish application correctness or adapter use.
MissX-Ghost-Miss: trueX-Gostly-Miss-ReasonNo tier matched. The status and body are the configured unmatched response, 404 by default; the reason header says why.
Chaos errorX-Ghost-Chaos: trueAn error injected by the service's chaos config instead of a real answer. Injected latency on a successful response has no X-Ghost-* header; it shows in Server-Timing.

These headers name the layer that chose the answer. They are not a checksum: a rebuilt answer can differ from the original response in formatting and headers.

The AI-cache path can answer with a closely matching same-service library entry instead of model output. That answer uses the stored-response marker (X-Ghost-Mock: true), not X-Ghost-Generated, and X-Ghost-Confidence carries the match similarity. Serving-source markers remain separate from the entry's capture or import provenance.

OSS proxy vs. the licensed product

The deterministic tiers — session-verbatim, exact, resource store, and smart-swap — are the core matching engine and run everywhere. The generative tier is the line between products:

OSS proxy

A separate open-source product, distributed via Homebrew and a container registry, and it ships a host CLI. It has no AI tier, so the cascade stops at smart-swap. The inference cache and pre-warm path are not part of the open-source build at all.

Licensed product

Distributed as a Docker Compose stack with prebuilt images (no host CLI). Every license includes the AI tier and the statechart editor / per-tenant overrides. SSO (SAML + OIDC), enforcement of the four roles (viewer < member < admin < owner) and an auth audit log that the application only appends to ship in the web container's auth layer on every license. Assigning roles through the user-management API is Team, with the rest of multi-user management.

Single-tenant per deployment

Each licensed deployment has one workspace identity. Application queries are tenant-scoped, and Postgres enforces RLS beneath them through the non-owner gostly_app role, transaction-bound tenant context and FORCE ROW LEVEL SECURITY on covered tables. Cross-tenant maintenance uses a separate privileged role. Outbound TLS fingerprint impersonation (Chrome / Firefox / Safari fingerprints) is included with every license.

Next steps