Files
magpie/internal/gateway/claude_cli_schema_test.go
T
yetone f5149a5332 gateway: Claude Code is given a schema without its root $schema (#3036)
Codex's title requests carry zod's draft 2020-12 schema, with
"$schema": "https://json-schema.org/draft/2020-12/schema" at the root.
magpie passed it to `claude --json-schema` as it came. Claude Code exited
with "--json-schema is not a valid JSON Schema: no schema with key or ref
...", and the client got a 502 that was asked three times.

What Claude Code rejects. 2.1.307 checks --json-schema with Ajv 8's default
class, which is draft-07: new Ajv({allErrors, validateFormats:false,
multipleOfPrecision:6}), then validateSchema and compile, in strict mode.
I ran Ajv 8.20.0 with those options:
- A root $schema for 2020-12, 2019-09 or draft-04 is refused (no schema
  with key or ref).
- Keywords only a later draft has (prefixItems, unevaluatedProperties,
  $anchor, $dynamicAnchor, dependentRequired) are refused (strict mode:
  unknown keyword).
- A draft-07 $schema, $id, $defs, definitions, $comment, and a nested
  $schema or $id all pass.
The real claude 2.1.307 agrees. I ran it in a sandbox HOME, with a fake
`security` on PATH so the Keychain was never touched. The 2020-12 schema
exits 1 with the reporter's exact words. The same schema with $id, and
one without $schema, both get past the check.

The fix. cliSchema drops only the root $schema and keeps everything else
as it came. A schema with no root $schema goes byte for byte. Later-draft
keywords are not rewritten. A schema that uses them is refused, and is now
answered as below.

No more retries. A schema Claude Code refuses is refused the same way on
every try and every account. When its stderr says "--json-schema is not
a valid JSON Schema" (or "is not valid JSON" / "must be a JSON object"),
the run now ends in a 400 with Claude Code's words from the flag on. It
is not retried, the saved-session restart is skipped, and no account
rests. The 400 holds both when Claude Code exits before it takes its
input (cliSchemaRefused from endedBefore) and when it exits after it took
the input (schemaEnded, emitted as a 400 KError before the segment
closes). Before, the second case was an empty 200 for a whole reply, or
a 502 "ended without an answer" for a stream. Any other exit is handled
as before.

Siblings, left as they are:
- anthropic.go's output_config.format goes to the Anthropic API, which
  takes a 2020-12 $schema; Claude Code's own tool schemas in
  testdata/context/claude-code.json carry one.
- codeassist.go's responseJsonSchema (Gemini, Antigravity) is not passed
  through plainSchema. Not tried against the real API; no report of it
  refusing $schema.
- format.go's chat()/responses() go to OpenAI unchanged.
- MCP tool input schemas go to Claude Code's MCP, not this check.
- No other CLI is given --json-schema.

Tests (internal/gateway/claude_cli_schema_test.go). A fake claude does
what Ajv does: it fails on a 2020-12 root $schema or on prefixItems, in
2.1.307's words.
- TestClaudeCodeTakesCodexTitleSchema sends the reporter's title schema
  through a Responses request. It checks for a 200 with the title, and that
  the schema reached the CLI minus only its $schema.
- TestCLISchemaKeepsTheRest checks that $id, $defs and a nested $schema
  are kept, and that a schema without $schema, non-JSON and `true` pass
  byte for byte.
- TestClaudeSchemaRefusedIsAskedOnce/{whole,stream} sends a prefixItems
  schema with two Claude accounts. It checks for a 400 in Claude Code's
  words, one run, and no account rested.

Broken by hand:
- cliSchema returning raw: the first two tests go red.
- No 400 for a refusal: both subtests go red (an empty 200 and a 502).
- No late-exit emit only: both subtests go red.

Record for this push: 13 commits on origin/main ca4a1cde0, head tree
539c84e92. Go 1.26.8, sandbox HOME, GOMODCACHE/GOCACHE pinned. The full Go
run and vet were at tree d6393dfc8, the same Go code as this head: only
app.js comments (cut under the core script budget) and one ja string
changed after it.
- gofmt -l: nothing. go build ./...; go vet ./... (darwin), GOOS=linux
  go vet -tags nogui ./..., GOOS=windows go vet ./...: clean.
- go test -timeout 45m ./..., through tee, one suite on the machine:
  68 packages ok. The one red was internal/gui's
  TestCoreScriptBudget: app.js 1,335,314 > 1,335,000, since main grew
  app.js under the stack. The autoscroll commit's own comments were cut
  (to 1,334,629) rather than the budget raised, and go test -count=1
  ./internal/gui is ok at this head (113s). Packages the run took from
  Go's test cache had the same inputs.
- GUI: the 18 files this stack touches or names, both engines,
  202 of 204 pass (tree 068acf128, this push less the last commit). The
  two reds: gui-ja, red on main since c2636b7b5 and fixed by this push's
  last commit (gui-ja and i18n-keys 6 of 6 there), and usage-fold's
  chromium "several accounts" (#2163, red on main the same way).
- internal/gateway ok in that run, with claude_cli_schema_test.go's three
  tests.
- No GUI change here.
  The whole GUI suite ran at 1c1fc7183 (this stack's first 12 commits on
  0ddcf28a1): 11713 of 11769 pass. Each of the 21 red files was then run
  alone at the stack and at origin/main 8278fd9b0. Eight are red the same
  way on main: plugin-card-update (#3079), quota-count-wrap and
  quota-name-translated (#2228), s3-sync (#2448), usage-agents-hide
  (#2276), usage-checkin (#3091), usage-fold's chromium "several
  accounts" (#2163), usage-ledger (#3104). The other 13 pass alone on both
  and were red only under that run's load (50 to 335): currency #3101,
  plugin-github #3218, provider-fetch-again #3292, rest-try-now #2564,
  routing-auto-reset #3293, routing-keys-fold #1612, routing-steady #1804,
  routing-wb-restricted #1905, sessions-folder-delete #2218,
  sessions-manage #3294, switch-only #3295, text-size #1866, usage-pack
  #3296.
2026-10-23 01:58:00 +08:00

170 lines
7.2 KiB
Go

package gateway
import (
"encoding/json"
"net/http/httptest"
"os"
"path/filepath"
"reflect"
"runtime"
"slices"
"strings"
"testing"
"github.com/yetone/magpie/internal/provider"
"github.com/yetone/magpie/internal/testenv"
)
// codexTitleSchema is a Codex title request's schema as #3036's reporter
// had it reach Claude Code: zod's toJSONSchema, its draft 2020-12 named
// at the root.
const codexTitleSchema = `{"$schema":"https://json-schema.org/draft/2020-12/schema","type":"object","properties":{"title":{"type":"string"}},"required":["title"],"additionalProperties":false}`
// fakeClaudeAjv stands in for Claude Code checking --json-schema as its
// Ajv does: a schema naming another draft than 07 at its root, or one
// with a keyword only a later draft has, ends it before it reads its
// input, with Claude Code 2.1.307's own words. Each run's arguments are
// kept in dir.
func fakeClaudeAjv(t *testing.T) string {
t.Helper()
if runtime.GOOS == "windows" {
t.Skip("a shell script stands in for Claude Code")
}
dir := t.TempDir()
script := `#!/bin/sh
case "$1" in auth) exit 1;; esac
if [ "$2" = "/usage" ]; then
echo '{"type":"result","is_error":false,"result":"Current session: 10% used"}'
exit 0
fi
for a in "$@"; do echo "$a"; done > ` + dir + `/args.$$
for a in "$@"; do
case "$a" in
*'"$schema":"https://json-schema.org/draft/2020-12/schema"'*)
echo 'Error: --json-schema is not a valid JSON Schema: no schema with key or ref "https://json-schema.org/draft/2020-12/schema"' >&2
exit 1;;
*'"prefixItems"'*)
echo 'Error: --json-schema is not a valid JSON Schema: strict mode: unknown keyword: "prefixItems"' >&2
exit 1;;
esac
done
while read -r line; do
echo '{"type":"stream_event","event":{"type":"message_start","message":{"id":"m","model":"claude-haiku-5-5","usage":{"input_tokens":1}}}}'
echo '{"type":"stream_event","event":{"type":"content_block_start","index":0,"content_block":{"type":"tool_use","id":"t1","name":"StructuredOutput","input":{}}}}'
echo '{"type":"stream_event","event":{"type":"content_block_delta","index":0,"delta":{"type":"input_json_delta","partial_json":"{\"title\": \"Fix login bug\"}"}}}'
echo '{"type":"user","message":{"role":"user","content":[{"type":"tool_result","tool_use_id":"t1","is_error":false,"content":"Structured output provided successfully"}]}}'
echo '{"type":"stream_event","event":{"type":"message_delta","delta":{"stop_reason":"tool_use"},"usage":{"output_tokens":5}}}'
echo '{"type":"stream_event","event":{"type":"message_stop"}}'
echo '{"type":"result","subtype":"success","is_error":false,"result":"","structured_output":{"title":"Fix login bug"}}'
done
`
testenv.Program(t, filepath.Join(dir, "claude"), script)
t.Setenv("PATH", dir+string(os.PathListSeparator)+os.Getenv("PATH"))
return dir
}
// cliSchemas are the --json-schema arguments of the runs fakeClaudeAjv
// kept in dir.
func cliSchemas(t *testing.T, dir string) []string {
t.Helper()
files, _ := filepath.Glob(filepath.Join(dir, "args.*"))
var out []string
for _, f := range files {
b, _ := os.ReadFile(f)
args := strings.Split(strings.TrimSpace(string(b)), "\n")
if i := slices.Index(args, "--json-schema"); i >= 0 && i+1 < len(args) {
out = append(out, args[i+1])
}
}
return out
}
// A Codex title request whose schema names draft 2020-12 is answered
// through a Claude subscription (#3036): Claude Code is given the schema
// without its root $schema, which its Ajv can't look up, and the rest of
// it as it came.
func TestClaudeCodeTakesCodexTitleSchema(t *testing.T) {
dir := fakeClaudeAjv(t)
s := New()
t.Cleanup(s.subscription.abortAll)
p := provider.Provider{ID: "claude", Account: &provider.Account{Agent: "claude", User: "u"}}
body := `{"model":"claude-haiku-5-5","stream":true,"reasoning":{"effort":"low"},"input":[{"type":"message","role":"user","content":[{"type":"input_text","text":"Generate a concise title. User prompt:\nfix the login bug"}]}],` +
`"text":{"format":{"type":"json_schema","name":"codex_output_schema","strict":true,"schema":` + codexTitleSchema + `}}}`
rec := httptest.NewRecorder()
var u Usage
if code, msg := s.serveClaudeSubscription(rec, httptest.NewRequest("POST", "/v1/responses", strings.NewReader(body)), provider.Responses, p, "claude-haiku-5-5", []byte(body), &u); code != 200 {
t.Fatalf("%d %s", code, msg)
}
if text, _ := outputText(t, rec.Body.String()); text != `{"title":"Fix login bug"}` {
t.Fatalf("answer %q", text)
}
schemas := cliSchemas(t, dir)
if len(schemas) != 1 {
t.Fatalf("--json-schema of runs: %q", schemas)
}
var got, want map[string]any
json.Unmarshal([]byte(schemas[0]), &got)
json.Unmarshal([]byte(codexTitleSchema), &want)
delete(want, "$schema")
if !reflect.DeepEqual(got, want) {
t.Fatalf("--json-schema %s, want %v", schemas[0], want)
}
}
// cliSchema takes the root $schema out and nothing else: $id, $defs and a
// $schema below the root pass Claude Code's Ajv as they are, and a schema
// without a root $schema goes byte for byte.
func TestCLISchemaKeepsTheRest(t *testing.T) {
in := `{"$schema":"https://json-schema.org/draft/2020-12/schema","$id":"https://example.com/title.json","type":"object",` +
`"properties":{"title":{"$ref":"#/$defs/t"},"note":{"$schema":"https://json-schema.org/draft/2020-12/schema","type":"string"}},"$defs":{"t":{"type":"string"}}}`
var got, want map[string]any
json.Unmarshal(cliSchema(json.RawMessage(in)), &got)
json.Unmarshal([]byte(in), &want)
delete(want, "$schema")
if !reflect.DeepEqual(got, want) {
t.Fatalf("cliSchema: %v", got)
}
for _, plain := range []string{`{"type":"object","properties":{"title":{"type":"string"}}}`, `not json`, `true`} {
if out := string(cliSchema(json.RawMessage(plain))); out != plain {
t.Fatalf("%s became %s", plain, out)
}
}
}
// A schema Claude Code's Ajv won't compile ends it the same way every
// time, on every account: the request's 400, said in Claude Code's words,
// from one run — not a 502 asked again after a moment and of the next
// account, three runs and more for the same refusal (#3036) — and no
// account rests for it.
func TestClaudeSchemaRefusedIsAskedOnce(t *testing.T) {
for _, stream := range []bool{false, true} {
t.Run(map[bool]string{false: "whole", true: "stream"}[stream], func(t *testing.T) { schemaRefusedOnce(t, stream) })
}
}
func schemaRefusedOnce(t *testing.T, stream bool) {
fresh(t)
claudeMadeFirst(t, false) // two Claude accounts
dir := fakeClaudeAjv(t)
s := New()
t.Cleanup(s.subscription.abortAll)
streamed := ""
if stream {
streamed = `"stream":true,`
}
body := `{"model":"claude/claude-sonnet-5","max_tokens":100,` + streamed + `"messages":[{"role":"user","content":"pair?"}],` +
`"output_config":{"format":{"type":"json_schema","schema":{"type":"array","prefixItems":[{"type":"string"},{"type":"number"}]}}}}`
r := httptest.NewRequest("POST", "/v1/messages", strings.NewReader(body))
r.Header.Set("x-api-key", Token)
r.RemoteAddr = "127.0.0.1:12345"
w := httptest.NewRecorder()
lanGuard(s.Handler()).ServeHTTP(w, r)
if w.Code != 400 || !strings.Contains(w.Body.String(), `--json-schema is not a valid JSON Schema: strict mode: unknown keyword`) {
t.Fatalf("%d %s", w.Code, w.Body)
}
if runs := cliSchemas(t, dir); len(runs) != 1 {
t.Fatalf("Claude Code ran %d times: %q", len(runs), runs)
}
noneRested(t, "claude")
}