From d8f9446e607743a6f4335ae273c11be491c24af3 Mon Sep 17 00:00:00 2001 From: Marek Langiewicz Date: Mon, 23 Nov 2026 19:30:18 +0100 Subject: [PATCH 1/2] perf(flow): a value read stops at the memo after a skipped merge and 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 Claude-Session: https://claude.ai/code/session_018NxUUR6W6YykYLUWo9RTMQ --- .../phase_tests/flow_read_memo_tests.rs | 85 +++++++++++++++++++ .../src/semantic_db/phase_tests/mod.rs | 1 + .../src/semantic_model/flow.rs | 43 ++++++++++ 3 files changed, 129 insertions(+) create mode 100644 crates/emmylua_code_analysis/src/semantic_db/phase_tests/flow_read_memo_tests.rs diff --git a/crates/emmylua_code_analysis/src/semantic_db/phase_tests/flow_read_memo_tests.rs b/crates/emmylua_code_analysis/src/semantic_db/phase_tests/flow_read_memo_tests.rs new file mode 100644 index 000000000..d6282007e --- /dev/null +++ b/crates/emmylua_code_analysis/src/semantic_db/phase_tests/flow_read_memo_tests.rs @@ -0,0 +1,85 @@ +//! Regression guards for two quadratic costs of reading a local through a long chain of flow +//! nodes that leave it alone or write it: +//! +//! ```lua +//! ---@param h H +//! local function f(h) +//! if h.a then elseif h.b then end -- n times +//! end +//! +//! local function g() +//! local x = 0 +//! x = x + 1 -- n times +//! return x +//! end +//! ``` +//! +//! A value read met the memo only where it started, so each read walked back through every +//! earlier untouched merge, or every earlier write: n reads × n nodes. 0.25.1 is linear here. + +use crate::VirtualWorkspace; +use crate::semantic_model::flow::flow_metrics; +use emmylua_parser::{LuaAstNode, LuaNameExpr}; + +fn untouched_merge_chain(n: usize) -> String { + let mut content = String::from( + "---@class H\n---@field a? boolean\n---@field b? boolean\n\n---@param h H\nlocal function f(h)\n", + ); + for _ in 0..n { + content.push_str(" if h.a then elseif h.b then end\n"); + } + content.push_str("end\nreturn f\n"); + content +} + +fn reassigned_chain(n: usize) -> String { + let mut content = String::from("local function g()\n local x = 0\n"); + for _ in 0..n { + content.push_str(" x = x + 1\n"); + } + content.push_str(" return x\nend\nreturn g\n"); + content +} + +/// Flow steps to read every `name` in `source`. +fn read_steps(source: &str, name: &str) -> u64 { + let mut ws = VirtualWorkspace::new(); + let fid = ws.def_file("chain.lua", source); + let model = ws.analysis.semantic_model(fid); + flow_metrics::reset(); + for expr in model.chunk().expect("chunk").descendants::() { + if expr.get_name_text().as_deref() == Some(name) { + let _ = model.type_of_expr_at(expr.get_syntax_id(), expr.get_position()); + } + } + flow_metrics::trace_steps() + flow_metrics::branch_scan_steps() +} + +/// Steps at n = 16, 64, 256 stay within twice a linear extrapolation from n = 16. +fn assert_linear(what: &str, steps_at: impl Fn(usize) -> u64) { + let measurements: Vec<_> = [16usize, 64, 256] + .into_iter() + .map(|n| (n, steps_at(n))) + .collect(); + let (n_first, steps_first) = measurements[0]; + for (n, steps) in &measurements { + let bound = steps_first * (*n as u64) / (n_first as u64) * 2; + assert!( + *steps <= bound, + "{steps} flow steps for {n} {what} (bound {bound}, linear from n = {n_first}): \ + each read walks back through all earlier ones. All: {measurements:?}" + ); + } +} + +#[test] +fn reads_past_untouched_merges_stay_linear() { + assert_linear("conditionals", |n| { + read_steps(&untouched_merge_chain(n), "h") + }); +} + +#[test] +fn reads_of_a_reassigned_local_stay_linear() { + assert_linear("writes", |n| read_steps(&reassigned_chain(n), "x")); +} diff --git a/crates/emmylua_code_analysis/src/semantic_db/phase_tests/mod.rs b/crates/emmylua_code_analysis/src/semantic_db/phase_tests/mod.rs index e1339e543..b813e9327 100644 --- a/crates/emmylua_code_analysis/src/semantic_db/phase_tests/mod.rs +++ b/crates/emmylua_code_analysis/src/semantic_db/phase_tests/mod.rs @@ -1,5 +1,6 @@ mod fix_tests; mod flow_loop_memo_tests; +mod flow_read_memo_tests; mod module_roots_tests; mod p0_tests; mod p10_tests; diff --git a/crates/emmylua_code_analysis/src/semantic_model/flow.rs b/crates/emmylua_code_analysis/src/semantic_model/flow.rs index 8da2de74f..dc482f239 100644 --- a/crates/emmylua_code_analysis/src/semantic_model/flow.rs +++ b/crates/emmylua_code_analysis/src/semantic_model/flow.rs @@ -2334,7 +2334,49 @@ fn trace_decl_uncached( let root_mode = mode; let mut current = flow_id; let mut frames = Vec::new(); + // Set when the walk skipped a merge whose branches leave `decl` alone (below). + let mut skipped_to_common = false; let result = 'trace: loop { + // A value read that lands here after skipping a merge, or that reaches a write of + // `decl`, uses and fills the memo, 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. + // Without this, each read of a long chain of such merges or writes walks back + // through all of them. At a write, the memo frame sits under the write's own frame, + // so it saves the state after the write. + let landed = std::mem::take(&mut skipped_to_common); + if matches!(purpose, DeclTracePurpose::ReadValue) + && (landed + || tree.get_flow_effects(current).iter().any( + |effect| matches!(effect, FlowEffect::AssignDecl { decl: d, .. } if d == decl), + )) + && mode == root_mode + && current != flow_id + && !tree.is_in_cycle(current) + && !path + .narrowings + .iter() + .any(|narrowing| matches!(narrowing, Narrowing::Correlated { .. })) + { + let key = decl_trace_key(model, decl, current, purpose, mode, path); + // An entry still in progress belongs to an outer query: walk on, and leave it alone. + let (memo, absent) = { + let cache = model.cache.borrow(); + match cache.trace_state.get(&key) { + None => (None, true), + Some(cache::CacheEntry::InProgress) => (None, false), + Some(entry) => (entry.get(&cache).cloned(), false), + } + }; + if let Some(state) = memo { + break 'trace state.map(|state| finalize(model, state, path)); + } + if absent && path.narrowings.is_empty() && path.casts.is_empty() { + frames.push(DeclTraceFrame::Memo { + key, + revision: model.cache.borrow().revision(), + }); + } + } // trace_decl owns the starting node's cache entry. Save intermediate // nodes here; casts use separate frames even when caching is disabled. if matches!(purpose, DeclTracePurpose::OriginalSignatures(_)) @@ -2597,6 +2639,7 @@ fn trace_decl_uncached( decl_branch_is_pure(model, tree, decl, purpose, *branch, common) }) { current = common; + skipped_to_common = true; continue; } if matches!(purpose, DeclTracePurpose::OriginalSignatures(_)) From 0a68b209fcd67b431c3bfb21a30bc75573e8d623 Mon Sep 17 00:00:00 2001 From: Marek Langiewicz Date: Mon, 23 Nov 2026 19:48:49 +0100 Subject: [PATCH 2/2] test(flow): the memo tests also pin the type of the last read; name the one-shot skip flag Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_018NxUUR6W6YykYLUWo9RTMQ --- .../phase_tests/flow_read_memo_tests.rs | 31 +++++++++++++------ .../src/semantic_model/flow.rs | 11 ++++--- 2 files changed, 28 insertions(+), 14 deletions(-) diff --git a/crates/emmylua_code_analysis/src/semantic_db/phase_tests/flow_read_memo_tests.rs b/crates/emmylua_code_analysis/src/semantic_db/phase_tests/flow_read_memo_tests.rs index d6282007e..881b38292 100644 --- a/crates/emmylua_code_analysis/src/semantic_db/phase_tests/flow_read_memo_tests.rs +++ b/crates/emmylua_code_analysis/src/semantic_db/phase_tests/flow_read_memo_tests.rs @@ -5,6 +5,7 @@ //! ---@param h H //! local function f(h) //! if h.a then elseif h.b then end -- n times +//! return h //! end //! //! local function g() @@ -28,7 +29,7 @@ fn untouched_merge_chain(n: usize) -> String { for _ in 0..n { content.push_str(" if h.a then elseif h.b then end\n"); } - content.push_str("end\nreturn f\n"); + content.push_str(" return h\nend\nreturn f\n"); content } @@ -41,27 +42,35 @@ fn reassigned_chain(n: usize) -> String { content } -/// Flow steps to read every `name` in `source`. -fn read_steps(source: &str, name: &str) -> u64 { +/// Flow steps to read every `name` in `source`, and the type of the last read. +fn read_steps(source: &str, name: &str) -> (u64, String) { let mut ws = VirtualWorkspace::new(); let fid = ws.def_file("chain.lua", source); let model = ws.analysis.semantic_model(fid); flow_metrics::reset(); + let mut last = None; for expr in model.chunk().expect("chunk").descendants::() { if expr.get_name_text().as_deref() == Some(name) { - let _ = model.type_of_expr_at(expr.get_syntax_id(), expr.get_position()); + last = Some(model.type_of_expr_at(expr.get_syntax_id(), expr.get_position())); } } - flow_metrics::trace_steps() + flow_metrics::branch_scan_steps() + let steps = flow_metrics::trace_steps() + flow_metrics::branch_scan_steps(); + (steps, ws.humanize_type(last.expect("a read"))) } -/// Steps at n = 16, 64, 256 stay within twice a linear extrapolation from n = 16. -fn assert_linear(what: &str, steps_at: impl Fn(usize) -> u64) { +/// Steps at n = 16, 64, 256 stay within twice a linear extrapolation from n = 16, and the last +/// read has the type `expected` at every n. +fn assert_linear(what: &str, expected: &str, read_at: impl Fn(usize) -> (u64, String)) { let measurements: Vec<_> = [16usize, 64, 256] .into_iter() - .map(|n| (n, steps_at(n))) + .map(|n| { + let (steps, ty) = read_at(n); + assert_eq!(ty, expected, "type of the last read for {n} {what}"); + (n, steps) + }) .collect(); let (n_first, steps_first) = measurements[0]; + assert!(steps_first > 0, "no flow steps counted: {measurements:?}"); for (n, steps) in &measurements { let bound = steps_first * (*n as u64) / (n_first as u64) * 2; assert!( @@ -74,12 +83,14 @@ fn assert_linear(what: &str, steps_at: impl Fn(usize) -> u64) { #[test] fn reads_past_untouched_merges_stay_linear() { - assert_linear("conditionals", |n| { + assert_linear("conditionals", "H", |n| { read_steps(&untouched_merge_chain(n), "h") }); } #[test] fn reads_of_a_reassigned_local_stay_linear() { - assert_linear("writes", |n| read_steps(&reassigned_chain(n), "x")); + assert_linear("writes", "integer", |n| { + read_steps(&reassigned_chain(n), "x") + }); } diff --git a/crates/emmylua_code_analysis/src/semantic_model/flow.rs b/crates/emmylua_code_analysis/src/semantic_model/flow.rs index dc482f239..c64545dc8 100644 --- a/crates/emmylua_code_analysis/src/semantic_model/flow.rs +++ b/crates/emmylua_code_analysis/src/semantic_model/flow.rs @@ -2334,8 +2334,9 @@ fn trace_decl_uncached( let root_mode = mode; let mut current = flow_id; let mut frames = Vec::new(); - // Set when the walk skipped a merge whose branches leave `decl` alone (below). - let mut skipped_to_common = false; + // Set when the walk skipped a merge whose branches leave `decl` alone (below), and + // consumed on the very next iteration, where the walk lands on the merge's predecessor. + let mut just_skipped_merge = false; let result = 'trace: loop { // A value read that lands here after skipping a merge, or that reaches a write of // `decl`, uses and fills the memo, as `trace_decl` does at its start: the memo holds @@ -2343,7 +2344,7 @@ fn trace_decl_uncached( // Without this, each read of a long chain of such merges or writes walks back // through all of them. At a write, the memo frame sits under the write's own frame, // so it saves the state after the write. - let landed = std::mem::take(&mut skipped_to_common); + let landed = std::mem::take(&mut just_skipped_merge); if matches!(purpose, DeclTracePurpose::ReadValue) && (landed || tree.get_flow_effects(current).iter().any( @@ -2370,6 +2371,8 @@ fn trace_decl_uncached( if let Some(state) = memo { break 'trace state.map(|state| finalize(model, state, path)); } + // Only an empty path may fill it: entries hold the empty-path state, as in + // `trace_decl`, and `finalize` applies the path's guards and casts on lookup. if absent && path.narrowings.is_empty() && path.casts.is_empty() { frames.push(DeclTraceFrame::Memo { key, @@ -2639,7 +2642,7 @@ fn trace_decl_uncached( decl_branch_is_pure(model, tree, decl, purpose, *branch, common) }) { current = common; - skipped_to_common = true; + just_skipped_merge = true; continue; } if matches!(purpose, DeclTracePurpose::OriginalSignatures(_))