Skip to content

baml_cranelift: an optional union inside a union gets one flat type key - #5867

Draft
antoniosarosi wants to merge 5 commits into
claude/cranelift-bex2-rebasedfrom
antoniosarosi/cranelift-flat-union-keys
Draft

antoniosarosi wants to merge 5 commits into
claude/cranelift-bex2-rebasedfrom
antoniosarosi/cranelift-flat-union-keys

Conversation

@antoniosarosi

@antoniosarosi antoniosarosi commented Dec 4, 2026 •

Copy link
Copy Markdown
Contributor

[🤖 Claude on behalf of Antonio]

The native backend gives an optional union inside a union one flat type key, as the type checker already treats it. On top of #5850.

Why

The type checker treats (int | string)? | bool, (int | string | bool)? and int | string | bool | null as one type. The backend builds its runtime type keys with its own normaliser, and that one left a case nested: for a member that is optional it hoisted the null and kept the inner type as one member, also when the inner type was a union. So the same type had different type objects depending on how it was written, and a member could appear twice.

The shared library in #5853 reads those type objects, so every SDK back end met the nested shape and had to rebuild it.

What changes

Area Change
baml_cranelift normalize_union_keys, the only place that builds union and optional type keys, splices optional and union members at any depth, hoists null and drops duplicates, keeping the first

Before and after

Source type Before After
(int | string)? | bool Optional(Union[Union[int, string], bool]) Optional(Union[int, string, bool])
(int | bool)? | bool Optional(Union[Union[int, bool], bool]), bool twice Optional(Union[int, bool])

Member order is unchanged (depth first, as declared), so the runtime's first-match order for type tests and JSON decoding stays the same.

Observable changes

Type tests, match, the JSON decoder and encoder and CLI argument parsing walk union members recursively and in order, and no value carries a member index, so no program matches another member than before. A review that ran the same programs on both sides found three differences, all in JSON decoding:

  • A recursive type through such a union decodes deeper: class Node { next: (Node | int)? | string } used 4 of the decoder's 128 depth levels per node and now uses 3.
  • A member that appeared twice is tried once, so a FromJson hook on it runs once where it ran twice ((A | B)? | A).
  • DecodeError text: a nested union is no longer wrapped twice, and where a duplicate was dropped the message names another last member.

Tests

  • Unit tests of the normaliser, split into the shapes its callers really pass (5 of them fail on the old code) and defensive input.
  • cranelift_e2e: a program that takes and returns both types and matches on every member and null, plus the three cases above (a 40-level decode, a hook that runs once, an error wrapped once), each of which fails on a base build.
  • baml_cranelift, cranelift_e2e, pack_native_e2e and the bex2 crates pass on arm64 and on x86-64 (Linux machine, Ryzen 9 5950X), except three failures that are identical on the base.

hellovai and others added 4 commits December 2, 2026 21:54
…ped JSON errors, and @@rust_type slots

- Fix ARM64 (FEAT_LRCPC) Dekker lost-wakeup races in bex2_scheduler by
  upgrading wake_task, io_notified, CancelToken, Semaphore admission,
  AtomicLockTable, Future settlement, and AwaitAnyGroup paired atomic
  loads/stores/CASes to Ordering::SeqCst.
- Support uint8array (BytesObject) indexing in array_get, array_set
  (with low-8-bit masking and COW protection on shared Arc), and array_len.
- Decode uint8array.to_string() lossily as UTF-8 via baml_rt_bytes_to_string_lossy
  instead of returning debug '<uint8array len=N>'.
- Register and throw typed baml.json.{ParseError, DecodeError, SerializationError}
  instances with jq-style paths and reason tags from baml_rt_json_* entrypoints.
- Emit synthetic handle slot 0 for @@rust_type classes with zero BAML fields in
  rodata.rs and align Semaphore._admit/_admitted/_wait_permit with Permit handles.
- Add unit, Dekker stress, and Cranelift E2E regression tests (29/29 passing).
…t type key

The type checker treats (int | string)? | bool, (int | string | bool)? and
int | string | bool | null as one type, but normalize_union_keys pushed the
inner type of an Optional member as a single member. When that inner type was
a union, the key stayed nested: Optional(Union[Union[int, string], bool]), and
(int | bool)? | bool listed bool twice. Equal types then got different static
type objects, and anything reading union members (the bex2_boundary library)
had to flatten them itself.

normalize_union_keys now splices every Optional and Union in a member at any
depth, depth first in declaration order, hoists null, and drops duplicates
keeping the first occurrence. Union members are never Null, Optional or Union.
The runtime tests and decodes union members in order and recursively, so the
flat key matches the same values in the same order.
@vercel

vercel Bot commented Dec 4, 2026 •

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated
developer-docs Ready Ready Preview Dec 4, 2026 5:59pm UTC

Request Review

@antoniosarosi

Copy link
Copy Markdown
Contributor Author

@coderabbitai review

@coderabbitai

coderabbitai Bot commented Dec 4, 2026 •

Copy link
Copy Markdown
Contributor

Explain Change →

No actionable comments were generated in the recent review.

Walkthrough

Union key normalization now recursively flattens nested unions and optionals, removes duplicate members, and handles nullability and degenerate results. Unit and end-to-end tests cover normalization and compiled behavior.

Changes: Optional union normalization

Layer / File(s) Summary
Normalize union keys and validate behavior
baml_language/crates/baml_cranelift/src/reach.rs, baml_language/crates/baml_tests/tests/cranelift_e2e.rs
Normalization recursively flattens nested unions and optionals, preserves each member’s first depth-first occurrence, and produces a result based on the remaining members and nullability. Unit tests cover nested, duplicate, null, and degenerate cases. An end-to-end test covers member matches, a type test, and JSON decoding and serialization for optional union shapes.

Estimated code review effort: 3 (Moderate) | ~20 minutes

Change: Bug fix

Suggested reviewers: hellovai

Merge Risk: Minimal · up to 6dda5

This change makes equivalent optional and union types share one flat runtime type key. No actionable merge-blocking risk was identified, and the new unit and end-to-end tests cover the changed behavior.

Security architecture risk: Minimal · up to 6dda5

baml_cranelift now emits one flat, ordered representation for equivalent optional unions. The native JSON decoder already walks union members in order and checks nullability recursively. The change introduces no identified access-control or deployment risk.

Security review details

Security Blast Radius

  • inferred — The representation change reaches native artifacts that emit the affected union types, not just the new test. The inspected change adds no caller or authority; downstream exposure depends on which consumers inspect the emitted type objects.

Trust Boundaries and Controls

  • observed — JSON supplies values, while compiler-emitted type metadata supplies the alternatives the decoder tries. For omitted fields, the decoder already accepts a null default when either the descriptor flag or the recursive type check establishes nullability; it does not rely solely on the top-level flag.

Dependencies

  • inferred — The PR cites the shared library from #5853 and SDK readers as consumers of these type objects. A reader that exposes immediate members or keys on the old nested structure would observe the change; the reader implementations were not available for verification, so compatibility at that boundary remains unconfirmed.

Data and control flow

  • observed — Template and runtime type conversion feed the same normalizer. Static type registration deduplicates equal keys, and rodata emits the resulting union arguments in slice order.

Resilience and Maintainability Implications

  • inferred — The JSON decoder still enforces its existing recursion limit and tries non-null alternatives in first-occurrence order. Flattening removes some type-wrapper traversals, so a decode near the limit can behave differently even though the limit itself is unchanged.
Pre-merge checks: Passed 4

Check name Status Explanation
Title check Passed The title names the main change: an optional union nested inside another union is normalized to a single flat type key in baml_cranelift. The raw summary states that normalize_union_keys now flattens …
Linked Issues check Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check Passed Check skipped because no linked issues were found for this pull request.
Description Check Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Full details: Title check

Explanation

The title names the main change: an optional union nested inside another union is normalized to a single flat type key in baml_cranelift. The raw summary states that normalize_union_keys now flattens nested Union and Optional members, hoists nullability, and removes duplicates. The PR objectives describe the same goal, with equivalent types such as (int | string)? | bool sharing one flat runtime type key. The title is specific and matches the changeset.

Finishing Touches

Generate unit tests (beta)

  • Commit to this branch
  • Create a new PR
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

A rabbit checks each nested type,
And gathers members in their order.
It keeps the first of each it finds,
Then lifts the null to wrap the border.
Tests hop through the compiled path,
While JSON travels out and back.

Recent review info

Run configuration

  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: Repository UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 0b22d3b2-c75e-4510-82e0-420cd438dbf9
Commits

Reviewing files that changed from the base of the PR and between 9b60d93 and 6dda5b1.

Files selected for processing: 2

  • baml_language/crates/baml_cranelift/src/reach.rs
  • baml_language/crates/baml_tests/tests/cranelift_e2e.rs

Included review availability: This review used your included allowance. Your plan provides up to 8 included reviews per hour; 7 remain after this review.

@coderabbitai

coderabbitai Bot commented Dec 4, 2026 •

Copy link
Copy Markdown
Contributor
Action performed

Review finished.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@blacksmith-sh

blacksmith-sh Bot commented Dec 4, 2026 •

Copy link
Copy Markdown
Contributor

Found 18 test failures on Blacksmith runners:

Failures

Test View Logs
Anthropic Provider/Anthropic Provider should support anthropic shorthand View Logs
Anthropic Provider/
Anthropic Provider Streaming should support anthropic shorthand streaming
View Logs
AWS Provider/
AWS Provider Dynamic Client Registry Credential Resolution should handle session creden
tials correctly
View Logs
AWS Provider/
AWS Provider Dynamic Client Registry should throw error when using temporary credential
s without session token
View Logs
Azure Provider/
Azure Provider should support o1 model with explicit max_completion_tokens
View Logs
Collector Tests/Collector Tests should track cached input tokens for Anthropic caching View Logs
Experimental OnTick/
Experimental OnTick should fire onTick callbacks for async non-streaming function
View Logs
Experimental OnTick/
Experimental OnTick should fire onTick callbacks for streaming function
View Logs
Experimental OnTick/Experimental OnTick should handle onTick callback errors View Logs
Experimental OnTick/Experimental OnTick should not significantly impact performance View Logs

...and 8 more test failures. View all on Blacksmith

Fix with [code]smith
Need help on this PR? Tag @codesmith-bot with what you need.

…rong

The end-to-end test passed on the base with the same output, so it did not
test the change. It now checks three things the nested keys did differently,
and all three lines fail on the base (checked by packing the same program
with a base build):
- decoding class Node { next: (Node | int)? | string } 40 levels deep
  succeeds; the base throws a DecodeError, because each node used 4 of the
  decoder's 128 depth levels through the nested key and uses 3 now;
- decoding into (A | B)? | A runs A's FromJson hook once when nothing
  matches; the base tried A twice and ran it twice;
- the DecodeError for [1] into bool | (int | string)? wraps the member
  error once; the base wrapped it twice, through the nested union.

The unit tests now use the member shapes the three callers really pass
(already normalised keys: Optional(Union), Union of plain members), including
a three-level type built level by level through the normaliser. Five of them
fail on the old normaliser; three guard shapes it already handled. Shapes the
callers never produce (a union holding null or an optional, Optional(Null),
a one-member union) moved to defensive_* tests, which the module comment
says.
@antoniosarosi

Copy link
Copy Markdown
Contributor Author

[🤖 Claude on behalf of Antonio]

An adversarial review built the base and this branch, packed 9 programs with baml pack --native and ran each plain and under GC stress. No program crashed, failed to compile or link, or matched another union member than on the base; linking with all three spellings in one program, generics, interface dispatch, closures, thrown values and containers held.

It found that the change is observable in JSON decoding in three ways, all listed in the description now, and that the first end-to-end test passed on the base too. 3f75675d1b replaces it with the three cases, each checked to fail on a base build, and separates the unit tests into the shapes the callers really pass and defensive input.

#5853 (the shared library) is retargeted onto this PR.

@hellovai
hellovai force-pushed the claude/cranelift-bex2-rebased branch from 9b60d93 to fb530c3 Compare December 4, 2026 19:04

This branch was successfully deployed

1 active deployment
Preview – developer-docs — 3f75675d Deployed Dec 4, 2026 by vercel[bot]
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