Skip to content

Fix root leaf handling in traverse_util - #5565

Draft
tandede wants to merge 1 commit into
google:mainfrom
tandede:fix/root-leaf-unflatten
Draft

Fix root leaf handling in traverse_util#5565
tandede wants to merge 1 commit into
google:mainfrom
tandede:fix/root-leaf-unflatten

Conversation

@tandede

@tandede tandede commented Aug 20, 2026

Copy link
Copy Markdown

What does this PR do?

flatten_dict() allows is_leaf to select the root dictionary. Without a separator this produces the valid flat representation {(): value}, but unflatten_dict() previously indexed the empty path and raised IndexError instead of restoring the original dictionary.

This change recognizes a sole empty tuple path as the root value. It also rejects a root path combined with other paths, since such an input cannot represent one tree unambiguously.

When a string separator is requested, the empty root path and a real empty-string key both encode as "". Root-leaf selection in that mode now raises a descriptive ValueError rather than silently restoring a different structure. Existing empty-string keys continue to round-trip unchanged.

Validation

  • uv run pytest -q tests/traverse_util_test.py tests/serialization_test.py tests/struct_test.py — 127 passed, 4 skipped
  • uv run pre-commit run --files flax/traverse_util.py tests/traverse_util_test.py — all hooks passed
  • Full core suite — 3196 passed, 14 skipped; one unrelated local-environment failure in SummaryTest.test_tabulate_enum because Rich emitted plain text while the test expects ANSI color escapes

Checklist

  • This PR fixes a minor issue (e.g.: typo or small bug) or improves the docs (you can dismiss the other checks if that's the case).
  • This change is discussed in a Github issue/discussion (not required for this minor bug).
  • The documentation and docstrings adhere to the documentation guidelines.
  • This change includes necessary high-coverage tests. (No quality testing = no merge!)

@google-cla

google-cla Bot commented Aug 20, 2026

Copy link
Copy Markdown

Thanks for your pull request! It looks like this may be your first contribution to a Google open source project. Before we can look at your pull request, you'll need to sign a Contributor License Agreement (CLA).

View this failed invocation of the CLA check for more information.

For the most up to date status, view the checks section at the bottom of the pull request.

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.

1 participant