Visual Studio Code, rebuilt in Rust
Rust
chore(port): measure peak footprint and RSS of the whole app tree
rokartur943e57c131d6
diff --git a/README.md b/README.mdindex 23053f71463..5020d8c7b77 100644--- a/README.md+++ b/README.md@@ -30,12 +30,14 @@ Opening the VS Code 1.148.0 source (21,627 files) with warm caches, median of 5| | VSRustium | VS Code 1.148.0 ||---|---|---|-| Window with the folder | **0.65 s** | 2.38 s |-| Ready (CPU settled) | **6.2 s** | 13.4 s |-| Memory (footprint, all processes) | **218 MiB** | 584 MiB |-| CPU time until ready | **2.2 s** | 9.4 s |-| Idle CPU, 60 to 90 s after launch | 0.4 % of a core | **0.3 %** of a core |-| Quit | **0.15 s** | 1.28 s |+| Window with the folder | **0.66 s** | 0.67 s |+| Ready (CPU settled) | **2.9 s** | 5.1 s |+| Peak memory (footprint, all processes) | **488 MiB** | 1042 MiB |+| Peak memory (RSS, all processes) | **755 MiB** | 1753 MiB |+| Memory at 90 s (footprint, all processes) | **223 MiB** | 584 MiB |+| CPU time until ready | **2.4 s** | 7.8 s |+| Idle CPU, 60 to 90 s after launch | 0.5 % of a core | **0.2 %** of a core |+| Quit | **0.13 s** | 0.23 s |Release builds of both with default settings and the same built-in extensions, AI features off in VS Code (VSRustium leaves them out), on a Mac Studio (M1 Max, 32 GB, macOS 27). Both are measured from outside the same way: [`port/tools/bench`](port/tools/bench) runs it, and [port/results/benchmark.md](port/results/benchmark.md) has the method, the raw samples and the command.diff --git a/port/ledger.md b/port/ledger.mdindex e4183b64e52..d2447ca2ab4 100644--- a/port/ledger.md+++ b/port/ledger.md@@ -761,4 +761,4 @@ One row per upstream unit, generated by `bun port/tools/gen-ledger.ts`; mileston| gallery/open-vsx | cross-cutting check | M18 | verified | | exthost/src/gallery.rs: query, latest-version resource, version choice, download with signature check; cargo test -p exthost gallery (upstream extensionGalleryService.test.ts sorting and filterLatestExtensionVersionsForTargetPlatform cases, Open VSX resource fixture); `workbench.extensions.installExtension redhat.vscode-yaml` downloads 2.0.0 from open-vsx.org, verifies it and activates without restart, not-found errors as upstream: PORT_GALLERY=1 port/tools/extensions-check || port/settings-import | port feature | M10 | verified | | app/src/settings_import.rs, workbench/settings_import.rs: cargo test -p app settings_import installed_extensions_bring extensions_open_vsx_lacks_are_copied_from_the_source accepting_the_contents_pick_imports_every_part imported_extensions_ask_for_publisher_trust_once installed_extensions_bring_the_themes_the_settings_name an_empty_profile_takes_keybindings_json_with_its_comments reads_the_disabled_extensions on port/fixtures/settings-import; release GUI on the host lane: one import each from VS Code, Cursor and VSCodium fixtures under a scratch HOME. AI, sign-in, telemetry, remote and the editors' own settings and extensions are left out; the UI state is what a VS Code profile export carries, the source global storage's `StorageTarget.USER` keys (view locations, pinned and hidden views; accepting_the_contents_pick_imports_every_part), not the part sizes (port/notes.md Settings import) || look/screenshot-diff | cross-cutting check | | verified | | port/tools/pixel-check: CDP reference capture and Metal readback in 3 themes, pixeldiff reference vs itself 0 different; baseline in port/results/pixels.md |-| perf/memory-benchmark | cross-cutting check | | verified | | port/tools/bench, median of 5 on the Studio, the VS Code 1.147.0 checkout open; port/results/benchmark.md: 218 MiB in all, extension host 74 MiB, VS Code 1.147.0 release 975 MiB and 195 MiB |+| perf/memory-benchmark | cross-cutting check | | verified | | port/tools/bench, median of 5 on the Studio, the VS Code 1.148.0 checkout open; port/results/benchmark.md: footprint peak 488 MiB and 223 MiB at 90 s, RSS peak 755 MiB, extension host 78 MiB; VS Code 1.148.0 release 1042, 584 and 1753 MiB, extension host 108 MiB |diff --git a/port/notes.md b/port/notes.mdindex ba74868a38e..105121104c1 100644--- a/port/notes.md+++ b/port/notes.md@@ -945,7 +945,7 @@ What to do (milestone 21, in order):## Benchmarks-- `port/tools/bench`: started as Wu's `script/memory-benchmark` method generalized to N apps (`APPS="name=cmd;..."`); now also window, ready, CPU, idle CPU and quit times with a folder open, for the README's table (method and numbers: port/results/benchmark.md). A fresh VS Code 1.147.0 profile opens a Copilot sign-in dialog that keeps the renderer and GPU process at about 65% of a core for minutes, and an untrusted folder runs without git: the benchmark sets `chat.disableAIFeatures` and passes `--disable-workspace-trust` to both apps.+- `port/tools/bench`: started as Wu's `script/memory-benchmark` method generalized to N apps (`APPS="name=cmd;..."`); now also window, ready, CPU, idle CPU and quit times with a folder open, and peak footprint and RSS of the whole tree from launch on (`port/tools/bench-memory.swift`: `proc_pid_rusage` every 250 ms and on every fork and exit in the tree, since a 10 s snapshot missed the startup peak of about twice the settled footprint), for the README's table (method and numbers: port/results/benchmark.md). A fresh VS Code 1.147.0 profile opens a Copilot sign-in dialog that keeps the renderer and GPU process at about 65% of a core for minutes, and an untrusted folder runs without git: the benchmark sets `chat.disableAIFeatures` and passes `--disable-workspace-trust` to both apps.- Wu's `.cargo/config.toml` links with Homebrew lld on aarch64-apple-darwin; the Studio has no lld, so Wu is built with `RUSTFLAGS="-C symbol-mangling-version=v0 --cfg tokio_unstable"` (same flags, Apple ld). Env `CARGO_TARGET_*_RUSTFLAGS` does not work for this: cargo appends it to the config array.- Scroll frame costs (branch port-fix-settings-scroll): `settings_scroll_frame_time` (ignored test, `cargo test --release -p app -- --ignored settings_scroll_frame_time --nocapture`) scrolls the whole settings tree (1810 rows) in a headless 1440x900 workbench with gpui's NoopTextSystem, 600 frames of a 30px trackpad delta. Before: median 37.1 ms, p95 51.2 ms; `sample` put about 90% of the frame in `wordify_key` compiling 14 regexes per call, twice per visible row, and a third of the rest in `trim_category_for_group` compiling its group id patterns. With the regexes compiled once: median 3.3 ms, p95 3.7 ms. With the `config.*` context keys kept by `Configuration` until a layer changes (they were flattened again on every `key_context` call): median 1.7 ms, p95 2.1 ms (3 runs). The real app (Settings, search "editor", 572 rows; scratch CGEvent probe at 120 Hz on the Studio lane, main thread sampled): `Window::draw` held the main thread 93 to 97% of the time before, 56% after with the same input; what is left is the whole Workbench rendering on each frame (the layout row's gap). CoreText needs the main thread, which libtest never gives, so the headless check cannot use real text shaping.- Scroll frame costs, every surface (branch port-fix-settings-scroll): `workbench/scroll_frame_time.rs` holds one ignored test per surface (`cargo test --release -p app -- --ignored scroll_frame_time --nocapture --test-threads=1`) on one fixture: a folder of 801 files with a 20000-line `large.ts` open, every built-in extension installed and running, 1440x900, gate median and p95 under 8 ms. Median / p95 ms for Explorer, Editor, Extensions @builtin and Settings (now with a folder open, so not comparable to the paragraph above): at abfb67458da 194.0 / 281.5, 236.2 / 252.2, 4.3 / 11.0, 190.8 / 228.0; with the Explorer drawing only the rows in view (taffy laid out all 801 rows) 35.8 / 41.0, 84.5 / 89.5, 4.2 / 4.5, 37.5 / 54.4; with `FileTree` reading a folder again only when its mtime changes (`rows()` listed and stat-ed every expanded folder, several times per frame through `key_context`) and glob patterns parsed once as glob.ts `CACHE` does (`resource_editors` compiled a regex per custom editor selector per `key_context` call) 13.3 / 39.2, 22.8 / 54.0, 4.3 / 5.5, 14.6 / 16.1. The Studio is shared, so runs vary by about 30%. What is left, from `sample`: in the Explorer half the frame is taffy laying out the whole workbench tree, where a nested flex item is measured twice per level; in the Editor render is 60% of the frame, of which the minimap 20% (`minimap_runs` resolves each token's theme style on every frame, where vscode-textmate keeps it in the token's metadata) and `key_context` 16% (built in full by the menubar, the timeline toolbar three times, the editor title actions, the outline pane and the floating menu). The Extensions badge the layout gap names does not show in a sample of the harness. Cached part views (`AnyView::cached`) would skip render and layout of the parts a scroll does not touch, but in the vendored gpui a notify of a rendered entity invalidates that entity's view only and fires no observers, so a part view drawn from the Workbench's state would not redraw when that state changes: this needs the parts' state in their own entities or a gpui change.diff --git a/port/results/benchmark.md b/port/results/benchmark.mdindex 7a4515b1bc0..70297defad9 100644--- a/port/results/benchmark.md+++ b/port/results/benchmark.md@@ -4,41 +4,63 @@ VSRustium against VS Code 1.148.0, both packaged release builds, opening the VS| | VSRustium | VS Code 1.148.0 ||---|---|---|-| Window with the folder | 0.65 s | 2.38 s |-| Ready (CPU settled) | 6.21 s | 13.38 s |-| CPU time until ready | 2.19 s | 9.35 s |-| Memory (footprint, all processes) | 218 MiB | 584 MiB |-| of which the extension host | 76 MiB | 108 MiB |-| Idle CPU, 60 to 90 s after launch | 0.4 % of a core | 0.3 % of a core |-| Quit | 0.15 s | 1.28 s |+| Window with the folder | 0.66 s | 0.67 s |+| Ready (CPU settled) | 2.89 s | 5.13 s |+| CPU time until ready | 2.42 s | 7.75 s |+| Peak memory (footprint, all processes) | 488 MiB | 1042 MiB |+| Peak memory (RSS, all processes) | 755 MiB | 1753 MiB |+| Memory at 90 s (footprint, all processes) | 223 MiB | 584 MiB |+| of which the extension host | 78 MiB | 108 MiB |+| Memory at 90 s (RSS, all processes) | 362 MiB | 1288 MiB |+| Sum of each process's peak footprint | 614 MiB | 1376 MiB |+| Sum of each process's peak RSS | 940 MiB | 2178 MiB |+| Idle CPU, 60 to 90 s after launch | 0.5 % of a core | 0.2 % of a core |+| Quit | 0.13 s | 0.23 s |Setup:-- Machine: Mac Studio, Apple M1 Max (10 cores), 32 GB, macOS 27.2.1. The Studio is shared with other build and test jobs (load average 17 to 32 during the runs), so single runs vary; the medians are steadier.-- VSRustium: `port/tools/package-app` of the `worktree-idle-reveal` branch at f461b689c0d, on `vsrustium/main` bbf7e6dd0ca (a release build, ad-hoc signed, the reference's built-in extensions).+- Machine: Mac Studio, Apple M1 Max (10 cores), 32 GB, macOS 27.2.1. The Studio is shared with other build and test jobs: its load did not fall under 10 in the 20 minutes before the runs, and the highest 1-minute load average of each run was 22 to 62. Memory pressure stayed normal (level 1) in every run, the compressor held 3.8 to 7.6 GiB of other processes' memory and swap was 562 to 578 MiB, so neither app was squeezed; single runs vary with the load, the medians are steadier.+- VSRustium: `port/tools/package-app` of `vsrustium/main` at 7f83fce8753 (a release build, ad-hoc signed, the reference's built-in extensions).- VS Code: the official 1.148.0 darwin-arm64 build from `update.code.visualstudio.com`, started with `--disable-extension GitHub.copilot-chat`: the port leaves Copilot Chat out by decision (`port/notes.md`), so both run the same built-in extensions.- Both: default settings except `"chat.disableAIFeatures": true` (without it VS Code opens its Copilot sign-in dialog on every start of a fresh profile and keeps a core busy drawing it), `--disable-workspace-trust` (otherwise both open the folder in Restricted Mode, without git and most extensions), an empty extensions folder, and one user data folder per app for all its runs, so caches are warm after the warm-up.-Method (`port/tools/bench`, header): window is launch to the first on-screen window of the launched process; ready is launch to the start of the first 2 s after the window in which the process tree used under 10% of a core in each 0.5 s; CPU time is the tree's at ready, without processes that exited before; idle CPU is the tree's from 60 s to 90 s after launch; memory is `footprint` summed over the tree after that; quit is the quit Apple event until every process of the tree is gone.+Method (`port/tools/bench`, header): window is launch to the first on-screen window of the launched process; ready is launch to the start of the first 2 s after the window in which the process tree used under 10% of a core in each 0.5 s; CPU time is the tree's at ready, without processes that exited before; idle CPU is the tree's from 60 s to 90 s after launch; quit is the quit Apple event until every process of the tree is gone.++Memory, plainly:++- Peak or snapshot: both. `port/tools/bench-memory.swift` reads every process of the tree with `proc_pid_rusage` (`RUSAGE_INFO_V4`) from launch to the end of the idle window, 90 s after launch: every 250 ms, and at once when a process of the tree forks or exits. Peak memory is the largest tree sum of one such scan, a sum at one instant. Memory at 90 s is the last scan, the settled snapshot. The sums of each process's peak add every process's own maximum, whenever it happened, so they are higher than any instant: the kernel's lifetime peak footprint (`ri_lifetime_max_phys_footprint`) per process, and the largest RSS seen per process (the kernel keeps no RSS peak).+- Footprint or RSS: both. Footprint (`ri_phys_footprint`) is what Activity Monitor calls Memory and `footprint(1)` prints: the process's own dirty, compressed and GPU memory. RSS (`ri_resident_size`) is Activity Monitor's Real Memory: resident pages, with shared pages (frameworks, Electron's mapped files) counted again in every process that maps them, so the RSS sums overstate the memory a tree takes.+- Subprocesses: included. The tree is the launched process and every descendant, git, ripgrep, tsserver and the extension host among them; a process stays counted after its parent exits, and a child that exits between two scans is read once more as a zombie when it exits, so its kernel peak counts.+- Cache: warm. Each app's user data folder keeps its caches across runs, after one warm-up run, and the file cache is not emptied. `COLD=1` runs `sudo -n purge` before every run for cold starts; that needs passwordless sudo for `purge`, which the Studio does not have, so no cold numbers here.+- Compression: footprint counts a process's compressed pages at their uncompressed size, RSS does not count them. Per run the bench records the machine's memory pressure level, compressor size, swap used and 1-minute load average (the highest of each over the run), in the samples below.Read with care:-- The idle window changed: it was the 10 s after each app's own ready, and is now the same 60 to 90 s after launch for both, and memory moved with it. From ready, the window caught each app in a different state: VSRustium's ready (2 to 8 s) comes before its extension activation ends (git and the extension host busy until about 9 s), and VS Code's ready is bimodal (a 2 s pause at about 5 s passes as settled) and VS Code 1.148.0 has a burst of 30 to 50 % of a core at about 30 s after launch. Per-second traces of both trees from 20 to 60 s after launch show that burst as the last busy stretch of either app. The 1.147.0 numbers from the old window (VSRustium 1.9 %, VS Code 1.147.0 0.2 %) are in this file's git history.-- VS Code's window and quit medians carry load outliers (window 0.53 to 2.64 s, quit 0.20 to 2.29 s); VSRustium's ready spreads from 2.12 to 8.01 s with the load. All stay in the samples.+- VSRustium's tree peaks at about twice its settled footprint (488 against 223 MiB), VS Code's at about 1.8 times (1042 against 584 MiB). When in the 90 s the peaks happen was not traced.+- VS Code's ready is bimodal (a 2 s pause at about 5 s passes as settled: 4.58 to 5.13 s in 3 runs, 11.79 and 16.02 s in 2); VSRustium's run 5 (window 2.00 s, ready 8.96 s) ran at a load of 62. All stay in the samples.Samples (s, %, MiB), in run order:| metric | VSRustium | VS Code 1.148.0 ||---|---|---|-| window | 0.65 1.30 0.64 1.46 0.48 | 1.71 0.53 2.40 2.38 2.64 |-| ready | 6.21 8.01 2.94 7.28 2.12 | 13.38 12.04 13.45 6.28 14.44 |-| CPU until ready | 1.65 2.19 2.90 2.08 2.28 | 10.02 8.78 9.35 7.05 10.35 |-| idle CPU | 0.5 0.4 0.4 0.4 0.4 | 0.2 0.3 0.3 0.6 0.2 |-| memory | 229 215 217 218 219 | 583 603 611 580 584 |-| extension host | 84 70 76 76 79 | 108 112 111 107 107 |-| quit | 0.23 0.12 0.15 0.14 0.24 | 2.29 0.26 1.28 0.20 1.58 |+| window | 0.62 0.57 0.66 1.41 2.00 | 0.67 0.51 0.44 0.78 1.12 |+| ready | 2.89 2.26 2.31 4.52 8.96 | 4.58 16.02 11.79 4.71 5.13 |+| CPU until ready | 2.93 2.42 2.34 3.30 2.18 | 6.92 9.77 8.73 7.29 7.75 |+| idle CPU | 0.4 0.4 0.7 0.5 0.6 | 0.2 0.2 0.2 0.3 1.2 |+| peak footprint | 460 492 506 485 488 | 1031 1050 1002 1123 1042 |+| peak RSS | 717 759 773 744 755 | 1760 1753 1732 1671 1837 |+| footprint at 90 s | 223 233 225 219 221 | 580 584 575 627 609 |+| extension host | 78 79 80 75 71 | 107 109 107 113 108 |+| RSS at 90 s | 361 363 362 361 367 | 1439 1288 1434 1088 1202 |+| sum of process peak footprints | 614 643 640 573 590 | 1338 1402 1332 1376 1420 |+| sum of process peak RSS | 935 1032 1059 932 940 | 2178 2205 2153 2127 2229 |+| quit | 0.12 0.13 0.13 0.13 0.20 | 0.19 0.19 0.44 1.42 0.23 |+| memory pressure level | 1 1 1 1 1 | 1 1 1 1 1 |+| compressor | 4076 4025 4090 3904 7043 | 4032 4276 4019 7754 6090 |+| swap used | 578 578 578 578 578 | 578 578 578 578 562 |+| 1-minute load | 35.8 22.0 24.6 34.1 62.2 | 28.1 36.8 32.5 28.8 38.4 |-To rerun, on the Studio after a release build and `port/tools/package-app`, with the VS Code build unpacked in `/tmp/vscode`:+To rerun, on the Studio after a release build and `port/tools/package-app`, with the VS Code build unpacked in `/tmp/vscode` (add `COLD=1` for cold starts):```FOLDER=$HOME/Developer/vscode-ref-1.148.0 SETTINGS='{"chat.disableAIFeatures": true}' \@@ -46,4 +68,4 @@ APPS='vsrustium=native/target/VSRustium.app/Contents/MacOS/vsrustium;vscode="/tmport/tools/bench```-Earlier memory-only numbers (milestones 1 and 2: an idle empty window, a dev build of the reference) are in this file's git history.+Earlier memory-only numbers (milestones 1 and 2: an idle empty window, a dev build of the reference) and the snapshot-only numbers before peaks were measured are in this file's git history.diff --git a/port/tools/bench b/port/tools/benchindex 0faf676d080..231838f9486 100755--- a/port/tools/bench+++ b/port/tools/bench@@ -8,14 +8,19 @@# cpu: CPU time of the process tree at ready (processes that exited before are not counted)# idle: CPU of the tree from IDLE_FROM s after launch over IDLE_SECONDS, % of a core: one window for every app, past# startup and extension activation (VS Code 1.148.0 bursts at about 30 s)-# memory: footprint(1) summed over the tree after that, and the part of it in extension host processes+# memory (port/tools/bench-memory.swift, from launch to the end of the idle window, every process of the tree, kept+# after its parent exits): peak footprint and peak RSS of the tree (the largest sum of one scan), the sums of+# each process's own peaks (the kernel's lifetime peak footprint, the largest RSS seen), footprint and RSS of+# the tree at the end of the idle window and the extension host processes' part of that footprint, and the+# machine's largest memory pressure level (1 normal, 2 warning, 4 critical), compressor, swap and 1-min load# quit: the quit Apple event to the launched process until every process of the tree is gone# Prints one TSV row per app and metric: the median and the samples.## APPS="name1=command1;name2=command2" FOLDER=<dir> port/tools/bench# Each command gets --disable-workspace-trust --user-data-dir <dir> --extensions-dir <dir> <FOLDER> appended; the# command must exec the app's binary (the process that owns its windows). SETTINGS (a JSON object) becomes every-# app's user settings.json. RUNS (5), IDLE_FROM (60) and IDLE_SECONDS (30) override the defaults.+# app's user settings.json. RUNS (5), IDLE_FROM (60) and IDLE_SECONDS (30) override the defaults. COLD=1 empties the+# file cache with `sudo -n purge` before every run (needs passwordless sudo for purge); by default the cache stays warm.set -euo pipefailsource "$(dirname "$0")/gui-lock.sh"@@ -27,6 +32,8 @@ IFS=';' read -r -a apps <<< "${APPS:?set APPS=\"name=command;...\"}"scratch=$(mktemp -d)trap 'rm -rf "$scratch"; [[ -n ${PORT_GUI_LOCK_HELD:-} ]] || rm -rf /tmp/port-gui.lock' EXITswiftc -O "$(dirname "$0")/bench-window.swift" -o "$scratch/bench-window"+swiftc -O "$(dirname "$0")/bench-memory.swift" -o "$scratch/bench-memory"+"$scratch/bench-memory" selftest >&2now() {perl -MTime::HiRes=time -e 'printf "%.3f", time'@@ -50,33 +57,24 @@ tree_cpu() {}'}-footprint_kb() {- local line value unit- line=$(timeout 30 footprint -p "$1" 2>/dev/null | rg -m1 'Footprint:') || return 1- value=$(sed -E 's/.*Footprint: ([0-9.]+) ([KMG]B).*/\1/' <<< "$line")- unit=$(sed -E 's/.*Footprint: ([0-9.]+) ([KMG]B).*/\2/' <<< "$line")- case "$unit" in- KB) awk -v v="$value" 'BEGIN { printf "%d", v }' ;;- MB) awk -v v="$value" 'BEGIN { printf "%d", v * 1024 }' ;;- GB) awk -v v="$value" 'BEGIN { printf "%d", v * 1024 * 1024 }' ;;- esac-}-# The extension host: bootstrap-exthost.js in its arguments (port), or an Electron utility process whose# environment has VSCODE_ESM_ENTRYPOINT=vs/workbench/api/node/extensionHostProcess (VS Code).is_extension_host() {ps -E -o command= -p "$1" | rg -q 'bootstrap-exthost|VSCODE_ESM_ENTRYPOINT=vs/workbench/api/node/extensionHostProcess'}-# Prints "<window s> <ready s> <cpu s> <idle %> <memory MiB> <extension host MiB> <quit s>".+# Prints "<window s> <ready s> <cpu s> <idle %> <extension host MiB> <quit s>" and the line of bench-memory watch.measure_once() {- local command=$1 dir=$2 start pid shown ready cpu before after p kb total=0 exthost=0 pids quit_start quit+ local command=$1 dir=$2 start pid sampler shown ready cpu before after memory p mib exthost=0 pids quit_start quit+ [[ -z ${COLD:-} ]] || sudo -n purgestart=$(now)bash -c "exec $command --disable-workspace-trust --user-data-dir '$dir/user-data' --extensions-dir '$dir/extensions' '$FOLDER'" >/dev/null 2>&1 &pid=$!+ "$scratch/bench-memory" watch "$pid" > "$dir/memory" &+ sampler=$!if ! shown=$("$scratch/bench-window" wait "$pid" 60); thenecho "bench: $command showed no window in 60 s" >&2- kill -9 $(descendant_pids "$pid") 2>/dev/null || true+ kill -9 $sampler $(descendant_pids "$pid") 2>/dev/null || truereturn 1fiready=@@ -99,7 +97,7 @@ measure_once() {fiif [[ -z $ready ]] && awk -v t="$sample_start" -v s="$start" 'BEGIN { exit !(t - s > 180) }'; thenecho "bench: CPU of $command did not settle in 180 s" >&2- kill -9 $(descendant_pids "$pid") 2>/dev/null || true+ kill -9 $sampler $(descendant_pids "$pid") 2>/dev/null || truereturn 1fidone@@ -108,13 +106,14 @@ measure_once() {idle_start=$(tree_cpu "$pid")sleep "$IDLE_SECONDS"idle=$(awk -v a="$(tree_cpu "$pid")" -v b="$idle_start" -v s="$IDLE_SECONDS" 'BEGIN { printf "%.1f", (a - b) / s * 100 }')- for p in $(descendant_pids "$pid"); do- kb=$(footprint_kb "$p") || continue- total=$((total + kb))+ kill -TERM "$sampler"+ wait "$sampler"+ memory=$(head -1 "$dir/memory")+ while read -r p mib; doif is_extension_host "$p"; then- exthost=$((exthost + kb))+ exthost=$((exthost + mib))fi- done+ done < <(tail -n +2 "$dir/memory")pids=$(descendant_pids "$pid")quit_start=$(now)"$scratch/bench-window" quit "$pid"@@ -135,16 +134,18 @@ measure_once() {return 1fiwait "$pid" 2>/dev/null || true- awk -v w="$shown" -v r="$ready" -v s="$start" -v c="$cpu" -v i="$idle" -v t="$total" -v x="$exthost" -v q="$quit" \- 'BEGIN { printf "%.2f %.2f %.2f %s %.0f %.0f %s\n", w - s, r - s, c, i, t / 1024, x / 1024, q }'+ awk -v w="$shown" -v r="$ready" -v s="$start" -v c="$cpu" -v i="$idle" -v x="$exthost" -v q="$quit" -v m="$memory" \+ 'BEGIN { printf "%.2f %.2f %.2f %s %d %s %s\n", w - s, r - s, c, i, x, q, m }'}median() {printf '%s\n' "$@" | sort -n | awk '{ v[NR] = $1 } END { m = NR % 2 ? v[(NR + 1) / 2] : (v[NR / 2] + v[NR / 2 + 1]) / 2; print m }'}-metrics=(window_s ready_s cpu_s idle_pct memory_mib exthost_mib quit_s)-# macOS ships bash 3.2: no associative arrays, so the samples of app i, metric m sit at index i * 7 + m.+metrics=(window_s ready_s cpu_s idle_pct exthost_mib quit_s peak_footprint_mib peak_rss_mib process_peaks_footprint_mib+ process_peaks_rss_mib footprint_mib rss_mib pressure_level compressor_mib swap_mib load)+n=${#metrics[@]}+# macOS ships bash 3.2: no associative arrays, so the samples of app i, metric m sit at index i * n + m.samples=()for i in "${!apps[@]}"; domkdir -p "$scratch/$i/user-data/User" "$scratch/$i/extensions"@@ -158,7 +159,7 @@ for ((run = 0; run <= RUNS; run++)); doecho " ${values[*]}" >&2((run > 0)) || continuefor m in "${!metrics[@]}"; do- samples[i * 7 + m]="${samples[i * 7 + m]:-}${values[$m]} "+ samples[i * n + m]="${samples[i * n + m]:-}${values[$m]} "donedonedone@@ -167,6 +168,6 @@ printf 'app\tmetric\tmedian\tsamples\n'for i in "${!apps[@]}"; dofor m in "${!metrics[@]}"; do# shellcheck disable=SC2086- printf '%s\t%s\t%s\t%s\n' "${apps[$i]%%=*}" "${metrics[$m]}" "$(median ${samples[i * 7 + m]})" "${samples[i * 7 + m]}"+ printf '%s\t%s\t%s\t%s\n' "${apps[$i]%%=*}" "${metrics[$m]}" "$(median ${samples[i * n + m]})" "${samples[i * n + m]}"donedonediff --git a/port/tools/bench-memory.swift b/port/tools/bench-memory.swiftnew file mode 100644index 00000000000..6a7475aa1dc--- /dev/null+++ b/port/tools/bench-memory.swift@@ -0,0 +1,235 @@+// Used by port/tools/bench: swiftc -O port/tools/bench-memory.swift -o <bin>+// <bin> watch <pid>: samples the process tree under <pid> until SIGTERM, then prints one line+// "<peak tree footprint> <peak tree RSS> <sum of per-process peak footprints> <sum of per-process peak RSS>+// <settled footprint> <settled RSS> (MiB) <max pressure level> <max compressor MiB> <max swap MiB> <max 1-min load>"+// and one "<pid> <footprint MiB>" line per process of the tree at SIGTERM.+// <bin> selftest: checks the tree and peak bookkeeping on made-up samples.+// A scan reads every process of the tree with proc_pid_rusage: every 250 ms, and at once when a process of the tree+// forks or exits (kqueue), so a git or tsserver child is seen while it lives and read again as a zombie before its+// parent reaps it. A process stays in the tree after its parent exits (launchd adopts it), until it exits itself.+import Darwin++struct ProcessKey: Hashable {+ let pid: pid_t+ let start: UInt64+}++struct Listed {+ let key: ProcessKey+ let parent: pid_t+ var zombie = false+}++struct Usage {+ let footprint: UInt64+ let lifetimeMaxFootprint: UInt64+ let resident: UInt64+}++struct Peaks {+ var members: Set<ProcessKey>+ var treeFootprint: UInt64 = 0+ var treeResident: UInt64 = 0+ var processFootprint: [ProcessKey: UInt64] = [:]+ var processResident: [ProcessKey: UInt64] = [:]+ var settled: [ProcessKey: Usage] = [:]++ init(root: ProcessKey) {+ members = [root]+ }++ // Members are the processes still listed that were members, or whose parent is one; the tree sums are of one scan.+ mutating func scan(_ listed: [Listed], usage: (ProcessKey) -> Usage?) {+ let live = Set(listed.map(\.key))+ let zombies = Set(listed.filter(\.zombie).map(\.key))+ members = members.intersection(live)+ var grew = true+ while grew {+ grew = false+ let parents = Set(members.map(\.pid))+ for process in listed where !members.contains(process.key) && parents.contains(process.parent) {+ members.insert(process.key)+ grew = true+ }+ }+ var footprint: UInt64 = 0+ var resident: UInt64 = 0+ settled = [:]+ for key in members {+ guard let read = usage(key) else { continue }+ record(key, read)+ // An exited process keeps its last numbers until reaped, but its memory is already free.+ if zombies.contains(key) { continue }+ settled[key] = read+ footprint += read.footprint+ resident += read.resident+ }+ treeFootprint = max(treeFootprint, footprint)+ treeResident = max(treeResident, resident)+ }++ mutating func record(_ key: ProcessKey, _ read: Usage) {+ processFootprint[key] = max(processFootprint[key] ?? 0, read.lifetimeMaxFootprint, read.footprint)+ processResident[key] = max(processResident[key] ?? 0, read.resident)+ }+}++func listProcesses() -> [Listed] {+ var mib: [Int32] = [CTL_KERN, KERN_PROC, KERN_PROC_ALL, 0]+ var size = 0+ precondition(sysctl(&mib, 4, nil, &size, nil, 0) == 0)+ // Processes start between the two calls: room for 64 more.+ size += 64 * MemoryLayout<kinfo_proc>.stride+ var procs = [kinfo_proc](repeating: kinfo_proc(), count: size / MemoryLayout<kinfo_proc>.stride)+ precondition(sysctl(&mib, 4, &procs, &size, nil, 0) == 0)+ return procs.prefix(size / MemoryLayout<kinfo_proc>.stride).map { proc in+ let start = proc.kp_proc.p_un.__p_starttime+ return Listed(+ key: ProcessKey(pid: proc.kp_proc.p_pid, start: UInt64(start.tv_sec) * 1_000_000 + UInt64(start.tv_usec)),+ parent: proc.kp_eproc.e_ppid, zombie: proc.kp_proc.p_stat == SZOMB)+ }+}++// Works on zombies too: the kernel keeps their rusage until the parent reaps them.+func readUsage(_ pid: pid_t) -> Usage? {+ var info = rusage_info_v4()+ let status = withUnsafeMutablePointer(to: &info) {+ $0.withMemoryRebound(to: rusage_info_t?.self, capacity: 1) { proc_pid_rusage(pid, RUSAGE_INFO_V4, $0) }+ }+ guard status == 0 else { return nil }+ return Usage(footprint: info.ri_phys_footprint, lifetimeMaxFootprint: info.ri_lifetime_max_phys_footprint, resident: info.ri_resident_size)+}++func sysctlValue<T: BitwiseCopyable>(_ name: String, _ initial: T) -> T {+ var value = initial+ var size = MemoryLayout<T>.size+ precondition(sysctlbyname(name, &value, &size, nil, 0) == 0)+ return value+}++func compressorBytes() -> UInt64 {+ var stats = vm_statistics64()+ var count = mach_msg_type_number_t(MemoryLayout<vm_statistics64>.size / MemoryLayout<integer_t>.size)+ let status = withUnsafeMutablePointer(to: &stats) {+ $0.withMemoryRebound(to: integer_t.self, capacity: Int(count)) { host_statistics64(mach_host_self(), HOST_VM_INFO64, $0, &count) }+ }+ precondition(status == KERN_SUCCESS)+ return UInt64(stats.compressor_page_count) * UInt64(vm_kernel_page_size)+}++func mib(_ bytes: UInt64) -> String {+ String(Int((Double(bytes) / 1_048_576).rounded()))+}++var stopRequested: sig_atomic_t = 0++func watch(_ root: pid_t) {+ guard let rootKey = listProcesses().first(where: { $0.key.pid == root })?.key else {+ fputs("bench-memory: no process \(root)\n", stderr)+ exit(1)+ }+ signal(SIGTERM) { _ in stopRequested = 1 }+ var peaks = Peaks(root: rootKey)+ var pressure: Int32 = 0+ var compressor: UInt64 = 0+ var swap: UInt64 = 0+ var load = 0.0+ let queue = kqueue()+ var watched = Set<ProcessKey>()+ var events = Array(repeating: kevent(), count: 64)+ var timeout = timespec(tv_sec: 0, tv_nsec: 250_000_000)+ while true {+ let stopping = stopRequested != 0+ peaks.scan(listProcesses()) { readUsage($0.pid) }+ pressure = max(pressure, sysctlValue("kern.memorystatus_vm_pressure_level", Int32(0)))+ compressor = max(compressor, compressorBytes())+ swap = max(swap, sysctlValue("vm.swapusage", xsw_usage()).xsu_used)+ var loads = [0.0]+ getloadavg(&loads, 1)+ load = max(load, loads[0])+ if stopping { break }+ var changes = Array(repeating: kevent(), count: 0)+ for key in peaks.members.subtracting(watched) {+ watched.insert(key)+ changes.append(kevent(ident: UInt(key.pid), filter: Int16(EVFILT_PROC), flags: UInt16(EV_ADD | EV_ONESHOT), fflags: UInt32(NOTE_EXIT) | UInt32(NOTE_FORK), data: 0, udata: nil))+ }+ // A process that exited before EV_ADD returns ESRCH as an error event: the next scan drops it.+ let count = kevent(queue, changes, Int32(changes.count), &events, Int32(events.count), &timeout)+ for event in events.prefix(max(Int(count), 0)) where event.flags & UInt16(EV_ERROR) == 0 {+ let pid = pid_t(event.ident)+ guard let key = peaks.members.first(where: { $0.pid == pid }) else { continue }+ if event.fflags & UInt32(NOTE_EXIT) != 0, let read = readUsage(pid) {+ peaks.record(key, read)+ } else if event.fflags & UInt32(NOTE_EXIT) == 0 {+ watched.remove(key)+ }+ }+ }+ let settledFootprint = peaks.settled.values.reduce(0) { $0 + $1.footprint }+ let settledResident = peaks.settled.values.reduce(0) { $0 + $1.resident }+ print([+ mib(peaks.treeFootprint), mib(peaks.treeResident),+ mib(peaks.processFootprint.values.reduce(0, +)), mib(peaks.processResident.values.reduce(0, +)),+ mib(settledFootprint), mib(settledResident),+ String(pressure), mib(compressor), mib(swap), String((load * 10).rounded() / 10),+ ].joined(separator: " "))+ for (key, read) in peaks.settled {+ print(key.pid, mib(read.footprint))+ }+}++func selftest() {+ let root = ProcessKey(pid: 10, start: 1)+ let child = ProcessKey(pid: 11, start: 2)+ let git = ProcessKey(pid: 12, start: 3)+ let grandchild = ProcessKey(pid: 13, start: 4)+ let stranger = ProcessKey(pid: 20, start: 5)+ let reused = ProcessKey(pid: 12, start: 9)+ let mb: UInt64 = 1_048_576+ var peaks = Peaks(root: root)+ // Scan 1: root, child, git under child, grandchild listed before its parent; a stranger outside the tree.+ peaks.scan([+ Listed(key: grandchild, parent: 11), Listed(key: root, parent: 1), Listed(key: child, parent: 10),+ Listed(key: git, parent: 11), Listed(key: stranger, parent: 1),+ ]) { key in+ switch key {+ case root: Usage(footprint: 100 * mb, lifetimeMaxFootprint: 150 * mb, resident: 200 * mb)+ case child: Usage(footprint: 50 * mb, lifetimeMaxFootprint: 50 * mb, resident: 60 * mb)+ case git: Usage(footprint: 30 * mb, lifetimeMaxFootprint: 40 * mb, resident: 35 * mb)+ case grandchild: Usage(footprint: 5 * mb, lifetimeMaxFootprint: 5 * mb, resident: 6 * mb)+ default: Usage(footprint: 999 * mb, lifetimeMaxFootprint: 999 * mb, resident: 999 * mb)+ }+ }+ precondition(peaks.members == [root, child, git, grandchild])+ precondition(peaks.treeFootprint == 185 * mb && peaks.treeResident == 301 * mb)+ // git exits and is read once more as a zombie with a higher kernel peak.+ peaks.record(git, Usage(footprint: 0, lifetimeMaxFootprint: 70 * mb, resident: 0))+ // Scan 2: child is a zombie, grandchild is adopted by launchd and stays; git's pid is reused by an unrelated process.+ peaks.scan([+ Listed(key: root, parent: 1), Listed(key: child, parent: 10, zombie: true), Listed(key: grandchild, parent: 1), Listed(key: reused, parent: 1),+ Listed(key: stranger, parent: 1),+ ]) { key in+ key == root+ ? Usage(footprint: 120 * mb, lifetimeMaxFootprint: 160 * mb, resident: 210 * mb)+ : Usage(footprint: 8 * mb, lifetimeMaxFootprint: 8 * mb, resident: 9 * mb)+ }+ precondition(peaks.members == [root, child, grandchild])+ // The tree peak stays the larger sum of one scan (scan 1), not the sum of the maxima.+ precondition(peaks.treeFootprint == 185 * mb && peaks.treeResident == 301 * mb)+ // Per-process peaks: root 160, child 50, git 70, grandchild 8.+ precondition(peaks.processFootprint.values.reduce(0, +) == 288 * mb)+ precondition(peaks.processResident.values.reduce(0, +) == 314 * mb)+ precondition(peaks.settled.keys.sorted { $0.pid < $1.pid } == [root, grandchild])+ print("bench-memory selftest: ok")+}++let args = CommandLine.arguments+switch (args.count, args.dropFirst().first) {+case (3, "watch"):+ watch(pid_t(args[2])!)+case (2, "selftest"):+ selftest()+default:+ fputs("usage: bench-memory watch <pid> | selftest\n", stderr)+ exit(2)+}