Skip to content

fix(flow): a memoized flow state keeps the guards a later query brings - #1360

Closed
mareklangiewicz wants to merge 3 commits into
EmmyLuaLs:mainfrom
mareklangiewicz:up-flow-memo-guards
Closed

mareklangiewicz wants to merge 3 commits into
EmmyLuaLs:mainfrom
mareklangiewicz:up-flow-memo-guards

Conversation

@mareklangiewicz

@mareklangiewicz mareklangiewicz commented Nov 4, 2026 •

Copy link
Copy Markdown
Contributor

Summary

A flow state memoized for one read loses the guards of a later read:

---@param w Res?
local function f(w)
  if w and w.ok then return end
  if not w then return take(w) end   -- this read fills the memo
  cool(w)                            -- false: expected `Res` but found `nil`
end

trace_decl keys its memo without the incoming path, on the basis that every route to a node crosses the same guards. That holds within one query, but the memo outlives the query. The memo now holds the state for an empty incoming path, and a query arriving with guards narrows it:

 if tree.is_loop_reachable(flow_id) {
     return trace_decl_uncached(...);
 }
+if !path.narrowings.is_empty() && path.casts.is_empty() && !has_correlated_narrowing {
+    let state = trace_decl(..., &mut PathState::default())?;
+    return Some(finalize(model, state, path));
+}
 let key = decl_trace_key(model, decl, flow_id, purpose, mode);

Queries with casts or correlated narrowings keep today's behavior. Sending them down the uncached walk instead times out test_deep_branch_casts_merge_surviving_overloads. narrows_a_merged_state matches every Narrowing variant, and its doc says when narrowing a merge agrees with narrowing each branch.

Evidence

  • Before (plain main de89376): test_and_narrows_after_merge_of_earlier_guard fails.
  • After: it passes. test_unguarded_read_after_merge_needs_check_nil is its control: the same fixture reports prev when no guard covers the read. Full emmylua_code_analysis suite: 1704 passed. clippy reports nothing new.
  • Speed: with fix(flow): a guard on a member no longer turns its memo off #1372 applied, emmylua_check on diffs.nvim takes 22 s, and about 4.5 s with this PR on top. On main 4136671, diffs.nvim restricted to lua/diffs/runtime/cache.lua and its type files takes 62 s, and 7 s with this PR.
  • Untested conditions: no test needs the casts and correlated conditions. Removing both still passes the suite, but it adds one need-check-nil on a real codebase, so I kept them.

Merge Danger

Door: two-way

Blast Radius: narrowing

emmylua_check (empty config) on 54 Neovim plugin trees, main 4136671 against this branch merged with it (43f8b0e): 58021 → 57696 hits.

lines same as 0.25.1
Removed 508 488
Added 198 30

Of the added lines, assign-type-mismatch (+36 −36) and undefined-field (+23 −23) balance: hits that moved, plus main's own run-to-run variation in which failing constructor field gets reported. Of the 53 added param-type-mismatch / need-check-nil lines, 41 are also reported by main with this memo switched off (trace_decl always taking the uncached walk). These are reads the memo was answering without their guards. The other 12 are in two trees, read by hand:

  • 11 in diffs.nvim, where the uncached walk doesn't finish. 6 are reads of fields that main already reports on the neighbouring reads in the same function. 4 are the same hits with found nil corrected to found string[]?. 1 is main not narrowing t.x after if not t.x then return end (a positive test, == nil, and the same test on a local do narrow), which the memo hid.
  • 1 in which-key comes from main dropping, after a conditional member write, the path that skips it:
---@param s S        -- ---@field desc? string
local function f(s)
  if c() then s.desc = "x" end
  local probe = s.desc   -- main: string (0.25.1: string?)
end

With this PR, unnecessary-if sees that type, so if s.desc then after such a write on a union receiver is reported.

The earlier three-codebase table is superseded by this one. The added string? hit it described (from dir ~= memo with a nil local) is still a separate main issue:

local memo
---@param dir string
local function g(dir)
  if dir ~= memo then else take(dir) end   -- main: expected `string` but found `nil`
  if dir == memo then take(dir) end        -- main: no warning
end

This is one of two fixes #1359 needs: see that PR.


Written with help from Claude Code.

🤖 Generated with Claude Code

https://claude.ai/code/session_018NxUUQmc3YFNEXrUcrVPxV

`trace_decl` memoizes a node's state without the incoming path, assuming every
route to a node crosses the same guards. Within one query it does, but the memo
outlives the query: a read that reached the node with no guards stored a state,
and a later read whose route crosses a guard got that state with the guard
dropped.

The memo now holds the state for an empty incoming path, and a query arriving
with guards narrows it. Incoming casts and correlated narrowings stay as they were.

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

@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 subtle narrowing bug: when a flow node's state is memoized for an empty incoming path, guards collected by the current query must be reapplied on top of the cached state. The fix adds a fast path that recomputes with an empty PathState and then finalizes with the caller's path. The test and doc updates are consistent with the new semantics.

Issues & Recommendations

1. Potential infinite recursion / cache bypass (High)

In the new branch, trace_decl is called recursively with &mut PathState::default(). Since path.narrowings is now empty, the new branch won't re-trigger, so this specific recursion is bounded. However:

  • The recursive call passes the same visited set. If flow_id was already inserted into visited by the caller before this point, the recursive call may return None prematurely (or behave differently than the cached path). Please confirm visited is not mutated before this branch, or that the recursive call is safe with the current visited contents.
  • The recursive call bypasses the cache lookup entirely (it goes through the same function, hits the empty-path branch, and then does the cache lookup). This is fine, but it means the "fast path" is actually a full re-entry. Consider extracting a helper like trace_decl_with_empty_path to make the intent explicit and avoid re-running the loop-reachability check.

2. finalize semantics with empty-path state (Medium)

The comment says guards "distribute over branch merges," but finalize(model, state, path) applies the path's narrowings to the result type. This is only correct if:

  • The cached state was computed for the same flow_id and purpose/mode (it is, via decl_trace_key), and
  • Applying narrowings post-hoc is equivalent to applying them during traversal.

For simple Narrowing::Type-style guards this holds, but the code explicitly excludes Correlated narrowings — good. Please add a comment or assertion documenting why non-correlated narrowings commute with the merge, since this is the core correctness argument and future narrowing variants may not satisfy it. Consider a match on Narrowing variants instead of matches!(.., Correlated) so new variants force a review.

3. Casts exclusion is correct but under-documented (Low)

path.casts.is_empty() is required because casts don't commute with merges. The comment mentions this, but a one-line note on why (casts are order-sensitive / not idempotent under merge) would help future maintainers.

4. Test robustness (Low)

The test relies on new_with_init_std_lib() and "every check" being enabled, per the comment. This is fragile:

  • If std lib loading changes, the test may silently stop exercising the bug (the comment even admits "the test passes without the fix" under weaker conditions).
  • Consider asserting the diagnostic is produced when the guard is removed (a negative control), or adding a direct unit test on trace_decl to lock in the behavior independent of std lib.

5. Doc comment consistency (Nit)

The updated TraceStateKey doc says "The memo is consulted only for nodes with no loop behind them" — but the new code path also consults the memo for nodes with incoming narrowings (via the recursive empty-path call). The doc is still accurate for the memo's contents, but consider clarifying that callers may layer guards on top.

6. Minor: redundant condition ordering

if !path.narrowings.is_empty()
    && path.casts.is_empty()
    && !path.narrowings.iter().any(...)

The !path.narrowings.is_empty() check is redundant with the any check (an empty iterator yields false, so !any is true). It's harmless and arguably clearer, but could be simplified to just the casts.is_empty() && !any(...) pair.

Verdict

The fix is logically sound for the stated case and the test covers the regression. Main follow-ups: document the commutation argument for narrowings, verify visited safety in the recursive call, and consider a negative-control test.

@mareklangiewicz

Copy link
Copy Markdown
Contributor Author

Thanks. On the review:

  • visited: trace_decl inserts nothing before this branch, only trace_decl_uncached does, so the recursive call starts with the same set the caller would have used.
  • A helper for the empty-path call: left as is, the re-entry is the point, and it is one call.

Still open before this leaves draft: the added hit noted in the body that looks false, not reproduced yet. The commutation comment and the negative control can go in with that.

New since opening: this is also a slowdown fix. With #1372 applied, emmylua_check on diffs.nvim takes 22 s, and about 4.5 s with this PR merged on top, the time being in trace_decl.


Written with help from Claude Code.

`narrows_a_merged_state` matches every `Narrowing`, so a new variant has to
be placed on purpose, and says when narrowing a merge agrees with narrowing
each branch. The new control test shows the fixture reports `prev` when no
guard covers the read.

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

Copy link
Copy Markdown
Contributor Author

Applied in 4cf1f18, no behaviour change:

  • Commutation (2): narrows_a_merged_state matches every Narrowing variant, so a new one has to be placed on purpose. Its doc gives the rule, f(A | B) = f(A) | f(B), says which variants keep it, and names the ones that look at the whole value: Remove on a lone integer constant, ArrayLen/ArrayMinLen. Those can come out less precise on a merge, but the guard still applies, where before the memo dropped it.
  • Casts (3): the comment now says a query with incoming casts keeps the memo as before. I haven't argued that casts commute. Sending them down the uncached walk times out test_deep_branch_casts_merge_surviving_overloads, as the body says.
  • Control (4): test_unguarded_read_after_merge_needs_check_nil runs the same fixture without the guard and expects one need-check-nil.
  • (6): with all, the !is_empty() check is no longer redundant: an empty list would pass all.

The added hit from the body is now explained there: main reports it too once the read comes before the write, and its cause is on main, in how the false side of x ~= y narrows.


Written with help from Claude Code.

@mareklangiewicz
mareklangiewicz marked this pull request as ready for review November 7, 2026 23:19
Main now memoizes every flow node outside a cycle (`is_in_cycle`, EmmyLuaLs#1401)
where this branch said "loop-free". The conflicts were in the two
comments both sides rewrote; they keep this branch's meaning (the memo
holds the state for an empty incoming path, and later guards apply on
top) in main's terms. The code merged cleanly: the narrowing block
follows main's cycle check.

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

Copy link
Copy Markdown
Contributor Author

Closing: main has fixed this independently.

I checked it with this PR's tests on main 2d2374f, without the flow.rs/cache.rs change. test_and_narrows_after_merge_of_earlier_guard passes there. With this PR's base versions of those two files (4136671) it fails (left: 1, right: 0), so the test still catches the bug, and main no longer has it. test_unguarded_read_after_merge_needs_check_nil is the control and passes on both.


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