Skip to content

fix(check): a record literal's first mismatching field is the same every run - #1437

Open
mareklangiewicz wants to merge 5 commits into
EmmyLuaLs:mainfrom
mareklangiewicz:fix-record-field-order
Open

mareklangiewicz wants to merge 5 commits into
EmmyLuaLs:mainfrom
mareklangiewicz:fix-record-field-order

Conversation

@mareklangiewicz

@mareklangiewicz mareklangiewicz commented Nov 19, 2026 •

Copy link
Copy Markdown
Contributor

Summary

A table literal with several entries that don't match the target record gets one assign-type-mismatch, placed on the first failing entry. check_table_record walks the record's fields in HashMap order, and check_all stops at the first failure. foldhash seeds every map anew, so which entry counts as "first" changes from run to run. On an unchanged tree, the same binary reports the mismatch on a different line, with a different reason, each run. This happens for ---@type {…} objects and for ---@class targets alike, since class_fields goes through the same function.

 // semantic_model/type_check/simple_type.rs, check_table_record
-    let field_checks = check_all(fields.get_fields().iter().map(|(key, expected)| {
+    let mut sorted: Vec<_> = fields.get_fields().iter().collect();
+    sorted.sort_unstable_by_key(|(key, _)| *key);
+    let field_checks = check_all(sorted.into_iter().map(|(key, expected)| {

The fields are now walked in LuaMemberKey order: integer keys ascending, then names. It's still one diagnostic per literal, now at the lowest key every time. This addresses one source of the run-to-run variation in #1091, but doesn't fix it all (see the end).

Evidence

---@type { [1]: integer, [2]: integer, [3]: integer }
local t
---@param a number
local function f(a)
  t = {
    a, -- line 6
    a, -- line 7
    a, -- line 8
  }
end

emmylua_check 30 times on this file. main reports line 6 ×11, 7 ×8, 8 ×11, while this PR reports line 6 ×30. The same file with ---@class P (fields x, y, z) and x = a, y = a, z = a spreads over all three lines the same way on main. With only one mismatching entry, main is stable (control).

  • Before: test_record_mismatch_reports_the_same_entry_every_run (new, assign_type_mismatch_test.rs) checks both target shapes in 16 fresh databases each. On main it fails with lines {10, 11, 12} reported where {10} was expected. After: it passes. All emmylua_code_analysis tests pass (1986 on main 48ef52a), as do cargo fmt and clippy.

  • Plugin corpus (emmylua_check, empty config, the 54 Neovim plugin trees that finish on main): main 48ef52a → this branch, one run each, 57302 → 57302 hits. All 6 changed lines are assign-type-mismatch in diffview.nvim and gitsigns.nvim, each a mismatch that moved to a neighbouring entry of the same literal. Four more runs of each build on the five trees where main varies (blink.cmp, diffview.nvim, gitsigns.nvim, nui.nvim, nvim-lspconfig):

    lines that vary across the 4 runs files
    main 48ef52a 16 4 (blink.cmp, diffview.nvim, gitsigns.nvim, nvim-lspconfig)
    this PR 5 1 (blink.cmp)

    The one file that still varies on this branch is blink.cmp lua/blink/cmp/config/sources.lua:76–81. There the inferred type of the literal itself changes between runs (opts: blink.cmp.SourceConfig vs opts: blink.cmp.CompleteFuncOpts). That's a separate source, not touched here.

Merge Danger

Door: two-way

Iteration order in one loop. Reverting it restores the current behaviour.

Blast Radius: diagnostics

Which entry of a literal carries the one assign-type-mismatch, and its reason text. Whether a literal is reported at all doesn't change. The sort costs one small Vec per record check.

🤖 Generated with Claude Code

https://claude.ai/code/session_018NxUUSXZWf4hp8CP3dKREA

…ery run

check_table_record walked the target record's fields in HashMap order,
and check_all stops at the first failure, which add_mismatch reports at
that field's entry. foldhash seeds each map anew, so a literal with
several mismatching entries was reported on a different line from run
to run, for object and class targets alike. Walk the fields in key
order instead.

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

@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

Overview

The change fixes a non-deterministic diagnostic ordering bug by sorting record fields before checking them. The test verifies the fix. Overall the change is sound, but there are a few points worth addressing.

Issues & Suggestions

1. Test comment overstates the guarantee (test file)

"so 16 runs would almost surely see two of three lines if the order leaked"

This is a probabilistic argument. With 3 candidate lines, the probability that 16 independent runs all land on the same line is (1/3)^15 ≈ 7e-8 per target — fine in practice, but any claim of "almost surely" is informal. More importantly, if the underlying ordering is deterministic-but-wrong (e.g., insertion order changed), the test won't catch it — it only asserts the result is stable, then separately asserts [10]. The [10] assertion is the real check; consider making that the primary claim and treating stability as secondary, or document the flakiness risk explicitly. 16 iterations × 2 targets is also somewhat slow for a unit test; 8 would give (1/3)^7 ≈ 4.6e-4, still acceptable, though 16 is defensible if runtime permits.

2. Fragile line-number detection in test

.map(|d| source[..usize::from(d.range.start())].matches('\n').count())

This assumes range.start() is a valid char/byte boundary into source and that it's an index into source. Slicing by a diagnostic offset is only safe if the offset is guaranteed to be at a UTF-8 boundary; if it isn't, this panics. It's fine here (ASCII source), but a helper like line_index_of(source, offset) would be more robust and self-documenting.

3. Magic number [10]

The expected line is derived from the raw string's indentation layout, which is easy to break by reformatting the literals. A comment mapping line 10 to "the first entry (a / x = a)" would save future maintainers a debugging cycle. Also note format! preserves the leading newline, so line 10 corresponds to the second element of the table — verify this is actually the entry the record's fields put first, and not an accident of layout.

4. Sorting by key requires Ord — check key semantics

sorted.sort_unstable_by_key(|(key, _)| *key);

*key is copied out of the tuple; confirm the key type is Copy/Ord and that the resulting ascending order matches the intended "fields put first" convention. If the record definition order (source order) is the intended authority, sorting by key value may not be correct — e.g., for {[3]: ..., [1]: ...} declared in that order, sorting by key yields [1] first, which may differ from what the user expects to be reported. Confirm the deterministic order chosen is the definition order the comment claims, not merely a stable-but-arbitrary key order.

5. Performance: allocates a Vec on every check

let mut sorted: Vec<_> = fields.get_fields().iter().collect();

This allocates for every table-literal-vs-record check. For small records it's negligible, but this is on a hot path for type checking. If get_fields() returns a map, consider documenting why sorting is necessary (done) or, if the field count is typically small, this is fine — just be aware. Alternative: iterate in key order via a BTreeMap-backed field storage if that's feasible, avoiding the per-check sort entirely.

6. Comment clarity

The comment "Key order, not hash order: the first failing field is the one reported, and a hash map's order changes per map, so the reported line moved between runs." is good. Minor: "a hash map's order changes per map" — consider clarifying whether it's per-map-instance or per-call; if the map's iteration order is stable for a given instance, the run-to-run difference is actually a per-instance seed, which the wording should reflect.

Summary

  • ✅ Fix is correct in spirit and the test guards against regression.
  • ⚠️ Verify sorted key order matches intended reporting convention (point 4).
  • ⚠️ Make test line-number/slice handling more robust (points 2, 3).
  • ℹ️ Comment on the probabilistic nature of the test's stability check (point 1) and the per-check allocation (point 5).

mareklangiewicz and others added 3 commits November 19, 2026 12:38
The keys were derived from the target string (`ends_with('P')`).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_018NxUUSXZWf4hp8CP3dKREA
…rder is by key

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

mareklangiewicz commented Nov 23, 2026 •

Copy link
Copy Markdown
Contributor Author

Thanks for the review. I took items 1, 3, 4 and 6 in a7b738f (comments only), and merged main 48ef52a in.

1, 3. The test comment now says which entry is pinned: the lowest key, [1] for the tuple-like target and x for the class, which is line 10 of source (the format! string starts with a newline). [10] is the main check; the 16 fresh databases per target are the stability half.
4. The order is key order (integers ascending, then names), not definition order. The fields come from a hash map, which keeps no definition order to use instead, so the lowest key is the deterministic choice available. The comment at the sort says so now.
6. The comment says each map's hash order is seeded anew.

Not taken:

  1. The diagnostic offset comes from the same source string and the source is ASCII, so the slice is on a char boundary.
  2. The sort is over one record's fields, and only when a table literal is checked against a record. Over the 54 corpus trees, one run each: 55.1 s on main, 56.6 s here, within run-to-run noise on this machine.

Re-measured on main 48ef52a (the body is updated): on the five plugin trees where main reports different lines from run to run, 4 runs of main vary on 16 lines in 4 files, and 4 runs of this branch vary on 5 lines in 1 file (blink.cmp config/sources.lua, a separate source).

Conflict in assign_type_mismatch_test.rs only: both sides appended a
test at the end of the module; kept both.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_018NxUUQZHt6a5njk8trY5BZ
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