aorecomp

Anarchy Online classic in the browser

git clone https://aorecomp.ubeagle.com/code/aorecomp.git


commit 61eee545e794496bf72ea920d849ce91200d80d5
parent 83c2ff90151e15e7eec91c389143a96077e8ede3
Author: anon <anon@example.com>
Date:   Wed, 11 Nov 2026 01:47:45 +0000

Prefetch startup chunks into RAM and profile guest workers

Diffstat:
Mclient/Makefile.linux | 2+-
Mclient/Makefile.wasm | 4++--
Mclient/browser/index.html | 2++
Mclient/browser/profile-worker.js | 24+++++++++++++++++++++++-
Mclient/runtime/browser_asset_cache.c | 72+++++++++++++++++++++++++++++++++++++++++++++++++++++-------------------
Mclient/runtime/browser_asset_cache.h | 3+++
Mclient/runtime/browser_fetch.js | 37++++++++++++++++++++++++++++++++++++-
Mclient/runtime/browser_host.c | 24++++++++++++++++++++++++
Mclient/runtime/browser_host.js | 3+++
Mclient/runtime/browser_profile.c | 24++++++++++++++++++++++++
Mclient/runtime/browser_profile.h | 2++
Mclient/runtime/browser_profile.js | 25++++++++++++++++++++++---
Mclient/runtime/linux_thread.c | 7+++++++
Mclient/tests/browser_asset_cache.c | 33+++++++++++++++++++++++++++++++++
Mclient/tests/browser_fetch.mjs | 62+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-
Mclient/tests/browser_profile.mjs | 35+++++++++++++++++++++++++++++++----
Mtools/client/read_profile.py | 6++++++
17 files changed, 333 insertions(+), 32 deletions(-)

diff --git a/client/Makefile.linux b/client/Makefile.linux @@ -24,7 +24,7 @@ objects: $(OBJECTS) build/linux/browser-asset-cache: tests/browser_asset_cache.c runtime/browser_asset_cache.c runtime/browser_asset_cache.h runtime/browser_profile.h @mkdir -p $(@D) - $(CC) $(CPPFLAGS) $(CFLAGS) $(filter %.c,$^) -Wl,--wrap=pread -o $@ + $(CC) $(CPPFLAGS) $(CFLAGS) $(filter %.c,$^) -Wl,--wrap=pread -pthread -o $@ test: build/linux/browser-asset-cache diff --git a/client/Makefile.wasm b/client/Makefile.wasm @@ -104,7 +104,7 @@ build/wasm/objects/%.o: %.c -include $(OBJECTS:.o=.d) -build/wasm/web/runtime-test.html: tests/browser_runtime.c runtime/browser_host.c runtime/browser_network.c runtime/linux_sync.c runtime/guest_memory.c runtime/recomp_state.c runtime/browser_host.js runtime/browser_fetch.js runtime/browser_network.js runtime/browser_profile.c runtime/browser_profile.js Makefile.wasm +build/wasm/web/runtime-test.html: tests/browser_runtime.c runtime/browser_host.c runtime/browser_asset_cache.c runtime/browser_network.c runtime/linux_sync.c runtime/guest_memory.c runtime/recomp_state.c runtime/browser_host.js runtime/browser_fetch.js runtime/browser_network.js runtime/browser_profile.c runtime/browser_profile.js Makefile.wasm @mkdir -p $(@D) $(CC) $(CPPFLAGS) $(CFLAGS) $(filter %.c,$^) -sWASMFS -sPROXY_TO_PTHREAD -sPTHREAD_POOL_SIZE=4 -sALLOW_BLOCKING_ON_MAIN_THREAD=0 -sALLOW_MEMORY_GROWTH --js-library runtime/browser_host.js --js-library runtime/browser_fetch.js --js-library runtime/browser_network.js -o $@ --js-library runtime/browser_profile.js @@ -116,7 +116,7 @@ build/wasm/web/files-test.html: tests/files.c runtime/linux_file.c runtime/guest @mkdir -p $(@D) $(CC) $(CPPFLAGS) $(CFLAGS) $(filter %.c,$^) -sWASMFS -sPROXY_TO_PTHREAD -sPTHREAD_POOL_SIZE=2 -sALLOW_BLOCKING_ON_MAIN_THREAD=0 -sALLOW_MEMORY_GROWTH -o $@ --js-library runtime/browser_profile.js -build/wasm/web/storage-test.html: tests/browser_storage.c runtime/browser_host.c runtime/browser_host.js runtime/browser_fetch.js Makefile.wasm runtime/browser_profile.c runtime/browser_profile.js +build/wasm/web/storage-test.html: tests/browser_storage.c runtime/browser_host.c runtime/browser_asset_cache.c runtime/browser_host.js runtime/browser_fetch.js Makefile.wasm runtime/browser_profile.c runtime/browser_profile.js @mkdir -p $(@D) $(CC) $(CFLAGS) $(filter %.c,$^) -sWASMFS -sPROXY_TO_PTHREAD -sPTHREAD_POOL_SIZE=2 -sALLOW_BLOCKING_ON_MAIN_THREAD=0 -sALLOW_MEMORY_GROWTH --js-library runtime/browser_host.js --js-library runtime/browser_fetch.js -o $@ --js-library runtime/browser_profile.js diff --git a/client/browser/index.html b/client/browser/index.html @@ -387,6 +387,8 @@ const url = new URL('browser-assets/cd_image/data/db/ResourceDatabase.dat', document.baseURI); const manifest = await fetch('browser-startup', {method: 'HEAD', cache: 'no-store'}); if (!manifest.ok) throw new Error(`Game assets: HTTP ${manifest.status}`); + Module.startupAssets = {url: url.href, version: manifest.headers.get('X-AO-Asset-Version'), + indices: manifest.headers.get('X-AO-Chunks').split(',').map(Number)}; let cached; try { cached = await Promise.all(manifest.headers.get('X-AO-Chunks').split(',').map(async index => { diff --git a/client/browser/profile-worker.js b/client/browser/profile-worker.js @@ -2,6 +2,7 @@ let configuration, memory, uploading = false, sequence = 0, dropped = 0; let events = [], frames = [], metrics = {}, visibility = 'visible', build = null; let started = 0; +const threads = new Map(); function record(event) { if (events.length < 4096) events.push(event); @@ -28,11 +29,32 @@ onmessage = event => { ts: (performance.timeOrigin + performance.now()) * 1000, args: {function: Atomics.load(memory, configuration.currentFunction >>> 2), phase: Atomics.load(memory, configuration.phase >>> 2)}}); + for (const {sample, thread, entry} of threads.values()) { + const pointer = Atomics.load(memory, sample >>> 2); + if (!pointer) continue; + const address = Atomics.load(memory, pointer >>> 2); + const phase = Atomics.load(memory, (sample + 4) >>> 2); + // An exiting thread invalidates its record before its TLS can be reused. + if (Atomics.load(memory, sample >>> 2) !== pointer) continue; + record({name: 'guest sample', ph: 'i', s: 't', pid: 1, tid: thread, + ts: (performance.timeOrigin + performance.now()) * 1000, + args: {function: address, phase, entry}}); + } }, 4); - setInterval(upload, configuration.detailed ? 5000 : 30000); + setInterval(upload, configuration.detailed ? 1000 : 30000); postMessage(`${configuration.detailed ? 'Detailed profile' : 'Performance summaries'}: ${configuration.session}`); return; } + if (data.register) { + if (data.memory.byteLength > memory.byteLength) memory = new Uint32Array(data.memory); + threads.set(data.register.sample, data.register); + return; + } + if (data.unregister) { + threads.delete(data.unregister); + postMessage({free: data.unregister}); + return; + } if (data.visibility) { upload(); visibility = data.visibility; return; } for (const item of data.events) record(item); for (const duration of data.frames) { diff --git a/client/runtime/browser_asset_cache.c b/client/runtime/browser_asset_cache.c @@ -1,11 +1,19 @@ #include "browser_asset_cache.h" #include "browser_profile.h" #include <errno.h> +#include <pthread.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> +#ifdef __EMSCRIPTEN__ +#include <emscripten.h> +EMSCRIPTEN_KEEPALIVE void browser_store_startup_chunk(uint32_t inode, uint32_t index, unsigned char *bytes) +{ + browser_asset_cache_store(inode, (off_t)index * 1048576, bytes, 1048576); +} +#endif static struct asset_chunk { ino_t inode; @@ -15,6 +23,35 @@ static struct asset_chunk { struct asset_chunk *next; } *chunks; static size_t cached_bytes; +static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; + +/* Publish complete chunks only. A demand read may have won the same race. */ +void browser_asset_cache_store(ino_t inode, off_t offset, unsigned char *bytes, size_t size) +{ + pthread_mutex_lock(&mutex); + for (struct asset_chunk *chunk = chunks; chunk; chunk = chunk->next) { + if (chunk->inode == inode && chunk->offset == offset) { + pthread_mutex_unlock(&mutex); + free(bytes); + return; + } + } + while (cached_bytes + size > 256 * 1024 * 1024) { + struct asset_chunk **oldest = &chunks; + while ((*oldest)->next) oldest = &(*oldest)->next; + cached_bytes -= (*oldest)->size; + free((*oldest)->bytes); + free(*oldest); + *oldest = NULL; + } + struct asset_chunk *chunk = malloc(sizeof(*chunk)); + if (!chunk) abort(); + *chunk = (struct asset_chunk){.inode = inode, .offset = offset, .size = size, + .bytes = bytes, .next = chunks}; + chunks = chunk; + cached_bytes += size; + pthread_mutex_unlock(&mutex); +} ssize_t browser_asset_read_locked(int descriptor, ino_t inode, off_t file_size, void *buffer, size_t length) @@ -24,51 +61,46 @@ ssize_t browser_asset_read_locked(int descriptor, ino_t inode, off_t file_size, if (position >= file_size || !length) return 0; if (length > (uint64_t)(file_size - position)) length = file_size - position; size_t copied = 0; + int filled = 0; while (copied < length) { off_t offset = (position + copied) / 1048576 * 1048576; + pthread_mutex_lock(&mutex); struct asset_chunk **entry = &chunks; while (*entry && ((*entry)->inode != inode || (*entry)->offset != offset)) entry = &(*entry)->next; struct asset_chunk *chunk = *entry; - double hit = chunk ? ao_profile_begin("asset cache hit") : 0; + double hit = chunk && !filled ? ao_profile_begin("asset cache hit") : 0; if (chunk) { /* Move resident chunks to the front without contacting the fetch worker. */ *entry = chunk->next; } else { size_t size = file_size - offset < 1048576 ? file_size - offset : 1048576; - while (cached_bytes + size > 256 * 1024 * 1024) { - struct asset_chunk **oldest = &chunks; - while ((*oldest)->next) oldest = &(*oldest)->next; - cached_bytes -= (*oldest)->size; - free((*oldest)->bytes); - free(*oldest); - *oldest = NULL; - } + pthread_mutex_unlock(&mutex); /* One worker request fills a complete chunk for subsequent small reads. */ - chunk = malloc(sizeof(*chunk)); - if (!chunk) abort(); - *chunk = (struct asset_chunk){.inode = inode, .offset = offset, .size = size, - .bytes = malloc(size)}; - if (!chunk->bytes) abort(); + unsigned char *bytes = malloc(size); + if (!bytes) abort(); double start = ao_profile_begin("asset cache fill"); ssize_t result; do { - result = pread(descriptor, chunk->bytes, size, offset); + result = pread(descriptor, bytes, size, offset); } while (result < 0 && errno == EINTR); + if (result == (ssize_t)size) browser_asset_cache_store(inode, offset, bytes, size); char detail[64] = ""; - if (start) snprintf(detail, sizeof(detail), "resident_bytes=%zu", cached_bytes + (result == (ssize_t)size ? size : 0)); + pthread_mutex_lock(&mutex); + if (start) snprintf(detail, sizeof(detail), "resident_bytes=%zu", cached_bytes); + pthread_mutex_unlock(&mutex); ao_profile_end("asset cache fill", start, detail); if (result != (ssize_t)size) { - free(chunk->bytes); - free(chunk); + free(bytes); if (result >= 0) errno = EIO; if (!copied) return -1; break; } - cached_bytes += size; + filled = 1; + continue; } chunk->next = chunks; chunks = chunk; @@ -78,6 +110,8 @@ ssize_t browser_asset_read_locked(int descriptor, ino_t inode, off_t file_size, if (size > length - copied) size = length - copied; memcpy((unsigned char *)buffer + copied, chunk->bytes + within, size); copied += size; + filled = 0; + pthread_mutex_unlock(&mutex); if (hit) ao_profile_end("asset cache hit", hit, NULL); } if (lseek(descriptor, position + copied, SEEK_SET) < 0) return -1; diff --git a/client/runtime/browser_asset_cache.h b/client/runtime/browser_asset_cache.h @@ -8,4 +8,7 @@ ssize_t browser_asset_read_locked(int descriptor, ino_t inode, off_t file_size, void *buffer, size_t length); +/* Takes ownership of one complete chunk; safe alongside guest reads. */ +void browser_asset_cache_store(ino_t inode, off_t offset, unsigned char *bytes, size_t size); + #endif diff --git a/client/runtime/browser_fetch.js b/client/runtime/browser_fetch.js @@ -1,10 +1,14 @@ addToLibrary({ + browser_prefetch_startup_js__deps: ['$AOResourcePrefetch', '$UTF8ToString'], + browser_prefetch_startup_js: (configuration, inode) => + AOResourcePrefetch.startup(JSON.parse(UTF8ToString(configuration)), inode), $AOResourcePrefetch: {}, browser_prefetch_resource_js__deps: ['$AOResourcePrefetch'], browser_prefetch_resource_js: (kind, identity) => AOResourcePrefetch.request(kind, identity), _wasmfs_create_fetch_backend_js__deps: [ '$wasmFS$backends', '_wasmfs_fetch_get_file_url', '_wasmfs_fetch_get_chunk_size', - '$AOResourcePrefetch', '$AOProfile', '$AOAssetRequest', 'browser_prefetch_resource_ready' + '$AOResourcePrefetch', '$AOProfile', '$AOAssetRequest', 'browser_prefetch_resource_ready', + 'malloc', 'browser_store_startup_chunk' ], _wasmfs_create_fetch_backend_js: async function(backend) { const files = new Map(); @@ -322,6 +326,37 @@ addToLibrary({ } }); }; + AOResourcePrefetch.startup = async ({url, version, indices}, inode) => { + const start = AOProfile.begin('startup RAM prefetch'); + let completed = 0; + try { + const cache = await caches.open('ao-asset-chunks-v1'); + if ((await fileMetadata(url))?.version !== version) return; + let next = 0; + const results = await Promise.allSettled(Array.from({length: 4}, async () => { + while (next < indices.length) { + const index = indices[next++], chunkURL = new URL(url); + chunkURL.searchParams.set('ao-chunk', `1048576:${index}`); + const response = await cache.match(chunkURL.href); + if (response?.headers.get('ETag') !== version) continue; + const bytes = new Uint8Array(await response.arrayBuffer()); + if (bytes.byteLength !== 1048576) continue; + const pointer = _malloc(bytes.byteLength); + if (!pointer) throw new Error('Could not allocate startup chunk'); + HEAPU8.set(bytes, pointer); + _browser_store_startup_chunk(inode, index, pointer); + ++completed; + } + })); + const failed = results.find(result => result.status === 'rejected'); + if (failed) throw failed.reason; + } catch (error) { + // Storage can disappear or be denied; demand reads remain authoritative. + console.warn('Startup RAM prefetch unavailable:', error); + } finally { + AOProfile.end('startup RAM prefetch', start, {chunks: completed}); + } + }; _browser_prefetch_resource_ready(); wasmFS$backends[backend] = { diff --git a/client/runtime/browser_host.c b/client/runtime/browser_host.c @@ -88,6 +88,19 @@ void browser_prefetch_resource(uint32_t kind, uint32_t identity) free(request); } +char *browser_startup_assets(void); +void browser_prefetch_startup_js(const char *configuration, uint32_t inode); +struct startup_prefetch { char *configuration; uint32_t inode; }; + +static void prefetch_startup(void *argument) +{ + /* The fetch worker can read storage while guest initialization continues. */ + struct startup_prefetch *request = argument; + browser_prefetch_startup_js(request->configuration, request->inode); + free(request->configuration); + free(argument); +} + void browser_initialize(unsigned character_id) { /* FetchFS performs range requests on its own worker while game threads wait. */ @@ -134,6 +147,17 @@ void browser_initialize(unsigned character_id) } free(manifest); + char *startup = browser_startup_assets(); + if (startup) { + struct stat info; + assert(stat("/remote/cd_image/data/db/ResourceDatabase.dat", &info) == 0); + assert(info.st_ino <= UINT32_MAX); + struct startup_prefetch *request = malloc(sizeof(*request)); + assert(request); + *request = (struct startup_prefetch){startup, info.st_ino}; + assert(emscripten_proxy_async(resource_queue, resource_thread, prefetch_startup, request)); + } + /* Register all remote files first so startup reads can prefetch their siblings. */ for (char *name = strtok(copy_manifest, "\n"); name; name = strtok(NULL, "\n")) { if (name[strlen(name) - 1] == '/' || diff --git a/client/runtime/browser_host.js b/client/runtime/browser_host.js @@ -1,4 +1,7 @@ addToLibrary({ + browser_startup_assets__deps: ['$stringToNewUTF8'], + browser_startup_assets__proxy: 'sync', + browser_startup_assets: () => Module.startupAssets ? stringToNewUTF8(JSON.stringify(Module.startupAssets)) : 0, $AOTest: {enabled: false, frame: 0}, ao_test_publish__deps: ['$AOTest', 'ao_test_publish_main'], ao_test_publish: (json) => { diff --git a/client/runtime/browser_profile.c b/client/runtime/browser_profile.c @@ -1,10 +1,15 @@ #include "browser_profile.h" #include <emscripten.h> #include <pthread.h> +#include <stdatomic.h> +#include <stdlib.h> static char *configuration; static uint32_t phase; +static _Thread_local _Atomic uint32_t *thread_sample; char *ao_profile_start(uint32_t *current_function, uint32_t *phase, uintptr_t thread); +void ao_profile_thread_start(uint32_t *sample, uint32_t entry); +void ao_profile_thread_stop(uint32_t *sample); EMSCRIPTEN_KEEPALIVE const char *browser_profile_configuration(void) { @@ -15,3 +20,22 @@ void browser_profile_initialize(uint32_t *current_function) { configuration = ao_profile_start(current_function, &phase, (uintptr_t)pthread_self()); } + +void browser_profile_thread_initialize(uint32_t *current_function, uint32_t entry) +{ + if (!configuration) return; + thread_sample = calloc(2, sizeof(*thread_sample)); + if (!thread_sample) abort(); + atomic_store(thread_sample, (uint32_t)current_function); + ao_profile_thread_start((uint32_t *)thread_sample, entry); +} + +void browser_profile_thread_finish(void) +{ + if (!thread_sample) return; + /* Invalidate before TLS is reclaimed. The collector releases this record + * after removing it from its sampling list, without delaying thread exit. */ + atomic_store(thread_sample, 0); + ao_profile_thread_stop((uint32_t *)thread_sample); + thread_sample = NULL; +} diff --git a/client/runtime/browser_profile.h b/client/runtime/browser_profile.h @@ -4,6 +4,8 @@ #ifdef __EMSCRIPTEN__ #include <stdint.h> void browser_profile_initialize(uint32_t *current_function); +void browser_profile_thread_initialize(uint32_t *current_function, uint32_t entry); +void browser_profile_thread_finish(void); double ao_profile_begin(const char *name); void ao_profile_end(const char *name, double start, const char *detail); #else diff --git a/client/runtime/browser_profile.js b/client/runtime/browser_profile.js @@ -79,7 +79,20 @@ addToLibrary({ this.events = []; this.frames = []; this.metrics = {}; this.dropped = 0; } }, - ao_profile_start__deps: ['$stringToNewUTF8'], + ao_profile_thread_start__deps: ['$AOProfile'], + ao_profile_thread_start: (sample, entry) => { + if (!AOProfile.connect()) return; + AOProfile.thread = _pthread_self(); + AOProfile.phaseAddress = sample + 4; + AOProfile.channel.postMessage({register: {sample, entry, thread: AOProfile.thread}}); + }, + ao_profile_thread_stop__deps: ['$AOProfile'], + ao_profile_thread_stop: sample => { + AOProfile.flush(); + AOProfile.phaseAddress = 0; + AOProfile.channel.postMessage({unregister: sample}); + }, + ao_profile_start__deps: ['$stringToNewUTF8', 'free'], ao_profile_start__proxy: 'sync', ao_profile_start: (currentFunction, phase, thread) => { const detailed = new URLSearchParams(location.search).get('profile') === '1'; @@ -93,11 +106,17 @@ addToLibrary({ return 0; } const channel = new BroadcastChannel(`ao-profile-${session}`); - channel.onmessage = event => worker.postMessage(event.data); + // Send shared memory directly between workers in this page's agent cluster. + // BroadcastChannel carries only the registration's addresses and identity. + channel.onmessage = event => worker.postMessage(event.data.register ? + {...event.data, memory: wasmMemory.buffer} : event.data); worker.postMessage({init: {session, detailed, memory: wasmMemory.buffer, currentFunction, phase, thread, started: performance.timeOrigin + performance.now(), visibility: document.visibilityState, client: {userAgent: navigator.userAgent, width: Module.canvas.width, height: Module.canvas.height}}}); - worker.onmessage = event => console.log(event.data); + worker.onmessage = event => { + if (event.data.free) _free(event.data.free); + else console.log(event.data); + }; worker.onerror = () => { channel.close(); console.warn('Profiler stopped; gameplay continues'); diff --git a/client/runtime/linux_thread.c b/client/runtime/linux_thread.c @@ -2,6 +2,7 @@ #include "linux_thread.h" #include "guest_heap.h" #include "guest_crt.h" +#include "browser_profile.h" #include <errno.h> #include <pthread.h> #include <time.h> @@ -62,6 +63,9 @@ static void finish_thread(void *argument) MEM32(g_fs_base) = UINT32_MAX; g_esp = g_fs_base - 0x100; linux_thread_notify(3); /* DLL_THREAD_DETACH */ +#ifdef __EMSCRIPTEN__ + browser_profile_thread_finish(); +#endif guest_free(thread->allocation); check_pthread(pthread_mutex_lock(&mutex)); thread->complete = 1; @@ -93,6 +97,9 @@ static void *run_thread(void *argument) check_pthread(pthread_mutex_unlock(&mutex)); pthread_cleanup_push(finish_thread, thread); +#ifdef __EMSCRIPTEN__ + browser_profile_thread_initialize(&g_cur_func, thread->entry); +#endif linux_thread_notify(2); /* DLL_THREAD_ATTACH */ if (thread->host_entry) { thread->host_entry(); diff --git a/client/tests/browser_asset_cache.c b/client/tests/browser_asset_cache.c @@ -3,6 +3,7 @@ #include <assert.h> #include <errno.h> #include <fcntl.h> +#include <pthread.h> #include <stdio.h> #include <stdlib.h> #include <string.h> @@ -11,11 +12,26 @@ static unsigned reads; static off_t failed_offset = -1; +static ino_t prefetch_inode; +static void *publish_during_read(void *argument) +{ + off_t offset = *(off_t *)argument; + unsigned char *bytes = calloc(1, 1048576); + assert(bytes); + bytes[0] = 'p'; + browser_asset_cache_store(prefetch_inode, offset, bytes, 1048576); + return NULL; +} ssize_t __real_pread(int descriptor, void *buffer, size_t size, off_t offset); ssize_t __wrap_pread(int descriptor, void *buffer, size_t size, off_t offset) { ++reads; if (offset == failed_offset) { errno = EIO; return -1; } + if (prefetch_inode) { + pthread_t thread; + assert(!pthread_create(&thread, NULL, publish_during_read, &offset)); + assert(!pthread_join(thread, NULL)); + } return __real_pread(descriptor, buffer, size, offset); } @@ -118,6 +134,22 @@ static void startup_chunks_survive_until_budget_eviction(int descriptor, ino_t i assert(byte == 'C' && reads == before + 1); } +static void prefetch_can_publish_while_a_demand_read_waits(int descriptor, ino_t inode, off_t size) +{ + unsigned char bytes[5]; + assert(lseek(descriptor, 100 * 1048576, SEEK_SET) == 100 * 1048576); + unsigned before = reads; + prefetch_inode = inode; + + assert(browser_asset_read_locked(descriptor, inode, size, bytes, 5) == 5); + + assert(bytes[0] == 'p' && reads == before + 1); + prefetch_inode = 0; + assert(lseek(descriptor, 100 * 1048576, SEEK_SET) == 100 * 1048576); + assert(browser_asset_read_locked(descriptor, inode, size, bytes, 5) == 5); + assert(bytes[0] == 'p' && reads == before + 1); +} + int main(void) { char path[] = "/tmp/ao-asset-cache-XXXXXX"; @@ -134,6 +166,7 @@ int main(void) boundaries_and_positions(first, second, info.st_ino, size); failed_fill_can_be_retried(first, info.st_ino, size); different_files_do_not_share_chunks(first, info.st_ino, size); + prefetch_can_publish_while_a_demand_read_waits(first, info.st_ino, size); startup_chunks_survive_until_budget_eviction(first, info.st_ino, size); assert(!close(first) && !close(second)); diff --git a/client/tests/browser_fetch.mjs b/client/tests/browser_fetch.mjs @@ -50,7 +50,8 @@ async function fixture(bytes, wholeFile = false, storage, version = '"one"', chu const initializing = library._wasmfs_create_fetch_backend_js(1); assert.ok(context.wasmFS$backends[1], 'WasmFS requires synchronous callback registration'); await initializing; - return {backend: context.wasmFS$backends[1], requests, manifests, heap, warnings, context}; + return {backend: context.wasmFS$backends[1], requests, manifests, heap, warnings, context, + prefetchStartup: library.browser_prefetch_startup_js}; } function diskCache() { @@ -462,3 +463,62 @@ await stalledRequestsAreAbortedAndRetried(); await permanentFailuresDoNotRetry(); await rejectedManifestDoesNotPoisonLaterReads(); console.log('PASS: indefinite retries, capped jittered backoff, shared recovery, transfer deadlines and permanent failures'); + + +async function startupChunksPrefetchInParallel() { + const stored = [], spans = []; + let active = 0, maximum = 0; + const test = await fixture(new Uint8Array(1048577), false, {open: async () => ({ + match: async url => { + const index = Number(new URL(url).searchParams.get('ao-chunk').split(':')[1]); + ++active; + maximum = Math.max(maximum, active); + await new Promise(resolve => setTimeout(resolve, 1)); + --active; + if (index === 4) return undefined; + return new Response(new Uint8Array(index === 5 ? 3 : 1048576).fill(index), { + headers: {ETag: index === 6 ? '"old"' : '"one"'}}); + } + })}); + test.context._malloc = size => { assert.equal(size, 1048576); return 1; }; + test.context._browser_store_startup_chunk = (inode, index, pointer) => { + assert.equal(inode, 42); + assert.equal(pointer, 1); + assert.equal(test.heap[1], index); + assert.equal(test.heap[1048576], index); + stored.push(index); + }; + test.context.AOProfile = {begin: () => 1, end: (name, start, detail) => spans.push(detail)}; + + await test.prefetchStartup(JSON.stringify({url: 'http://example.test/browser-assets/asset', + version: '"one"', indices: [0, 1, 2, 3, 4, 5, 6, 7]}), 42); + + assert.equal(maximum, 4); + assert.deepEqual(stored.sort((a, b) => a - b), [0, 1, 2, 3, 7]); + assert.equal(spans[0].chunks, 5); + assert.deepEqual(test.requests, []); + assert.deepEqual(test.warnings, []); + + // A startup HEAD from an older deployment must not seed the current file. + stored.length = 0; + await test.prefetchStartup(JSON.stringify({url: 'http://example.test/browser-assets/asset', + version: '"old"', indices: [6]}), 42); + assert.deepEqual(stored, []); +} + +async function startupPrefetchToleratesDeniedStorage() { + const test = await fixture(new Uint8Array(1), false, { + open: async () => { throw new Error('Storage denied'); } + }); + test.warnings.length = 0; + + await test.prefetchStartup(JSON.stringify({url: 'http://example.test/browser-assets/asset', + version: '"one"', indices: [0]}), 42); + + assert.equal(test.warnings.length, 1); + assert.deepEqual(test.requests, []); +} + +await startupChunksPrefetchInParallel(); +await startupPrefetchToleratesDeniedStorage(); +console.log('PASS: four parallel startup reads publish only valid cached chunks and tolerate denied storage'); diff --git a/client/tests/browser_profile.mjs b/client/tests/browser_profile.mjs @@ -5,7 +5,7 @@ import vm from 'node:vm'; function fixture(detailed, status = 204) { const uploads = [], timers = [], messages = []; let rejectUpload = false, pendingUpload; - const memory = new SharedArrayBuffer(16); + const memory = new SharedArrayBuffer(32); new Uint32Array(memory).set([0x12345678, 3]); const context = vm.createContext({ Uint32Array, Atomics, performance: {timeOrigin: 1000, now: () => 100}, @@ -27,7 +27,7 @@ function fixture(detailed, status = 204) { vm.runInContext(fs.readFileSync(new URL('../browser/profile-worker.js', import.meta.url), 'utf8'), context); context.onmessage({data: {init: {session: 'test', detailed, memory, currentFunction: 0, phase: 4, thread: 7, started: 1000, visibility: 'visible'}}}); - return {uploads, timers, messages, send: data => context.onmessage({data}), + return {uploads, timers, messages, memory, send: data => context.onmessage({data}), offline: () => { rejectUpload = true; }, hold: promise => { pendingUpload = promise; }}; } @@ -83,6 +83,29 @@ await boundedSamplingAndFailedUpload(); await slowUploadDoesNotAccumulateRequests(); console.log('PASS: gameplay profile summaries, sampling, queue bounds and failed/slow uploads'); +// Worker TLS may be reclaimed before its unregister message reaches the collector. +{ + const test = fixture(true); + const memory = new SharedArrayBuffer(64), heap = new Uint32Array(memory); + heap.set(new Uint32Array(test.memory)); + heap.set([48, 3], 8); + heap[12] = 0x400110E0; + test.send({register: {sample: 32, entry: 0x1234, thread: 8}, memory}); + test.timers[0].callback(); + Atomics.store(heap, 8, 0); + heap[12] = 0xFFFFFFFF; + test.timers[0].callback(); + test.send({unregister: 32}); + test.timers[0].callback(); + await test.timers[1].callback(); + + const samples = test.uploads[0].traceEvents.filter(event => event.tid === 8); + assert.equal(samples.length, 1); + assert.deepEqual(samples[0].args, {function: 0x400110E0, phase: 3, entry: 0x1234}); + assert.equal(test.messages.filter(message => message.free === 32).length, 1); +} +console.log('PASS: guest worker sampling handles memory growth and invalidated TLS'); + // Normal play starts no worker, timers or collection channel. for (const search of ['', '?profile=0', '?profile=other']) { let library; @@ -104,12 +127,13 @@ for (const search of ['', '?profile=0', '?profile=other']) { // Explicit opt-in starts the collector with the detailed configuration. { let library; - const workers = [], messages = []; + const workers = [], messages = [], channels = []; const context = vm.createContext({ addToLibrary: value => { library = value; }, URLSearchParams, URL, location: {search: '?profile=1'}, crypto: {randomUUID: () => 'test'}, Worker: class { constructor(url) { workers.push(url.pathname); } postMessage(message) { messages.push(message); } }, - BroadcastChannel: class {}, wasmMemory: {buffer: new SharedArrayBuffer(64)}, + BroadcastChannel: class { constructor() { channels.push(this); } }, + wasmMemory: {buffer: new SharedArrayBuffer(64)}, document: {baseURI: 'https://example.test/', visibilityState: 'visible', addEventListener() {}}, navigator: {userAgent: 'test'}, Module: {canvas: {width: 640, height: 480}}, performance: {timeOrigin: 1000, now: () => 10}, stringToNewUTF8: value => value @@ -119,6 +143,9 @@ for (const search of ['', '?profile=0', '?profile=other']) { assert.deepEqual(workers, ['/wasm/profile-worker.js']); assert.equal(messages.length, 1); assert.equal(messages[0].init.detailed, true); + channels[0].onmessage({data: {register: {sample: 32, entry: 0x1234, thread: 8}}}); + assert.equal(messages[1].register.sample, 32); + assert.equal(messages[1].memory, context.wasmMemory.buffer); } console.log('PASS: profiling stays off until explicitly enabled'); diff --git a/tools/client/read_profile.py b/tools/client/read_profile.py @@ -8,6 +8,7 @@ path = pathlib.Path(sys.argv[1]) events = [] metrics = {} functions = collections.Counter() +thread_functions = collections.defaultdict(collections.Counter) phases = collections.Counter() frames = 0 frame_ms = 0 @@ -38,6 +39,7 @@ with path.open() as source: # Exclude explicit pacing and I/O; other unmarked host waits can remain. if phase in (0, 2): functions[address] += 1 + thread_functions[event['tid']][address] += 1 events.append(event) print('Builds:', ', '.join(str(build) for build in builds)) @@ -49,6 +51,10 @@ print('Wall-time sample phases (0 guest/host, 1 RAF, 2 render, 3 file, 4 setup, print('Guest/render residency samples, NOT CPU self-time:') for address, count in functions.most_common(20): print(f' sub_{address:08X}: {count}') +for thread, samples in thread_functions.items(): + print(f'Thread {thread}, guest/render residency samples:') + for address, count in samples.most_common(10): + print(f' sub_{address:08X}: {count}') if events: output = path.with_suffix('.trace.json') output.write_text(json.dumps({'traceEvents': events}, separators=(',', ':')) + '\n')