Repository navigation
perf(flow): a value read stops at the memo after a skipped merge and at a write - #1456
Conversation
…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
There was a problem hiding this comment.
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
-
Correctness risk: memo lookup ignores
correlatednarrowing 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 onpath.narrowings.is_empty() && path.casts.is_empty(), but the lookup doesn't require the state to be equivalent to an empty path forabsent == falsecases. It's fine as long as the key includes path, but confirmdecl_trace_keyactually 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.
- The insert condition guards on
-
landedsemantics unclear / fragileskipped_to_commonis set only inside thepure-branch skip path, then immediately consumed at the next loop iteration viamem::take. The conditioncurrent != flow_idalso 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 tojust_skipped_merge.
-
Repeated
tree.get_flow_effects(current)scan on every iterationget_flow_effects(current).iter().any(...)is executed on every loop iteration whenpurpose == 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 assigndecl?" boolean, or short-circuiting via a cheaper check (e.g., only run the scan whenlandedis false butcurrentis aWrite-class node).
-
Multiple
model.cache.borrow()calls in one blockcache.trace_state.get(&key)and latermodel.cache.borrow().revision()are performed in separate borrows. If cleanup logic ever touchesInProgressstate on the sameborrow, this could panic. Currently fine since the firstborrowis dropped, but consider holding a singleborrowfor the lookup-and-absent branch.
-
CacheEntry::InProgresspath 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::Pendingor similar is desirable to avoid re-walk; at minimum, note the trade-off in the comment.
- 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
-
Test robustness:
assert_linearbound is loosebound = steps_first * n / n_first * 2allows 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. Ifsteps_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 > 0to ensure the test isn't vacuous if metrics are broken.
-
Test uses
flow_metrics::reset()— potential parallel-test hazardreset()andtrace_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_metricsis thread-local.
- Mark with
- Verify
flow_metricsis thread-local; if it's a globalAtomicU64, this test file will cause flaky CI.
-
VirtualWorkspace::new()+def_filedefault analysis- New test relies on the default
analysisconfig 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.
- New test relies on the default
-
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., assertxisnumber(or whatever) alongside step linearity.
- The tests only check step counts. It would be valuable to also verify the resolved type is correct at the end (
Minor / Style
skipped_to_commonname and comment "the memo frame sits under the write's own frame" is helpful; adding a one-line note on whypath.narrowings.is_empty() && path.casts.is_empty()is required for insert would complete the invariant picture.- The test helper
read_stepspanics onchunkfor non-Lua input; fine for internal tests. assert_linearmessage is informative; good.
Recommendations
- Confirm
decl_trace_keyincludes narrowing/casts; add a debug assertion if needed. - Cache or reduce the cost of the per-iteration
get_flow_effectsscan. - Ensure
flow_metricscounters are thread-local, or serialize the tests; otherwise CI will flake. - Add a correctness assertion on the resolved type in the tests.
- Tighten the comment around
landedto 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
|
Thanks for the review. I took items 2, 6 and 9 in 0a68b20.
Not taken, with reasons:
|
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:
n reads × n nodes. 6400 lines of
x = x + 1take 115 s inemmylua_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_declalready 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.Evidence
emmylua_checkwith an empty config on one generated file, wall time:x = x + 1in one functionx = x + 1if h.a then elseif h.b then end,ha class paramreads_past_untouched_merges_stay_linearandreads_of_a_reassigned_local_stay_linear(new,phase_tests/flow_read_memo_tests.rs) fail with main'sflow.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 hisH,return xisinteger). On main the steps at n = 256 are 1043222 for the merges and 33153 for the writes.After: both pass. All
emmylua_code_analysistests pass, as docargo fmtandclippy.emmylua_check, empty config, the 54 Neovim plugin trees that finish on main): 57302 → 57302 hits. The 6 changed lines areassign-type-mismatchpairs 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 ofh.awitha: boolean?, main readshasneverfor one conditional andunknownfor two or more, whereHis right (main's false branch of a member test drops an owner whose member can be falsy; #1361 fixes that). With this PR it isneverfrom three conditionals on. With #1361 applied, the memo and the full walk both giveHat 1, 2, 3, 4, 8 and 16 conditionals.🤖 Generated with Claude Code
https://claude.ai/code/session_018NxUUR6W6YykYLUWo9RTMQ