Skip to content

Visual Studio Code, rebuilt in Rust

Rust

perf: stop the memory growth and CPU spin of a long session (#121)

Artur Rokd3122c5bef6f
diff --git a/docs/performance.md b/docs/performance.md
index 68a156d02de..9f80825fecd 100644
--- a/docs/performance.md
+++ b/docs/performance.md
@@ -39,7 +39,7 @@ The margins come from the spread of the samples in `port/results/benchmark.md`.
### No budget yet
-Terminal throughput, time to open a large file, search time and memory with many editors open have no number and no gate. A budget for one of them starts with a measurement in `port/notes.md`.
+Terminal throughput, time to open a large file and search time have no number and no gate. A budget for one of them starts with a measurement in `port/notes.md`.
### Zed
@@ -81,6 +81,8 @@ The machine is shared, and its load changes a time by about 30%. Check the load
| Typing | `cargo gc test --release -p app -- --ignored typing_latency_on_a_large_file --nocapture` | p95 per edit is 16 ms or more |
| Scroll frames | `cargo gc test --release -p app -- --ignored scroll_frame_time --nocapture --test-threads=1` | A median or p95 is 8 ms or more. The same filter runs `app/src/workbench/scroll_frame_time.rs::terminal_typing_frame_time`: p95 per frame is 16 ms or more |
| Render counts | `port/tools/cargo-test part_view` | A part draws that did not change |
+| Quick Open | `cargo gc test --release -p app -- --ignored quick_open_keystroke_time --nocapture` | Scoring 100,000 files takes 150 ms or more per keystroke |
+| Memory over a session | `port/tools/studio --lane 'port/tools/memory-soak'` with `MODE` browse, typing or all, after `port/tools/package-app` | The window process's footprint over the last 5 rounds is over 1.3 times that of rounds 3 to 7 (`port/notes.md`, issue 116) |
`port/tools/bench-check.ts` reads the output of `port/tools/bench` and `port/budgets.json`. It prints each metric with its limit and exits 1 on a failure. `port/tools/bench-check.test.ts` shows it red on a planted regression.
diff --git a/native/crates/app/src/anything_quick_access.rs b/native/crates/app/src/anything_quick_access.rs
index 01e675bc705..4fd90a98858 100644
--- a/native/crates/app/src/anything_quick_access.rs
+++ b/native/crates/app/src/anything_quick_access.rs
@@ -10,7 +10,7 @@ use regex::Regex;
use config::workspace::Workspace;
use crate::filters::Matches;
-use crate::fuzzy_scorer::{self, FuzzyScorerCache, PreparedQuery, ScorerItem};
+use crate::fuzzy_scorer::{self, FuzzyScorerCache, ItemScore, PreparedQuery, ScorerItem};
use crate::quick_input::path_label;
/// `AnythingQuickAccessProvider.MAX_RESULTS`, also the `maxResults` of its file search.
@@ -117,12 +117,12 @@ pub struct FileEntry {
/// `getFileSearchResults` over the file list the query cache loaded: the first value of a multi-value query
/// searches, the full query again when that hits the result limit.
-pub fn file_search_results(files: &[FileEntry], query: &PreparedQuery, cache: &mut FuzzyScorerCache) -> Vec<PathBuf> {
+pub fn file_search_results(files: &[FileEntry], query: &PreparedQuery) -> Vec<PathBuf> {
let multiple = query.values.as_ref().filter(|values| values.len() > 1);
let file_pattern = multiple.map_or(&query.piece.original, |values| &values[0].original);
- let (mut results, limit_hit) = sorted_file_search(files, file_pattern, cache);
+ let (mut results, limit_hit) = sorted_file_search(files, file_pattern);
if limit_hit && multiple.is_some() {
- let (additional, _) = sorted_file_search(files, &query.piece.original, cache);
+ let (additional, _) = sorted_file_search(files, &query.piece.original);
for path in additional {
if !results.contains(&path) {
results.push(path);
@@ -133,16 +133,34 @@ pub fn file_search_results(files: &[FileEntry], query: &PreparedQuery, cache: &m
}
/// rawSearchService.ts `doSortedSearch` from the cache: `isFilePatternMatch`, then the `maxResults` best by
-/// `FileMatchItemAccessor`.
-fn sorted_file_search(files: &[FileEntry], file_pattern: &str, cache: &mut FuzzyScorerCache) -> (Vec<PathBuf>, bool) {
+/// `FileMatchItemAccessor`. Each match is scored once, and only the best `maxResults` are sorted (`arrays.top`).
+fn sorted_file_search(files: &[FileEntry], file_pattern: &str) -> (Vec<PathBuf>, bool) {
let query = fuzzy_scorer::prepare_query(file_pattern);
- let mut matches: Vec<&FileEntry> = files.iter().filter(|file| search::file_search::fuzzy_contains(&file.relative_path, &query.piece.normalized_lowercase)).collect();
+ let mut matches = Vec::new();
+ for file in files {
+ if search::file_search::fuzzy_contains(&file.relative_path, &query.piece.normalized_lowercase) {
+ let item = file_match_item(file);
+ matches.push(ScoredFile { index: matches.len(), item, score: fuzzy_scorer::score_item_uncached(&item, &query, true), path: &file.path });
+ }
+ }
+ // The index breaks ties, so the unstable selection keeps the order a stable sort gives.
+ let compare = |a: &ScoredFile, b: &ScoredFile| fuzzy_scorer::compare_item_scores(&a.item, &a.score, &b.item, &b.score, &query).then(a.index.cmp(&b.index));
let limit_hit = matches.len() > MAX_RESULTS;
- matches.sort_by(|a, b| fuzzy_scorer::compare_items_by_fuzzy_score(&file_match_item(a), &file_match_item(b), &query, true, cache));
- matches.truncate(MAX_RESULTS);
+ if limit_hit {
+ matches.select_nth_unstable_by(MAX_RESULTS, compare);
+ matches.truncate(MAX_RESULTS);
+ }
+ matches.sort_unstable_by(compare);
(matches.into_iter().map(|file| file.path.clone()).collect(), limit_hit)
}
+struct ScoredFile<'a> {
+ index: usize,
+ item: ScorerItem<'a>,
+ score: ItemScore,
+ path: &'a PathBuf,
+}
+
/// `FileMatchItemAccessor`: `basename` and `dirname` of the relative path; dirname is "." for a bare name and "/"
/// for a root file.
fn file_match_item(file: &FileEntry) -> ScorerItem<'_> {
@@ -189,7 +207,7 @@ pub fn file_picks(files: &[FileEntry], query: &PreparedQuery, history: &[FilePic
pick.description_highlights = if pick.description.is_empty() { Vec::new() } else { vec![0..pick.description.chars().count()] };
return vec![pick];
}
- let mut results = file_search_results(files, query, cache);
+ let mut results = file_search_results(files, query);
if let Some(relative) = relative_path_results(query, &workspace.iter().flat_map(|workspace| &workspace.folders).map(|folder| folder.path.as_path()).collect::<Vec<_>>()) {
results.retain(|path| !relative.contains(path));
results.extend(relative);
diff --git a/native/crates/app/src/anything_quick_access/tests.rs b/native/crates/app/src/anything_quick_access/tests.rs
index 24b0b3b57ce..fbaabb8e6ca 100644
--- a/native/crates/app/src/anything_quick_access/tests.rs
+++ b/native/crates/app/src/anything_quick_access/tests.rs
@@ -88,14 +88,51 @@ fn entries(root: &str, relative: &[&str]) -> Vec<FileEntry> {
fn file_results_put_label_matches_first() {
let files = entries("/w", &["README.md", "docs/guide.md", "notes.txt", "package.json", "src/main.ts", "src/util.ts"]);
let query = prepare_query("main");
- let results = file_search_results(&files, &query, &mut FuzzyScorerCache::new());
+ let results = file_search_results(&files, &query);
assert_eq!(results, [PathBuf::from("/w/src/main.ts")]);
let query = prepare_query("ts");
- let results = file_search_results(&files, &query, &mut FuzzyScorerCache::new());
+ let results = file_search_results(&files, &query);
// Equal label scores fall back to `compareAnything`, which sorts the labels.
assert_eq!(results, [PathBuf::from("/w/src/main.ts"), PathBuf::from("/w/src/util.ts"), PathBuf::from("/w/notes.txt")]);
}
+fn large_workspace(count: usize) -> Vec<FileEntry> {
+ let relative: Vec<String> = (0..count).map(|i| format!("modules/module{}/sub{}/file{i}Controller.php", i % 300, i % 17)).collect();
+ entries("/w", &relative.iter().map(String::as_str).collect::<Vec<_>>())
+}
+
+// rawSearchService.ts `sortResults` keeps the top `maxResults` (`arrays.top`): the same picks as a full stable sort.
+#[test]
+fn file_results_over_the_limit_are_the_best_of_a_full_sort() {
+ let files = large_workspace(3000);
+ for filter in ["co", "file1", "m1/s"] {
+ let query = prepare_query(filter);
+ let mut cache = FuzzyScorerCache::new();
+ let mut expected: Vec<&FileEntry> = files.iter().filter(|file| search::file_search::fuzzy_contains(&file.relative_path, &query.piece.normalized_lowercase)).collect();
+ assert!(expected.len() > MAX_RESULTS, "{filter} matches {}", expected.len());
+ expected.sort_by(|a, b| fuzzy_scorer::compare_items_by_fuzzy_score(&file_match_item(a), &file_match_item(b), &query, true, &mut cache));
+ expected.truncate(MAX_RESULTS);
+ let expected: Vec<PathBuf> = expected.into_iter().map(|file| file.path.clone()).collect();
+ assert_eq!(file_search_results(&files, &query), expected, "{filter}");
+ }
+}
+
+// Quick Open in a 100k file workspace, scored off the main thread: 808 ms per keystroke before issue 116, 74 ms after
+// (M1 Max). cargo gc test --release -p app -- --ignored quick_open_keystroke_time --nocapture
+#[test]
+#[ignore]
+fn quick_open_keystroke_time() {
+ let files = large_workspace(100_000);
+ let start = std::time::Instant::now();
+ let filters = ["c", "co", "con", "cont", "contr", "file12"];
+ for filter in filters {
+ file_search_results(&files, &prepare_query(filter));
+ }
+ let per_keystroke = start.elapsed() / filters.len() as u32;
+ println!("quick open, 100k files: {per_keystroke:?} per keystroke");
+ assert!(per_keystroke < std::time::Duration::from_millis(150), "{per_keystroke:?} per keystroke");
+}
+
#[test]
fn picks_show_the_folder_relative_to_the_workspace_and_highlight_the_match() {
let folder = Workspace::folder("/w".into());
diff --git a/native/crates/app/src/editor.rs b/native/crates/app/src/editor.rs
index 8a09ac4a63e..b19ab829365 100644
--- a/native/crates/app/src/editor.rs
+++ b/native/crates/app/src/editor.rs
@@ -719,6 +719,8 @@ pub struct TextModel {
/// When the extension host last opened this model (`$tryOpenDocument`): it stays open without an editor
/// for `BoundModelReferenceCollection`'s 3 minutes after that.
pub host_reference: Option<Instant>,
+ /// The text length when the host last opened it: `BoundModelReferenceCollection` holds 80 MB at most.
+ pub host_reference_length: usize,
/// An untitled model the host opened for a path (`hasAssociatedFilePath`): dirty from the start, saved to that file.
pub associated_file: bool,
/// fileEditorInput.ts `preferredName`: the name an opener gave the resource's editor, kept while the model lives.
@@ -821,12 +823,24 @@ pub struct Scroll {
/// `BoundModelReferenceCollection` maxAge.
pub const HOST_REFERENCE_AGE: Duration = Duration::from_secs(3 * 60);
+/// `BoundModelReferenceCollection` maxLength.
+const HOST_REFERENCE_MAX_LENGTH: usize = 80 * 1024 * 1024;
+/// `BoundModelReferenceCollection` maxSize.
+const HOST_REFERENCE_MAX_COUNT: usize = 50;
+
+impl TextModel {
+ /// `BoundModelReferenceCollection.add` with `getValueLength`.
+ pub fn add_host_reference(&mut self, opened: Instant) {
+ self.host_reference = Some(opened);
+ self.host_reference_length = self.document.lines.iter().map(String::len).sum::<usize>() + self.document.lines.len().saturating_sub(1) * self.document.eol.len();
+ }
+}
impl OpenEditor {
fn new(document: TextDocument, preview: bool, model_id: u32, undo_redo: edit_stack::UndoService) -> Self {
let indentation = document.indentation;
let guides = indent_guides(&document.lines, indentation.tab_size, indentation.indent_size(), document.off_side);
- let model = TextModel { document, version_id: 1, history: History::default(), undo_redo, initial_undo_redo_snapshot: None, guides, host_reference: None, associated_file: false, preferred_name: None, markers: Vec::new(), markers_truncated: false, edits: Vec::new(), custom_document_dirty: false, semantic_tokens: Default::default() };
+ let model = TextModel { document, version_id: 1, history: History::default(), undo_redo, initial_undo_redo_snapshot: None, guides, host_reference: None, host_reference_length: 0, associated_file: false, preferred_name: None, markers: Vec::new(), markers_truncated: false, edits: Vec::new(), custom_document_dirty: false, semantic_tokens: Default::default() };
Self::of_model(Rc::new(RefCell::new(model)), preview, model_id)
}
@@ -1648,13 +1662,43 @@ impl EditorGroup {
self.release_models_except(now, |_| false);
}
- /// `release_models`, keeping the models the workbench `hold`s too (the SCM input boxes').
- pub fn release_models_except(&mut self, now: Instant, hold: impl Fn(&OpenEditor) -> bool) {
+ /// `release_models`, keeping the models the workbench `hold`s too (the SCM input boxes'). Returns when the next
+ /// host reference expires.
+ pub fn release_models_except(&mut self, now: Instant, hold: impl Fn(&OpenEditor) -> bool) -> Option<Instant> {
+ let next_expiry = self.bound_host_references(now);
let (kept, released) = std::mem::take(&mut self.models).into_iter().partition(|model| hold(model) || self.is_referenced(model, now));
self.models = kept;
for model in released.into_iter().filter(|model| Rc::strong_count(&model.model) == 1) {
self.disposed.insert(model);
}
+ next_expiry
+ }
+
+ /// `BoundModelReferenceCollection._cleanup`: from 60 host references the oldest go down to 50, and the oldest go
+ /// while the referenced text is over 80 MB. Returns when the next one left expires.
+ fn bound_host_references(&mut self, now: Instant) -> Option<Instant> {
+ let mut referenced: Vec<Rc<RefCell<TextModel>>> = Vec::new();
+ for editor in self.all_editors() {
+ let live = editor.text_model().host_reference.is_some_and(|opened| now.duration_since(opened) < HOST_REFERENCE_AGE);
+ if live && !referenced.iter().any(|model| Rc::ptr_eq(model, &editor.model)) {
+ referenced.push(editor.model.clone());
+ }
+ }
+ referenced.sort_by_key(|model| std::cmp::Reverse(model.borrow().host_reference));
+ let keep = if referenced.len() >= HOST_REFERENCE_MAX_COUNT * 6 / 5 { HOST_REFERENCE_MAX_COUNT } else { referenced.len() };
+ let mut length = 0;
+ let mut next_expiry: Option<Instant> = None;
+ for (index, model) in referenced.iter().enumerate() {
+ let mut model = model.borrow_mut();
+ length += model.host_reference_length;
+ if index >= keep || length > HOST_REFERENCE_MAX_LENGTH {
+ model.host_reference = None;
+ continue;
+ }
+ let expiry = model.host_reference.expect("live above") + HOST_REFERENCE_AGE;
+ next_expiry = Some(next_expiry.map_or(expiry, |next| next.min(expiry)));
+ }
+ next_expiry
}
/// textModelResolverService.ts `destroyReferencedObject`: a diff, multi diff or merge editor's side, a peek widget's
diff --git a/native/crates/app/src/editor/edit.rs b/native/crates/app/src/editor/edit.rs
index 54bee35f089..0bd8cb16cad 100644
--- a/native/crates/app/src/editor/edit.rs
+++ b/native/crates/app/src/editor/edit.rs
@@ -4,11 +4,13 @@
//! the host hears them in the document's EOL.
use std::cmp::Reverse;
+use std::path::PathBuf;
+use std::rc::Rc;
use super::auto_indent::{AutoIndent, Model};
use super::cursor::{self, Position, Selection};
use super::word_operations::{self, AutoClosing, DeleteWordContext, WordClassifier, WordDelete, WordDeleteKind, WordNavigation};
-use super::edit_stack::{AppliedEdit, SingleModelEditStackElement, UndoElement};
+use super::edit_stack::{AppliedEdit, ModelResource, SingleModelEditStackElement, UndoElement};
use super::{OpenEditor, SharedModel, anchor_select, clipboard, folding, indent_guides};
use crate::undo_redo::{Direction, Next};
@@ -1128,11 +1130,19 @@ impl OpenEditor {
element.append(edits, eol, version_id, self.selections.clone());
return;
}
- let mut element = SingleModelEditStackElement::new(key, &scheme, path, alternative_before, eol_before, selections_before);
+ let mut element = SingleModelEditStackElement::new(Self::undo_resource(&service, key, &uri, &scheme, path), alternative_before, eol_before, selections_before);
element.append(edits, eol, version_id, self.selections.clone());
service.push(super::edit_stack::TYPING_LABEL.into(), vec![element.resource()], 0, 0, false, UndoElement::Model(element));
}
+ /// The resource of the stack's last element when it is this model's, so the elements of a typing session share one.
+ fn undo_resource(service: &crate::undo_redo::UndoRedoService<UndoElement>, key: String, uri: &str, scheme: &str, path: PathBuf) -> Rc<ModelResource> {
+ match service.last_element(&key) {
+ Some(UndoElement::Model(last)) if last.resource.uri == uri => last.resource.clone(),
+ _ => ModelResource::new(key, scheme, path),
+ }
+ }
+
/// Another editor of the shared model changed it: the cursors move with its edits as tracked ranges do
/// (`_onModelContentChanged`), or clamp to the text when the log no longer reaches back. The folding regions
/// move with the edits and wait for the update Delayer (`folding_stale`); without the log they are computed again.
diff --git a/native/crates/app/src/editor/edit_stack.rs b/native/crates/app/src/editor/edit_stack.rs
index da83967edb4..c870abbda0e 100644
--- a/native/crates/app/src/editor/edit_stack.rs
+++ b/native/crates/app/src/editor/edit_stack.rs
@@ -41,12 +41,8 @@ pub(super) struct AppliedEdit {
/// `SingleModelEditStackElement` with its `SingleModelEditStackData`; open until `close` (upstream serializes it).
#[derive(Clone)]
pub struct SingleModelEditStackElement {
- /// The stack it is on: `getUriComparisonKey` of the model's URI.
- pub key: String,
- /// The model's URI string (`matchesResource`, `canAppend`).
- pub uri: String,
- pub scheme: String,
- pub path: PathBuf,
+ /// Shared by the model's elements: a typing session holds thousands (issue 116).
+ pub resource: Rc<ModelResource>,
pub(super) is_open: bool,
pub(super) before_version_id: u32,
pub(super) after_version_id: u32,
@@ -63,14 +59,27 @@ pub struct MultiModelEditStackElement {
pub elements: Vec<SingleModelEditStackElement>,
}
+/// The model an element edits.
+pub struct ModelResource {
+ /// The stack it is on: `getUriComparisonKey` of the model's URI.
+ pub key: String,
+ /// The model's URI string (`matchesResource`, `canAppend`).
+ pub uri: String,
+ pub scheme: String,
+ pub path: PathBuf,
+}
+
+impl ModelResource {
+ pub fn new(key: String, scheme: &str, path: PathBuf) -> Rc<Self> {
+ Rc::new(ModelResource { key, uri: super::uri_string(scheme, &path), scheme: scheme.to_owned(), path })
+ }
+}
+
impl SingleModelEditStackElement {
/// `SingleModelEditStackData.create`: the model's alternative version, EOL and cursors before the first change.
- pub fn new(key: String, scheme: &str, path: PathBuf, alternative_version_id: u32, eol: &'static str, before_cursor_state: Vec<Selection>) -> Self {
+ pub fn new(resource: Rc<ModelResource>, alternative_version_id: u32, eol: &'static str, before_cursor_state: Vec<Selection>) -> Self {
SingleModelEditStackElement {
- key,
- uri: super::uri_string(scheme, &path),
- scheme: scheme.to_owned(),
- path,
+ resource,
is_open: true,
before_version_id: alternative_version_id,
after_version_id: alternative_version_id,
@@ -84,7 +93,7 @@ impl SingleModelEditStackElement {
/// The `(comparison key, label)` the service keeps its stack under.
pub fn resource(&self) -> (String, String) {
- (self.key.clone(), self.path.to_string_lossy().into_owned())
+ (self.resource.key.clone(), self.resource.path.to_string_lossy().into_owned())
}
pub(super) fn append(&mut self, changes: Vec<AppliedEdit>, after_eol: &'static str, after_version_id: u32, after_cursor_state: Vec<Selection>) {
@@ -128,8 +137,8 @@ impl UndoElement {
/// `canAppend`: the open element of the model `uri` that the model's next change joins.
pub(super) fn append_target(&mut self, uri: &str) -> Option<&mut SingleModelEditStackElement> {
match self {
- UndoElement::Model(element) => (element.is_open && element.uri == uri).then_some(element),
- UndoElement::MultiModel(multi) if multi.is_open => multi.elements.iter_mut().find(|element| element.uri == uri),
+ UndoElement::Model(element) => (element.is_open && element.resource.uri == uri).then_some(element),
+ UndoElement::MultiModel(multi) if multi.is_open => multi.elements.iter_mut().find(|element| element.resource.uri == uri),
_ => None,
}
}
@@ -158,8 +167,8 @@ impl UndoElement {
/// `heapSize(resource)` of an edit stack element of the model `uri`; `None` for another element.
pub fn edit_stack_heap_size(&self, uri: &str) -> Option<usize> {
match self {
- UndoElement::Model(element) => (element.uri == uri).then(|| element.heap_size()),
- UndoElement::MultiModel(multi) => multi.elements.iter().find(|element| element.uri == uri).map(SingleModelEditStackElement::heap_size),
+ UndoElement::Model(element) => (element.resource.uri == uri).then(|| element.heap_size()),
+ UndoElement::MultiModel(multi) => multi.elements.iter().find(|element| element.resource.uri == uri).map(SingleModelEditStackElement::heap_size),
UndoElement::File(_) | UndoElement::Cells { .. } | UndoElement::CustomEdit { .. } | UndoElement::MergeHandled { .. } => None,
}
}
diff --git a/native/crates/app/src/editor/edit_stack/tests.rs b/native/crates/app/src/editor/edit_stack/tests.rs
index 79d9fff78e5..9ca49308d6e 100644
--- a/native/crates/app/src/editor/edit_stack/tests.rs
+++ b/native/crates/app/src/editor/edit_stack/tests.rs
@@ -4,7 +4,7 @@ use super::*;
/// the BOM removed at offset 428 is one unit (2 bytes), not its 3 UTF-8 bytes.
#[test]
fn issue_118041_unicode_character_counts_in_utf16() {
- let mut element = SingleModelEditStackElement::new("file:///a.txt".into(), "file", PathBuf::from("/a.txt"), 1, "\n", vec![Selection::caret(Position::new(9, 1))]);
+ let mut element = SingleModelEditStackElement::new(ModelResource::new("file:///a.txt".into(), "file", PathBuf::from("/a.txt")), 1, "\n", vec![Selection::caret(Position::new(9, 1))]);
let change = AppliedEdit { start: Position::new(0, 428), removed: "\u{feff}".into(), inserted: String::new() };
element.append(vec![change], "\n", 2, vec![Selection::caret(Position::new(9, 0))]);
assert_eq!(element.heap_size(), 4 + 4 + 1 + 1 + 20 + 20 + 4 + (4 + 4 + 4 + 2 + 4) + 168);
diff --git a/native/crates/app/src/fuzzy_scorer.rs b/native/crates/app/src/fuzzy_scorer.rs
index d9821dd7c5f..be24eedca37 100644
--- a/native/crates/app/src/fuzzy_scorer.rs
+++ b/native/crates/app/src/fuzzy_scorer.rs
@@ -192,6 +192,14 @@ pub fn score_item_fuzzy(item: Option<&ScorerItem>, query: &PreparedQuery, allow_
item_score
}
+/// `scoreItemFuzzy` without the cache, for a list scored once per query.
+pub fn score_item_uncached(item: &ScorerItem, query: &PreparedQuery, allow_non_contiguous_matches: bool) -> ItemScore {
+ if query.piece.normalized.is_empty() || item.label.is_empty() {
+ return ItemScore::default();
+ }
+ do_score_item_fuzzy(item.label, item.description, item.path, query, allow_non_contiguous_matches)
+}
+
fn do_score_item_fuzzy(label: &str, description: Option<&str>, path: Option<&str>, query: &PreparedQuery, allow_non_contiguous_matches: bool) -> ItemScore {
let prefer_label_matches = path.is_none_or(str::is_empty) || !query.contains_path_separator;
@@ -310,6 +318,11 @@ fn normalize_matches(mut matches: Matches) -> Matches {
pub fn compare_items_by_fuzzy_score(item_a: &ScorerItem, item_b: &ScorerItem, query: &PreparedQuery, allow_non_contiguous_matches: bool, cache: &mut FuzzyScorerCache) -> Ordering {
let item_score_a = score_item_fuzzy(Some(item_a), query, allow_non_contiguous_matches, cache);
let item_score_b = score_item_fuzzy(Some(item_b), query, allow_non_contiguous_matches, cache);
+ compare_item_scores(item_a, &item_score_a, item_b, &item_score_b, query)
+}
+
+/// `compareItemsByFuzzyScore` with both items scored already.
+pub fn compare_item_scores(item_a: &ScorerItem, item_score_a: &ItemScore, item_b: &ScorerItem, item_score_b: &ItemScore, query: &PreparedQuery) -> Ordering {
let score_a = item_score_a.score;
let score_b = item_score_b.score;
@@ -350,8 +363,8 @@ pub fn compare_items_by_fuzzy_score(item_a: &ScorerItem, item_b: &ScorerItem, qu
}
// 5.) scores are identical: prefer more compact matches (label and description)
- let a_match_distance = compute_label_and_description_match_distance(item_a, &item_score_a);
- let b_match_distance = compute_label_and_description_match_distance(item_b, &item_score_b);
+ let a_match_distance = compute_label_and_description_match_distance(item_a, item_score_a);
+ let b_match_distance = compute_label_and_description_match_distance(item_b, item_score_b);
if a_match_distance != 0 && b_match_distance != 0 && a_match_distance != b_match_distance {
return if b_match_distance > a_match_distance { Ordering::Less } else { Ordering::Greater };
}
diff --git a/native/crates/app/src/main_thread.rs b/native/crates/app/src/main_thread.rs
index 02820321cda..20facd3f41d 100644
--- a/native/crates/app/src/main_thread.rs
+++ b/native/crates/app/src/main_thread.rs
@@ -172,8 +172,9 @@ impl MainThread for WorkbenchMainThread {
false => session.send_request(message.proxy, message.method, args),
}
};
- if let Some(reply) = message.reply {
- self.waiting.push((req, message.cancellable, reply));
+ match message.reply {
+ Some(reply) => self.waiting.push((req, message.cancellable, reply)),
+ None => session.forget_result(req),
}
}
let mut still_waiting = Vec::new();
diff --git a/native/crates/app/src/main_thread_commands.rs b/native/crates/app/src/main_thread_commands.rs
index 983a0ee2801..e360f463f35 100644
--- a/native/crates/app/src/main_thread_commands.rs
+++ b/native/crates/app/src/main_thread_commands.rs
@@ -23,10 +23,12 @@ impl Workbench {
/// Answers one host request, forwarded or blocking; the reply goes back to the host once the outcome is ready.
pub fn handle_host_request(&mut self, request: ForwardedRequest, window: &mut Window, cx: &mut Context<Self>) -> Outcome {
let Some((path, handle)) = route(request.proxy, &request.method) else { return unknown_method(self, request, window, cx) };
+ let outcome = handle(self, request, window, cx);
+ // After the call, as `BoundModelReferenceCollection.add` cleans up after it adds a reference.
if path == Path::Blocking {
self.release_host_models(cx);
}
- handle(self, request, window, cx)
+ outcome
}
}
diff --git a/native/crates/app/src/syntax.rs b/native/crates/app/src/syntax.rs
index 90fe883f3bc..1e6675b68e6 100644
--- a/native/crates/app/src/syntax.rs
+++ b/native/crates/app/src/syntax.rs
@@ -89,7 +89,7 @@ fn normalize_color(color: &str) -> Option<String> {
/// of the whole document.
#[derive(Default)]
pub struct Tokenization {
- grammar: Option<Grammar>,
+ grammar: Option<Rc<Grammar>>,
/// Filled while drawing, so behind a RefCell.
lines: RefCell<TokenStore>,
/// Dropped whenever a line's tokens change (bracketPairsTree.ts `handleDidChangeTokens`).
@@ -137,7 +137,7 @@ impl TokenStore {
}
impl Tokenization {
- pub fn new(grammar: Option<Grammar>) -> Self {
+ pub fn new(grammar: Option<Rc<Grammar>>) -> Self {
Tokenization { grammar, lines: RefCell::default(), brackets: RefCell::default(), background_scheduled: Cell::new(false) }
}
@@ -783,6 +783,18 @@ mod tests {
Tokenization::new(None).force_retokenize(&lines);
}
+ // Issue 116: each document compiled its own grammar (3.3 MB for TypeScript) and each token held its own scopes.
+ #[test]
+ fn documents_share_the_grammar_and_tokens_share_their_scopes() {
+ let extensions = exthost::scan::scan_builtin_extensions(&Path::new(env!("VSCODE_SRC")).join("extensions")).unwrap();
+ let languages = Languages::new(&extensions);
+ let grammar = languages.grammars.grammar("typescript").unwrap();
+ assert!(Rc::ptr_eq(&grammar, &languages.grammars.grammar("typescript").unwrap()));
+ let (first, state) = grammar.tokenize_line("let a = 1;", None).unwrap();
+ let (second, _) = grammar.tokenize_line("let b = 2;", Some(&state)).unwrap();
+ assert!(Rc::ptr_eq(&first[0].scopes, &second[0].scopes), "{:?}", first[0].scopes.names());
+ }
+
/// An edit that leaves a line's end state as it was retokenizes that line only; one that changes it carries on
/// down, line by line, as far as the lines are read.
#[test]
diff --git a/native/crates/app/src/undo_redo.rs b/native/crates/app/src/undo_redo.rs
index bf19e3d0d1e..5be737a8ffe 100644
--- a/native/crates/app/src/undo_redo.rs
+++ b/native/crates/app/src/undo_redo.rs
@@ -119,7 +119,8 @@ pub struct Running<E> {
}
pub struct UndoRedoService<E> {
- elements: BTreeMap<u64, StackElement<E>>,
+ /// Boxed: a tree node keeps room for 11 values, and a 376 byte element left half of each empty.
+ elements: BTreeMap<u64, Box<StackElement<E>>>,
stacks: BTreeMap<String, ResourceEditStack>,
next_id: u64,
next_order: u64,
@@ -166,9 +167,11 @@ impl<E: Split> UndoRedoService<E> {
self.next_order += 1;
let id = self.insert(StackElement { id: 0, label, confirm_before_undo, group, source, order, resources, kind, actual: Some(actual), running_parts: Vec::new() });
let resources = self.elements[&id].resources.clone();
+ let mut dropped_future = false;
for (key, label) in resources {
let stack = self.stacks.entry(key.clone()).or_insert_with(|| ResourceEditStack { label, past: Vec::new(), future: Vec::new(), locked: false, version: 1 });
let future = std::mem::take(&mut stack.future);
+ dropped_future |= !future.is_empty();
stack.past.push(id);
stack.version += 1;
let label = stack.label.clone();
@@ -176,7 +179,10 @@ impl<E: Split> UndoRedoService<E> {
self.remove_resource(future, &key, &label, RemovedResourceReason::NoParallelUniverses);
}
}
- self.collect_garbage();
+ // Only a dropped future can leave an element on no stack; the scan visits every element, each keystroke.
+ if dropped_future {
+ self.collect_garbage();
+ }
id
}
@@ -243,7 +249,7 @@ impl<E: Split> UndoRedoService<E> {
Direction::Undo => stack.past.last(),
Direction::Redo => stack.future.last(),
};
- id.map(|id| &self.elements[id])
+ id.map(|id| &*self.elements[id])
}
/// `_findClosestUndoElementInGroup` / `_findClosestRedoElementInGroup`: of the group's elements next on some
@@ -437,7 +443,7 @@ impl<E: Split> UndoRedoService<E> {
let id = self.next_id;
self.next_id += 1;
element.id = id;
- self.elements.insert(id, element);
+ self.elements.insert(id, Box::new(element));
id
}
@@ -707,7 +713,7 @@ impl<E: Split> UndoRedoService<E> {
/// `WorkspaceStackElement.removeResource`; resource elements ignore it.
fn remove_resource(&mut self, id: u64, key: &str, label: &str, reason: RemovedResourceReason) {
- let Some(StackElement { kind: Kind::Workspace { removed, .. }, .. }) = self.elements.get_mut(&id) else { return };
+ let Some(StackElement { kind: Kind::Workspace { removed, .. }, .. }) = self.elements.get_mut(&id).map(|element| &mut **element) else { return };
if !removed.iter().any(|(removed, _, _)| removed == key) {
removed.push((key.to_owned(), label.to_owned(), reason));
}
diff --git a/native/crates/app/src/workbench.rs b/native/crates/app/src/workbench.rs
index c92f210b251..5c8af10272f 100644
--- a/native/crates/app/src/workbench.rs
+++ b/native/crates/app/src/workbench.rs
@@ -569,6 +569,8 @@ pub struct Workbench {
installed_menubar: Option<menubar::Menubar>,
/// menubarControl.ts `menuUpdater`, pending.
menubar_update: Option<Task<()>>,
+ /// `BoundModelReferenceCollection`'s timeout: the next host reference to expire, and the task that releases it.
+ host_model_release: Option<(std::time::Instant, Task<()>)>,
/// StorageScope.PROFILE of the current profile, shared with the extension host's MainThreadStorage.
pub(crate) profile_storage: Arc<Mutex<Storage>>,
/// StorageScope.APPLICATION: the default profile's storage, the same as `profile_storage` in that profile.
@@ -948,6 +950,7 @@ impl Workbench {
hovers: hover::Hovers::default(),
installed_menubar: None,
menubar_update: None,
+ host_model_release: None,
profile_storage: Arc::new(Mutex::new(Storage::in_memory())),
application_storage: Arc::new(Mutex::new(Storage::in_memory())),
workspace_storage: Arc::new(Mutex::new(Storage::in_memory())),
diff --git a/native/crates/app/src/workbench/bulk_text_edits.rs b/native/crates/app/src/workbench/bulk_text_edits.rs
index 28fa9b167ad..aefd05295ba 100644
--- a/native/crates/app/src/workbench/bulk_text_edits.rs
+++ b/native/crates/app/src/workbench/bulk_text_edits.rs
@@ -10,7 +10,7 @@ use serde_json::{Value, json};
use super::Workbench;
use super::format::more_minimal_edits;
use super::host_requests::{range, snippet_edits, uri_parts};
-use crate::editor::edit_stack::{MultiModelEditStackElement, SingleModelEditStackElement, UndoElement};
+use crate::editor::edit_stack::{ModelResource, MultiModelEditStackElement, SingleModelEditStackElement, UndoElement};
use crate::editor::{EditReason, Position, SharedModel, TextDocument, expand_snippet, uri_string};
use crate::local_history;
@@ -72,10 +72,10 @@ impl Workbench {
if tasks.len() == 1 && is_no_op {
return Ok(Value::Null);
}
- elements.push(SingleModelEditStackElement::new(model.undo_key(), scheme, path.clone(), model.alternative_version_id(), model.document().eol, model.selections.clone()));
+ elements.push(SingleModelEditStackElement::new(ModelResource::new(model.undo_key(), scheme, path.clone()), model.alternative_version_id(), model.document().eol, model.selections.clone()));
}
let Some(first) = elements.first() else { return Ok(Value::Null) };
- let first_key = first.key.clone();
+ let first_key = first.resource.key.clone();
let element = match elements.len() {
1 => UndoElement::Model(elements.pop().expect("one element")),
_ => UndoElement::MultiModel(MultiModelEditStackElement::new(elements)),
diff --git a/native/crates/app/src/workbench/bulk_undo.rs b/native/crates/app/src/workbench/bulk_undo.rs
index eb105baf447..02df7fe28bb 100644
--- a/native/crates/app/src/workbench/bulk_undo.rs
+++ b/native/crates/app/src/workbench/bulk_undo.rs
@@ -77,18 +77,18 @@ impl Workbench {
}
let mut elements = running.work.model_elements(direction == Direction::Undo);
// `SingleModelEditStackElement.undo` throws for a model that went without invalidating its elements.
- if elements.iter().any(|element| self.editors.model(&element.scheme, &element.path).is_none()) {
+ if elements.iter().any(|element| self.editors.model(&element.resource.scheme, &element.resource.path).is_none()) {
drop(elements);
service.borrow_mut().fail(running);
return Next::Done;
}
let active = self.editors.active().map(|editor| editor.document().uri_string());
for element in elements.iter_mut() {
- if active.as_ref() == Some(&element.uri) {
+ if active.as_ref() == Some(&element.resource.uri) {
drop(self.run_on_active_editor(|editor| editor.apply_stack_element(element, direction), cx));
continue;
}
- let model = self.editors.model_mut(&element.scheme, &element.path).expect("checked above");
+ let model = self.editors.model_mut(&element.resource.scheme, &element.resource.path).expect("checked above");
if let Some(change) = model.apply_stack_element(element, direction) {
self.model_content_changed(Some(change), crate::workbench::model_events::Cursor::model_change(), cx);
}
diff --git a/native/crates/app/src/workbench/host_requests.rs b/native/crates/app/src/workbench/host_requests.rs
index 64cf0fcae0b..47aece25b76 100644
--- a/native/crates/app/src/workbench/host_requests.rs
+++ b/native/crates/app/src/workbench/host_requests.rs
@@ -98,7 +98,7 @@ impl Workbench {
let scm_inputs = self.scm_input_models();
// A notebook cell's text model lives as long as its notebook, a playground snippet's as long as the playground.
let playground_open = self.playground_open();
- self.editors.release_models_except(Instant::now(), |model| {
+ let next_expiry = self.editors.release_models_except(Instant::now(), |model| {
let scheme = model.document().scheme.clone();
matches!(scheme.as_str(), crate::notebook::CELL_SCHEME | super::interactive::INPUT_SCHEME | super::comments::INPUT_SCHEME)
|| (playground_open && scheme == super::walkthrough_part::SNIPPET_SCHEME)
@@ -107,6 +107,27 @@ impl Workbench {
if self.editors.models.len() != count {
self.editors_changed(cx);
}
+ self.schedule_host_model_release(next_expiry, cx);
+ }
+
+ /// The `setTimeout` of `BoundModelReferenceCollection.add`: the models go when their reference expires, without
+ /// waiting for the next host call.
+ fn schedule_host_model_release(&mut self, next_expiry: Option<Instant>, cx: &mut Context<Self>) {
+ let Some(next_expiry) = next_expiry else {
+ self.host_model_release = None;
+ return;
+ };
+ if self.host_model_release.as_ref().is_some_and(|(scheduled, _)| *scheduled == next_expiry) {
+ return;
+ }
+ let task = cx.spawn(async move |workbench, cx| {
+ cx.background_executor().timer(next_expiry.saturating_duration_since(Instant::now())).await;
+ let _ = workbench.update(cx, |workbench, cx| {
+ workbench.host_model_release = None;
+ workbench.release_host_models(cx);
+ });
+ });
+ self.host_model_release = Some((next_expiry, task));
}
/// `$tryOpenDocument`: the model of a file, of the bytes an extension's file system provider read
@@ -124,7 +145,7 @@ impl Workbench {
}
let requested = options["encoding"].as_str();
if let Some(model) = self.editors.model_mut(scheme, path) {
- model.text_model_mut().host_reference = Some(Instant::now());
+ model.text_model_mut().add_host_reference(Instant::now());
if let Some(requested) = requested {
let provider_bytes = provider_content.is_array().then(|| serde_json::from_value(provider_content.clone()).expect("bytes from main_thread.rs"));
self.set_model_encoding(uri, scheme, path, requested, provider_bytes, cx)
@@ -166,7 +187,7 @@ impl Workbench {
};
let index = self.editors.open_model(document);
let model = &mut self.editors.models[index];
- model.text_model_mut().host_reference = Some(Instant::now());
+ model.text_model_mut().add_host_reference(Instant::now());
model.text_model_mut().associated_file = scheme == "untitled";
self.editors_changed(cx);
// `_handleUntitledScheme` ends in `_doCreateUntitled`, which marks the host's document dirty.
@@ -324,7 +345,7 @@ impl Workbench {
document.encoding = options["encoding"].as_str().map_or(document.encoding, str::to_string);
let uri = document.uri();
let index = self.editors.open_model(document);
- self.editors.models[index].text_model_mut().host_reference = Some(Instant::now());
+ self.editors.models[index].text_model_mut().add_host_reference(Instant::now());
self.editors_changed(cx);
// mainThreadDocuments.ts `_doCreateUntitled` tells the host the new document is dirty, whatever the model says.
self.host.send("ExtHostDocuments", "$acceptDirtyStateChanged", vec![uri.clone(), json!(true)]);
diff --git a/native/crates/app/src/workbench/notebook_editor.rs b/native/crates/app/src/workbench/notebook_editor.rs
index 183a9666de0..5199900148e 100644
--- a/native/crates/app/src/workbench/notebook_editor.rs
+++ b/native/crates/app/src/workbench/notebook_editor.rs
@@ -1590,8 +1590,8 @@ impl Workbench {
Direction::Redo => future.first().copied(),
};
match element {
- Some(UndoElement::Model(element)) => vec![element.uri.clone()],
- Some(UndoElement::MultiModel(multi)) => multi.elements.iter().map(|element| element.uri.clone()).collect(),
+ Some(UndoElement::Model(element)) => vec![element.resource.uri.clone()],
+ Some(UndoElement::MultiModel(multi)) => multi.elements.iter().map(|element| element.resource.uri.clone()).collect(),
_ => Vec::new(),
}
};
diff --git a/native/crates/app/src/workbench/quick_open.rs b/native/crates/app/src/workbench/quick_open.rs
index 94d63aff7d8..b012eed3963 100644
--- a/native/crates/app/src/workbench/quick_open.rs
+++ b/native/crates/app/src/workbench/quick_open.rs
@@ -36,7 +36,10 @@ pub struct FilePickState {
pub last_range: Option<TextRange>,
scorer_cache: FuzzyScorerCache,
/// The workspace files; `None` while the search loads them.
- files: Option<Vec<FileEntry>>,
+ files: Option<Arc<Vec<FileEntry>>>,
+ /// The file picks of a filter and the history picks they leave out, scored in the background.
+ file_results: Option<(String, Vec<PathBuf>, Vec<FilePick>)>,
+ _scoring: Option<Task<()>>,
merge_delay_passed: bool,
cancellation: Arc<Cancellation>,
_load: Task<()>,
@@ -173,9 +176,21 @@ impl Workbench {
let query = fuzzy_scorer::prepare_query(&filter);
let history = anything_quick_access::editor_history_picks(&self.quick_access.editor_history.entries, &query, workspace.as_ref(), include_history, sort_by_recency, &mut state.scorer_cache);
+ let history_paths: Vec<PathBuf> = history.iter().map(|pick| pick.path.clone()).collect();
let files = match &state.files {
_ if query.piece.normalized.is_empty() => Some(Vec::new()),
- Some(files) => Some(anything_quick_access::file_picks(files, &query, &history, workspace.as_ref(), &home, &mut state.scorer_cache)),
+ Some(files) => match &state.file_results {
+ Some((scored_filter, scored_history, picks)) if *scored_filter == filter && *scored_history == history_paths => Some(picks.clone()),
+ // Scoring a large workspace takes longer than a frame; the shown picks stay until it ends.
+ _ => {
+ let (files, history) = (files.clone(), history.clone());
+ state._scoring = Some(cx.spawn_in(window, async move |workbench, cx| {
+ let picks = cx.background_spawn(async move { anything_quick_access::file_picks(&files, &query, &history, workspace.as_ref(), &home, &mut FuzzyScorerCache::default()) }).await;
+ let _ = workbench.update_in(cx, |workbench, window, cx| workbench.file_picks_scored(id, (filter, history_paths, picks), window, cx));
+ }));
+ return None;
+ }
+ },
None => None,
};
// applyFastAndSlowPicks: history picks alone show once the merge delay passed, and not when empty.
@@ -297,17 +312,30 @@ impl Workbench {
last_range: None,
scorer_cache: FuzzyScorerCache::default(),
files: None,
+ file_results: None,
+ _scoring: None,
merge_delay_passed: false,
cancellation,
_load: load,
}
}
+ /// The file picks of a filter, scored off the main thread: the picker's picks update with them.
+ fn file_picks_scored(&mut self, id: i64, results: (String, Vec<PathBuf>, Vec<FilePick>), window: &mut Window, cx: &mut Context<Self>) {
+ let Some(state) = self.quick_access.files.as_mut().filter(|state| state.input == id) else { return };
+ state.file_results = Some(results);
+ // The value did not change; a cleared last filter keeps the `:line` check in file_picks from skipping the update.
+ state.last_filter = None;
+ self.update_quick_access_picks(id, window, cx);
+ self.flush_quick_input_events(window, cx);
+ cx.notify();
+ }
+
/// The merge delay passed (`None`) or the file list loaded: the picker's picks update.
fn file_query_cache_progress(&mut self, id: i64, files: Option<Vec<FileEntry>>, window: &mut Window, cx: &mut Context<Self>) {
let Some(state) = self.quick_access.files.as_mut().filter(|state| state.input == id) else { return };
match files {
- Some(files) => state.files = Some(files),
+ Some(files) => state.files = Some(Arc::new(files)),
None => state.merge_delay_passed = true,
}
// The value did not change; a cleared last filter keeps the `:line` check in file_picks from skipping the update.
diff --git a/native/crates/app/src/workbench/text_model_resolver.rs b/native/crates/app/src/workbench/text_model_resolver.rs
index 612f48ef68d..64005848d0e 100644
--- a/native/crates/app/src/workbench/text_model_resolver.rs
+++ b/native/crates/app/src/workbench/text_model_resolver.rs
@@ -115,6 +115,35 @@ mod tests {
assert_eq!(text(&group, "file", "/path/file_resolver.txt"), None);
}
+ // mainThreadDocuments.test.ts "max count", with the default 50: from 60 references the oldest 10 go.
+ #[test]
+ fn host_references_from_sixty_keep_the_newest_fifty() {
+ let opened = Instant::now();
+ let mut group = EditorGroup::default();
+ for index in 0..60 {
+ referenced(&mut group, document("file", &format!("/path/{index}.txt"), "text"), opened + std::time::Duration::from_millis(index));
+ }
+ group.release_models(opened + std::time::Duration::from_millis(60));
+ assert_eq!(group.models.len(), 50);
+ assert_eq!(text(&group, "file", "/path/9.txt"), None);
+ assert!(text(&group, "file", "/path/10.txt").is_some());
+ }
+
+ // mainThreadDocuments.test.ts "max size", with the default 80 MB.
+ #[test]
+ fn host_references_over_80_mb_drop_the_oldest() {
+ let opened = Instant::now();
+ let mut group = EditorGroup::default();
+ for (index, megabytes) in [6, 6, 70].into_iter().enumerate() {
+ referenced(&mut group, document("file", &format!("/path/{index}.txt"), "text"), opened + std::time::Duration::from_millis(index as u64));
+ group.models[index].text_model_mut().host_reference_length = megabytes * 1024 * 1024;
+ }
+ group.release_models(opened + std::time::Duration::from_millis(3));
+ assert_eq!(text(&group, "file", "/path/0.txt"), None);
+ assert_eq!(text(&group, "file", "/path/1.txt").as_deref(), Some("text"));
+ assert_eq!(text(&group, "file", "/path/2.txt").as_deref(), Some("text"));
+ }
+
#[test]
fn resolved_dirty_file_eventually_disposes() {
let mut group = EditorGroup::default();
diff --git a/native/crates/exthost/src/session.rs b/native/crates/exthost/src/session.rs
index 1db21c6d3e3..b82fe08fc00 100644
--- a/native/crates/exthost/src/session.rs
+++ b/native/crates/exthost/src/session.rs
@@ -167,6 +167,8 @@ pub struct Session {
pub host: ExtensionHost,
next_req: u32,
results: HashMap<u32, CallResult>,
+ /// Requests whose reply nobody takes: it is dropped when it arrives, where `results` kept one per edit (issue 116).
+ unawaited: HashSet<u32>,
pub log: SessionLog,
/// `IExtensionDescription`s by lowercase id, for `$getExtension`.
extensions: HashMap<String, Value>,
@@ -221,6 +223,7 @@ impl Session {
host,
next_req: 0,
results: HashMap::new(),
+ unawaited: HashSet::new(),
log: SessionLog::default(),
extensions: HashMap::new(),
extensions_version: 1,
@@ -408,7 +411,7 @@ impl Session {
self.host.send(rpc::encode(&message));
}
- /// The host's answer to a `notify`, once it arrived.
+ /// The host's answer to a request, once it arrived.
pub fn take_result(&mut self, req: u32) -> Option<Result<Value, Value>> {
Some(match self.results.remove(&req)? {
CallResult::Ok(Reply::Json(value)) => Ok(value),
@@ -422,9 +425,17 @@ impl Session {
})
}
- /// Sends a request without waiting for its reply.
- pub fn notify(&mut self, proxy: &str, method: &str, args: Vec<Value>) -> u32 {
- self.send_request(proxy, method, args.into_iter().map(Arg::from_value).collect())
+ /// Sends a request and drops its reply.
+ pub fn notify(&mut self, proxy: &str, method: &str, args: Vec<Value>) {
+ let req = self.send_request(proxy, method, args.into_iter().map(Arg::from_value).collect());
+ self.forget_result(req);
+ }
+
+ /// Nobody takes the reply to `req`.
+ pub fn forget_result(&mut self, req: u32) {
+ if self.results.remove(&req).is_none() {
+ self.unawaited.insert(req);
+ }
}
/// `notify` of a host method that takes a `CancellationToken`; `cancel` cancels it.
@@ -518,7 +529,7 @@ impl Session {
}
for outgoing in self.workspace.as_mut().map(MainThreadWorkspace::take_outgoing).unwrap_or_default() {
match outgoing {
- Outgoing::TextSearchResult(args) => _ = self.notify("ExtHostWorkspace", "$handleTextSearchResult", args),
+ Outgoing::TextSearchResult(args) => self.notify("ExtHostWorkspace", "$handleTextSearchResult", args),
Outgoing::Reply(reply) => self.host.send(rpc::encode(&reply)),
}
}
@@ -625,10 +636,14 @@ impl Session {
self.serve(req, rpc_id, method, args);
}
Message::ReplyOk { req, value } => {
- self.results.insert(req, CallResult::Ok(value));
+ if !self.unawaited.remove(&req) {
+ self.results.insert(req, CallResult::Ok(value));
+ }
}
Message::ReplyErr { req, error } => {
- self.results.insert(req, CallResult::Err(error));
+ if !self.unawaited.remove(&req) {
+ self.results.insert(req, CallResult::Err(error));
+ }
}
// A cancelled search or forwarded request; each side ignores a req it does not own.
Message::Cancel { req } => {
@@ -938,4 +953,25 @@ mod tests {
let waited = started.elapsed();
assert!(waited >= Duration::from_millis(300) && waited < Duration::from_secs(5), "{waited:?}");
}
+
+ // Issue 116: the reply to every model change the workbench sent stayed in `results`.
+ #[test]
+ fn replies_nobody_takes_are_dropped() {
+ let (host, mut peer) = ExtensionHost::silent(crate::Inbox::default());
+ let mut session = Session::new(host);
+ session.notify("ExtHostDocuments", "$acceptModelChanged", Vec::new());
+ let forgotten = session.send_request("ExtHostDocuments", "$acceptModelSaved", Vec::new());
+ session.forget_result(forgotten);
+ let taken = session.send_request("ExtHostCommands", "$executeContributedCommand", Vec::new());
+ for (id, req) in [1, 2, 3].into_iter().zip([forgotten - 1, forgotten, taken]) {
+ let mut bytes = Vec::new();
+ crate::frame::encode_frame(&crate::frame::Frame { kind: crate::frame::FrameType::Regular, id, ack: 0, data: rpc::encode(&Message::ReplyOk { req, value: Reply::Empty }) }, &mut bytes);
+ std::io::Write::write_all(&mut peer, &bytes).unwrap();
+ }
+ while !session.results.contains_key(&taken) {
+ assert!(session.pump(Duration::from_secs(5)).unwrap());
+ }
+ assert_eq!(session.results.len(), 1);
+ assert!(session.unawaited.is_empty());
+ }
}
diff --git a/native/crates/files/src/watcher.rs b/native/crates/files/src/watcher.rs
index 255db491c4e..20cc3b36ab8 100644
--- a/native/crates/files/src/watcher.rs
+++ b/native/crates/files/src/watcher.rs
@@ -75,6 +75,8 @@ struct Watch {
real_root: PathBuf,
recursive: bool,
excludes: Vec<Glob>,
+ /// Whether the FSEvents stream has the path; a path below a recursive watch's gets its events from that one.
+ registered: bool,
}
impl Watch {
@@ -126,20 +128,42 @@ impl Watcher {
// parseWatcherPatterns: relative to the watched path, ignoring case as macOS does.
let excludes = excludes.iter().map(|pattern| glob::parse(pattern, glob::Options { ignore_case: true, ..glob::Options::default() })).collect();
let real_root = std::fs::canonicalize(path).unwrap_or_else(|_| path.to_path_buf());
- let mode = if recursive { RecursiveMode::Recursive } else { RecursiveMode::NonRecursive };
- self.fs_events.watch(path, mode)?;
- self.watches.lock().unwrap().insert(id, Watch { root: path.to_path_buf(), real_root, recursive, excludes });
+ // nodejsWatcherLib.ts `doWatchWithExistingWatcher`: notify restarts its one FSEvents stream, resolving every
+ // path again, on each watch, so a language server watching thousands of files kept a core busy (issue 116).
+ let registered = !covered_by_recursive(&self.watches.lock().unwrap(), &real_root);
+ if registered {
+ let mode = if recursive { RecursiveMode::Recursive } else { RecursiveMode::NonRecursive };
+ self.fs_events.watch(path, mode)?;
+ }
+ self.watches.lock().unwrap().insert(id, Watch { root: path.to_path_buf(), real_root, recursive, excludes, registered });
Ok(())
}
pub fn unwatch(&mut self, id: u64) {
- let Some(watch) = self.watches.lock().unwrap().remove(&id) else { return };
- if !self.watches.lock().unwrap().values().any(|other| other.root == watch.root) {
- let _ = self.fs_events.unwatch(&watch.root);
+ let mut watches = self.watches.lock().unwrap();
+ let Some(watch) = watches.remove(&id) else { return };
+ if !watch.registered || watches.values().any(|other| other.registered && other.root == watch.root) {
+ return;
+ }
+ let _ = self.fs_events.unwatch(&watch.root);
+ // The watches below this one's path get their own place in the stream.
+ let mut uncovered: Vec<u64> = watches.iter().filter(|(_, other)| !other.registered).map(|(id, _)| *id).collect();
+ uncovered.sort_by_key(|id| watches[id].real_root.as_os_str().len());
+ for id in uncovered {
+ if covered_by_recursive(&watches, &watches[&id].real_root) {
+ continue;
+ }
+ let other = watches.get_mut(&id).expect("listed above");
+ let mode = if other.recursive { RecursiveMode::Recursive } else { RecursiveMode::NonRecursive };
+ other.registered = self.fs_events.watch(&other.root, mode).is_ok();
}
}
}
+fn covered_by_recursive(watches: &HashMap<u64, Watch>, real_path: &Path) -> bool {
+ watches.values().any(|watch| watch.registered && watch.recursive && real_path.starts_with(&watch.real_root))
+}
+
/// parcel's FSEvents handling: a create, remove or rename is an add when the path exists afterwards, else a delete.
fn forward(event: notify::Result<notify::Event>, sender: &Sender<Change>) {
let Ok(event) = event else { return };
@@ -233,4 +257,50 @@ mod tests {
assert!(!seen.iter().any(|change| change.path.starts_with(dir.join(".git"))), "{seen:?}");
std::fs::remove_dir_all(dir).unwrap();
}
+
+ // tsserver watches each file it reads: 2000 watches below a workspace folder took seconds of a core.
+ #[test]
+ fn files_below_a_recursive_watch_do_not_restart_the_stream() {
+ let dir = std::env::temp_dir().join(format!("files-watch-many-{}", std::process::id()));
+ let _ = std::fs::remove_dir_all(&dir);
+ std::fs::create_dir_all(&dir).unwrap();
+ for id in 1..=2000 {
+ std::fs::write(dir.join(format!("{id}.ts")), "").unwrap();
+ }
+ let mut watcher = Watcher::new(|_| {}).unwrap();
+ watcher.watch(0, &dir, true, &[]).unwrap();
+ let start = Instant::now();
+ for id in 1..=2000 {
+ watcher.watch(id, &dir.join(format!("{id}.ts")), false, &[]).unwrap();
+ }
+ assert!(start.elapsed() < Duration::from_millis(500), "{:?}", start.elapsed());
+ std::fs::remove_dir_all(dir).unwrap();
+ }
+
+ #[test]
+ fn a_file_below_a_recursive_watch_keeps_its_events_when_that_watch_goes() {
+ let dir = std::env::temp_dir().join(format!("files-watch-covered-{}", std::process::id()));
+ let _ = std::fs::remove_dir_all(&dir);
+ std::fs::create_dir_all(&dir).unwrap();
+ let file = dir.join("watched.txt");
+ std::fs::write(&file, "").unwrap();
+ let (sender, receiver) = channel();
+ let mut watcher = Watcher::new(move |changes| sender.send(changes).unwrap()).unwrap();
+ watcher.watch(1, &dir, true, &[]).unwrap();
+ watcher.watch(2, &file, false, &[]).unwrap();
+ assert!(!watcher.watches.lock().unwrap()[&2].registered, "the folder's stream covers the file");
+ watcher.unwatch(1);
+ assert!(watcher.watches.lock().unwrap()[&2].registered);
+ std::thread::sleep(Duration::from_millis(200));
+ std::fs::write(&file, "changed").unwrap();
+ let mut seen = Vec::new();
+ while let Ok(changes) = receiver.recv_timeout(Duration::from_secs(3)) {
+ seen.extend(changes);
+ if seen.iter().any(|change| change.path == file) {
+ break;
+ }
+ }
+ assert!(seen.iter().any(|change| change.path == file), "{seen:?}");
+ std::fs::remove_dir_all(dir).unwrap();
+ }
}
diff --git a/native/crates/search/src/file_search.rs b/native/crates/search/src/file_search.rs
index 5827b69904d..3b9dea76e96 100644
--- a/native/crates/search/src/file_search.rs
+++ b/native/crates/search/src/file_search.rs
@@ -429,15 +429,13 @@ pub fn fuzzy_contains(target: &str, query: &str) -> bool {
if target.is_empty() || query.is_empty() {
return false;
}
- let target = target.to_lowercase();
- let mut rest = target.as_str();
- for char in query.to_lowercase().chars() {
- match rest.find(char) {
- Some(index) => rest = &rest[index + char.len_utf8()..],
- None => return false,
- }
+ // Without a lowercase copy of each path: Quick Open runs this over every workspace file per keystroke.
+ if target.is_ascii() && query.is_ascii() {
+ let mut target = target.bytes();
+ return query.bytes().all(|byte| target.any(|candidate| candidate.eq_ignore_ascii_case(&byte)));
}
- true
+ let mut target = target.chars().flat_map(char::to_lowercase);
+ query.chars().flat_map(char::to_lowercase).all(|char| target.any(|candidate| candidate == char))
}
fn strings_equal(a: &str, b: &str, ignore_case: bool) -> bool {
diff --git a/native/crates/textmate/src/grammar.rs b/native/crates/textmate/src/grammar.rs
index f3e4906ef54..fd23b6ca686 100644
--- a/native/crates/textmate/src/grammar.rs
+++ b/native/crates/textmate/src/grammar.rs
@@ -1,7 +1,7 @@
//! A compiled grammar and line tokenization, ported from vscode-textmate 9.3.2 (grammar.ts,
//! tokenizeString.ts, basicScopesAttributeProvider.ts). Offsets are UTF-8 byte offsets in the line.
-use std::cell::Cell;
+use std::cell::{Cell, OnceCell, RefCell};
use std::collections::HashMap;
use std::rc::Rc;
@@ -105,6 +105,10 @@ pub struct Grammar {
unbalanced_brackets: Vec<Matcher>,
balanced_allow_any: bool,
next_line_id: Cell<u64>,
+ /// The root scope and each scope pushed on a scope once: the tokens of every line share them, where a scope per
+ /// token held 190 bytes a token (issue 116). Keyed by the parent's address, which the child keeps alive.
+ root_scopes: OnceCell<Rc<ScopeStack>>,
+ child_scopes: RefCell<HashMap<usize, HashMap<String, Rc<ScopeStack>>>>,
}
/// One element of the rule stack; the state between lines is the innermost one.
@@ -257,6 +261,8 @@ impl Grammar {
unbalanced_brackets: matchers(&configuration.unbalanced_bracket_selectors),
balanced_allow_any,
next_line_id: Cell::new(0),
+ root_scopes: OnceCell::new(),
+ child_scopes: RefCell::default(),
}
}
@@ -288,6 +294,8 @@ impl Grammar {
for token in &mut tokens.tokens {
token.end = token.end.min(line_length - 1);
}
+ // A document keeps every line's tokens: without the growth slack they take a third less.
+ tokens.tokens.shrink_to_fit();
Ok((tokens.tokens, state))
}
@@ -297,13 +305,13 @@ impl Grammar {
}
fn initial_state(&self) -> State {
- let root_name = self.rule(self.root_id).name(None, None).unwrap_or_else(|| "unknown".into());
- let root = Rc::new(ScopeStack {
- parent: None,
- language: self.scope_language(&root_name).or_else(|| self.language.clone()),
- token_type: standard_token_type(&root_name),
- scope_name: root_name,
- });
+ let root = self
+ .root_scopes
+ .get_or_init(|| {
+ let root_name = self.rule(self.root_id).name(None, None).unwrap_or_else(|| "unknown".into());
+ Rc::new(ScopeStack { parent: None, language: self.scope_language(&root_name).or_else(|| self.language.clone()), token_type: standard_token_type(&root_name), scope_name: root_name })
+ })
+ .clone();
Rc::new(StateStack { parent: None, rule_id: self.root_id, enter_pos: Cell::new(-1), anchor_pos: Cell::new(-1), begin_rule_captured_eol: false, end_rule: None, name_scopes: root.clone(), content_name_scopes: root })
}
@@ -315,13 +323,21 @@ impl Grammar {
fn push_scopes(&self, target: &Rc<ScopeStack>, names: Option<String>) -> Rc<ScopeStack> {
let Some(names) = names else { return target.clone() };
let mut result = target.clone();
+ let mut child_scopes = self.child_scopes.borrow_mut();
for name in names.split(' ') {
- result = Rc::new(ScopeStack {
+ let children = child_scopes.entry(Rc::as_ptr(&result) as usize).or_default();
+ if let Some(child) = children.get(name) {
+ result = child.clone();
+ continue;
+ }
+ let child = Rc::new(ScopeStack {
language: self.scope_language(name).or_else(|| result.language.clone()),
token_type: standard_token_type(name).or(result.token_type),
parent: Some(result),
scope_name: name.to_string(),
});
+ children.insert(name.to_string(), child.clone());
+ result = child;
}
result
}
diff --git a/native/crates/textmate/src/registry.rs b/native/crates/textmate/src/registry.rs
index d75e7afc56b..e00137a6449 100644
--- a/native/crates/textmate/src/registry.rs
+++ b/native/crates/textmate/src/registry.rs
@@ -27,6 +27,8 @@ pub struct Registry {
injections: HashMap<String, Vec<String>>,
injected_embedded_languages: HashMap<String, Vec<(String, String)>>,
sources: RefCell<HashMap<String, Option<Rc<RawGrammarSource>>>>,
+ /// vscode-textmate `SyncRegistry._grammars`: one grammar per language, its compiled regexes shared by every document.
+ grammars: RefCell<HashMap<String, Option<Rc<Grammar>>>>,
}
impl Registry {
@@ -44,6 +46,7 @@ impl Registry {
/// One `contributes.grammars` entry of the extension in `location`.
pub fn register(&mut self, location: &Path, grammar: &Value) {
let (Some(scope_name), Some(path)) = (grammar["scopeName"].as_str(), grammar["path"].as_str()) else { return };
+ self.grammars.get_mut().clear();
let pairs = |key: &str| grammar[key].as_object().into_iter().flatten().filter_map(|(k, v)| Some((k.clone(), v.as_str()?.to_string()))).collect::<Vec<_>>();
let embedded_languages = pairs("embeddedLanguages");
let token_types = pairs("tokenTypes")
@@ -95,7 +98,16 @@ impl Registry {
/// `createGrammar`: the grammar of a language with its contribution's settings; `None` when no
/// grammar is contributed for it or its file does not load.
- pub fn grammar(&self, language: &str) -> Option<Grammar> {
+ pub fn grammar(&self, language: &str) -> Option<Rc<Grammar>> {
+ if let Some(grammar) = self.grammars.borrow().get(language) {
+ return grammar.clone();
+ }
+ let grammar = self.create_grammar(language).map(Rc::new);
+ self.grammars.borrow_mut().insert(language.to_string(), grammar.clone());
+ grammar
+ }
+
+ fn create_grammar(&self, language: &str) -> Option<Grammar> {
let scope_name = self.language_to_scope.get(language)?;
let definition = self.definitions.get(scope_name)?;
let mut embedded_languages = definition.embedded_languages.clone();
diff --git a/port/fixtures/extensions/memory-soak/extension.js b/port/fixtures/extensions/memory-soak/extension.js
new file mode 100644
index 00000000000..30cc205531c
--- /dev/null
+++ b/port/fixtures/extensions/memory-soak/extension.js
@@ -0,0 +1,2 @@
+// A main makes the host map tests/ to this extension.
+exports.activate = () => { };
diff --git a/port/fixtures/extensions/memory-soak/package.json b/port/fixtures/extensions/memory-soak/package.json
new file mode 100644
index 00000000000..a0aaa9278df
--- /dev/null
+++ b/port/fixtures/extensions/memory-soak/package.json
@@ -0,0 +1,7 @@
+{
+ "name": "memory-soak",
+ "publisher": "port",
+ "version": "0.0.1",
+ "engines": { "vscode": "^1.90.0" },
+ "main": "./extension.js"
+}
diff --git a/port/fixtures/extensions/memory-soak/tests/index.js b/port/fixtures/extensions/memory-soak/tests/index.js
new file mode 100644
index 00000000000..0bb78952acb
--- /dev/null
+++ b/port/fixtures/extensions/memory-soak/tests/index.js
@@ -0,0 +1,72 @@
+// port/tools/memory-soak: repeats a workload and fails when the window process's footprint keeps growing (issue 116).
+// browse: 40 files not opened before, each scrolled, then closed. typing: 300 edits in a file, reverted and closed.
+// all: Quick Open, Find in Files, and the same 60 files opened and closed.
+const assert = require('assert');
+const vscode = require('vscode');
+const { execFileSync } = require('child_process');
+
+const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));
+const rounds = Number(process.env.ROUNDS || 20);
+const mode = process.env.MODE || 'browse';
+
+// footprint(1) of the window process, which starts the extension host.
+function footprintMib() {
+ const out = execFileSync('/usr/bin/footprint', ['-p', String(process.ppid)], { encoding: 'utf8' });
+ const [, value, unit] = out.match(/Footprint:\s+([\d.]+)\s+(\w+)/);
+ return Number(value) * ({ KB: 1 / 1024, MB: 1, GB: 1024 })[unit];
+}
+
+const median = values => [...values].sort((a, b) => a - b)[Math.floor(values.length / 2)];
+
+async function browse(files, round) {
+ for (const uri of files.slice(round * 40, round * 40 + 40)) {
+ const editor = await vscode.window.showTextDocument(uri, { preview: false });
+ for (let line = 0; line < Math.min(editor.document.lineCount, 2000); line += 40) {
+ editor.revealRange(new vscode.Range(line, 0, line, 0));
+ await sleep(16);
+ }
+ }
+ await vscode.commands.executeCommand('workbench.action.closeAllEditors');
+}
+
+async function typing(files, round) {
+ const editor = await vscode.window.showTextDocument(files[round % files.length]);
+ for (let i = 0; i < 300; i++) {
+ await editor.edit(builder => builder.insert(new vscode.Position(i % 50, 0), 'let x = 1; '));
+ }
+ await vscode.commands.executeCommand('workbench.action.files.revert');
+ await vscode.commands.executeCommand('workbench.action.closeActiveEditor');
+}
+
+async function all(files, round) {
+ for (const filter of ['a', 'co', 'con', 'cont', 'contr', 'controller', 'index.ts', 'zz']) {
+ await vscode.commands.executeCommand('workbench.action.quickOpen', filter);
+ await sleep(400);
+ }
+ await vscode.commands.executeCommand('workbench.action.closeQuickOpen');
+ await vscode.commands.executeCommand('workbench.action.findInFiles', { query: round % 2 ? 'function' : 'return', triggerSearch: true });
+ await sleep(3000);
+ await vscode.commands.executeCommand('search.action.clearSearchResults');
+ for (const uri of files.slice(0, 60)) {
+ await vscode.window.showTextDocument(uri, { preview: false });
+ }
+ await vscode.commands.executeCommand('workbench.action.closeAllEditors');
+}
+
+exports.run = async () => {
+ const workload = { browse, typing, all }[mode];
+ assert(workload, `MODE ${mode}: browse, typing or all`);
+ const files = await vscode.workspace.findFiles('**/*.{ts,rs,js,md,json,css}', '**/node_modules/**', (rounds + 1) * 40);
+ const samples = [];
+ for (let round = 1; round <= rounds; round++) {
+ await workload(files, round);
+ await sleep(1500);
+ samples.push(footprintMib());
+ console.log(`round ${round}: ${samples.at(-1).toFixed(0)} MiB`);
+ }
+ // The first rounds fill caches up to their bounds; growth after them is a leak.
+ const early = median(samples.slice(2, 7));
+ const late = median(samples.slice(-5));
+ console.log(`median of rounds 3 to 7: ${early.toFixed(0)} MiB, of the last 5: ${late.toFixed(0)} MiB`);
+ assert(late <= early * 1.3, `the footprint grew from ${early.toFixed(0)} to ${late.toFixed(0)} MiB`);
+};
diff --git a/port/notes.md b/port/notes.md
index 8b6c7ac9801..bf6af4441bf 100644
--- a/port/notes.md
+++ b/port/notes.md
@@ -1107,6 +1107,18 @@ Work the port does at another time than 1.147.0, accepted with a measured same r
- Smart select's bracket ranges (bracketSelections.ts) scan to the document's ends in one go (smart_select.rs `bracket_ranges`), where upstream yields after `_maxDuration` (30 ms) and stops the right scan after 2 rounds. The scan takes 7.22 to 7.76 ms on the 52k-line file, so upstream's scan ends in its first round with the same ranges; upstream's smartSelect.test.ts raises `_maxDuration` to 5 s for that full scan. The typing check gates the scan under 30 ms.
- Ported instead (they changed the result): the minimap's sticky sampling (`MinimapSampling::compute` with the last state, `on_lines_deleted`, `on_lines_inserted`, replayed from the model's edit log while view lines are model lines; with word wrap or folds the state is not moved through the edits, an open class 3 gap on the editor/browser row), and `tokenizeIfCheap` and `hasAccurateTokensForLine` in the comment commands and trim trailing whitespace (the action and the save participant). Trim on a file just opened took 6.8 s and comment at line 49000 5.3 s, tokenizing the file; now 3.70 and 13.53 ms, gated under 16 ms by the typing check.
+## Memory and CPU over a long session (issue 116, branch perf/memory-116)
+
+The report: 3.41 GB in the window process of 1.148.0.2 after a day with two windows of 5 folders, and Quick Open lagging while typing. The loop that found it: `port/tools/memory-soak` (an extension test that repeats a workload and reads the window process's `footprint(1)` each round). Opening and closing 40 files not opened before, each round, grew the footprint by 40 to 90 MB a round (797 MB at round 12); the same 40 files each round stayed flat. Typing 300 edits in a file, then reverting and closing it, grew it by 1.9 MB a round (213 to 326 MB in 60 rounds); `malloc_history` between round 5 and round 60 named the live allocations. Seven causes, each fixed where upstream does it:
+
+- The extension host's documents never went. `BoundModelReferenceCollection` drops a reference after 3 minutes (a `setTimeout`), from 60 references down to the newest 50, and the oldest while the referenced text is over 80 MB; the port had the age only, checked on the next blocking host call (`EditorGroup::release_models_except`, `Workbench::schedule_host_model_release`). With the bounds and the timer, the 30-round browse run stays at 186 to 204 MB.
+- Every document compiled its own grammar: 3.3 MB for TypeScript, regexes compiled again per file. `Registry::grammar` keeps one per language, as vscode-textmate's `SyncRegistry._grammars`.
+- Every token held its own scope nodes: 187 bytes a token, 5 MB for the 109 KB textModel.ts. The grammar now keeps each scope pushed on a scope once (`Grammar::push_scopes`) and the token vectors lose their slack (1.3 MB with it): 27,606 tokens at 32 bytes, 0.86 MB. Upstream keeps 8 bytes a token (encoded metadata); the port keeps the scopes the theme and `Inspect Editor Tokens` read, at 32 bytes a token.
+- A watch made notify's FSEvents stream start again with every watched path resolved, so a language server watching each file it read kept the extension host session thread at 100% of a core (2000 watches: 8.96 s). A watch below a recursive watch of the same watcher now uses that stream, as nodejsWatcherLib.ts `doWatchWithExistingWatcher` does; upstream does it for files only, because its recursive watcher dispatches by exact path, which `Watch::covers` does not need.
+- Quick Open scored a full sort of every match on the main thread, each comparison scoring both items again through a cache keyed by cloned strings: 808 ms per keystroke on 100,000 files, 508,000 cache entries. Each match is scored once, the best 512 are selected as rawSearchService.ts `sortResults` (`arrays.top`) does, and the scoring runs on the background executor: 74 ms per keystroke, off the main thread (`quick_open_keystroke_time`).
+- The reply to every request the workbench sent without waiting (each `$acceptModelChanged`) stayed in `Session::results`. Upstream's RPC protocol keeps no reply it was not asked to; `Session::forget_result` drops it when it arrives.
+- Each undo element held its own copies of the model's key, URI and path, in a 376 byte value inside the service's B-tree, and every push scanned all elements for garbage. The elements of a model share one `ModelResource`, the tree holds boxes, and `push` collects garbage only when it dropped a future. With both, the typing run grows 182 to 202 MB in 60 rounds. The first run after `package-app` is several times slower and higher for the old build and the new one (950 MB for the old), so a soak number comes from a second run.
+
## GPUI on gpui-fast (milestone 26, branch worktree-gpui-fast)
- Decision (Artur, 2026-12-01): the port's GPUI moves from Wu (dstrml/wu `a3ced28`, `native/vendor/wu`) to gpui-fast (longbridge/gpui-fast `f0a91cf952678e4d205da1ec189b6d134e975bcd`, `UPSTREAM` zed `a36d4850f3c087bfef8a3552e2e15d72d97efdf4`, import commit `d8c5342`). Reason: its Retained Mode (`fast/retained.rs`) redraws only views that called `cx.notify()`, and its layout caches (`fast/layout.rs`, `fast/layout_key.rs`) skip unchanged subtrees, the frame cost the port's long lists and editors pay on Wu. `main` stays on Wu until the M26 "done when" gate is green.
diff --git a/port/tools/memory-soak b/port/tools/memory-soak
new file mode 100755
index 00000000000..b7ecc20dd6c
--- /dev/null
+++ b/port/tools/memory-soak
@@ -0,0 +1,22 @@
+#!/bin/bash
+# Repeats a workload in the packaged app and fails when the window process's footprint keeps growing (issue 116):
+# the median of the last 5 rounds over 1.3 times that of rounds 3 to 7. The workloads are in
+# port/fixtures/extensions/memory-soak/tests/index.js. Run on the Studio after port/tools/package-app:
+# port/tools/studio --lane 'port/tools/memory-soak' env MODE (browse, typing or all; default browse),
+# ROUNDS (default 20, at least 10), FOLDER (default the VS Code 1.148.0 checkout), APP (default native/target/VSRustium.app),
+# SETTINGS (the user settings.json, default the start editor and AI features off)
+set -uo pipefail
+APP=${APP:-$PWD/native/target/VSRustium.app}
+FOLDER=${FOLDER:-$HOME/Developer/vscode-ref-1.148.0}
+tests=$PWD/port/fixtures/extensions/memory-soak
+source port/tools/gui-lock.sh
+dir=$(mktemp -d)
+trap 'rm -rf "$dir"; [[ -n ${PORT_GUI_LOCK_HELD:-} ]] || rm -rf /tmp/port-gui.lock' EXIT
+settings='{"workbench.startupEditor":"none","chat.disableAIFeatures":true}'
+mkdir -p "$dir/user-data/User" && echo "${SETTINGS:-$settings}" >"$dir/user-data/User/settings.json"
+env -u VSCODE_GPUI_EXTENSIONS MODE=${MODE:-browse} ROUNDS=${ROUNDS:-20} "$APP/Contents/MacOS/vsrustium" "$FOLDER" --user-data-dir "$dir/user-data" \
+ --extensions-dir "$dir/extensions" --disable-workspace-trust --skip-welcome --extensionDevelopmentPath="$tests" --extensionTestsPath="$tests/tests" >"$dir/log" 2>&1
+code=$?
+grep -E '^(round|median)|^extension tests failed' "$dir/log"
+echo "memory soak: exit $code"
+exit $code