Skip to content

fix(types): a union with a repeated member equals itself - #1365

Closed
mareklangiewicz wants to merge 4 commits into
EmmyLuaLs:mainfrom
mareklangiewicz:fix-union-eq-repeated-member
Closed

mareklangiewicz wants to merge 4 commits into
EmmyLuaLs:mainfrom
mareklangiewicz:fix-union-eq-repeated-member

Conversation

@mareklangiewicz

@mareklangiewicz mareklangiewicz commented Nov 5, 2026 •

Copy link
Copy Markdown
Contributor

Summary

LuaUnionMembers::eq is not reflexive when a member repeats, and that can overflow the stack.

 eq(self, other)
-  types = HashSet(self.types)            # A|A|B collapses to {A, B}
-  every other member: types.remove(ty)   # the second A is not found: a == a is false
+  if self.types == other.types: return true
+  count self.types, then take each of other.types off its count

unify_call_bindings takes expanded_arg != arg as progress, so it recurses for as long as a union with a repeated member differs from its own rebuild:

unify_call_bindings(Holder<T>, A|A|B)
  expand_alias_generic -> A|A|B, != arg
  unify_call_bindings(Holder<T>, A|A|B)
    ...

The union comes from flow analysis, not from an annotation: here parse is assigned the same call twice, with a closure in between.

---@class Holder<T>
local Tree = {}
---@generic T
---@param f Holder<T>
local function take(f, ...) end
function Tree:start(range)
  ---@type fun(): table<integer, TSTree>, boolean
  local parse = coroutine.wrap(self._parse)
  local function step()
    if type(source) == 'number' then
      if buf.changedtick ~= ct then
        parse = coroutine.wrap(self._parse)
      end
    end
    take(parse, self, range)
  end
end
function Tree:_parse(range) end

It is reduced from neovim's runtime/lua/vim/treesitter/languagetree.lua.

Main reaches the loop on real code too: on b889a2d1, emmylua_check aborts with a stack overflow on async.nvim (lua/async/_core.lua). Reduced, with no generic param on the callee:

---@class Task<R>
---@field _parent? Task<any>
local Task = {}
---@param task Task<any>
local function clear(task) end
function Task:_resume()
  if self._awaiting._parent ~= self or self._awaiting:completed() then end
  clear(self)
end

The flow type of self at clear(self) is Task|Task<any>|nil|Task, and the Generic arm recurses on it.

Since the need-check-nil rewrite (#1418, first bad commit 280987f7 by bisect from 0.25.1), main can also hang on it. A return union with a repeated member is unequal to itself, so Comparisons::intern never finds its own key, and each read interns a new comparison. On main 48ef52a0, emmylua_check does not finish these two files (>90 s, flat memory); with this change it takes 0.14 s. Reduced from snacks.nvim (picker/config/init.lua, picker/actions.lua):

-- a.lua
---@class G
---@field cfg Cfg
---@class Cfg
local M = {}
function M.layout(opts)
  local layout = M.resolve(opts)
  ---@cast layout X
  if not layout.layout then
    ---@cast layout X|{preview: boolean}
    if layout.preview == false then
    end
  end
  return layout -- table|X|X
end
---@generic T
---@return T
function M.resolve(v)
end
-- b.lua
local layout = G.cfg.layout()

On the whole snacks.nvim tree main gets through in 7.4 s, but a small change to flow narrowing elsewhere is enough to route it into this shape and time out (#1361 does).

Evidence

The three tests are in this PR, on the branch merged with main 48ef52a0; "before" is LuaUnionMembers::eq as on main:

  • Before:
    union_with_a_repeated_member_equals_itself: FAILED, A|A|B != A|A|B
    test_union_arg_with_repeated_member_no_crash: has overflowed its stack
    test_return_union_with_repeated_member_no_hang: times out at 5 s, 10 runs of 10 (after: 0.02 s, 10 of 10)
  • After: all pass. emmylua_code_analysis 1988 and emmylua_ls 243 lib tests pass; fmt and clippy pass.
  • Corpus (emmylua_check on 59 Neovim plugin trees and neovim's runtime/, against main 48ef52a0): async.nvim, bufferline.nvim and neovim-runtime no longer crash and finish. On the trees both builds finish, 13 lines change, all assign-type-mismatch on record literals in blink.cmp, diffview.nvim and nui.nvim; main alone flips the same lines from run to run (the field order picked for the message, fix(check): a record literal's first mismatching field is the same every run #1437), so no hit changes (57302 → 57301 is one such pair).

Merge Danger

Door: two-way

Blast Radius: diagnostics

Any code comparing unions now gets true for equal unions with repeated members, and A|A|B stays unequal to A|B|B. On a fork of main carrying this change, diagnostics on three Lua repos did not change.


Written with help from Claude Code.

LuaUnionMembers::eq collected one side into a HashSet and removed the
other side's members from it, so a repeated member failed its second
remove: `a == a` was false. unify_call_bindings takes `expanded_arg !=
arg` as progress, so such a union passed to a generic class param never
settled and overflowed the stack.

Count members instead, which matches the hash, a sum over members. An
in-order compare answers first, so the usual equal case allocates nothing.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_018NxUUN2Yt6d9cgKQzcoC84

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

Summary

The change fixes a real correctness bug: PartialEq for LuaUnionMembers used a HashSet, which silently collapses duplicate members. A union containing a repeated member (e.g. A | A | B) could therefore compare unequal to itself, breaking the reflexivity contract of PartialEq and causing infinite recursion/stack overflow during generic expansion. The fix is sound and the tests are appropriate.

Issues & Suggestions

1. PartialEq / Hash contract (important)

The new implementation makes equality multiset-based (order-insensitive, count-sensitive). This is only correct if Hash for LuaUnionMembers is also multiset-based (i.e. order-insensitive and count-sensitive). Please verify:

  • If Hash iterates members in order, then A|B and B|A would be equal but hash differently → violates the Hash/Eq contract.
  • If Hash uses a HashSet/dedup, then A|A|B and A|B would hash the same but compare unequal → also a violation.

The test comment ("their hashes differ, so they must not be equal") suggests hashing is count-sensitive, but this should be asserted explicitly, e.g.:

assert_eq!(FxBuildHasher.hash_one(&union()), FxBuildHasher.hash_one(&union()));
assert_ne!(FxBuildHasher.hash_one(&union()), FxBuildHasher.hash_one(&other));

and ideally a test that A|B == B|A with equal hashes.

2. Fast path is redundant but harmless

if self.types == other.types {
    return true;
}

This is a reasonable optimization for the common case, but note it relies on Vec element-wise equality. It's fine, though the comment could clarify it's a fast path rather than a semantic requirement.

3. HashMap import

The diff uses HashMap in complex.rs but the import isn't shown. Ensure use rustc_hash::FxHashMap as HashMap; (or equivalent) is present — otherwise this won't compile. Given the file already uses FxBuildHasher, prefer FxHashMap for consistency and performance over std::collections::HashMap.

4. Missing len check in the new path

The old code implicitly relied on types.is_empty() after removal. The new code checks count > 0 per element, which is correct, but if other.types has fewer elements than self.types, leftover counts are never checked. Example: self = [A, A], other = [A] → all() returns true, but the multisets differ. The early self.types.len() != other.types.len() check at the top of the function (visible in context) covers this — please confirm it's still present and runs before the new logic. If it was removed, this is a bug.

5. Test quality

  • test_union_arg_with_repeated_member_no_crash only asserts "no panic". Consider also asserting the expected diagnostic count (or at least that diagnose_file returns Ok) to catch regressions where the crash is fixed but diagnostics are wrong.
  • The test uses undefined globals (source, buf, ct, TSTree) intentionally to reproduce the bug; a brief comment noting this is deliberate would help future readers.

6. Style nit

let mut counts = HashMap::<_, usize>::with_capacity(self.types.len());

The turbofish is unnecessary; HashMap::with_capacity(...) infers fine. Minor.

Verdict

The core fix is correct and well-motivated. Main follow-ups: verify the Hash/Eq contract for the multiset semantics, confirm the length pre-check still exists, and use FxHashMap for consistency.

…changes the hash

Answers the review: Eq counts members and the hash sums over them, so
order does not count and repeats do, on both sides.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_018NxUUPGy5eT16LumQqytKE
@mareklangiewicz

Copy link
Copy Markdown
Contributor Author

Thanks. Point by point:

  1. Hash/Eq contract: the hash is a wrapping sum of the member hashes plus the length, so it ignores order and counts repeats, the same as the new eq. b25bc0d asserts it: A|A|B == B|A|A with equal hashes, and A|A|B hashes differently from A|B.
  2. Fast path: yes, it is only a fast path. It makes the common in-order case cheaper (test_issue_1100: 1.27 s with it, 2.1 s without).
  3. HashMap: the file already imports hashbrown::{HashMap, HashSet}, and the old code used that HashSet. I kept the same crate.
  4. Length check: still there, and it still runs first, so [A, A] against [A] is rejected before counting.
  5. Crash test: it only guards the overflow. The diagnostics are not what it is about, and the unit test covers the equality.
  6. Turbofish: fine either way, so I left it.

This is now a crash on main, not just a latent one: on b889a2d1, emmylua_check aborts with a stack overflow on async.nvim. I've updated the description with a 9-line repro, and I'm marking this ready.


Written with help from Claude Code.

mareklangiewicz and others added 2 commits November 23, 2026 22:01
…e check

Reduced from snacks.nvim: since the need-check-nil rewrite (EmmyLuaLs#1418), checking
the second file compares `table|X|X` against a closure signature. Without
the fix that union is unequal to itself, so Comparisons::intern never finds
its own key and the check never ends (main 48ef52a: >90 s on the two files).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_018NxUURcPwXMM3gTzFZqTDa
@mareklangiewicz

Copy link
Copy Markdown
Contributor Author

Merged main 48ef52a0 and added a third test. Since the need-check-nil rewrite (#1418), main can also hang on this bug: a return union with a repeated member never settles in Comparisons::intern. Two files reduced from snacks.nvim make emmylua_check on main run for 90 s+ without finishing; with this change they take 0.14 s. The fixture and re-measured numbers are in the description. On the corpus this change also lets async.nvim, bufferline.nvim and neovim's runtime/ finish where main crashes.


Written with help from Claude Code.

@mareklangiewicz

Copy link
Copy Markdown
Contributor Author

Closing: b740a84 ("Refactor the union") fixed this at the source. LuaType::union now deduplicates members, and from_vec goes through it, so a union with a repeated member can no longer be built and the multiset compare here has nothing left to handle.

I checked it on main 2d2374f with only this PR's tests added, without its complex.rs change. test_union_arg_with_repeated_member_no_crash and test_return_union_with_repeated_member_no_hang (the snacks.nvim fixture) both pass. On 48ef52a the hang test failed 10 runs out of 10.


Written with help from Claude Code.

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