Skip to content

Speed up browser cold open by promoting staged records and batching index reads - #2043

Merged
callumalpass merged 3 commits into
mainfrom
optimize-10k-browser-opfs-performance
Nov 28, 2026
Merged

callumalpass merged 3 commits into
mainfrom
optimize-10k-browser-opfs-performance

Conversation

@callumalpass

@callumalpass callumalpass commented Nov 28, 2026 •

Copy link
Copy Markdown
Member

Refs #1648

Promote the staged SQLite record table inside the existing snapshot-swap transaction. SQLite keeps the table's document pages in place. The transaction restores the canonical path and bucket indexes, recreates empty staging, swaps the remaining tables and publishes the head together. The rollback test aborts a later link insert after promotion and then retries the full swap.

Raw backfill now reads a bounded group of IDs with one ordered left join. Each missing or over-limit source keeps its slot, and a row above its share of the page still gets a bounded singleton read. The app SQLite bridge borrows batch parameters. Core borrows parsed frontmatter and skips runs of plain text while scanning for tags, preserving the existing admission charges.

GCP Chrome with real OPFS

Baseline 611f93f5e3438911c4bdd2561885484301546590, candidate source 5c481c30ff05b4b3a79425d8d3c395f8ad16a49b, publication pin 9b94bb14254824d9962fb32e3b25f17b788a83fd. Chrome 155.0.8059.84, Linux, ext4-backed fresh persistent profile and SQLite-WASM SAH-pool per sample. Seven pairs per fixture, alternating A/B then B/A. Timings exclude setup, digesting and teardown. Each combined value is the sum of the two phases from the same run. Nearest-rank p95 is the slowest of seven. The query is the first SDK top-50 task page after replay, filtering on priority and ordering descending.

10,000 notes, 10,080 records at head

Metric Stage 3 median / p95 Stage 4 median / p95
Install (ms) 4,479.52 / 4,697.87 2,935.76 / 3,952.44
Replay + index (ms) 5,772.53 / 5,992.46 5,371.41 / 5,512.02
Combined (ms) 10,434.49 / 10,503.24 8,349.06 / 9,288.96
First indexed top-50 SDK query (ms) 13.35 / 13.90 13.53 / 14.59

100-note control, 180 records at head

Metric Stage 3 median / p95 Stage 4 median / p95
Install (ms) 83.53 / 90.40 83.12 / 90.06
Replay + index (ms) 164.80 / 184.25 160.62 / 187.49
Combined (ms) 248.33 / 274.65 245.19 / 277.55
First indexed top-50 SDK query (ms) 13.14 / 17.83 13.61 / 16.00

The 10k combined median fell 20.0% and p95 fell 11.6%. The first browser query was 0.18 ms slower at the median. The 100-note combined median fell 3.14 ms while its p95 rose 2.90 ms.

A supplemental native 10k top-50 benchmark measured median query time of 606.64 → 582.14 µs, index selection of 223.18 → 215.81 µs and hydration of 178.59 → 176.83 µs. Each revision ran separately on the shared builder using cd runtime && rcargo test --release -p mdbn-bench --test indexed_query indexed_top50_over_10k_timing -- --ignored --nocapture.

Where the 10k open spends time

Phase SQL statements, before → after WASM-to-host calls Request bytes, before → after
Install 1,956 → 1,962 536 → 536 25,766,695 → 25,767,121
Replay + index 75,380 → 65,930 5,027 → 5,027 45,092,565 → 43,952,895

The separate profile run measured 5,875 ms before and 2,973 ms after for install. SQLite accounted for 4,755 → 1,985 ms, including 1,504 → 841 ms in OPFS writes and 2,115 → 320 ms in flushes. Stepping explicit commits took 2,477 → 1,293 ms. Copying staged records into confirmed storage took 398 ms before promotion. These measurements overlap. The alternating unprofiled pairs above measure wall-clock performance.

The 9,450 statements removed from replay are record reads (11,589 → 2,139). The remaining 65,930 include 10,080 raw fact inserts, 10,080 raw record inserts, 10,030 raw atom inserts, 4,410 field inserts, and 3,090 link inserts. On the candidate, SQLite stepping took 706 ms for the raw atom inserts, 635 ms for explicit commits, 605 ms for FTS inserts and 333 ms for the field index. An earlier candidate batched raw fact writes and cut replay to 48,957 statements, but its median replay was 82 ms slower than its paired baseline. That version was discarded.

Equivalence and validation

The digest run hashes typed, length-delimited values in primary-key order for record blobs, resources, links, unique and field indexes, query projections and the FTS shadow tables. The query digest covers the ordered 50 IDs, paths and revisions. Each digest matched across both binaries.

Fixture After install After replay Ordered query
10k a4e947b1d1fc78f12013192b916585c8b9a849059139d33247e6591a95fd246a bc2a028fa902b1aaf9ba149287882a46c96c540e9d2718c69b2c68f35e8d3a9c 5af203ccfeae071c9ff1c4447d2f2febe8fb51eaca5bcb5a1a8530bd6430f045
100 ac7ff338e5e4e9ccc2dddacb81cc773e1f2db412097cf8124eac8e91d689b7c9 256ffec33590e0c615e555628a02ba36f7912c4edb9e82cab5398e3f6eb997d3 36bf33863d46477401458b745210d2770babc28ab18ffe0e85c1699eae4d1dba
  • The benchmark used the Stage 3 pinned binary bc0ece9ff1f987117ecb040b074278851284a3d828573a3f76c894683962afc7 and the Stage 4 local build 5ef991a30f99fdcca221058ff260bd932156559d42d693e5b5d504400ce15a2f. Two local builds reproduced that candidate. The publication build uses the same Rust source and remaps source paths, including Cargo registry paths. Its SHA-256 is d5452814d656c9611d0be04a934278d88ca8c83d3e823353f9842811a63a4795, raw 4,141,990 bytes (+1,534 over Stage 3), gzip 1,666,594 bytes, Brotli 1,219,256 bytes. The browser timing table applies to the benchmark builds. Runtime CI artifact
  • The independent remapped rcargo rebuild matched the GitHub artifact byte-for-byte. On the corrected pin, check-runtime-pin and pack-all passed. Cold consumer checks passed and the extracted WASM in each of the production, staging and lab archives matched the published pin.
  • All gates selected by pnpm ci:local passed. The six-crate rcargo suite passed 2,661 tests (7 ignored), and all three store-format upgrade tests passed. Native and WASM clippy, the runtime architecture check, 17 native/WASM golden replay fixtures, the app-WASM SQLite smoke tests, and the daemon end-to-end request path passed.
  • The SDK suite passed 3,095 Vitest tests and 65 Node tests. SDK build and node scripts/sdk-publication.mjs check-runtime-pin passed.
  • The broad native SQLite suite includes restart, failed-swap rollback, retry and mixed-size backfill in reverse projection order. A local workerd Durable Object independently rolled back and retried the table/index DDL with real SQLite.
  • GCP desk gcp/w16-opfs4 destroyed and absence verified with desk ls.
Reproduce the publication build and archive verification

From the repository root on a Linux build host with the pinned Rust toolchain, Node 24 and npm installed, run the same app build and path normalization as the publication workflow.

repo_root=$(git rev-parse --show-toplevel)
export RUSTFLAGS="--remap-path-prefix=$repo_root=/source --remap-path-prefix=${CARGO_HOME:-$HOME/.cargo}=/cargo"
npm ci --prefix runtime/tools/wasm --ignore-scripts
(cd runtime && cargo build --locked --release -p mdbn-trust --bin mdbn-trust && cargo xtask wasm-app)
node scripts/sdk-publication.mjs check-runtime-pin
out=$(mktemp -d)
GITHUB_SHA=$(git rev-parse HEAD) node scripts/sdk-publication.mjs pack-all "$out/archives"
Reproduce the benchmark

Use the pinned Stage 3 binary as BEFORE. Its SHA-256 is listed above. In the Stage 4 source checkout, build the benchmark candidate as AFTER with the pinned Binaryen and Rust toolchain:

cd runtime
npm ci --prefix tools/wasm
rcargo --pull wasm32-unknown-unknown/wasm-release/mdbn_wasm.wasm build --locked -p mdbn-wasm --lib --target wasm32-unknown-unknown --profile wasm-release --features app-runtime
mkdir -p target/wasm
tools/wasm/node_modules/.bin/wasm-opt -Oz --converge --enable-bulk-memory --enable-bulk-memory-opt --enable-sign-ext --enable-mutable-globals --enable-nontrapping-float-to-int --enable-reference-types --enable-multivalue --strip-debug --strip-producers target/wasm32-unknown-unknown/wasm-release/mdbn_wasm.wasm -o target/wasm/app-runtime.wasm

From the root of the baseline checkout generate the signed fixtures. Use the baseline SDK harness and SQLite package for both variants.

pnpm install --frozen-lockfile
cd runtime
npm ci --prefix packages/sdk
rcargo --pull tmp/cold-open.cbor test --release -p mdbn-bench --test catalog_reindex seven_cold_opens_at_10k -- --ignored --nocapture
rcargo --pull tmp/cold-open-small.cbor test --release -p mdbn-bench --test catalog_reindex seven_cold_opens_at_100 -- --ignored --nocapture
sha256sum target/tmp/cold-open*.cbor
# 10k   62fb23a7f8ba6b8d26a53d3ae812581469b8356b5e73fb20673be3efe8bf2b83
# small dccdc0d2ad8ab8a7c07f45e364641ec292967f80df5c60e227a00e4c1bc0137c

For the query and its digest, apply this measurement-only probe to the disposable copy of the baseline worker. The probe runs after both cold-open timers stop.

python3 - packages/sdk/scripts/cold-open-worker.mjs <<'PY'
from pathlib import Path
import sys
p=Path(sys.argv[1])
s=p.read_text()
s='import { MdbaseClient } from "../src/client.ts";\nimport { inProcessConnector } from "../src/transport/inprocess.ts";\n'+s
s=s.replace('if (!(await runtime.close()))', '''const client = await MdbaseClient.connect({connector: inProcessConnector(runtime, {collection}), app:{name:"cold-open-bench",version:"1"}, timezone:"UTC",reconnect:false});
        const startQuery = performance.now();
        const page = await client.query({types:["task"],where:"priority >= 2",order_by:[{field:"priority",direction:"desc"}],limit:50});
        const queryMs = performance.now() - startQuery;
        if (page.records.length !== 50) throw Error("incomplete query page");
        if (verify) digests.query = hex(sha256(encode(page.records.map(r => [r.id, r.path, r.revision]))));
        client.close();
        if (!(await runtime.close()))''').replace('return { install, replay,','return { install, replay, queryMs,')
p.write_text(s)
PY

Run from the baseline checkout’s runtime directory on the same disk-backed Chrome host using Bash. Set BEFORE and AFTER to the absolute paths of the two optimized modules.

export TMPDIR=/config/tmp COLD_OPEN_CHROMIUM=/usr/bin/google-chrome
mkdir -p "$TMPDIR"
for fixture in large small; do
  size=()
  if [[ "$fixture" == small ]]; then size=(--small); fi
  node packages/sdk/scripts/cold-open-bench.mjs "${size[@]}" --verify "$BEFORE" "$AFTER"
  node packages/sdk/scripts/cold-open-bench.mjs "${size[@]}" "$BEFORE" "$AFTER"
done
node packages/sdk/scripts/cold-open-bench.mjs --profile "$BEFORE" "$AFTER"

@callumalpass
callumalpass added this pull request to the merge queue Nov 28, 2026
@callumalpass
callumalpass removed this pull request from the merge queue due to a manual request Nov 28, 2026
@callumalpass
callumalpass added this pull request to the merge queue Nov 28, 2026
Merged via the queue into main with commit 3c0016f Nov 28, 2026
46 checks passed
@callumalpass
callumalpass deleted the optimize-10k-browser-opfs-performance branch November 28, 2026 14:26
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant