Skip to content

feat(gateway): hermetic mock gateway with INFER_GATEWAY_MOCK mode, scenario e2e harness, streaming fixes - #817

Merged
edenreich merged 9 commits into
mainfrom
test/hermetic-e2e-mock-gateway
Jul 10, 2026
Merged

edenreich merged 9 commits into
mainfrom
test/hermetic-e2e-mock-gateway

Conversation

@edenreich

@edenreich edenreich commented Jul 9, 2026 •

Copy link
Copy Markdown
Contributor

Closes #815.

What

A hermetic end-to-end test harness for the agent: a mock inference-gateway that serves the exact API surface the CLI consumes, selecting canned scenarios via regex on the user prompt — no real LLM, no API key, deterministic and fast (the full binary e2e suite runs in ~6s). Plus a zero-config way to use it:

INFER_GATEWAY_MOCK=true infer chat

One env var: the container serves the embedded scenario library in-process on an ephemeral localhost port, rewrites gateway.url to it and forces gateway.run off. Chat lands in the model-selection view with the mock model; every scenario works interactively. Same for infer agent -m openai/gpt-4o "...".

Design (stateless by construction)

Every request carries the full message history, so the mock needs no session state:

  • Scenario = first regex (file order) matching the latest user message that is not an injected <system-reminder> — each interactive chat prompt re-routes to its scenario, while the headless loop's automated-check reminder never re-routes a run.
  • Turn = count of assistant messages after that anchor → turns[step], so every new prompt restarts its scenario at turn 0; past the end, a fallback turn is served, which lets the headless "two consecutive no-tool-call turns" termination happen naturally.
  • Responses marshal the SDK's own types (CreateChatCompletionResponse / ...StreamResponse) for wire fidelity; the only mutable state is the error-injection counter and request recording. Zero new dependencies.

Pieces

Path What
internal/mockgateway http.Handler: /v1/models, /v1/chat/completions (sync JSON + SSE), /v1/health; YAML scenario schema (strict decode); embedded library of 13 scenarios; Requests() recording for assertions
config / internal/container gateway.mock (INFER_GATEWAY_MOCK): boots the mock in-process and points the SDK client at it
tests/mockgateway standalone mock-gateway binary (-port, -scenarios) for custom scenario files and the future tmux TUI harness; first stdout line is the readiness protocol
tests/integration in-process e2e: real container + real SDK client + real SSE parsing via RunWithStream/Run — fragment accumulation, parallel tool dispatch, multi-turn loops, retry, hard errors, malformed frames, cancel mid-stream, usage capture. Runs in plain go test ./...
tests/e2e (-tags e2e) the built infer binary as a subprocess: headless JSON output contract, termination rule, parallel reads, write blocked without approver, bash allow-list gate, agent_error + non-zero exit, piped-chat streaming, one-env-var mock mode
Taskfile / CI task test:e2e, task build:mockgateway; new e2e CI job

Streaming tool-call arguments are deliberately emitted in ≥2 fragments per call so the CLI's index-keyed accumulator is always exercised; content chunks split on runes (UTF-8-safe).

Bugs the harness caught immediately (fixed here)

  1. Stream-failure hang + goroutine leak: a failed GenerateContentStream (or stream timeout) transitioned the state machine to Error from the streaming goroutine without waking the event loop — the chat event channel never closed. Fixed with an event nudge after the transition.
  2. Context cancellation ignored: cancelling the ctx passed to RunWithStream aborted the HTTP stream but nothing closed the session cancel channel, parking the machine in StreamingLLM forever (also hit non-interactive chat on gateway timeout). Fixed with context.AfterFunc(sessionCtx, sc.Cancel).
  3. Usage-only chunks dropped: usage was read inside the per-choice loop, so the OpenAI-style final usage chunk (stream_options.include_usage, choices: []) was discarded and stats fell back to the tokenizer polyfill. Fixed by hoisting the capture.
  4. Data race: Registry.SetReadToolUsed raced under parallel tool execution (e.g. four Read calls in one turn). Now an atomic.Bool.
  5. INFER_* env vars dead for optioned mapstructure tags: resolveViperEnvironmentVariables built viper keys from the raw tag, so fields tagged debug,omitempty looked up gateway.debug,omitempty — INFER_GATEWAY_DEBUG/INFER_GATEWAY_OCI never resolved. Tag options are stripped before building the key.

Try it

INFER_GATEWAY_MOCK=true infer chat

Prompts that trigger scenarios (internal/mockgateway/scenarios.yaml is the reference): say hello, please search for TODO, run the echo command, explore the project structure, create a file named blocked.txt (approval prompt), stream slowly, think step by step, report your usage; please execute the Read tool 4 times in parallel reads a.txt–d.txt from the cwd. Anything else answers with the fallback (Done.).

Custom scenario files use the standalone binary: task build:mockgateway && .infer/bin/mock-gateway -port 0 -scenarios my.yaml + INFER_GATEWAY_URL.

Out of scope

TUI automation (tmux screen-capture harness) — follow-up in #818; the mock gateway here is its prerequisite.

…flag race

Three latent bugs surfaced by the new hermetic e2e harness (#815):

- A failed GenerateContentStream (or stream timeout) transitioned the state
  machine to Error from the streaming goroutine without waking the event
  loop, leaving the loop blocked forever: the chat event channel never
  closed and both agent goroutines leaked. The transition now nudges the
  loop with a MessageReceivedEvent so it observes the terminal state.
- Cancelling the context passed to RunWithStream aborted the HTTP stream
  but nothing closed the session cancel channel, parking the state machine
  in StreamingLLM indefinitely (this also affected non-interactive chat on
  gateway timeout). context.AfterFunc now propagates ctx cancellation to
  sessionCancel, which is idempotent via sync.Once.
- Usage was only captured inside the per-choice loop, so the OpenAI-style
  final usage chunk (include_usage: true, choices: []) was silently
  dropped and token stats fell back to the tokenizer polyfill. Usage is
  now read before iterating choices.
- Registry.SetReadToolUsed raced under parallel tool execution (several
  Read calls in one assistant turn); the flag is now an atomic.Bool.
…ence-gateway

Adds internal/mockgateway, a stateless stand-in for the inference-gateway
API surface the CLI consumes (GET /v1/models, POST /v1/chat/completions in
both sync JSON and SSE streaming form, GET /v1/health). A scenario is
selected by regex against the first user message; the turn within a
scenario is derived from the assistant-message count already in the
request, so the server needs no session state and is race-safe.

- internal/mockgateway: handler, YAML scenario schema (strict decode),
  embedded built-in library of 13 scenarios (text, parallel tool calls,
  search, sequential tools, approval-blocked write, bash allow/block,
  429-retry, hard 500, malformed SSE, slow stream, usage, reasoning),
  self-tests round-tripping frames through the SDK types
- tests/mockgateway: standalone mock-gateway binary (-port, -scenarios)
  for manual runs and future terminal-automation harnesses; first stdout
  line is the readiness protocol
- tests/integration: in-process e2e driving the real container, real SDK
  client and real SSE parsing through RunWithStream and Run - fragment
  accumulation, parallel tool dispatch, multi-turn loops, retry, hard
  errors, malformed frames, cancel mid-stream, usage capture
- tests/e2e (build tag e2e): the built infer binary as a subprocess -
  headless JSON output contract, termination after two no-tool turns,
  parallel reads, write blocked without approver, bash allow-list gate,
  agent_error + non-zero exit, piped chat streaming
- Taskfile: test:e2e and build:mockgateway targets
…options

resolveViperEnvironmentVariables built viper keys from the raw mapstructure
tag, so fields tagged with options (e.g. "debug,omitempty") looked up
gateway.debug,omitempty and their env overrides (INFER_GATEWAY_DEBUG,
INFER_GATEWAY_OCI) never resolved. Strip tag options before building the key.
Interactive chat sends one growing conversation, so first-user-message
routing pinned the whole session to whatever the first prompt matched and
the assistant-count step never reset: every later prompt answered with the
fallback. Anchor scenario matching on the latest user message that is not
an injected <system-reminder> and count steps as the assistant messages
after it. Each chat prompt starts its scenario at turn 0; the headless
loop's automated-check reminder still never re-routes a run.
…rocess

One env var for hermetic local runs: the container serves the scenario
library from internal/mockgateway on an ephemeral localhost port, rewrites
gateway.url to it and forces gateway.run off. infer chat lands in the
model selection view with the mock model and every scenario works
interactively; no real gateway, LLM, or API key involved.
@edenreich edenreich changed the title fix(agent): streaming lifecycle bugs uncovered by new hermetic mock-gateway e2e harness feat(gateway): hermetic mock gateway with INFER_GATEWAY_MOCK mode, scenario e2e harness, streaming fixes Jul 10, 2026
@edenreich edenreich added this to 2026 Jul 10, 2026
@edenreich edenreich moved this to QA in 2026 Jul 10, 2026
@edenreich
edenreich merged commit 03f9860 into main Jul 10, 2026
1 check passed
@edenreich
edenreich deleted the test/hermetic-e2e-mock-gateway branch July 10, 2026 10:19
@edenreich edenreich moved this from QA to Done in 2026 Jul 10, 2026
@inference-gateway-releaser

Copy link
Copy Markdown
Contributor

🎉 This PR is included in version 0.141.0 🎉

The release is available on:

Your semantic-release bot 📦🚀

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

released Shipped in a release

Projects

No open projects
Status: Done

1 participant