Skip to content

Prove a provider adapter with the conformance suite

View as Markdown

conformance.Run is the provider adapter contract as a test: it drives a weft.Model through every behaviour the loop relies on, one subtest per case. When it is green, the adapter honours the contract. Every first-party adapter (weft/openai, weft/anthropic, weft/google) runs it offline against recorded wire fixtures in CI and live against the provider behind -tags live. A new adapter passes it the same way.

The OpenAI adapter’s offline run, from testing/conformance_test.go:

testing/conformance_test.go
func TestConformance(t *testing.T) {
conformance.Run(t, conformance.Caps{
Files: true, // accepts a FilePart image
Sequential: true, // forwards SequentialTools
ToolArgDeltas: true, // streams argument fragments
ToolChoice: true, // forwards ToolChoice (asserted on the request bytes)
Usage: true, // the provider reports token usage
ErrorHeaders: true, // the SDK error keeps the HTTP response
}, newModel)
}

testing/conformance_test.go on GitHub

newModel(t, name) builds the adapter for one case, pointed at a local server that plays that case’s recorded bytes.

The suite lives in the core module, core/wefttest/conformance, and the framework re-exports it as weft/wefttest/conformance through a generated facade. It imports no vendor SDK and reaches the model through weft’s public API only, so it also runs against wefttest models; weft’s own tests use that to prove the harness. ADR 0013 is the prose; the cases are the contract:

CasePasses when
text_onlyOne step, StopEndTurn, non-empty text; usage above zero with Caps.Usage
thinking_optionA run with weft.Thinking(ThinkOff) completes normally
tool_roundtrip_structThe model calls the suite’s probe tool with arguments, the struct result {"n":3,"doubled":6} round-trips, and the answer mentions 6
parallel_three_callsThree calls in one step with distinct, non-empty ids; their results on one tool message
usage_nonzero (Usage)Every step reports input and output tokens; cached, cache-write and reasoning splits never exceed their totals
cancel_mid_streamCancelling after the first text delta ends the run with context.Canceled: exactly one error, nothing after it
max_tokensThe adapter’s token-limit option maps to StopMaxTokens
sequential_hint (Sequential)Under weft.Sequential(), at most one call per step
tool_choice_forcing (ToolChoice)any yields a call, a named choice calls that tool, none calls nothing; offline, every request body carries tool_choice or toolConfig
reasoning_passthrough (Reasoning)A ReasoningPart comes first in the assistant message, and feeding the transcript back succeeds
file_inputWith Files an inline PNG is answered; without, the run fails wrapping weft.ErrUnsupported
idle_timeout (offline)A stalled stream fails wrapping weft.ErrStreamIdle
idle_timeout_before_headers (offline)A server that never sends headers fails the same way
provider_error (offline)A 429 reaches the caller as a *weft.RunError with the SDK’s error on the chain: mw.HTTPStatus reads 429, and with ErrorHeaders mw.RetryAfter reads 7 s
slow_stream (offline)A stream that drips under the idle timeout, while its total exceeds it, succeeds
tool_args_delta (ToolArgDeltas, offline)Argument fragments arrive as ToolArgsDelta before the call’s ToolStart
kill_switchUnder WEFT_MODEL_REQUESTS=deny the run fails wrapping weft.ErrModelRequestsDenied. Wired to NoRequestServer, a request that slips through fails the test
never_contract_violationNo case’s run error wraps weft.ErrModelContract; a detector checks every case and fails the suite at cleanup

ADR 0013 also states rules every adapter keeps, some of which the cases assert. Requests go through the vendor’s official SDK, never an owned HTTP client. The adapter does not retry (transport retries are the SDK’s, logic retries are mw.Retry). Vendor errors pass through unchanged so callers can errors.As them; tool calls arrive whole, before ModelFinish.

Run(t, caps, newModel) runs each case as a subtest named after it. It calls newModel once per case, with the case’s fixture key (usually the case’s name; thinking_option asks for text_only), so cases share no state and each can be built its own way. From docs-site/examples:

Terminal window
WEFT_MODEL_REQUESTS=deny go test ./testing -run TestConformance -v
--- PASS: TestConformance (0.57s)
--- PASS: TestConformance/text_only (0.00s)
--- PASS: TestConformance/thinking_option (0.00s)
--- PASS: TestConformance/tool_roundtrip_struct (0.00s)
--- PASS: TestConformance/parallel_three_calls (0.00s)
--- PASS: TestConformance/usage_nonzero (0.00s)
--- PASS: TestConformance/cancel_mid_stream (0.00s)
--- PASS: TestConformance/max_tokens (0.00s)
--- PASS: TestConformance/sequential_hint (0.00s)
--- PASS: TestConformance/tool_choice_forcing (0.00s)
--- PASS: TestConformance/file_input (0.00s)
--- PASS: TestConformance/idle_timeout (0.20s)
--- PASS: TestConformance/idle_timeout_before_headers (0.20s)
--- PASS: TestConformance/provider_error (0.00s)
--- PASS: TestConformance/slow_stream (0.16s)
--- PASS: TestConformance/tool_args_delta (0.00s)
--- PASS: TestConformance/kill_switch (0.00s)
--- PASS: TestConformance/never_contract_violation (0.00s)
PASS
ok weftgo.dev/docs/examples/testing 0.576s

reasoning_passthrough is absent: the OpenAI adapter declares Reasoning off, because reasoning_content is a compatible-server extension, not an OpenAI field.

conformance.Caps says what the adapter supports, so the suite asserts the right behaviour instead of skipping silently. A false field is a declared gap, not a hidden one.

FieldSet it whenCases it changes
ReasoningThe adapter emits reasoning deltas and accepts a ReasoningPart, with its signature, backruns reasoning_passthrough
FilesIt accepts a FilePart imagefile_input expects an answer, else ErrUnsupported
SequentialIt forwards SequentialTools and the provider honours itruns sequential_hint
ToolArgDeltasIt surfaces argument fragments while the provider streams a callruns tool_args_delta (offline)
ToolChoiceIt forwards ToolChoice and the provider honours itruns tool_choice_forcing; offline it needs a RecordingModel
UsageThe provider reports token usage. Leave it false for a server that never does: the adapter must not fake numberstext_only’s usage check; runs usage_nonzero
ErrorHeadersThe SDK’s error type carries the HTTP response, so mw.RetryAfter can read a retry-after headerprovider_error’s retry-after check; the status is asserted always
LiveThe model is reached over the networkcases where a live model may choose differently t.Skip; the offline-only cases are skipped

What the first-party adapters declare offline:

AdapterReasoningFilesSequentialToolArgDeltasToolChoiceUsageErrorHeaders
weft/openai—✓✓✓✓✓✓
weft/anthropic✓✓✓✓✓✓✓
weft/google✓✓——✓✓—

Gemini has no parallel-tool-calls switch, its calls arrive whole, and genai’s APIError keeps the status code but not the headers.

Each case needs a server that behaves a certain way. The package has one per behaviour, each an httptest.Server closed at the test’s cleanup:

ServerBehaviourCases
FixtureServer(t, file)Serves the recorded responses in file, in order, one per request, as text/event-stream. A request past the last one fails with 500 naming the filethe recorded cases
RecordingFixtureServer(t, file)FixtureServer plus a func returning every request body, in ordertool_choice_forcing
StallServer(t, firstChunk)Writes one SSE event, then holds the stream open until the request endscancel_mid_stream, idle_timeout
SilentServer(t)Accepts the connection and never answers, not even headersidle_timeout_before_headers
SlowServer(t, drip, done, interval, count)Writes drip every interval, count times, then doneslow_stream
ErrorServer(t, status, header, body)Answers every request with that status, headers and bodyprovider_error
NoRequestServer(t)Fails the test if any request arriveskill_switch

A fixture file holds one or more responses, the provider’s own stream bytes. A line === response 2 === separates them; everything before the first separator is response 1. The OpenAI tool round trip, testing/testdata/conformance/tool_roundtrip_struct.sse, is a tool call streamed in argument fragments, with usage, then the answer:

testing/testdata/conformance/tool_roundtrip_struct.sse
data: {"id":"c1","object":"chat.completion.chunk","created":1700000000,"model":"m","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"id":"call_probe","type":"function","function":{"name":"probe","arguments":""}}]},"finish_reason":null}]}
data: {"id":"c1","object":"chat.completion.chunk","created":1700000000,"model":"m","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"function":{"name":"","arguments":"{\"n"}}]},"finish_reason":null}]}
data: {"id":"c1","object":"chat.completion.chunk","created":1700000000,"model":"m","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"function":{"name":"","arguments":"\":3"}}]},"finish_reason":null}]}
data: {"id":"c1","object":"chat.completion.chunk","created":1700000000,"model":"m","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"function":{"name":"","arguments":"}"}}]},"finish_reason":null}]}
data: {"id":"c1","object":"chat.completion.chunk","created":1700000000,"model":"m","choices":[{"index":0,"delta":{},"finish_reason":"tool_calls"}]}
data: {"id":"c1","object":"chat.completion.chunk","created":1700000000,"model":"m","choices":[],"usage":{"prompt_tokens":9,"completion_tokens":5,"total_tokens":14,"prompt_tokens_details":{"cached_tokens":4},"completion_tokens_details":{"reasoning_tokens":2}}}
data: [DONE]
=== response 2 ===
data: {"id":"c1","object":"chat.completion.chunk","created":1700000000,"model":"m","choices":[{"index":0,"delta":{"role":"assistant","content":"The doubled value is 6."},"finish_reason":null}]}
data: {"id":"c1","object":"chat.completion.chunk","created":1700000000,"model":"m","choices":[{"index":0,"delta":{},"finish_reason":"stop"}]}
data: {"id":"c1","object":"chat.completion.chunk","created":1700000000,"model":"m","choices":[],"usage":{"prompt_tokens":9,"completion_tokens":5,"total_tokens":14,"prompt_tokens_details":{"cached_tokens":4},"completion_tokens_details":{"reasoning_tokens":2}}}
data: [DONE]

View testing/testdata/conformance/tool_roundtrip_struct.sse on GitHub

Cases with the same behaviour can share a recording: usage_nonzero and tool_args_delta replay the tool round trip, never_contract_violation replays text_only.

tool_choice_forcing asserts on what the adapter sent, not only on what came back. Wrap the model in a conformance.RecordingModel with the body func RecordingFixtureServer returned:

MemberMeaning
ModelThe adapter under test
BodiesThe server’s body func
RecordedBodies()The captured request bodies, in request order
Stream, InfoForwarded to Model

It is a pass-through for that wiring, not a general proxy. Offline, tool_choice_forcing fails with offline tool_choice_forcing must wire a RecordingFixtureServer (wrap the model in conformance.RecordingModel) when the model it gets has no RecordedBodies. A live run cannot capture bodies and skips that check.

newModel is where an adapter meets the suite. The OpenAI wiring, from testing/conformance_test.go:

testing/conformance_test.go
// newModel builds the adapter for one case. Every case but kill_switch
// injects an SDK client pointed at a local server, so the suite runs
// under WEFT_MODEL_REQUESTS=deny.
func newModel(t *testing.T, name string) weft.Model {
at := func(srv *httptest.Server, opts ...openai.Option) weft.Model {
c := openaisdk.NewClient(option.WithBaseURL(srv.URL), option.WithAPIKey("test"))
return openai.Model("m", append([]openai.Option{openai.Client(&c)}, opts...)...)
}
switch name {
case "kill_switch": // a self-built client: the switch must fire before any I/O
return openai.Model("m", openai.BaseURL(conformance.NoRequestServer(t).URL), openai.APIKey("test"))
case "cancel_mid_stream":
return at(conformance.StallServer(t, stallChunk))
case "idle_timeout":
return at(conformance.StallServer(t, stallChunk), openai.IdleTimeout(200*time.Millisecond))
case "idle_timeout_before_headers":
return at(conformance.SilentServer(t), openai.IdleTimeout(200*time.Millisecond))
case "slow_stream": // a chunk every 40 ms for 160 ms, under a 120 ms idle timeout
done := "data: {\"id\":\"c1\",\"object\":\"chat.completion.chunk\",\"created\":1700000000,\"model\":\"m\"," +
"\"choices\":[{\"index\":0,\"delta\":{},\"finish_reason\":\"stop\"}]}\n\ndata: [DONE]\n\n"
return at(conformance.SlowServer(t, stallChunk, done, 40*time.Millisecond, 4), openai.IdleTimeout(120*time.Millisecond))
case "provider_error": // one 429, the SDK's own retries off
srv := conformance.ErrorServer(t, 429, http.Header{"Retry-After": {"7"}},
`{"error":{"message":"slow down","type":"rate_limit_error","param":null,"code":"rate_limit_exceeded"}}`)
c := openaisdk.NewClient(option.WithBaseURL(srv.URL), option.WithAPIKey("test"), option.WithMaxRetries(0))
return openai.Model("m", openai.Client(&c))
case "max_tokens":
return at(conformance.FixtureServer(t, fixture(name)), openai.MaxTokens(16))
case "tool_choice_forcing": // the case reads back the request bodies
srv, bodies := conformance.RecordingFixtureServer(t, fixture(name))
return conformance.RecordingModel{Model: at(srv), Bodies: bodies}
default:
return at(conformance.FixtureServer(t, fixture(name)))
}
}

testing/conformance_test.go on GitHub

Each case wants something specific from it:

  • Inject the SDK client. Point a client at the case’s server and pass it through the adapter’s Client(c) option. An injected client is a test double, so the whole suite runs under WEFT_MODEL_REQUESTS=deny.
  • Build kill_switch’s client from credentials and point it at NoRequestServer. That case proves the switch fires before any I/O, which only holds for a client the adapter built itself.
  • Pass the token-limit option for max_tokens (here openai.MaxTokens(16)); the case checks the mapping to StopMaxTokens.
  • Use a short idle timeout for idle_timeout, idle_timeout_before_headers and slow_stream: the slow stream drips every 40 ms under a 120 ms timeout, and its total of 160 ms exceeds it.
  • Turn the SDK’s own retries off for provider_error, so the one 429 comes back as the SDK’s error type, header and all.
  • Wrap tool_choice_forcing in RecordingModel.
  • Record realistic fixtures. They are committed bytes of the provider’s wire format; when the vendor changes it, regenerate the fixture and review the diff.

Then declare Caps honestly. A capability you set must pass; one you leave false is a gap the suite does not assert (Files false asserts ErrUnsupported instead), and readers of your adapter see it in the test.

Live runs point the same Run at the real API, with Caps.Live set. They sit behind the live build tag, read the key from the environment, skip without it, and never run in CI:

Terminal window
OPENAI_API_KEY=… OPENAI_MODEL=gpt-4o-mini go test -tags live ./openai

make live runs go test -tags live ./... over every module. Under Live, a case where the model made a different valid choice (answered without the tool, finished under the token cap) skips; a breach of the contract still fails. The offline-only cases do not run. Each first-party adapter’s live_test.go builds the model per case, adding its token-limit option for max_tokens.

make fuzz runs every Fuzz* target of the core module, found with go test -list 'Fuzz.*', one invocation each (Go fuzzes one target at a time), FUZZTIME apiece (default 10s). At v0.20.2 there are six:

TargetDecodes
FuzzToolInvokeArgsA tool’s JSON arguments into its input type
FuzzRepairA transcript through weft.Repair
FuzzUnmarshalEventAn event from its wire JSON
FuzzMessageUnmarshalA message from its wire JSON
FuzzPartialJSONA truncated JSON prefix, decoded while it streams
FuzzRawRedactionHeader names and values through a raw record’s credential stripping

make fuzz-thread does the same for weft/thread’s decoders: entries, headers, signed decisions, grant predicates and the jsonl loader. A crasher fails the run; Go writes it under the fuzzed package’s testdata/fuzz/<Target>/ (core/testdata/fuzz/ for make fuzz, thread/ and thread/jsonl/ for make fuzz-thread), and the fix commits it as a regression seed, as the FuzzRepair seed was. A new message part or event type adds a seed.

Terminal window
make fuzz FUZZTIME=30s

Adapter fuzz targets are out of scope: the adapters parse through their vendor SDKs (ADR 0017).

testing/conformance_test.go runs the suite against weft/openai over copies of its fixtures in testing/testdata/conformance/:

testing/conformance_test.go
package main
import (
"net/http"
"net/http/httptest"
"path/filepath"
"testing"
"time"
openaisdk "github.com/openai/openai-go"
"github.com/openai/openai-go/option"
"github.com/weftgo/weft"
"github.com/weftgo/weft/openai"
"github.com/weftgo/weft/wefttest/conformance"
)
// The OpenAI adapter's offline conformance run, wired the way
// weft/openai/conformance_test.go wires it, over copies of its .sse
// fixtures in testdata/conformance/.
func TestConformance(t *testing.T) {
conformance.Run(t, conformance.Caps{
Files: true, // accepts a FilePart image
Sequential: true, // forwards SequentialTools
ToolArgDeltas: true, // streams argument fragments
ToolChoice: true, // forwards ToolChoice (asserted on the request bytes)
Usage: true, // the provider reports token usage
ErrorHeaders: true, // the SDK error keeps the HTTP response
}, newModel)
}
// fixture maps a case to its recorded stream; cases with the same
// behaviour share one recording.
func fixture(name string) string {
switch name {
case "usage_nonzero", "tool_args_delta":
name = "tool_roundtrip_struct"
case "never_contract_violation":
name = "text_only"
}
return filepath.Join("testdata", "conformance", name+".sse")
}
// stallChunk is one complete SSE event, the first and last a stalled stream sends.
const stallChunk = `data: {"id":"c1","object":"chat.completion.chunk","created":1700000000,"model":"m","choices":[{"index":0,"delta":{"content":"one"},"finish_reason":null}]}` + "\n\n"
// newModel builds the adapter for one case. Every case but kill_switch
// injects an SDK client pointed at a local server, so the suite runs
// under WEFT_MODEL_REQUESTS=deny.
func newModel(t *testing.T, name string) weft.Model {
at := func(srv *httptest.Server, opts ...openai.Option) weft.Model {
c := openaisdk.NewClient(option.WithBaseURL(srv.URL), option.WithAPIKey("test"))
return openai.Model("m", append([]openai.Option{openai.Client(&c)}, opts...)...)
}
switch name {
case "kill_switch": // a self-built client: the switch must fire before any I/O
return openai.Model("m", openai.BaseURL(conformance.NoRequestServer(t).URL), openai.APIKey("test"))
case "cancel_mid_stream":
return at(conformance.StallServer(t, stallChunk))
case "idle_timeout":
return at(conformance.StallServer(t, stallChunk), openai.IdleTimeout(200*time.Millisecond))
case "idle_timeout_before_headers":
return at(conformance.SilentServer(t), openai.IdleTimeout(200*time.Millisecond))
case "slow_stream": // a chunk every 40 ms for 160 ms, under a 120 ms idle timeout
done := "data: {\"id\":\"c1\",\"object\":\"chat.completion.chunk\",\"created\":1700000000,\"model\":\"m\"," +
"\"choices\":[{\"index\":0,\"delta\":{},\"finish_reason\":\"stop\"}]}\n\ndata: [DONE]\n\n"
return at(conformance.SlowServer(t, stallChunk, done, 40*time.Millisecond, 4), openai.IdleTimeout(120*time.Millisecond))
case "provider_error": // one 429, the SDK's own retries off
srv := conformance.ErrorServer(t, 429, http.Header{"Retry-After": {"7"}},
`{"error":{"message":"slow down","type":"rate_limit_error","param":null,"code":"rate_limit_exceeded"}}`)
c := openaisdk.NewClient(option.WithBaseURL(srv.URL), option.WithAPIKey("test"), option.WithMaxRetries(0))
return openai.Model("m", openai.Client(&c))
case "max_tokens":
return at(conformance.FixtureServer(t, fixture(name)), openai.MaxTokens(16))
case "tool_choice_forcing": // the case reads back the request bodies
srv, bodies := conformance.RecordingFixtureServer(t, fixture(name))
return conformance.RecordingModel{Model: at(srv), Bodies: bodies}
default:
return at(conformance.FixtureServer(t, fixture(name)))
}
}

View testing/conformance_test.go on GitHub

View on GitHub · run it from docs-site/examples with WEFT_MODEL_REQUESTS=deny go test ./testing -run TestConformance -v; the output is under Run the suite.

  • Declare a gap instead of faking it. An adapter for a server that reports no usage sets Usage false rather than inventing numbers. (Source: weft/core/wefttest/conformance/conformance.go:47-50, ADR 0013)
  • An under-recorded fixture is loud. A request past the last response gets a 500 naming the file; add the missing response. (Source: weft/core/wefttest/conformance/fixture.go:14-27)
  • Conformance proves parsing; replay does not. Application replay sits above the adapter at the Model seam; the wire fixtures stay the adapter’s proof. (Source: ADR 0013 “Fixtures and live runs”, ADR 0017)
  • Do not call Run from a parallel test. The kill_switch case sets WEFT_MODEL_REQUESTS=deny itself with t.Setenv, and Go refuses t.Setenv under t.Parallel. After t.Parallel() the case panics with testing: test using t.Setenv, t.Chdir, or cryptotest.SetGlobalRandom can not use t.Parallel (Go 1.26’s wording), and the panic ends the whole test binary. The suite does not need the variable from you: it passes with WEFT_MODEL_REQUESTS unset too. (Source: weft/core/wefttest/conformance/conformance.go:623-627)
  • Never retry inside the adapter. provider_error wants the 429 back as the SDK’s own error type; retries belong to mw.Retry. (Source: ADR 0013 cross-cutting rules, weft/openai/conformance_test.go:62-69)
  • Keep fuzz crashers. Commit each one under the fuzzed package’s testdata/fuzz/ with its fix. (Source: weft/Makefile:109-117, ADR 0017 T12)

Symbols used: conformance.Run · conformance.Caps · conformance.RecordingModel · conformance.FixtureServer · conformance.RecordingFixtureServer · conformance.StallServer · conformance.SilentServer · conformance.SlowServer · conformance.ErrorServer · conformance.NoRequestServer · openai.Model · openai.Client · openai.MaxTokens · openai.IdleTimeout · mw.HTTPStatus · mw.RetryAfter · weft.ErrModelRequestsDenied · weft.ErrModelContract · weft.ErrStreamIdle · weft.ErrUnsupported · weft.Repair