Skip to content

perf(compiler): reuse inference caches - #4461

Merged
antoniosarosi merged 1 commit into
canaryfrom
agent/perf-followups-4458
Aug 17, 2026
Merged

antoniosarosi merged 1 commit into
canaryfrom
agent/perf-followups-4458

Conversation

@antoniosarosi

@antoniosarosi antoniosarosi commented Aug 17, 2026 •

Copy link
Copy Markdown
Contributor

Summary

  • Thread the existing canonical subtype cache through provable_subtype call sites while retaining equality and infer/error filtering before cache entry.
  • Extract uncached definition and enum lookup helpers so short-lived AliasOnlyFacts avoids allocating memo maps.
  • Keep memoization on long-lived Facts, with the existing debug assertions preserving cache consistency checks.

This is a pure performance refactor with no intended semantic delta.

Benchmarks

benchmark canary baseline candidate repeats repeat-median delta
compile_baml_tests_project 2.114 s 2.193 s / 2.194 s +3.8%
compile_empty_project 490.7 ms 505.5 ms / 504.4 ms +2.9%

Both deltas are within the established +/-5% run-to-run band. The aggregate result is neutral/noisy, so this PR does not claim an end-to-end speedup; the win is the removal of redundant cache construction and canonical subtype work.

Scope note

The optional #4453 M4 item was skipped because it belongs to separate VM/GC benchmark and retention work rather than this contained compiler follow-up.

Validation

  • Focused nextest: 384/384 passed for baml_type, baml_compiler2_hir, and baml_compiler2_hir_ty with all features.
  • Strict Clippy passed for those packages across all targets and features.
  • Cargo format and diff checks passed.
  • Exact pinned full gate passed: 3748/3748 tests, 24 skipped, 51 slow, 1409.829 s; doctests clean; no unreferenced snapshots and no snapshots to review.

Full gate command: CARGO_BUILD_JOBS=8 rustup run 1.93.0 cargo insta test --test-runner nextest -p baml_tests -p baml_cli -p baml_lsp2_actions -p baml_lsp2_actions_tests -p baml_surface --all-features --unreferenced=reject

Summary by CodeRabbit

  • Bug Fixes

    • Improved type resolution for aliases and enum variants.
    • Improved type checking for pattern matching, assignment narrowing, and catch-arm handling.
    • Made subtype checks more consistent across interfaces, classes, arrays, unions, and pattern-based matching.
    • Improved handling of type narrowing and subtraction in flow analysis.
  • Performance

    • Reduced repeated subtype calculations during compilation, which may improve compiler responsiveness for complex type definitions.

@vercel

vercel Bot commented Aug 17, 2026 •

Copy link
Copy Markdown

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

Project Deployment Actions Updated (UTC)
beps Ready Ready Preview Aug 17, 2026 2:48am
promptfiddle2 Ready Ready Preview Aug 17, 2026 2:48am

Request Review

@vercel
vercel Bot temporarily deployed to Preview – beps August 17, 2026 02:41 Inactive
@github-actions

Copy link
Copy Markdown

⏭️ Performance benchmarks were skipped

Perf benchmarks (CodSpeed) are opt-in on pull requests — they no longer run on every push. They always run automatically after merge to canary/main.

To run them on this PR, do any of the following, then push a commit (or re-run CI):

  • Add RUN_CODSPEED=1 to the PR description, or
  • Include run-perf or /perf in the PR title or any commit message.

@coderabbitai

coderabbitai Bot commented Aug 17, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: b9d3b3f4-9c0c-4a8a-b2b9-faa4e77746ce

📥 Commits

Reviewing files that changed from the base of the PR and between fdd05ac and b4460b7.

📒 Files selected for processing (5)
  • baml_language/crates/baml_compiler2_hir_ty/src/facts.rs
  • baml_language/crates/baml_compiler2_hir_ty/src/impls.rs
  • baml_language/crates/baml_compiler2_hir_ty/src/infer.rs
  • baml_language/crates/baml_compiler2_hir_ty/src/infer/flow.rs
  • baml_language/crates/baml_compiler2_hir_ty/src/infer/pat.rs

Included review availability: Your plan includes up to 8 reviews per rolling hour; 7 remain after this review.


📝 Walkthrough

Walkthrough

The PR centralizes alias and enum-variant fact resolution and updates HIR inference, flow narrowing, and pattern analysis to use canonical subtype caching.

Changes

HIR type resolution and inference

Layer / File(s) Summary
Centralized fact resolution
baml_language/crates/baml_compiler2_hir_ty/src/facts.rs, baml_language/crates/baml_compiler2_hir_ty/src/impls.rs
Alias and enum-variant lookups use shared uncached helpers. AliasOnlyFacts stores the PPIR database directly. Existing cached queries remain in place.
Cached subtype contract
baml_language/crates/baml_compiler2_hir_ty/src/infer/pat.rs
provable_subtype accepts InternedCanonicalCache and uses cached subtype evaluation.
Inference and pattern consumers
baml_language/crates/baml_compiler2_hir_ty/src/infer/pat.rs, baml_language/crates/baml_compiler2_hir_ty/src/infer/flow.rs, baml_language/crates/baml_compiler2_hir_ty/src/infer.rs
Pattern coverage, narrowing, assignment checks, catch-arm matching, and union filtering pass the canonical cache to subtype checks.

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

Merge Risk: ⚪ Minimal · up to b4460

This performance refactor reuses existing inference caches without an intended behavior change. The reported validation passes, and no actionable merge-blocking risk remains after normal checks and review.

Possibly related PRs

Suggested reviewers: codeshaunted

Poem

I’m a rabbit with cached type hops,
Through aliases, patterns, and subtype stops.
Facts resolve clean, unions align,
Canonical checks save time in the line.
HIR burrows now compile just fine.

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly and concisely describes the primary change: reusing compiler inference caches.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.
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.
✨ 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 agent/perf-followups-4458

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.

@vercel
vercel Bot temporarily deployed to Preview – promptfiddle2 August 17, 2026 02:48 Inactive
@github-actions

Copy link
Copy Markdown

Binary size checks passed

✅ 7 passed

Artifact Platform File Gzip Gated on Baseline Delta Status
✅ baml-cli Linux 🔒 31.7 MB 12.6 MB file 31.7 MB +4.8 KB (+0.0%) OK
✅ packed-program Linux 🔒 24.9 MB 9.1 MB file 24.9 MB +23.8 KB (+0.1%) OK
✅ baml-cli macOS 🔒 25.4 MB 11.1 MB file 25.4 MB +54.4 KB (+0.2%) OK
✅ packed-program macOS 🔒 20.6 MB 8.2 MB file 20.6 MB +41.7 KB (+0.2%) OK
✅ baml-cli Windows 🔒 27.2 MB 11.3 MB file 27.2 MB +15.8 KB (+0.1%) OK
✅ packed-program Windows 🔒 21.7 MB 8.2 MB file 21.7 MB +8.8 KB (+0.0%) OK
✅ bridge_wasm WASM 21.3 MB 🔒 5.4 MB gzip 5.3 MB +33.8 KB (+0.6%) OK

🔒 = the size this artifact is GATED on (ceiling + delta). Binaries gate on file size (installed binary); WASM gates on gzip (download size). The other size is shown for information only.


Generated by cargo size-gate · workflow run

@antoniosarosi
antoniosarosi added this pull request to the merge queue Aug 17, 2026
Merged via the queue into canary with commit 07c118b Aug 17, 2026
73 checks passed
@antoniosarosi
antoniosarosi deleted the agent/perf-followups-4458 branch August 17, 2026 03:05
@antoniosarosi

Copy link
Copy Markdown
Contributor Author

Post-merge audit — this PR merged before its adversarial review completed

Verdict had this been pre-merge: SHIP-WITH-FIXES. Part (a) — threading the canonical cache through provable_subtype — is clean on all four attack angles (infer-filtering precedes every cache entry across all 16 routes with a deep has_infer flag verified variant-by-variant; no cross-body sharing is constructible; scoped-rigid/skolem safety carries over; the cached oracle is a line-for-line mirror). Part (b) — removing the AliasOnlyFacts memos — has two MAJOR problems now live on canary:

F1 (likely perf regression): the memo removal hit impls.rs:808 (impls_for_type_cached) and impls.rs:1114 (resolve_within_depth) — single instances deliberately hoisted across all-packages × all-impl-candidate scans. Alias-headed types there now re-run type_alias_value (NOT salsa-tracked — full RHS re-lowering) per candidate instead of once per scan; a List<SomeAlias> receiver against ~136 stdlib implements blocks re-lowers the alias ~136×. The stated rationale ("avoids allocating memo maps") is false: empty FxHashMaps don't allocate. Keep the memo-free form only at the four genuinely per-call sites (Facts::project, obligations.rs:527, method_resolution.rs:753, impls.rs:1757); restore memoization at the two scan sites.

F2 (measurement honesty): the PR's bench baseline was NOT rerun in-session (the log says so), and both table rows are regressions (+3.8% / +2.9%) waved off as within-band — compile_empty_project has no user bodies so part (a) barely runs there, while F1's scans do; a uniform ~3% is more consistent with F1 than with noise. Rerun back-to-back, split (a)-only vs (a)+(b).

Minor: F4 — make provable_subtype an InferenceContext method so the facts/cache pairing is structural; F3 — fix the "short-lived contexts" doc claim; F6 — one-sentence doc caveat on the salsa-cycle window widening (inherited from #4458, not a blocker).

Fast-follow PR dispatched.

meefs pushed a commit to meefs/baml that referenced this pull request Aug 17, 2026
## Summary

- restore alias and enum memoization only in the project-scale candidate
scans in impls_for_type_cached and resolve_within_depth
- keep the memo-free AliasOnlyFacts constructor at Facts::project,
infer/obligations.rs, method_resolution.rs, and interface_requires_inner
- make provable_subtype an InferenceContext method so the body facts and
canonical cache are structurally paired at every call
- correct the one-shot context documentation and document the Salsa
re-entrancy-window caveat for scan-local memos

This is the focused correction for the BoundaryML#4461 post-merge audit. It
restores repeated alias-head lookup reuse without widening memoization
to the four one-shot sites.

## Fresh back-to-back A/B

Both refs were measured consecutively in the same shell and target cache
with profiling disabled. Both workloads used exactly five one-compile
samples:

cargo bench -p baml_tests --bench compiler_benchmark -- compile_
--sample-count 5 --sample-size 1

Environment: Rust 1.93.0, CARGO_BUILD_JOBS=8, BAML_PROFILE=0.

| benchmark | canary 07c118b, 5 samples | candidate 0eb5f09, 5
samples | median delta |
| --- | ---: | ---: | ---: |
| compile_baml_tests_project | 2.180 s (2.144-2.351 s) | 2.133 s
(2.122-2.295 s) | -47 ms (-2.2%) |
| compile_empty_project | 497.5 ms (485.8-499.9 ms) | 485.6 ms
(478.2-488.5 ms) | -11.9 ms (-2.4%) |

No earlier baseline values are reused. Canary 07c118b was the exact
BoundaryML#4461 tip when this branch and A/B began; BoundaryML#4462 landed afterward and
changes only nextest scheduling configuration.

## Validation

- cargo check -p baml_compiler2_hir_ty
- focused nextest: 384/384 passed for baml_type, baml_compiler2_hir, and
baml_compiler2_hir_ty with all features
- strict all-target/all-feature Clippy passed for those packages;
workspace commit-hook Clippy also passed
- cargo fmt --all -- --check and git diff --check
- exact pinned full gate: 3,748/3,748 passed, 24 skipped, 50 slow in
1,375.321 s
- doctests clean; no unreferenced snapshots and no snapshots to review

Full gate command: CARGO_BUILD_JOBS=8 rustup run 1.93.0 cargo insta test
--test-runner nextest -p baml_tests -p baml_cli -p baml_lsp2_actions -p
baml_lsp2_actions_tests -p baml_surface --all-features
--unreferenced=reject

<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
## Summary by CodeRabbit

* **Improvements**
* Improved type inference consistency across assignments, pattern
matching, flow narrowing, and catch-arm analysis.
* Enhanced handling of aliases and enum variants during type resolution.
* Repeated type checks are now more efficient, helping reduce
unnecessary compiler work.
* Existing subtype, union, coverage, and narrowing behavior remains
consistent while benefiting from more centralized analysis.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->

This branch was previously deployed

2 inactive deployments
Preview – promptfiddle2 — b4460b7b Deployed Aug 17, 2026 by vercel[bot]
Preview – beps — b4460b7b Deployed Aug 17, 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.

1 participant