Skip to content

Fix msgspec enum discriminator tag#3170

Merged
koxudaxi merged 1 commit into
mainfrom
fix-msgspec-enum-discriminator-tag
May 23, 2026
Merged

Fix msgspec enum discriminator tag#3170
koxudaxi merged 1 commit into
mainfrom
fix-msgspec-enum-discriminator-tag

Conversation

@koxudaxi

@koxudaxi koxudaxi commented May 23, 2026

Copy link
Copy Markdown
Owner

Fixes #3152

Summary by CodeRabbit

Release Notes

  • Bug Fixes

    • Fixed discriminator tag assignment in msgspec.Struct code generation when handling single literal enum values in OpenAPI schemas.
  • Tests

    • Added test coverage for msgspec.Struct discriminator generation with single-value enums.

Review Change Stack

@coderabbitai

coderabbitai Bot commented May 23, 2026

Copy link
Copy Markdown

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 38b7f7be-78cf-4249-aae8-77b2e98fb765

📥 Commits

Reviewing files that changed from the base of the PR and between fcb57e6 and 9b08b55.

⛔ Files ignored due to path filters (1)
  • tests/data/openapi/discriminator_enum_single_value_msgspec.yaml is excluded by !tests/data/**/*.yaml and included by none
📒 Files selected for processing (3)
  • src/datamodel_code_generator/parser/base.py
  • tests/data/expected/main/openapi/discriminator/enum_single_value_msgspec.py
  • tests/main/openapi/test_main_openapi.py
✅ Files skipped from review due to trivial changes (1)
  • tests/data/expected/main/openapi/discriminator/enum_single_value_msgspec.py

📝 Walkthrough

Walkthrough

Sets msgspec.Struct variant tag to the literal representation (repr(expected_value)) for single-value enum discriminators and adds a test with expected generated Msgspec models validating the change.

Changes

Enum Discriminator Literal Resolution

Layer / File(s) Summary
Discriminator tag value resolution in msgspec.Struct
src/datamodel_code_generator/parser/base.py
In the msgspec.Struct discriminator path, when a single literal matches the expected value, the base-class kwarg tag is now set to repr(expected_value) instead of using discriminator_field.represented_default.
Test case and expected output
tests/main/openapi/test_main_openapi.py, tests/data/expected/main/openapi/discriminator/enum_single_value_msgspec.py
Adds test_main_openapi_discriminator_enum_single_value_msgspec which generates msgspec.Struct output for a discriminator with single-value enums and compares against the new golden file defining StartedEvent and StoppedEvent tagged Structs and an Event union alias.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~12 minutes

Possibly related PRs

  • koxudaxi/datamodel-code-generator#3070: Both PRs modify src/datamodel_code_generator/parser/base.py’s OpenAPI discriminator value handling—Fix non-string OpenAPI discriminator literals #3070 changes how expected_value/discriminator candidates are derived for non-string literals, and the main PR adjusts the emitted msgspec.Struct discriminator tag based on that expected_value.
  • koxudaxi/datamodel-code-generator#3115: Both PRs modify src/datamodel_code_generator/parser/base.py discriminator handling to correctly compute discriminator literals/tag values (main: msgspec single-literal default uses repr(expected_value); retrieved: /reuse discriminator subclasses recover the proper literal instead of injecting/duplicating the wrong one).

Suggested labels

breaking-change-analyzed

Poem

🐰
I hopped through enums to find the right name,
Repr of the literal put tags in their frame.
No more None in the class declaration,
Msgspec structs now match expectation. 🎉

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 75.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title 'Fix msgspec enum discriminator tag' is clear and directly addresses the main change—fixing how msgspec.Struct discriminator tags are generated for single-value enum fields.
Linked Issues check ✅ Passed The PR addresses issue #3152 by modifying the discriminator tag generation logic to use repr(expected_value) instead of discriminator_field.represented_default for msgspec.Struct single-literal discriminators [#3152].
Out of Scope Changes check ✅ Passed All changes are directly related to fixing msgspec discriminator tag generation: the core fix in parser/base.py, test data file, and new test case all focus on the discriminator tag issue.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix-msgspec-enum-discriminator-tag

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@github-actions

github-actions Bot commented May 23, 2026

Copy link
Copy Markdown
Contributor

📚 Docs Preview: https://pr-3170.datamodel-code-generator.pages.dev

@codspeed-hq

codspeed-hq Bot commented May 23, 2026

Copy link
Copy Markdown

Merging this PR will not alter performance

⚠️ Unknown Walltime execution environment detected

Using the Walltime instrument on standard Hosted Runners will lead to inconsistent data.

For the most accurate results, we recommend using CodSpeed Macro Runners: bare-metal machines fine-tuned for performance measurement consistency.

✅ 11 untouched benchmarks
⏩ 98 skipped benchmarks1


Comparing fix-msgspec-enum-discriminator-tag (9b08b55) with main (4d0d9a9)

Open in CodSpeed

Footnotes

  1. 98 benchmarks were skipped, so the baseline results were used instead. If they were deleted from the codebase, click here and archive them to remove them from the performance reports.

@koxudaxi koxudaxi marked this pull request as ready for review May 23, 2026 08:06
@koxudaxi koxudaxi marked this pull request as draft May 23, 2026 08:07
@koxudaxi koxudaxi marked this pull request as ready for review May 23, 2026 08:09
@codecov

codecov Bot commented May 23, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 100.00%. Comparing base (4d0d9a9) to head (9b08b55).

Additional details and impacted files
@@            Coverage Diff            @@
##              main     #3170   +/-   ##
=========================================
  Coverage   100.00%   100.00%           
=========================================
  Files           93        93           
  Lines        20025     20027    +2     
  Branches      2338      2338           
=========================================
+ Hits         20025     20027    +2     
Flag Coverage Δ
unittests 100.00% <100.00%> (ø)

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@koxudaxi koxudaxi force-pushed the fix-msgspec-enum-discriminator-tag branch from fcb57e6 to 9b08b55 Compare May 23, 2026 08:20
@koxudaxi koxudaxi marked this pull request as draft May 23, 2026 08:20
@koxudaxi koxudaxi marked this pull request as ready for review May 23, 2026 08:25
@koxudaxi koxudaxi marked this pull request as draft May 23, 2026 08:29
@koxudaxi koxudaxi marked this pull request as ready for review May 23, 2026 08:30
@koxudaxi koxudaxi merged commit 0db5cdc into main May 23, 2026
44 of 45 checks passed
@koxudaxi koxudaxi deleted the fix-msgspec-enum-discriminator-tag branch May 23, 2026 08:45
@github-actions

Copy link
Copy Markdown
Contributor

Breaking Change Analysis

Result: No breaking changes detected

Reasoning: The PR contains two categories of changes: (1) A bug fix for msgspec discriminator tag generation (parser/base.py), changing from discriminator_field.represented_default to repr(expected_value). This corrects previously incorrect generated code for single-value enum discriminators with msgspec.Struct output — the tag value was wrong before and is now correct. This is a correctness fix, not a breaking change. (2) Removal of _schema_requires_model_type and _allof_requires_model_type methods from parser/jsonschema.py, which reverts changes introduced in the immediate parent commit (53ba11d). That parent commit is NOT included in any released version (it sits between 0.57.0 and this PR), so users upgrading from 0.57.0 would never have seen the reverted behavior. Therefore, neither change constitutes a breaking change for released users.


This analysis was performed by Claude Code Action

@github-actions

Copy link
Copy Markdown
Contributor

🎉 Released in 0.58.0

This PR is now available in the latest release. See the release notes for details.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

msgspec.Struct discriminator tag is generated as None for single-value enum discriminator fields

1 participant