Skip to content

fix(merge): replace discriminated union fields when the variant changes - #36

Merged
jimmy-phantom merged 1 commit into
mainfrom
fix/union-field-variant-replace
Jun 4, 2026
Merged

jimmy-phantom merged 1 commit into
mainfrom
fix/union-field-variant-replace

Conversation

@jimmy-phantom

Copy link
Copy Markdown
Collaborator

Problem

The runtime entity merge does not handle a discriminated union field whose variant changes. A union's compiled shape is keyed by __typename (e.g. { VariantA: ..., VariantB: ... }), not by field. When mergeFields hit a union field with two plain-object values, it recursed into that typename-keyed shape, which matches none of the actual payload fields. As a result, on a variant change the old variant's object was left untouched (its discriminator and fields persisting) and the new variant's fields never landed.

The single-object-union path (t.union(t.object({...}), t.string)) was unaffected because it collapses to a flat field shape; the bug only surfaced with a true discriminated union of two or more object variants.

Fix

Treat a union field as an atomic tagged value and replace it wholesale rather than merging field by field. A changed variant becomes the new value; the old variant's fields can no longer survive.

This mirrors how entity unions already behave: a changed __typename yields a different entity key, so the field repoints to a fresh entity. Non-entity unions have no key, so the merge has to reproduce that explicitly. There is no partial-update path to preserve for non-entity unions: a partial variant payload fails validation, so every update carries the full variant.

Test

branch-fixes.test.ts adds a regression test: an entity with a t.union(QueuedState, RunningState) field, flipped from one variant to the other on refetch, asserting the new discriminator and fields are present and no field from the old variant survives.

Full suite green; type-check clean (one unrelated pre-existing error in react/__tests__/component.test.tsx).

The runtime merge recursed into a union's typename-keyed shape, which
matches no real field, so when a field's variant changed the old
variant's fields stayed in place and the new variant's never landed.
Treat union fields atomically and replace them wholesale.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
@nithilan-phantom

Copy link
Copy Markdown

🔥

@jimmy-phantom
jimmy-phantom merged commit 08950ad into main Jun 4, 2026
1 of 3 checks passed
@jimmy-phantom
jimmy-phantom deleted the fix/union-field-variant-replace branch June 4, 2026 22:05
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.

3 participants