Skip to content

fix(structured-output): skip LLM extraction when the final answer is valid JSON (DRO-4207) - #560

Merged
Cyro292 merged 5 commits into
developfrom
fix/structured-output-json-fast-path
Dec 4, 2026
Merged

Cyro292 merged 5 commits into
developfrom
fix/structured-output-json-fast-path

Conversation

@Cyro292

@Cyro292 Cyro292 commented Dec 2, 2026

Copy link
Copy Markdown
Collaborator

Fixes DRO-4207.

Problem

Tasks with outputSchema sometimes end with success = true and structured_output = None, even when the final answer is already valid JSON for the schema. StructuredOutputAgent always runs a second LLM extraction call. That call must finish inside the 60 s finalization budget; when it doesn't, it is cancelled and the output is lost.

Fix

In StructuredOutputAgent.extract_structured_output:

  1. Validate the whole answer with pydantic_model.model_validate_json(answer_text).
  2. If it validates and the alias-aware JSON-mode dump contains only finite numbers, return it directly. No LLM call.
  3. Otherwise (ValidationError, or NaN/Infinity anywhere in the payload), use the existing LLM extraction unchanged.

Whole-message only: no code-fence stripping, no substring extraction. Non-finite numbers are rejected because downstream JSON storage (Postgres JSON) rejects them; this covers bare NaN/Infinity, 1e999, and quoted "NaN" coerced to float. A NaN in an extra field the model ignores is dropped by Pydantic, so the stored payload stays finite and the fast path is used (documented in code).

Final answer Result
{"value": "direct"} Direct, no LLM call
{"some-key": "direct", "note": null} (alias + null) Direct; dumps as {"some-key": "direct", "note": null}
Prose, missing required field, forbidden extra field, fenced JSON LLM extraction (unchanged)
Non-finite numbers, unpaired surrogate LLM extraction

Tests

  • New tests/test_structured_output_agent.py: 18 offline tests (fake LLM, asserts no call on the fast path).
  • pytest tests/test_structured_output_agent.py tests/test_finalization_workflow.py tests/test_bounded_finalization.py: 50 passed.
  • Full suite: 2,933 passed, 10 failed. The same 10 fail on develop (c59fedf): CLI/device selection tests unrelated to this change.
  • ruff and black clean.

Out of scope

  • The 60 s finalization budget.
  • Task success semantics when extraction fails.
  • tasks-api pin bump: follow-up after this merges.

@Cyro292
Cyro292 requested a review from RasulOs December 2, 2026 15:37

@RasulOs RasulOs left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Codex: Preserve recoverable structured output

All 50 focused tests passed on df2c4225. I reproduced two cases where the fast path skips extraction and loses the answer. Please address both inline findings and add a regression test for each.

self.llm, self.pydantic_model, prompt, text=self.answer_text
)
try:
structured_output = self.pydantic_model.model_validate_json(

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Codex: [P2] Fall back when validation discards the entire answer

The documented dark-mode schema makes success and darkModeEnabled optional. With {"message":"Dark mode was successfully enabled"}, Pydantic ignores message, supplies both defaults, and the fast path reports success with {"success":null,"darkModeEnabled":null}. The original answer contains the information the extractor needs.

Please fall back when validation discards every field in a nonempty object. A regression test should also keep the fast path working when the answer supplies a recognized field alongside an ignored extra.

structured_output = self.pydantic_model.model_validate_json(
self.answer_text
)
except ValidationError:

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Codex: [P2] Preserve extraction after input-dependent conversion errors

For an SDK output model with ratio: Fraction, Pydantic raises TypeError on {"ratio":{"numerator":1,"denominator":2}}. This handler lets that exception reach the outer failure path. I ran the same input with a stub extractor on both revisions. The base called it once and accepted the normalized "1/2" value. This revision made zero calls and returned structured_output=None.

Please route recoverable errors from direct validation or the JSON-mode dump through the existing extractor, and cover an input the extractor can normalize.

…ops or can't parse the answer

- Nonempty objects take the fast path only if a key matches a declared
  field, validation alias, or retained extra.
- Any error from direct validation or JSON-mode serialization falls back
  to the existing extractor; only the exception type is logged.
- Second parse limited to object JSON on non-root models.

Refs DRO-4207
@Cyro292
Cyro292 requested a review from RasulOs December 2, 2026 17:41

@RasulOs RasulOs left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Codex: Preserve recoverable output in nested models

Both original examples now reach the extractor, and all 72 focused tests passed. I’m requesting changes for the remaining nested-object case documented inline.

and not (
answer.keys() & (structured_output.model_extra or {}).keys()
)
and not self._has_recognized_input_field(answer)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Codex: [P2] Fall back when a nested object loses all its fields

With an optional settings.darkModeEnabled field, the answer {"settings":{"message":"Dark mode enabled"}} passed this check because settings is recognized. The workflow returned {"settings":{"darkModeEnabled":null}} with success and zero extractor calls. The same loss occurs for model objects inside lists and for RootModel[Settings].

Please apply the discarded-field check to nonempty objects as they are matched to nested models, including list elements and model-valued roots. A regression test should assert that the extractor receives the original answer in this case and that a nested object supplying darkModeEnabled still takes the fast path.

…fields

Apply the discarded-field check to every input object matched to a model,
including nested fields, list/tuple elements, dict values and root models.
Fall back to extraction when input containers can't be matched to validated
values (length or key changes, unsupported container types).
…d beside discarded keys

If a model-matched object drops any input keys, the fast path now requires at
least one recognized non-null value, so answers like
{"success": null, "message": "..."} reach the extractor.
@Cyro292
Cyro292 requested a review from RasulOs December 3, 2026 17:11
if item is PydanticUndefined:
continue
recognized_keys.add(key)
recognized_non_null |= item is not None

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Codex: [P2] Preserve the answer when recognized fields contain only nulls

With {"settings":{"darkModeEnabled":null},"message":"Dark mode enabled"}, the workflow returned success with darkModeEnabled=null and made zero extractor calls. Line 93 counts the settings object as non-null even though its only field is null. I also reproduced this with a Pydantic AliasPath when message sits beside the null field inside settings.

When the check discards input, use the recognized leaf values to decide whether to skip extraction, and account for siblings along alias paths. An explicit null with no discarded input should still take the fast path.

@Cyro292
Cyro292 merged commit 6fe345a into develop Dec 4, 2026
9 checks passed
@Cyro292
Cyro292 deleted the fix/structured-output-json-fast-path branch December 4, 2026 07:33
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.

2 participants