garage44.eu/jeroen/cartopolis

logclone: git clone https://garage44.eu/jeroen/cartopolis.git

.. /docs/notes/wasm-performance.md

raw


topic: wasm-performance triggers: [gecko_profile, "gecko-profile", hardwareConcurrency, "?workers", CARTO_WORKERS, Firefox, crates/mvt_reader, mvt-reader, platform/heap.rs, heap_labels, frame_split.rs, gpu_log.ts, firefox_probe, rust_oom, "out of memory", platform/workers.rs, crates/wgpu/src/meter.rs, crates/wgpu/src/backend/webgpu, crates/bevy_shader, shader_store.rs, wgsl-v1.bin, keep-profile, map_wgt_features, pipeline_log, height.rs, debug_switches.rs, pipeline_health.rs, quality.rs, index.html, lod22.rs, osm_buildings.rs, ground_detail.rs, wet_surfaces.rs, refresh_tile_lod_blend, "get_mut", "Assets<GroundMaterial>", IoTaskPool, cdp_probe, callgrind, "wasm", "web build", "phone", "mobile", "render scale", "devicePixelRatio", "hitch", "hang"] updated: 2026-10-31

What actually costs frames on the web build

The standing rule — on wasm IoTaskPool runs on the main thread, because Bevy disables multi_threaded there, so parse and mesh work must go to platform::workers — is documented where it bites, at lod22.rs:349. This note holds only what the code cannot.

The measurement

2026-07-26, tools/cdp_probe.ts --gpu --profile against the real adapter (vendor=intel architecture=xe-lpg, Meteor Lake Arc, Mesa 26.1.5) — not SwiftShader, which headless Chromium falls back to silently and which makes any frame number meaningless.

Before: median 1–2 fps, 500–2000 ms frames. Cause was serde_json on the main thread — ~32% of total samples, ~46% of non-idle, led by drop_glue::<serde_json::Value> (14.2%) and Value as Deserialize::deserialize (10.6% + 4.9% visitor).

After moving parse+mesh to platform::workers (1ba27b0, 11f8d7e, 9a9b67d): median 52 fps, 16–20 ms frames, and serde_json is absent from the main-thread profile.

Ruled out — do not re-test these first

A/B'd on the real GPU, all within noise of baseline: atmosphere, env-map IBL, haze, clouds, rain. GPU load is implausible as a cause at ~520 draws / 1.5 M triangles on this device. Shadows were never tested and are ~79% of submitted triangles — ?no_shadows exists to check that one.

Still true, still costing

Parsing is half fixed (restated 2026-08-10). lod22.rs is typed now — its parse_cell uses a derived Deserialize — so the 3DBAG path no longer boxes every coordinate of a ~4 MB cell. The OSM building path is partly there (checked 2026-10-31): since adbf7d1b the client's parse_buildings calls cartopolis_geo::formats::osm_buildings::parse, which no longer builds one Value tree of the whole multi-megabyte Overpass response — but its Element still deserializes through a Value per element and copies out of it, so every coordinate and every tag map is still boxed once and dropped. Dropping those still costs more than building them, off the main thread. A derived Element (with a lenient geometry) is the remaining win.

check: grep -q 'Value::deserialize(d)' crates/geo/src/formats/osm_buildings.rs

The previous check pointed at lod22.rs and had become a false green: after that file was typed, its only remaining match was the comment explaining that it is not a Value walk, so the grep kept passing while the fact it guarded had already changed. Hence the pattern above matches a parse call, not a mention.

Overpass's validate-before-persist survived the move via a derived OverpassRemark struct (serde skips elements without allocating). Its 200-status remark error channel must still be rejected before caching — a 200 response is not a success there.

Where a load's hitches went (2026-10-16)

Measured with tools/cdp_probe.ts --gpu --profile-from 0 --profile-out, a release build kept unstripped (CARGO_PROFILE_WEB_RELEASE_STRIP=none, so the profile has function names), in Chrome for Testing on a Mac node's Apple GPU (how to set that up is in the probe's header and in checking-the-web-build.md). One 75 s load over Groningen per run, two runs per side, alternated:

deployed codefixed
main-thread busy time32.5 s, 42.8 s24.4 s, 22.9 s
of which in stretches ≥100 ms with no idle15.8 s, 26.2 s5.0 s, 4.5 s
re-preparing ground materials6.6 s, 8.5 s26 ms, 24 ms
a basemap tile's future, on the main thread1.8 s, 2.2 s0.3 s, 0.1 s

The big one was material churn, and it is a rule, not a one-off. get_mut on an Assets<M> marks the asset changed the moment it is dereferenced mutably — assigning a field the value it already has counts — and a changed material is re-prepared: its bind groups rebuilt from scratch. Three systems (ground_detail::refresh_ground_detail, map_stream::refresh_tile_lod_blend, wet_surfaces::apply_wet_surfaces) re-ran whenever the number of materials changed, so that a newcomer gets the current value — which is right — and then wrote every material unconditionally — which re-prepared the whole clipmap and every ground surface once per tile landing, all through a load. Read first, write only what differs. building_fade and sewers already did.

Re-preparing was so expensive on the web for a second reason: almost all of it was wgpu::backend::webgpu::map_wgt_features. wgpu's webgpu backend answers Device::features() by asking the browser about each of ~60 feature names, every call, marshalling a string each way, and bevy's AsBindGroup asks it several times per material prepare. It is not cached anywhere in wgpu 30. With the churn gone it is ~0.4 s a load, which did not justify vendoring wgpu to cache it; if a new hot path calls RenderDevice::features() per item, it is worth reconsidering. (2026-10-19: one did, and wgpu is vendored — next section.)

The rest was CPU work running between awaits in futures on the IoTaskPool — on the web, the main thread. workers::compute existed for exactly this, and three places still did not use it: surveyed::raster_survey (a projection per vertex and a formatted key per area, then freeing two parsed files of megabytes), municipal register parses, and tzf_rs::DefaultFinder::new (250 ms, in a system). The shape to look for: anything after an .await in a future that loops over a parsed file, or a large value whose drop happens there.

Still costing, and upstream: bevy compiles each new pipeline's WESL to WGSL on the main thread — ~1 s a load, and the single worst remaining frame (~600 ms on the M5) — and its mesh slab allocator copies vertex data there (~0.5 s). The first frame after start is ~0.9 s of browser and bevy start-up.

A freeze in the container's browser is the container's. Headless Chrome there presents on lavapipe; its GPU process spends 7–8 s inside single WebGPU flushes, the page blocks on it (GpuChannel::WaitForGetOffsetInRange in a --trace), and neither the debugger nor the profiler can reach the main thread meanwhile. On the Mac's GPU the same build never froze. Use a node with a GPU for anything about time.

Moving the camera, and the wgpu fork (2026-10-19)

A load with the camera standing still under-reports what a person feels: a settled scene streams nothing. cdp_probe --drive 25 repeats a fixed script from 25 s on (pan, turn, zoom in and back out, pan), so runs compare. Same setup as above: release build kept unstripped, Chrome for Testing on mac-1's Apple GPU, 1600×900, 100 s, Groningen.

Without the fixes, a 75 s drive held ~53 fps on that machine (60 is vsync), with 100–700 ms freezes most seconds and the odd 1.5 s one. Each of these was found inside those freezes and moved:

Two runs each side, alternated:

per 100 s runbeforeafter
main-thread busy47.2 s, 51.4 s38.8 s, 41.1 s
in stretches ≥100 ms with no idle13.7 s, 21.2 s9.0 s, 11.1 s
mean fps while driving53.2, 54.655.5, 53.9

The fps barely moves because this machine is vsync-bound. The busy time is the headroom a slower machine would spend.

This instrument is noisy, and it shows how noisy. The Mac mini hosts both Mac nodes, and while another session renders on the other one the host's load average sits at 7–8 on 6 cores. V8's sampler then misses ticks: 12–30 s of each 100 s profile is gaps between samples, not code. A run-to-run spread of ±20 % on the same build is normal under that load. Look at ioreg -r -c IOAccelerator and uptime before trusting one run, alternate the builds, and run each at least twice.

Still costing, in order:

  1. Shader composing on a first visit, ~0.4 s a run. ?pipeline_log logs each new pipeline with its shaders and defs (pipeline_health.rs). One run built 69 pipelines from 56 distinct (shader, defs) pairs. Most mid-drive ones are mesh.wesl + ground_detail.wesl again for a new vertex layout: ground-detail meshes arrive with and without VERTEX_COLORS and VERTEX_UVS, three combinations each composed separately. Giving every ground-detail mesh one layout would remove two of them. The rest of what this item used to cost is gone (next section).
  2. The render schedule itself: render_system, camera_driver and extraction are ~40 % of busy time while driving. They scale with draws and entities, and on the web they share the one thread with everything else.
  3. One 790 ms writeTexture inside GpuImage::prepare_asset, seen once, during a frame that also queued 10–14 MB of uploads. upload_meter warns about those frames. Which image it was is not established.

Composed shaders are kept, and composed without WESL's checks (2026-10-19)

crates/bevy_shader is bevy_shader 0.20.0 with two changes, both marked cartopolis::

Main-thread time composing WESL over one 100 s drive, same probe as above (sampler gaps capped at 3 ms, so these read low against the earlier table):

composing
before612 ms
first visit409–441 ms
second visit8–11 ms

On a second visit the time inside ≥100 ms freezes was 3.4–4.2 s, against 9.3 s for the build before. Most of that difference is not the shaders: the browser also keeps its compiled copy of the wasm module and the app's tile caches. The sampler gaps that made every first-visit profile noisy (12–30 s of 100) fell to ~2 s on a second visit, so much of that noise was the browser compiling the 157 MB module and not the shared host.

Two things to know when working on shaders:

Zooming out ran the heap out (2026-10-20)

What a user saw: the viewer hung on loading in Firefox, every reload, and zooming out "almost always" broke it. What it was: the wasm heap reaching wasm32's 4 GiB ceiling. An allocation then fails, Rust aborts under rust_oom, and Chrome logs RuntimeError: unreachable. Firefox shows its slow-page banner instead. GPU memory was not the cause: resident stayed under 0.8 GB throughout.

Reproducing it takes a scripted flight, because a hand zoom is not repeatable. cdp_probe --drive-script flight and firefox_probe --flight <s> post cartopolis.place messages through gpu_log.ts's FLIGHT_ALTITUDES (1200 → 300 → 50 → 12 → … → 40 000 → 5000 → 1200 → 12 m over the Groningen centre, 8 s apart). Before the fixes Chrome died about 89 s in, a few seconds after coming down from 40 km.

The instruments the client now logs, every five seconds, and the probes tabulate:

What held the heap, found with the labels, and what was done:

holdersizefix
finished ground cells queued behind the upload ceiling, for cells the ring no longer wanted~1.3 GBCellStream::keep_only drops them each frame; Budget::surface_jobs (3 browser, 2 phone, 9 desktop) caps how many are built at once
decoding one zoomed-out globe tile (globe: draw layers peaked at 2231 MB)214 MB for a 108 kB z8 tilecrates/mvt_reader: upstream reserved the whole feature's command count for every ring, and kept it
platform::storage's in-memory view, which kept every cache entry read or writtengrew without boundonly Data is kept now (web-persistence.md)

The decoder one is the general lesson: a compact input can decode to a hundred times its size. vector_tiles::raster::render_peak (an ignored test, CARTO_PEAK_TILES=<dir of z_x_y.mvt>) measures each tile's retained decode and render peak natively through cartopolis_geo::perf's counting allocator. That is the place to check a new tile source, not the browser.

After all three, same flight, Chrome on mac-2 (M5 Pro): it completed the whole 125 s, wasm_memory_mb stopped at 1478, the heap swung between 0.34 and 1.19 GB, mean frames 17–20 ms. Firefox on the same node completed it too and stopped at 1485 MB, but drew only 8–50 frames in each 2 s while the map streamed, against 120 once it settled; its frame split puts that in both the main world and "other". What the rest of the heap is, from a labelled build over the same flight: no holder grows any more. The swings to ~1 GB are working memory. The three ground cells being built at once peak at 400–520 MB together (surfaces: after bridges and after paving, ~150 MB a cell). The first 3DBAG cells parse at up to 480 MB (lod22) in the first 15 s. main settles at 200–240 MB and render at 70–90 MB. The 1478 MB high-water mark is those two overlapping at startup. Lowering it means fewer ground jobs at once (Budget::surface_jobs), or a cell build that holds less between its stages.

Firefox stuttered because the page had too many workers (2026-10-21)

After the out-of-memory fix, Firefox still stuttered while the map streamed: on mac-1 (a six-core M5 Pro VM) it drew 31–40 fps over the scripted flight, with 5 s windows under 30 fps and gaps of over a second, where Chrome drew 57–59.

The instrument is Firefox's own profiler, from a script: firefox_probe --gecko-profile PATH starts it at launch through the MOZ_PROFILER_STARTUP variables, and tools/gecko_profile.ts PATH --wasm <the module> reads it: per thread, running time and how much of it was on a CPU, the innermost Bevy system on each stack, and the stretches without a pause. Read its header before trusting a figure; three of its rules came from being fooled:

What it showed, with the pool at five workers (navigator.hardwareConcurrency - 1): no system or function dominated the page's thread (the largest single one, pipeline compiling, was 19% of the stretches over 100 ms, all of it at startup), the thread was off the CPU for 39% of its running time, and a third of its refresh ticks were "waiting for paint". Taking cores back from the pool fixed it:

same flight, mac-1Firefox fps5 s windows < 30 fpsChrome fps
5 workers31–406–16 of 2056.7
3 workers53–55058.8
2 workers55–560—

and a cold load with no flight filled about as fast with three as with five (Firefox 38–58 s against 37–40 s, Chrome 36 s against 42 s; noisy), while two was slower in Chrome (50 s). So the web build's pool is half the cores (lib.rs); ?workers=N overrides it, for the next machine that says otherwise.

What is not settled is why. Under the profiler, three workers took the page's off-CPU share from 39% to 32%, not to zero, and its "waiting for paint" ticks rose (1,751 of 3,544, against 1,099 of 3,242). mac-1 has two system daemons using ~1.1 cores around the clock (audiomxd, configd), the profiler costs CPU of its own, and the main thread also spent 3.1 s blocked inside Atomics.notify waking workers, which in Firefox takes a lock every waiting worker shares. Measure frame rates without the profiler; use the profile for where, not for how much.

The phone tier (2026-08-09)

The measurement above was taken on a workstation GPU, and everything it ruled out was ruled out there. A handset is a different machine in three ways at once, and crate::quality exists to hold the one answer the rest of the client reads:

?quality=phone / CARTO_QUALITY=phone forces the tier on any platform that has a query string or an environment — which is how it gets profiled on a machine that can profile it, and which excludes Android (see below); ?quality=high forces it off. Auto-detection has two arms, not one: on the web it is coarse-pointer and a viewport under 900 px (either alone catches a touchscreen laptop or a narrow desktop window), decided in index.html; on Android quality::auto() simply is the phone budget, because there is nothing to detect.

Render scale is a page-layout problem, not a renderer setting

This is the part that is not discoverable from Rust, and the reason the detector lives in index.html rather than in quality.rs.

On the web the client does not choose its render resolution. wgpu's surface configure writes canvas.width/height from the window's physical size (wgpu/src/backend/webgpu.rs), and that size is whatever winit's ResizeObserver measured — it observes with ResizeObserverBoxOptions:: DevicePixelContentBox, i.e. CSS content box × DPR (winit/src/platform_impl/web/web_sys/resize_scaling.rs).

Two consequences, both verified in the dependency sources rather than reasoned about:

Pointer coordinates survive the transform — winit takes them from offsetX/offsetY (web_sys/event.rs), which the browser reports in the element's own untransformed space, the same space the backing store is in. Note Canvas::position() does use getBoundingClientRect, which is transform-affected; nothing on the input path reads it, and anything new that does will be wrong by exactly k.

What is in the phone budget, and why each is there

SettingPhoneReason
Render scale≤1.5 DPR, ≤1.3 Mpx~30% of the pixels on a 2.75× screen
Shadowsoff (1024² if re-enabled)shadow casters were ~79% of submitted triangles
Bloomintensity = 0.0skips ~13 full-screen passes; the node early-returns on exactly 0
Sky IBLoffa cubemap + mip chain re-baked every frame
Trees, furniture, labels, textured roads, water shaderoffper-cell geometry the single thread meshes and draws
Clipmap424 → 224 tilesover half the ground draw list and the streaming behind it
Globe leaf tiles320 → 160~450 draws of planet, from one thread
Per-frame build/upload/despawn budgetshalvedthese bound the worst-case hitch, not the throughput
CPU workers≤3see thermals above
MSAAoffcorrectness, not cost: only 1× and 4× are guaranteed in Vulkan's framebufferColorSampleCounts, and a sample count the device rejects fails main_texture_sampled and renders nothing
Atmosphere LUTsevery axis halved~4 M ray-march steps per frame at Bevy's defaults, rebuilt every frame; sizes, not sample counts, because starving the integration bands instead
Space-tier raymarchingoff
Tile raster edge512² → 256²~310 MB of clipmap texture against ~78 MB — tile-raster-cost.md

The atmosphere deliberately stays on: it is the sky, it A/B'd within noise above, and the alternative is a void.

The table is the tier, so a knob that has no Budget field is a knob the phone does not get. That is the rule the four rows added on 2026-08-10 exist to enforce, and it is not a style preference: a zygote-launched NativeActivity process has no settable environment and no ?query=, so on the one platform the phone tier was written for, "force it with a raw env var" is not an answer to anything.

Corrected 2026-08-16. This used to say every env-var escape hatch is unreachable on Android, naming CARTO_FPS_CAP, CARTO_NO_SPACE_RAYMARCH and CARTO_QUALITY. That is true only of switches read through raw std::env::var. Anything going through crate::env_flag / env_value maps to a debug.carto.<name> system property on Android, which is the one namespace adb shell setprop may write on a production build without root — so those are reachable on a shipped APK with no rebuild. CARTO_QUALITY and CARTO_NO_SPACE_RAYMARCH were always on that path; CARTO_FPS_CAP was the one switch still bypassing it, and was moved onto it on 2026-08-16. The rule the paragraph exists to defend is unchanged — a tier decision belongs in Budget, not behind a debugging knob — but "unreachable" was the wrong reason for it, and it hid the fact that a real device can be instrumented from adb alone (docs/notes/render-performance-survey.md).

Not measured

Nothing here has been run on the device. It was written against the constraints, and the container it was written in has no GPU and no browser — cdp_probe cannot run there at all, and --shot needs a Vulkan driver it does not have. So the table above is a set of predictions with mechanisms, not results.

The one number that would settle it is a tools/cdp_probe.ts --gpu --profile run, or a frame counter on the handset, before and after, at the same place and altitude. Until someone has that, treat "phone tier holds 30 fps" as untested — and in particular do not assume the ordering in the table is the ordering of the wins. Render scale is first on reasoning about fill; if the device turns out to be main-thread-bound instead, the clipmap radius and the draw-count rows are the ones doing the work and the resolution could be given back.