Skip to content

perf(flow): a value read stops at the memo after a skipped merge and at a write - #1456

Merged
CppCXY merged 2 commits into
EmmyLuaLs:mainfrom
mareklangiewicz:perf-flow-read-memo
Nov 24, 2026
Merged

CppCXY merged 2 commits into
EmmyLuaLs:mainfrom
mareklangiewicz:perf-flow-read-memo

Conversation

@mareklangiewicz

@mareklangiewicz mareklangiewicz commented Nov 23, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Reading a local through a long chain of flow nodes is quadratic. A value read meets the trace memo only where it starts, so:

  • a merge whose branches leave the local alone is skipped by jumping to its common predecessor, and the walk then goes on without the memo, so each read walks back through every earlier such merge;
  • each read of a reassigned local walks back through every earlier write.

n reads × n nodes. 6400 lines of x = x + 1 take 115 s in emmylua_check.

A value read now uses and fills the memo where it lands after such a skip and at each write of the local, as trace_decl already does at its start: the memo holds the state for an empty incoming path, and the guards collected so far narrow it. At a write the memo frame sits under the write's own frame, so it saves the state after the write. Nodes on a cycle, a path with a correlated narrowing, and an entry still in progress for an outer query are left alone.

 // semantic_model/flow.rs, trace_decl_uncached
+    let mut skipped_to_common = false;
     let result = 'trace: loop {
+        let landed = std::mem::take(&mut skipped_to_common);
+        if matches!(purpose, DeclTracePurpose::ReadValue)
+            && (landed || /* `current` writes `decl` */)
+            && mode == root_mode && current != flow_id && !tree.is_in_cycle(current)
+            && /* no correlated narrowing on the path */
+        {
+            // use the memo at `current` if there is one, else push a Memo frame to fill it
+        }
 …
                         current = common;
+                        skipped_to_common = true;
                         continue;

Evidence

emmylua_check with an empty config on one generated file, wall time:

file 0.25.1 main 48ef52a this PR
1600 × x = x + 1 in one function 0.19 s 3.74 s 0.17 s
6400 × x = x + 1 0.59 s 115 s 0.30 s
1600 × if h.a then elseif h.b then end, h a class param 0.21 s 7.10 s 0.20 s
  • Before: reads_past_untouched_merges_stay_linear and reads_of_a_reassigned_local_stay_linear (new, phase_tests/flow_read_memo_tests.rs) fail with main's flow.rs. They count flow steps for reading every name at n = 16, 64 and 256, require them to stay within twice a linear extrapolation from n = 16, and check the type of the last read (return h is H, return x is integer). On main the steps at n = 256 are 1043222 for the merges and 33153 for the writes.
    After: both pass. All emmylua_code_analysis tests pass, as do cargo fmt and clippy.
  • Plugin corpus (emmylua_check, empty config, the 54 Neovim plugin trees that finish on main): 57302 → 57302 hits. The 6 changed lines are assign-type-mismatch pairs in diffview.nvim and nui.nvim that move from run to run on main itself. Total time over the 54 trees, one run each: 55.1 s → 52.2 s.

Merge Danger

Door: two-way

A memo lookup at two more kinds of node on an existing path; reverting it brings back the walk.

Blast Radius: inference speed

The memo already stood at the read's start node with the same key, so a read finds the state an equal read would compute. The corpus shows no changed diagnostic beyond main's run-to-run noise.

One read changes value, and it is already wrong on main. Inside elseif h.b, on the false branch of h.a with a: boolean?, main reads h as never for one conditional and unknown for two or more, where H is right (main's false branch of a member test drops an owner whose member can be falsy; #1361 fixes that). With this PR it is never from three conditionals on. With #1361 applied, the memo and the full walk both give H at 1, 2, 3, 4, 8 and 16 conditionals.

🤖 Generated with Claude Code

https://claude.ai/code/session_018NxUUR6W6YykYLUWo9RTMQ

…at a write

A value read of a local met the memo only where it started. A merge whose
branches leave the local alone is skipped by jumping to its common
predecessor, and the walk then went on without the memo, so each read of a
long chain of such merges walked back through all of them. The same held for
each earlier write of the local. n reads x n nodes: on emmylua_check,
6400 `x = x + 1` lines take 115 s and 1600 `if h.a then elseif h.b then end`
lines 7.1 s, against 0.59 s and 0.21 s on 0.25.1.

A value read now uses and fills the memo where it lands after such a skip and
at each write of the local, as trace_decl does at its start: the memo holds the
state for an empty incoming path, and the guards collected so far narrow it.
At a write the memo frame sits under the write's own frame, so it saves the
state after the write. Nodes on a cycle, a correlated narrowing on the path, or
an entry still in progress for an outer query are left alone.

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

@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.

Overview

The change adds a regression test file and an optimization in trace_decl_uncached to avoid quadratic walks past merges/writes. Overall direction is sensible, but there are correctness and maintainability concerns.

Issues

  1. Correctness risk: memo lookup ignores correlated narrowing not present at insert time

    • The insert condition guards on !path.narrowings.iter().any(Correlated), and the lookup also guards on that. Good.
    • However, the frames.push(DeclTraceFrame::Memo { .. }) insert is conditional on path.narrowings.is_empty() && path.casts.is_empty(), but the lookup doesn't require the state to be equivalent to an empty path for absent == false cases. It's fine as long as the key includes path, but confirm decl_trace_key actually encodes narrowing/casts; if it doesn't, memo entries inserted at non-empty paths (when cache pre-populated) could be returned incorrectly. Worth a comment or explicit invariant check.
  2. landed semantics unclear / fragile

    • skipped_to_common is set only inside the pure-branch skip path, then immediately consumed at the next loop iteration via mem::take. The condition current != flow_id also filters the first iteration. This works but is subtle; a comment stating "one-shot flag consumed on the immediately following iteration" would help. Consider renaming to just_skipped_merge.
  3. Repeated tree.get_flow_effects(current) scan on every iteration

    • get_flow_effects(current).iter().any(...) is executed on every loop iteration when purpose == ReadValue, even when no assign effect exists. This adds a per-node cost that partly undermines the optimization goal. Consider caching the "does this flow node assign decl?" boolean, or short-circuiting via a cheaper check (e.g., only run the scan when landed is false but current is a Write-class node).
  4. Multiple model.cache.borrow() calls in one block

    • cache.trace_state.get(&key) and later model.cache.borrow().revision() are performed in separate borrows. If cleanup logic ever touches InProgress state on the same borrow, this could panic. Currently fine since the first borrow is dropped, but consider holding a single borrow for the lookup-and-absent branch.
  5. CacheEntry::InProgress path does not record anything

    • The comment says "walk on, and leave it alone," but there's no frame inserted. That means the outer query's result won't be reused by this walk even though we're traversing the exact same key. Consider whether a DeclTraceFrame::Pending or similar is desirable to avoid re-walk; at minimum, note the trade-off in the comment.
  6. Test robustness: assert_linear bound is loose

    • bound = steps_first * n / n_first * 2 allows 2× linear, which is quite permissive but reasonable. However, Vec<_> measurements use n=16 as baseline; if the constant term dominates at n=16, slope estimates can understate linear cost, but the 2× slack absorbs this. Acceptable.
    • The test asserts *steps <= bound, including the baseline itself. If steps_first == 0 (unlikely), no assertion would ever fail — but that would be a bug in the metric anyway.
    • Consider adding an assertion that steps_first > 0 to ensure the test isn't vacuous if metrics are broken.
  7. Test uses flow_metrics::reset() — potential parallel-test hazard

    • reset() and trace_steps() appear to use globals. If tests run in parallel (default), counters could interleave and produce flaky results. Since the test module only has these two tests and each is #[test], they will run in parallel by default. Either:
      • Mark with #[serial] / a lock, or
      • Use thread-local metric storage (preferred), or
      • Document that flow_metrics is thread-local.
    • Verify flow_metrics is thread-local; if it's a global AtomicU64, this test file will cause flaky CI.
  8. VirtualWorkspace::new() + def_file default analysis

    • New test relies on the default analysis config producing flow effects. If defaults change (e.g., cache disabled), the memo path may not activate and the test could pass for the wrong reason. Consider asserting the memo was exercised, or leave a comment noting dependency on caching being enabled.
  9. Missing regression assertion on correctness, not only performance

    • The tests only check step counts. It would be valuable to also verify the resolved type is correct at the end (return x / return f), so an over-aggressive memo that returns wrong types wouldn't pass silently. E.g., assert x is number (or whatever) alongside step linearity.

Minor / Style

  • skipped_to_common name and comment "the memo frame sits under the write's own frame" is helpful; adding a one-line note on why path.narrowings.is_empty() && path.casts.is_empty() is required for insert would complete the invariant picture.
  • The test helper read_steps panics on chunk for non-Lua input; fine for internal tests.
  • assert_linear message is informative; good.

Recommendations

  1. Confirm decl_trace_key includes narrowing/casts; add a debug assertion if needed.
  2. Cache or reduce the cost of the per-iteration get_flow_effects scan.
  3. Ensure flow_metrics counters are thread-local, or serialize the tests; otherwise CI will flake.
  4. Add a correctness assertion on the resolved type in the tests.
  5. Tighten the comment around landed to make the one-shot flag semantics explicit.

…he one-shot skip flag

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

Copy link
Copy Markdown
Contributor Author

Thanks for the review. I took items 2, 6 and 9 in 0a68b20.

  1. The flag is now just_skipped_merge, and its comment says it is consumed on the very next iteration, where the walk lands on the merge's predecessor.
  2. The test asserts the step count at n = 16 is not zero.
  3. Each measurement also checks the type of the last read: return h is H and return x is integer at every n. That check turned up one read whose value changes. It is already wrong on main, and the body now says so under Merge Danger.

Not taken, with reasons:

  1. decl_trace_key keeps only correlated narrowings, on purpose. trace_decl caches only with ordinary narrowings and casts stripped, then applies them with finalize, so every entry holds the state for an empty ordinary path. This change fills an entry only when the path is empty, and looks one up only when there is no correlated narrowing on the path, so finalize(model, state, path) is the same as trace_decl's finalize(…, &path.for_origin(None)). There is now a comment on that at the insert.
  2. get_flow_effects(current) is a lookup of the node's own effects, which are few. The tests count flow steps, and the timings in the body include this scan.
  3. Each borrow is dropped before the next one is taken, as in trace_decl just above.
  4. An InProgress entry belongs to a query further up the same walk. Pushing a frame for it would fill an entry that its owner fills on its way out, so the walk goes on without it.
  5. flow_metrics counters are thread_local! (flow.rs, mod flow_metrics), and each test runs on its own thread.
  6. Both tests fail with main's flow.rs (1043222 and 33153 steps at n = 256), so they exercise this path.

@mareklangiewicz
mareklangiewicz marked this pull request as ready for review November 23, 2026 19:06
@CppCXY
CppCXY merged commit 1460735 into EmmyLuaLs:main Nov 24, 2026
16 checks passed
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