Skip to content

fix(batch): validate complete root model payloads - #2743

Closed
imharjot wants to merge 2 commits into
567-labs:mainfrom
imharjot:fix/batch-root-model-results
Closed

imharjot wants to merge 2 commits into
567-labs:mainfrom
imharjot:fix/batch-root-model-results

Conversation

@imharjot

@imharjot imharjot commented Oct 4, 2026 •

Copy link
Copy Markdown

Describe your changes

Batch result parsing rejects valid Pydantic root models when the wrapped object has a field named root. Validate the complete decoded payload with model_validate() in both BatchProcessor and the BatchJob compatibility parser. Empty objects are also validated, allowing models with defaults to work.

Rebased onto current main at 035c77b7b04dbbf70ae4457eb102038907b5a2a4, preserving the new 1.18.0 release entries and keeping this fix under Unreleased. The production change and regression cases remain focused on batch result parsing.

Validation on Python 3.11.15, macOS, rebased head 923521d2c3a6c2d98d9cd5fd79dd23b3c0998acf:

  • Against exact unchanged current upstream, the 28 new regressions give 16 failures and 12 passing controls. With the fix, all 28 pass for OpenAI/Anthropic formats, ordinary/root models, file/string parsing, empty defaults and invalid records.
  • Focused batch suites: 140 passed.
  • Current CI's full offline selection (coverage run --branch -m pytest tests/ --asyncio-mode=auto --strict-config --strict-markers -m 'not llm' -k 'not docs'): 4,046 passed, 200 skipped, 862 deselected. The coverage gate passes with zero missing statements and 99.97% combined coverage. Provider credentials were removed; no live LLM requests were made.
  • Repository Ruff lint/format, source/test type checks, and configured changed-file pre-commit hooks pass. Type checks also pass with Python 3.9 and 3.14 and all-platform targets.
  • Installed-package public typing passes in an isolated wheel environment.
  • Core installed-wheel contracts, dependency checks and CLI help pass outside the checkout. All 28 batch regressions also pass with the Anthropic extra installed for the fresh compatible SDK selection (OpenAI 3.3.0 / Pydantic 2.14.1 / Anthropic 0.93.0) and declared floors (OpenAI 2.0.0 / Pydantic 2.8.0 / Anthropic 0.93.0).
  • The default packaging script hits macOS system Bash's empty-array/nounset issue. Its unchanged build/install/contract/CLI steps were completed with a portable Python runner; the minimum-SDK script itself also passes. No packaging script or project dependency change is included.
  • git diff --check passes; only the two parsers, their regression file and the existing changelog entry differ from upstream.

Latest-head GitHub Actions: maintainer approval required for Test, Package compatibility, Release Readiness, ty, Ruff. These workflows have not completed validation. Review/security bot checks are separate from build, test and runtime-matrix validation.

Issue ticket number and link

Fixes #2742

Checklist before requesting a review

  • I have performed a self-review of my code
  • If it is a core feature, I have added thorough tests.
  • If it is a core feature, I have added documentation.

AI-assisted implementation and regression testing; validation is recorded above.

@imharjot
imharjot force-pushed the fix/batch-root-model-results branch from 5c03dfd to 923521d Compare October 14, 2026 05:04
jxnl added a commit that referenced this pull request Oct 20, 2026
## Scope

Current candidate: **68f4e4e1211e7672463ae76495bade22f8c41c17**. All 29
runnable current-head checks passed; publication skipped. Independent
review found a recursive-schema crash in f4d7424; it was fixed and
independently re-reviewed at 93a913e. The external autofix then added
one more regression test in two commits; the runtime tree is unchanged.
That test-only delta has also been independently reviewed with no
actionable findings. Required approving GitHub review requested from
`vm` remains the sole merge blocker. Publication remains explicitly on
hold.

The user additionally selected batch strict-schema and failed-result
retrieval fixes. OpenAI schemas now require defaulted/nested fields,
normalize references/compositions, preserve aliases and metadata, and do
not mutate caller-owned schemas. Arbitrary-key mappings raise an
explicit error instead of silently losing their value schema; Anthropic
mappings are unchanged. Boolean-schema preservation is compatibility
behavior, not proof that OpenAI accepts every custom schema.

Completed OpenAI retrieval includes both output and error files, waits
for files indicated by request counts, and supports error-only batches.
With unknown counts it reads announced files without claiming their
completeness. Ended Anthropic batches return failed request records even
when none succeeded. Provider error type/message, request IDs and
original records are preserved. Running jobs remain unavailable. Added
native SDK/localhost retrieve-download contracts without new mocks or
paid requests.

## Current Validation

- Entire 25-file independent review found one P2: recursive described
references could create a cyclic dictionary and raise RecursionError.
Self-recursive and mutually recursive tests reproduced the failure
before the fix. Copied reference nodes and path-local active references
now preserve recursive back-references, metadata and strictness without
cycles. The generated schemas validate nested instances with Draft
2020-12 validation.
- Independent re-review verified the immutable 93a913e patch and found
no remaining actionable issue. 457 tests passed during the whole-diff
review at f4d7424; 78 focused tests passed after the repair. This
engineering review cannot substitute for the required independent GitHub
approval.
- The final test-only delta was independently reviewed at immutable
68f4e4e; all 19 schema cases passed. All **43 batch regressions pass
against the runtime-identical 93a913e installed wheel** on Python
3.9/OpenAI 2.0/Pydantic 2.8 and Python 3.13/OpenAI 3.3/Pydantic 2.14.
That wheel was built from sdist and passed Twine checks without
uploading.
- [Final exact-head full coverage
CI](https://github.com/567-labs/instructor/actions/runs/38118982055)
passed **4,140 tests, 200 skipped, 862 deselected**, 106 existing
warnings. It independently reports zero missing of 9,906 statements and
four missing of 3,514 branches; the unchanged 99% gate and zero-missing
assertion passed. Local runtime-identical 93a913e validation separately
passed 4,139 tests with **99.9702% coverage**. No old-head CI is reused.
- All 29 runnable final-head checks passed, including source/test
typing, lint, Python 3.9-3.13 offline coverage, wheel matrix and
provider jobs. [Current-head release-readiness
CI](https://github.com/567-labs/instructor/actions/runs/38118982058)
passed artifact preparation and Python 3.9/3.13 wheel smoke; publication
was skipped. Provider success badges do not certify skipped live
scenarios.
- Checkout and final diff are clean; all 25 files are maintained code,
tests, docs or changelog. No ad hoc reports or task plans are included.
- The matching old-head Bugbot finding is addressed in [this review
thread](#2767 (comment))
and resolved after test-backed independent verification. Requested
maintainer approval must cover the current head, not f4d7424. No admin
waiver applies to this PR.

## Prior Validation At f4d7424

- Final frozen-file combined offline suite: **4,137 passed, 200 skipped,
862 deselected**, 106 existing warnings, with CI mode, dotenv disabled
and API_KEY environment variables removed (374.22 seconds).
- **9,906 statements, zero missing; 3,514 branches, four missing;
99.9702% combined coverage.** The unchanged 99% gate and
zero-missing-statement assertion passed. The initial run overlapped
final schema edits and is not used as coverage proof; a fresh
separate-database run produced these final totals.
- Full source and test typing, Ruff lint/format checks, normal commit
hooks and clean diff passed.
- Final MkDocs build passed with existing nav/docstring warnings; wheel
built from sdist, and both Twine checks passed.
- **40 new batch regressions passed against the installed final wheel in
each environment:** Python 3.9/OpenAI 2.0/Pydantic 2.8 and Python
3.13/OpenAI 3.3/Pydantic 2.14. Site-packages imports verified, not
source-checkout imports. Prior 95-case installed-wheel proof belongs to
7ca0073.
- Common provider finalization/regression suite: 215 passed; falsey
adapter matrix rerun passed all 28 cases after test typing refinement.
- Independent read-only re-review of the new batch fixes, generated
TypedDict serializer and inherited finalizer found no actionable
finding. Review did not itself run tests and does not constitute GitHub
approval. Nested TypedDict-with-optional-key and direct
provider-entry-point matrix extensions remain additional coverage
opportunities; existing broad provider suites are separately validated.
- Independent final read-only batch review found no remaining actionable
issue after reference normalization and readiness/JSONL test gaps were
addressed. This does not constitute GitHub approval.
- All **29 runnable exact-head CI checks passed**; publication skipped.
[Full coverage
CI](https://github.com/567-labs/instructor/actions/runs/38092004959)
independently confirms 4,137 passed, 200 skipped, 862 deselected and
zero missing statements. [Release-readiness
CI](https://github.com/567-labs/instructor/actions/runs/38092004970)
passed preparation and wheel smoke tests without publishing. Provider
job success is not a claim that every live provider scenario ran; for
example, Google core-provider tests were skipped for missing settings.
- Initial independent GitHub review request sent to `vm` with
[exact-head
evidence](#2767 (comment)),
then updated to corrected head 93a913e in the addressed review thread
above. Do not treat approval of the old head as approval of the fix.

## Production-Wide Simplicity Review

Inspected all 205 production Python files across provider
implementations, core/DSL/validation, public/legacy/batch/CLI,
Decisions, and root integration. This is an
implementation/maintainability review with targeted regression
validation, not exhaustive security certification or universal
live-provider proof.

- Consolidated four identical OpenAI/Anthropic/Mistral/xAI result
finalizers into the existing ModeHandler base. Preserve SDK-specific
parsing, iterator laziness, falsey adapters, and exact raw-response
identity; old imported module names remain explicit compatibility
exports. Added a common four-provider behavioral matrix.
- Reproduced and repaired missing Anthropic tool input being accepted as
a defaulted empty result. Explicit returned empty objects still work.
- Reproduced and repaired request-ID/metadata loss on invalid non-object
batch payloads.
- Reproduced and repaired underscore TypedDict cache misses and
optional-key omission loss. Generated TypedDict models use narrowly
scoped round-trip serialization; arbitrary user-model alias behavior is
untouched.
- Kept compatibility facades, provider wire/SDK exceptions, security
limits, and streaming transport paths intact. Strict-schema and
failed-batch retrieval findings are now fixed with user authorization.
Streaming validation, native xAI context, CLI and registry-capability
issues remain focused follow-ups, not silently folded into this patch.

Integrate the five user-selected compact fixes onto main after #2708,
retaining version 1.18.0. Publication is explicitly on hold.

- [#2743](#2743) at
5c03dfd: validate complete batch
payloads with Pydantic, including RootModel and empty objects with
defaults.
- [#2758](#2758) at
13a11f4: retain Anthropic errored
result type/message, custom ID and raw record; preserve legacy error
handling.
- [#2757](#2757) at
3156d55: preserve underscore-prefixed
TypedDict keys with collision-safe internal fields and original aliases.
- [#2764](#2764) at
ab9b0c2: replace nonfunctional logging
environment instructions and unsupported correlation-ID claims.
- [#2765](#2765) at
faae38e: use the public Maybe model
factory instead of nonexistent field APIs.

The batch processor overlap is reconciled against merged main
035c77b. Release notes are consolidated
under 1.18 rather than separate Unreleased sections. Dynamic TypedDict
test construction and prepared-model narrowing were repaired for the
full test typing gate, without weakening assertions.

## Prior Validation

Candidate head: 128cf44.

- Focused combined regressions and Decisions contracts: 341 passed, 1
existing skip.
- Full source and test typing passed; repository Ruff lint/format checks
and normal commit hooks passed.
- Full MkDocs build passed with existing navigation/docstring warnings.
- Wheel built from sdist; Twine checks passed for both distributions.
- All 47 new batch/TypedDict regression cases passed against the
installed wheel on Python 3.9 with OpenAI 2.0.0/Pydantic 2.8.0 and
Python 3.13 with current core dependencies. Imports were verified to use
site-packages, not the checkout.
- Release metadata/notes validation passed for 1.18.0.
- Exact-head remote full offline suite: 4,057 passed, 200 skipped, 862
deselected; zero missing statements and four missing branches. The
unchanged 99% coverage gate passed.
- All 29 runnable exact-head CI checks passed, including Python 3.9-3.13
coverage, lint/type checks, wheel matrix, and release readiness/smoke
tests. Publication was skipped. Independent approval remains required;
this PR stays draft while the user-requested production-wide simplicity
review is ongoing.

The initial local full-suite invocation inherited provider keys and
lacked INSTRUCTOR_ENV=CI; it unexpectedly selected unmarked provider
tests and was stopped after 1,286 passes/15 skips. It is not complete
offline validation and is not used as a release gate. The corrected full
coverage run uses the repository's CI mode with API keys removed. No
intentional paid-provider experiments were added.

No new mocks, threshold changes, tags, issue closures or publication.
All 25 final files are maintained code, tests, docs or changelog; no ad
hoc reports/task plans are included. Source PRs are credited without
automatic issue-closing keywords.
@imharjot

Copy link
Copy Markdown
Author

This fix is now included in main through #2767 (6cd771c). The complete-payload validation and the root-model regressions from this PR are present upstream, along with additional batch error-handling coverage. The changelog also links back to #2743. I verified the unchanged upstream snapshot locally: all 148 tests across the root-model, batch processor, in-memory and batch coverage suites pass, without live provider requests. Closing this PR because there is no remaining runtime fix to merge here. Thanks for integrating it.

@imharjot imharjot closed this Oct 22, 2026
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.

Batch result parsers reject valid RootModel objects with a root field

1 participant