Skip to content

Fix: drop structured-output options unconditionally on retry - #277

Merged
Sanjay Singh (san360) merged 3 commits into
microsoft:mainfrom
mayuriphad:fix/retry-structured-output-detection
Nov 21, 2026
Merged

Sanjay Singh (san360) merged 3 commits into
microsoft:mainfrom
mayuriphad:fix/retry-structured-output-detection

Conversation

@mayuriphad

Copy link
Copy Markdown
Contributor

Summary

Fixes #276.

callLlmJson in src/webview/panel-llm.ts only cleared options.modelOptions (the structured-output request) on retry when the error message matched a narrow regex: /response_format|modelOptions|not supported|JSON|parse/i. Models/providers that reject response_format with a generic error bypass this guard entirely, so every retry attempt fails identically in structured mode and the retry budget is exhausted with no recovery.

Fix

  • Drop modelOptions unconditionally on the first failure whenever it is set, since plain-text mode already has its own JSON-extraction fallback (parseLlmJson). No need to pattern-match the error message to decide whether to fall back.
  • Append a truncated (300-char) raw response snippet to the failure debug log so silent structured-output failures are easier to diagnose (logs (empty) when the response is blank).

Test plan

  • Added src/webview/panel-llm.test.ts, mocking the vscode module to simulate a model that rejects the first (structured) request with a generic, non-pattern-matching error and succeeds on the second (plain) request. Asserts modelOptions is cleared between attempts and the call ultimately recovers.
  • Verified the new test fails against the old code (Cannot read properties of undefined (reading 'text') — retries exhausted) and passes with the fix.
  • Ran the full suite: npx vitest run — 1342 passed; the 7 pre-existing failures in src/core/github-app-analytics.test.ts are unrelated to this change and fail identically on main.

callLlmJson only cleared options.modelOptions on retry when the error
message matched a narrow regex (response_format|modelOptions|not
supported|JSON|parse). Providers that reject structured output with a
generic error bypassed this guard, so every retry attempt failed
identically and exhausted the retry budget with no recovery.

Drop modelOptions unconditionally on the first failure instead, since
plain-text mode has its own JSON-extraction fallback. Also log a raw
response snippet on failure for easier diagnosis.
Copilot AI balanced review requested due to automatic review settings September 29, 2026 13:11

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot was unable to review this pull request because the user who requested the review has reached their quota limit.

@mayuriphad

Copy link
Copy Markdown
Contributor Author

Hi maintainers, a gentle ping on this PR whenever you have a moment to review. I'm happy to make any changes or add tests if something needs adjusting. Thank you for your time!

@san360 Sanjay Singh (san360) self-assigned this Oct 19, 2026
@san360

Copy link
Copy Markdown
Contributor

Mayuri Phad (@mayuriphad), Could you provide the steps to reproduce? I do understand the issue though not sure about the scenarios where it will fail

@mayuriphad

Copy link
Copy Markdown
Contributor Author

Sure. The failure needs a model or provider that rejects the structured-output request (modelOptions / response_format) with an error message that does not match the old regex /response_format|modelOptions|not supported|JSON|parse/i. Examples are a generic 400 Bad Request or Request failed from a provider that has no JSON-schema mode.

Steps:

  1. Select a chat model whose API rejects response_format with a generic error.
  2. Trigger any panel action that goes through callLlmJson (it passes modelOptions for structured output).
  3. The first attempt fails. The old guard does not match the message, so modelOptions stays set.
  4. Every remaining retry sends the same structured request and fails the same way, so the retry budget is used up and the call fails, even though plain-text mode would have worked via parseLlmJson.

src/webview/panel-llm.test.ts reproduces this without a real provider: the mocked model rejects the first (structured) request with a generic error and accepts the second (plain) one. On the old code the test fails with Cannot read properties of undefined (reading 'text'); with this change it recovers on the second attempt.

@mayuriphad

Copy link
Copy Markdown
Contributor Author

Thanks Sanjay Singh (@san360). The failing scenario is any model or provider that rejects the structured-output request (modelOptions / response_format) with an error message that does not match the old regex /response_format|modelOptions|not supported|JSON|parse/i, for example a plain 400 Bad Request.

Steps:

  1. Pick a model through the VS Code LM API that does not accept structured output.
  2. Run a panel action that calls callLlmJson with modelOptions set.
  3. The first request fails with the generic error. The old guard does not match it, so modelOptions stays set and every retry fails the same way until the retry budget runs out.

I can't point to a specific provider that does this. src/webview/panel-llm.test.ts simulates it with a mocked vscode module: the first (structured) request rejects with a non-matching error and the second (plain) request succeeds. On main the test fails with Cannot read properties of undefined (reading 'text'). With the fix it passes, because modelOptions is cleared after the first failure and the plain-text path (parseLlmJson) takes over.

@mayuriphad

Copy link
Copy Markdown
Contributor Author

Sanjay Singh (@san360) It fails whenever the first, structured request (modelOptions.response_format with a strict json_schema) is rejected with an error whose message contains none of response_format, modelOptions, not supported, JSON or parse. Then modelOptions is never cleared, all LLM_MAX_RETRIES + 1 attempts send the same structured request, and callLlmJson throws the provider error.

Messages like that come from the provider, not from this extension. Examples are a bare HTTP status (Request Failed: 400, Bad Request, Invalid request body) or a stream that ends with Response contained no choices. I don't have a specific model I can point to that does this today. The unit test reproduces it without one.

Steps to reproduce:

  1. Register a model through vscode.lm.registerLanguageModelChatProvider (or use a BYOK model). Its provideLanguageModelChatResponse throws new Error('Bad Request') whenever options.modelOptions?.response_format is set, and otherwise returns {"ok":true}.
  2. Select that model for the extension and trigger any feature that goes through callLlmJson with a schema.
  3. On main, the panel-llm call-failed debug lines show structured=true on every attempt, and the feature fails with Bad Request. With this PR, attempt 2 logs structured=false and the call returns {"ok":true} through the plain-text path.

src/webview/panel-llm.test.ts does steps 1–3 with a mocked sendRequest. It throws upstream provider error: request failed on the structured call and checks that the second call has no modelOptions. On main that test fails with Cannot read properties of undefined (reading 'text'), because the second mock is never reached with modelOptions cleared and the retries run out. With this change it passes.

Plain mode already has its own JSON extraction (parseLlmJson). So dropping structured output after the first failure costs at most one plain attempt when the error was unrelated.

@mayuriphad

Copy link
Copy Markdown
Contributor Author

Thanks Sanjay Singh (@san360). Steps to reproduce:

  1. Call callLlmJson(messages, schema). The first request is sent with modelOptions.response_format (json_schema, strict: true).
  2. The selected model or provider rejects that request, and its error message does not contain any of response_format, modelOptions, not supported, JSON or parse. For example, a provider returns a plain 400 Bad Request, or vscode.LanguageModelError carries a generic message such as upstream provider error: request failed.
  3. The guard at panel-llm.ts:435 does not match, so options.modelOptions stays set. All LLM_MAX_RETRIES + 1 attempts send the same structured request and fail the same way. The call then throws the last error, and the plain-text path (parseLlmJson) is never tried.

src/webview/panel-llm.test.ts reproduces this with a mocked vscode model: the first call throws new Error('upstream provider error: request failed') and the second call returns valid JSON. On main the test fails because the retries are used up. With the change, attempt 2 runs without modelOptions and returns the parsed object.

I don't have a confirmed list of exact provider messages. The regex depends on how each provider words its error, so the fix stops depending on the wording. After any failure in structured mode, the next attempt uses plain mode. If you'd rather keep structured mode for some errors (for example cancellations, which are already rethrown, or rate limits), I can limit the fallback to those cases.

@san360 Sanjay Singh (san360) left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks again Mayuri Phad (@mayuriphad) for this fix, and for the patient, detailed answers to our questions. The mocked regression test makes the failure easy to see, and the change itself is small and focused.

What we verified on the latest main with your commit merged in:

  • src/webview/panel-llm.test.ts passes with your change and fails without it (Cannot read properties of undefined (reading 'text')), so it covers the bug well.
  • Typecheck passes, and all webview tests pass (42 files, 840 tests).

Two small things before we merge:

  1. Rebase on main. The branch is from September, and its CI runs expired before they were approved. A rebase (or merging main in) gives us a fresh run, and a maintainer will approve it. There are no conflicts.

  2. Please don't log the model's reply (inline suggestion below). raw= writes up to 300 characters of the reply to runtime.log and to the extension's Output channel. That reply can repeat content from the user's chat transcripts or repository files. We redact prompts before sending them, but this text isn't redacted, and people often paste their Output channel into bug reports. Also, in the case this PR fixes (the request itself is rejected), nothing has streamed yet, so the log would only say raw=(empty). A content-free hint about the reply's shape keeps the diagnostic value without the private text.

Optional, if you have time: two more cases in the new test file would be nice:

  • a reply that can't be parsed still adds the "respond ONLY with JSON" message exactly once;
  • a vscode.CancellationError is rethrown without another attempt.

Happy to merge once 1 and 2 are in and CI is green. Thanks again for the contribution!

Comment thread src/webview/panel-llm.ts Outdated
Comment on lines +430 to +433
const rawSnippet = text ? text.slice(0, 300) : '(empty)';
runtimeDebug('panel-llm', 'call-failed',
`schema=${schemaName} attempt=${attempt + 1} structured=${options.modelOptions !== undefined} ` +
`model=${model.id} textLen=${text.length} error=${err instanceof Error ? err.message : String(err)}`);
`model=${model.id} textLen=${text.length} error=${err instanceof Error ? err.message : String(err)} raw=${rawSnippet}`);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could we log the shape of the reply instead of its content? The reply can repeat transcript or repository content, and this line ends up in runtime.log and the Output channel. For the rejection case this PR fixes, text is empty anyway.

Suggested change
const rawSnippet = text ? text.slice(0, 300) : '(empty)';
runtimeDebug('panel-llm', 'call-failed',
`schema=${schemaName} attempt=${attempt + 1} structured=${options.modelOptions !== undefined} ` +
`model=${model.id} textLen=${text.length} error=${err instanceof Error ? err.message : String(err)}`);
`model=${model.id} textLen=${text.length} error=${err instanceof Error ? err.message : String(err)} raw=${rawSnippet}`);
const shape = !text ? 'empty' : /^\s*```/.test(text) ? 'fenced' : /^\s*[[{]/.test(text) ? 'json-like' : 'text';
runtimeDebug('panel-llm', 'call-failed',
`schema=${schemaName} attempt=${attempt + 1} structured=${options.modelOptions !== undefined} ` +
`model=${model.id} textLen=${text.length} shape=${shape} error=${err instanceof Error ? err.message : String(err)}`);

Add tests for the JSON-only nudge being added once and for
CancellationError being rethrown without a retry.

Signed-off-by: mayuriphad <[email protected]>
@mayuriphad

Copy link
Copy Markdown
Contributor Author

Thanks Sanjay Singh (@san360). Pushed two commits, no force-push:

  1. Merged current main into the branch in 32b6187 (no conflicts).
  2. 4af8900 applies your suggestion: the failed-call log now records shape=empty|fenced|json-like|text and textLen, and no longer writes any of the reply text.

It also adds the two optional cases to src/webview/panel-llm.test.ts:

  • replies that cannot be parsed get the "respond ONLY with a valid JSON" message exactly once on each retry, and not on the first request;
  • a vscode.CancellationError is rethrown after a single sendRequest call.

Locally on the merged head: npm run typecheck passes, and npx vitest run src/webview passes (42 files, 842 tests).

@san360
Sanjay Singh (san360) merged commit d877b59 into microsoft:main Nov 21, 2026
6 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

LLM call retry logic fails silently when model doesn't support structured output

3 participants