Runtime
Implementation-Grade Architecture for Bounded Browser-Local Large Model Ingestion and Execution
Report summary
The deployment of gigabyte-scale machine learning artifacts, specifically .slm models, into a browser-local environment introduces severe architectural challenges spanning memory bounding, asynchronous coordination, hardware-accelerated memory alignment, and durable persistence. The engineering reco
Key topics
- Runtime
- AI
- Rust
- Privacy
- Semantic Systems
- Research Archive
- Strategy
- Audit
Research provenance
For citation, use the report title and canonical URL. Archival presence does not establish authorship or promote report statements into portfolio evidence.
This page renders the archived Markdown as safe, formatted HTML. It is background research and does not become a portfolio claim without evidence review.
Full report
On this page
1. Executive Lifecycle Recommendation and Assumptions
The deployment of gigabyte-scale machine learning artifacts, specifically .slm models, into a browser-local environment introduces severe architectural challenges spanning memory bounding, asynchronous coordination, hardware-accelerated memory alignment, and durable persistence. The engineering recommendation synthesized in this report dictates a strict, single-path ingestion lifecycle relying on dedicated Web Workers, the Origin Private File System (OPFS) for durable persistence, WebAssembly (WASM) with Memory64 for deterministic execution, and WebGPU for hardware-accelerated inference. This architecture actively deprecates any legacy IndexedDB-based blob storage or main-thread parsing implementations, demanding a complete cutover to a highly controlled streaming ingestion pipeline. This analysis operates under fixed constraints and assumptions derived from the public product context. The browser-local chat application, TinyRustLM, functions entirely client-side without hosting or receiving model bytes on project websites. A model enters the system exclusively through an explicit local file selection or direct peer-to-peer transfer mediated by a local companion. Consequently, the browser must maintain exact artifact identity, ensuring that byte ownership transitions seamlessly across JavaScript, WASM boundaries, and WebGPU buffers without triggering unmanaged garbage collection pauses, out-of-memory process terminations, or main-thread locking. The browser runs a Rust-generated WebAssembly runtime where heavy loading, hashing, parsing, and inference must never freeze the interaction surface. Furthermore, persistence is treated as an explicit, user-controlled action. A model chosen for a single session must not silently become durable, and deletion claims require verifiable evidence that the owned logical object and all associated application-owned staging state are eradicated. Multi-tab coordination is strictly enforced to prevent conflicting writers or the simultaneous activation of inconsistent state. Finally, extreme privacy boundaries are assumed; prompts, outputs, agent tokens, and raw hosted-memory payloads must never enter model receipts, URLs, logs, screenshots, crash reports, service-worker caches, or public diagnostics. This report provides the definitive state machine, byte-ownership topology, and memory derivation formulas required to safely execute this lifecycle.
2. Current Standards and Browser Capability Matrix
The foundation of the application relies on rapidly evolving browser APIs. The following capability matrix delineates current standard guarantees, browser-specific implementation observations, and experimental features across the major engine lineages (Blink/Chromium, Gecko/Firefox, and WebKit/Safari) across desktop and mobile platforms.
| Capability / API | Chromium (Chrome/Edge/Android) | Gecko (Firefox) | WebKit (Safari/iOS) | Standard Guarantee vs Implementation Observation |
|---|---|---|---|---|
| Origin Private File System (OPFS) | Supported (Desktop/Mobile)1 | Supported (Desktop/Mobile)1 | Supported (Desktop/Mobile 15.2+)1 | Standard guarantee: Provides a private storage endpoint per origin, obfuscated from the user's visible file system2. |
| OPFS FileSystemSyncAccessHandle | Supported (Worker only)1 | Supported (Worker only)1 | Supported (Worker only)1 | Standard guarantee: Synchronous read/write access isolated strictly to dedicated Web Workers, preventing main-thread blocking1. |
| OPFS readwrite-unsafe mode | Supported (121+)1 | Not Supported1 | Not Supported1 | Experimental feature: Allows concurrent access handles to bypass exclusive locking. Implementation observation: Relying on this breaks Safari and Firefox compatibility1. |
| WebGPU | Supported (113+)4 | Experimental/Nightly4 | Supported (macOS/iOS 17+)4 | Standard guarantee: Low-level GPU access. Implementation observation: Fragmented driver support dictates rigorous error scope checking4. |
| WebGPU maxStorageBufferBindingSize | 128MB Default6 | 128MB Default7 | Highly Restricted (e.g., 256MB on some iOS)4 | Standard guarantee: The specification mandates a 128MB baseline. Applications must explicitly request higher limits during adapter initialization7. |
| WASM Memory64 | Supported (Requires specific BigInt API)8 | Supported8 | Supported | Standard guarantee: Allows 64-bit addressing for linear memory. Implementation observation: V8 requires the address: "i64" initialization parameter8. |
| Transferable Streams / Objects | Supported9 | Supported9 | Supported | Standard guarantee: Zero-copy transfer of ArrayBuffer ownership via postMessage, detaching the buffer in the sending thread10. |
| SharedArrayBuffer (SAB) | Supported (Requires COOP/COEP)12 | Supported (Requires COOP/COEP) | Supported (Requires COOP/COEP) | Standard guarantee: Zero-copy shared memory, rigidly gated behind cross-origin isolation headers to mitigate Spectre12. |
| Web Locks API | Supported13 | Supported | Supported | Standard guarantee: Cross-tab origin-scoped locking mechanism for resource coordination, inherently resolving deadlocks upon context crash14. |
| Storage Buckets API | Supported (122+)15 | Positive Signal16 | Unknown/Draft | Experimental API: Permits durability: 'strict' vs 'relaxed' to govern OS-level flush urgency15. |
| Storage Quota (navigator.storage.estimate) | \~60% of disk space19 | \~10% of disk space or 10GB19 | \~60% (Browser App), \~15% (Embedded)19 | Implementation observation: Quotas are obfuscated for anti-fingerprinting. The API returns a conservative estimate, not exact bytes20. |
An engineering recommendation derived directly from this capability matrix is to entirely avoid the Chromium-only readwrite-unsafe mode for OPFS, as it fragments the codebase and prohibits standard compatibility across Firefox and Safari1. Instead, the architecture must rely on standard exclusive locks managed through the Web Locks API14. Furthermore, WebGPU implementations require aggressive boundary checking, as the W3C specification mandates a strict minStorageBufferOffsetAlignment of 256 bytes6, which fundamentally dictates how tensors are packed into memory and prevents standard packed-struct mappings.
3. Byte-Ownership and Copy Topology
The ingestion of a local .slm file involves crossing multiple rigid isolation boundaries within the browser environment. At every boundary, memory is either copied, transferred (where ownership is relinquished by the sender), mapped, pinned, or viewed. The architectural imperative is to account for every byte allocation and definitively prevent silent memory copies that lead to Out-Of-Memory (OOM) process terminations. The byte ownership transitions through the following topology:
1. OS-Selected File to Browser File Object: When a user selects a file via a file input or drag-and-drop, the browser creates a File object. Standard guarantee: This represents a metadata reference to the underlying file descriptor. It does not map or load the file payload into the JavaScript heap.
2. Browser File to Blob Slice: The application utilizes the Blob.slice() method to read fixed regions (such as the header). Standard guarantee: Slicing a blob merely creates a new metadata reference with updated byte offsets; it does not duplicate the underlying physical bytes.
3. Stream Chunk to JavaScript ArrayBuffer: As the Blob.stream() is consumed by a ReadableStreamDefaultReader, the browser allocates small Uint8Array chunks within the main thread's JavaScript heap.
4. Main Thread to Dedicated Worker Memory: The main thread delegates chunks to the ingestion worker. Engineering recommendation: This must be executed using postMessage(chunk.buffer, \[chunk.buffer\]). Standard guarantee: The inclusion of the transfer array results in a zero-copy transfer of ownership. The buffer becomes entirely detached in the main thread, instantly freeing the main thread's memory footprint without waiting for garbage collection10.
5. Worker Memory to WASM Linear Memory: Implementation observation: A WebAssembly linear memory is a contiguous, isolated block. Chunks transferred to the worker cannot be natively mapped directly into the WASM memory without an explicit copy operation, unless the chunk itself is used to instantiate the WASM module, which is impossible for streaming. Therefore, a strict copy occurs via new Uint8Array(wasmMemory.buffer, offset).set(chunk).
6. Worker Memory to OPFS Staging File: Using the synchronous FileSystemSyncAccessHandle.write(chunk) method, the byte ownership is copied from the JavaScript heap into the browser's internal I/O buffer, which subsequently flushes to the OS-level file system2.
7. WASM Arena to WebGPU Staging Buffer: During model activation, tensors must be uploaded to the GPU. Standard guarantee: The device.queue.writeBuffer() method or mapping a buffer via mapAsync() requires copying from the WASM linear memory into a CPU-side GPU staging buffer. The graphics driver then executes a Direct Memory Access (DMA) transfer to the GPU21.
8. WebGPU Staging to GPU Storage Buffer: Managed entirely by the graphics driver. The memory is now resident in VRAM and detached from the JavaScript/WASM heap context.
To maintain bounded memory, the pipeline must implement a strict backpressured ring-buffer approach. Once a chunk is copied into WASM memory and written to OPFS, the JavaScript ArrayBuffer reference must be explicitly discarded.
4. Ingestion, Activation, Persistence, Switching, and Deletion State Machine
The loading of a massive multi-gigabyte artifact requires a highly resilient, interruptible state machine. The application must treat model ingestion as a transactional operation featuring explicitly defined legal transitions and idempotent retry points.
- idle: The baseline state. No active model is loaded. Background dedicated workers are initialized and awaiting input messages.
- file\_selected: The user interface acquires a File object. The application immediately requests an exclusive Web Lock (navigator.locks.request) to ensure no other tab or worker initiates a concurrent ingestion that could corrupt the staging environment14.
- metadata\_preflight: A bounded 4KB slice of the file is read to extract the structural header, tensor dimensions, and magic bytes. Bounded structural validation is executed in WASM.
- allocation\_reservation: Utilizing the preflight metadata, peak memory formulas are calculated against device capabilities (queried via navigator.storage.estimate()20 and WebGPU device.limits7). The transition to the subsequent state only proceeds if hardware resources are deemed sufficient.
- payload\_transfer: A continuous streaming hash pass commences. Chunks are transferred to the worker, cryptographically hashed, and simultaneously streamed into an OPFS staging file (e.g., .slm\_staging.tmp). This is an idempotent retry point; if the transfer fails, the staging file can be safely overwritten on the next attempt.
- validation\_commit: The final computed streaming hash is compared against the declared header hash. If successful, the file is structurally and cryptographically sound. A candidate state is isolated.
- optional\_persistence: If the user has explicitly granted persistence for this session, the OPFS staging file is atomically renamed to a content-addressed final name (e.g., model\_\<hash\>.slm). This is achieved by updating an IndexedDB pointer to reference the new OPFS file name. If persistence is declined, the staging file remains marked for session-only cleanup.
- activation: The candidate state is committed. The active WASM instance mounts the validated model, initializes the tokenizer, and allocates an empty Key-Value (KV) cache for inference.
- active\_use: The model is actively serving chat requests.
- cancellation / failure: Any error during transfer, quota exhaustion, or validation routes here. The staging file is immediately unlinked, WASM memory is logically zeroed, and the exclusive Web Lock is released.
- switching: A request to change models. Current text generation is halted, GPU buffers are aggressively destroyed via GPUBuffer.destroy()23, and the state machine returns to file\_selected or active\_use (if loading a pre-persisted OPFS model).
- deletion: An explicit user request to wipe the model. All active worker handles are closed, OPFS entries are unlinked, and IDB metadata is purged.
- recovery: On application startup, an orphan discovery routine identifies OPFS files lacking IndexedDB references (resulting from a previous hard crash) and deletes them.
5. Preflight Algorithm and Checked Resource Formulas
Before committing to gigabytes of memory allocation, the system must execute a bounded two-stage preflight to protect the browser process from out-of-memory terminations and malicious payloads. The first stage is the fixed-header preflight. The worker requests only a maximum 4KB slice of the Blob via blob.slice(0, 4096).stream(). This precise slice contains the .slm magic bytes, version metadata, tensor shapes, and byte offsets. The Rust WASM module parses this header utilizing strict checked arithmetic to prevent integer overflows. Integer overflows represent a known and historically exploited vulnerability pattern in browser engines (e.g., CVE-2013-6632 SMI Overflows in TypedArray allocations)24. If the declared tensor offsets exceed the declared file size, or if computed dimensions yield impossible allocations, the payload is rejected instantly. The second stage dictates the derivation of peak memory. Browser memory limits are implementation-dependent and must not be substituted with an invented universal per-tab limit. Instead, formulas must dictate admission. Externally sourced facts indicate that WebGPU enforces rigorous alignment rules; specifically, minStorageBufferOffsetAlignment is universally guaranteed to be 256 bytes6. Therefore, tensor allocations must be mathematically padded to match this alignment before calculating peak footprint. The peak memory equation [Figure omitted from source export] is derived as follows: [Figure omitted from source export] Where the individual components are defined as:
- [Figure omitted from source export] (This accounts for double buffering for the streaming worker, for instance, [Figure omitted from source export]).
- [Figure omitted from source export] (Engineering recommendation: Original tensor bytes are strictly not retained in WASM memory if they are uploaded to the GPU, preventing [Figure omitted from source export] from illegally duplicating [Figure omitted from source export]).
- [Figure omitted from source export] (Each individual tensor is explicitly padded to 256-byte alignment to satisfy the WebGPU specification6).
- [Figure omitted from source export] (Batch size [Figure omitted from source export] Layers [Figure omitted from source export] Heads [Figure omitted from source export] Head Dimension [Figure omitted from source export] bytes per fp16 float).
- [Figure omitted from source export] (The maximum size of a single tensor during the sequential upload copy phase to prevent VRAM spikes).
- [Figure omitted from source export] (Accounts for browser JavaScript engine overhead, JIT compilation heuristics, and DOM renderer demands25).
The transition to a full streaming validation and hash pass only commences if [Figure omitted from source export] is securely below the available device capabilities reported by navigator.storage.estimate()20 and the queried maxStorageBufferBindingSize limits of the GPUDevice7.
6. Worker Protocol, Backpressure, Cancellation, and Stale-Message Defense
To maintain UI responsiveness, all heavy ingestion, hashing, and WASM interaction must occur in a dedicated Web Worker. Comparing loading topologies reveals that direct main-thread reads fatally freeze the interaction surface, while shared workers lack OPFS synchronous access capabilities across all major browsers3. Therefore, the dedicated worker pattern with transferable streams is the only viable topology. The communication protocol between the main thread (Producer) and the dedicated worker (Consumer) requires a strict implementation featuring sequence numbers, bounded chunk sizes, and backpressure to prevent the rapid accumulation of unprocessed ArrayBuffers in the worker's event loop queue, which would otherwise induce silent memory leaks. Engineering recommendation: Specify a bounded chunk size of 4MB and a maximum queue depth (MAX\_INFLIGHT) of 2\. The pseudocode for the producer (main thread) and consumer (worker) paths demonstrates this backpressure:
JavaScript // Producer (Main Thread) Pseudocode let sequence\_number \= 0; let ack\_sequence \= 0; const MAX\_INFLIGHT \= 2; const current\_generation \= crypto.randomUUID();
worker.onmessage \= (msg) \=\> { if (msg.generation \!== current\_generation) return; // Stale message defense if (msg.type \=== 'ACK') { ack\_sequence \= msg.seq; readNextChunk(); // Resume reading if backpressure is relieved } else if (msg.type \=== 'ERROR') { cancelIngestion(msg.error\_code); } };
function pump(stream) { if (sequence\_number \- ack\_sequence \>= MAX\_INFLIGHT) return; // Wait for ACK stream.read().then(({done, value}) \=\> { if (done) return worker.postMessage({type: 'EOF', generation: current\_generation}); sequence\_number++; worker.postMessage( {type: 'CHUNK', seq: sequence\_number, generation: current\_generation, payload: value.buffer}, \[value.buffer\] // Zero-copy transfer of ownership ); pump(stream); // Recurse }); }
JavaScript // Consumer (Worker) Pseudocode let active\_generation \= null;
self.onmessage \= (msg) \=\> { if (msg.type \=== 'START') { active\_generation \= msg.generation; } if (msg.generation \!== active\_generation) { // Discard stale message; transferred buffer is automatically garbage collected return; } if (msg.type \=== 'CHUNK') { processChunkInWasm(msg.payload); writeChunkToOPFS(msg.payload); self.postMessage({type: 'ACK', seq: msg.seq, generation: active\_generation}); } };
Cancellation and stale-message defense are critical. Because workers operate asynchronously, a user might rapidly switch models, implicitly sending a cancellation token to the worker. Due to the event loop architecture, old chunks from a prior load generation might still be enqueued when the worker begins processing the new model. The engineering recommendation is to mandate that every ingestion session generates a unique generation\_id. The worker validates this ID on every incoming message; stale messages are rejected instantly, preventing cumulative state corruption.
7. WASM Memory and Allocator Design
WebAssembly linear memory is a contiguous array of bytes that inherently grows in 64KiB pages26. The management of this memory fundamentally dictates the stability of the browser process. Comparing exact pre-sizing against bounded growth reveals a critical architectural hazard. Implementation observation: When a WASM module executes a memory.grow instruction, the browser's JavaScript engine (such as V8 or SpiderMonkey) may be forced to reallocate the underlying continuous memory block. When this reallocation occurs, all previously created JavaScript Uint8Array views into the WASM memory are instantaneously detached. Any subsequent JavaScript access to these detached views throws a fatal TypeError27. Therefore, the engineering recommendation mandates exact pre-sizing. Based on the Stage 2 Preflight, the exact required WASM page count must be calculated, and the WASM memory must be instantiated with an initial size equal to this maximum requirement, with dynamic growth explicitly prohibited during active inference. For models where the required WASM memory strictly exceeds 4GB—a hard limit imposed by standard 32-bit addressing—the application must utilize the memory64 WebAssembly extension27. Implementation observation: When instantiating a Memory64 object in JavaScript, parameters must explicitly declare the address type as a 64-bit integer. Recent specification updates require the address: "i64" parameter, as V8 correctly rejects BigInt memory initializations missing this explicit typing8:
JavaScript const wasmMemory \= new WebAssembly.Memory({ initial: BigInt(calculated\_pages), maximum: BigInt(calculated\_pages), address: "i64", shared: false });
The use of shared memory via shared: true (SharedArrayBuffer) is prohibited by the project constraints unless cross-origin isolation headers (COOP/COEP) are perfectly maintained on the host12. Given that TinyRustLM demands zero-configuration local deployment, relying on SharedArrayBuffers introduces unacceptable brittleness. Segmented application-level address spaces via standard ArrayBuffers transferred to the worker represent a vastly superior and universally supported topology for local-first deployments.
8. OPFS, IndexedDB, Cache Storage, and Native-Store Role Matrix
Browser storage mechanisms serve fundamentally different purposes, possess divergent performance characteristics, and must be strictly partitioned to prevent catastrophic degradation.
| Storage API | Permitted Role in Architecture | Engineering Rationale & Prohibition |
|---|---|---|
| Origin Private File System (OPFS) | Heavy Model Bytes (.slm), Staging Journals | Provides the only synchronous, high-performance FileSystemSyncAccessHandle for sequential reads without main-thread blocking1. |
| IndexedDB (IDB) | Metadata, Receipts, KV configurations, Pointers to OPFS files | Capable of storing structured data and supporting atomic transactions. Strictly banned from storing raw model bytes due to 100MB+ performance degradation and documented Safari stack-overflow bugs3. |
| Cache Storage | Application assets (HTML, CSS, JS, WASM binaries) | Used exclusively by the Service Worker for offline app loading. Banned from storing model bytes because an HTTP cache hit cannot cryptographically prove possession of a complete verified model payload. |
| Native Companion Storage | P2P mediation, bypassing browser limits if authorized | Explicit out-of-band application. The browser must never assume native storage exists without an explicitly authorized local port connection. |
Optional OPFS persistence must be designed with strict atomicity guarantees. Fact: OPFS is not a native memory-mapped (mmap) file system2. Utilizing FileSystemSyncAccessHandle.write() copies data to an OS-level buffer. Invoking FileSystemSyncAccessHandle.flush() is required to force the OS to commit the buffer to the physical disk2. By default, opening a file in OPFS takes an exclusive lock3. If a tab crashes while holding a lock, the file remains locked until the browser's internal garbage collection resolves the orphaned worker. To achieve atomic updates without relying on the experimental, Chromium-only readwrite-unsafe mode1, the architecture must write to a staging file (e.g., .slm\_staging), invoke flush(), invoke close(), and only then execute an IndexedDB transaction that updates the "active model" pointer to the new OPFS file name. Where applicable, the experimental Storage Buckets API can govern eviction urgency. For instance, temporary staging models can be initialized in a bucket with durability: 'relaxed' to improve write performance at the risk of power-loss dropping, while permanently persisted models utilize durability: 'strict'15.
9. Atomic Activation, Rollback, Restart, and Multi-Tab Coordination
A paramount requirement is that a failed candidate model must not corrupt the active model, tokenizer, or conversation state. Furthermore, multiple tabs running the application must coordinate so they do not simultaneously attempt to replace or delete the active artifact. Multi-tab coordination is definitively solved utilizing the standard Web Locks API (navigator.locks)14. When a tab intends to ingest or delete a model, it must request an exclusive lock:
JavaScript navigator.locks.request("tinyrustlm\_model\_writer", { mode: 'exclusive', ifAvailable: true }, async (lock) \=\> { if (\!lock) throw new Error("Another context is currently modifying the model state."); // Proceed with staging ingestion or deletion });
Standard guarantee: If the tab holding the lock crashes or is terminated by the OS, the browser automatically releases the lock, inherently preventing deadlocks14. The controversial steal: true option30 should only be utilized as a fallback if a Service Worker strictly determines a backgrounded tab has irrevocably hung and user interaction explicitly demands an override13. Atomic activation and rollback are achieved by isolating the candidate state from the active state. Validation builds a candidate state in the staging OPFS file. The commit point strictly binds the model hash, tokenizer version, chat template, runtime backend, sampling defaults, and an empty composition-bound KV cache into a single IndexedDB transaction. Failure before this commit point safely unlinks the candidate OPFS file, discarding the state. Failure after the commit point triggers a rigorously specified last-known-good strategy, reverting the IDB pointer to the previously known model hash.
10. Privacy and Exact Network Policy
A strict requirement of the architecture is that prompts, outputs, and model bytes must never leave the local browser environment. Proving this requires rigorous architectural restrictions enforced at the browser level. The application must implement a strict Content Security Policy (CSP) delivered via HTTP headers or \<meta\> tags to deny unexpected third-party uploads:
HTTP Content-Security-Policy: default-src 'self'; connect-src 'self'; script-src 'self' 'wasm-unsafe-eval'; worker-src 'self';
Fact: The 'wasm-unsafe-eval' directive is strictly required to compile and execute WebAssembly modules in modern browsers31. By aggressively omitting external domains in the connect-src directive, the browser actively blocks fetch, XHR, WebSocket, EventSource, WebTransport, and beacons from reaching third-party servers. To validate the absence of implicit telemetry, the architecture dictates intercepting all outbound network requests via a Service Worker. Any FetchEvent.respondWith()33 must strictly serve from Cache Storage or pass-through directly to 'self'. Furthermore, monitoring CSP violation reports ensures that no stealth tracking pixels or rogue source map requests attempt to reach external telemetry endpoints, ensuring raw hosted-memory payloads never enter service-worker caches or public diagnostics.
11. Memory-Pressure and Page-Lifecycle Behavior
Browsers, particularly on mobile platforms like iOS Safari and Android Chrome, aggressively suspend or discard background tabs to reclaim memory under OS-level pressure. The architecture must not promise reliable callbacks at process death, as unload or beforeunload events are historically unreliable and frequently bypassed by the OS. Standard guarantee: A tab transitioning to the background may have its WebGPU device abruptly revoked to free VRAM for the foreground application. This results in a GPUDevice.lost promise resolving with the reason unknown or destroyed35. To handle extreme memory pressure and page lifecycle events:
1. Resumption & Recovery: The application listens to the document.wasDiscarded boolean upon page reload36. If true, the application seamlessly restores the conversation state from IndexedDB without prompting the user.
2. Worker Termination: If a dedicated worker is forcefully terminated during a partial OPFS write, the Web Lock is released. The application detects the incomplete write on the next launch.
3. Orphan Discovery: Because temporary OPFS files might be abandoned during a sudden process kill, the initialization sequence always iterates through the OPFS root directory. Any file matching the .tmp staging extension that lacks a corresponding IndexedDB receipt, or represents an incomplete transaction, is systematically unlinked.
12. Fault-Injection and Cross-Browser Automation Matrix
The architecture must be verified through a robust Test-Driven Development (TDD) fault-injection matrix utilizing Playwright or Puppeteer to validate edge cases across Chromium, Firefox, and WebKit37. The required test vectors include:
- Structural Fixtures: Load a 1MB sparse .slm file featuring valid headers but zeroed payload bytes to verify ingestion state machine logic without heavy payload timing.
- Corrupted Header: Mutate the 4KB header to intentionally trigger a checked-arithmetic panic. Verify the state machine cleanly reverts to idle.
- Late Hash Mismatch: Modify the final byte of a real admitted artifact. The streaming hash will fail. Verify the temporary OPFS file is deleted and the active model is not partially replaced.
- Quota Exhaustion: Utilize Chrome DevTools' "Simulate custom storage quota"38 to trigger a QuotaExceededError during FileSystemSyncAccessHandle.write(). Verify clean rollback and error surfacing.
- Web Lock Contention: Open two headless browser contexts. Context A initiates ingestion. Context B attempts ingestion. Verify Context B is rejected gracefully due to exclusive lock contention.
- Device Loss: Simulate a TDR (Timeout Detection and Recovery) event forcing GPUDevice.lost35. Verify the WASM runtime recovers or halts safely without memory leaks.
- Model Switch Loops: Rapidly switch between two models to verify the worker generation UUID stale-message defense correctly discards lagging chunks.
13. Public-Safe Receipt Schema
To provide concrete evidence of state transitions, deletion results, and ingestion success without logging sensitive payloads, the application generates a rigidly defined JSON receipt. This schema strictly excludes model bytes, prompts, private paths, secrets, invitation URLs, and raw browser storage dumps.
JSON { "event": "INGESTION\_SUCCESS", "artifact\_hash": "sha256-8a9f...", "byte\_size": 1048576000, "browser\_engine": "Blink", "wasm\_memory\_pages\_allocated": 16384, "webgpu\_max\_buffer\_used": 134217728, "transition\_state": "activation\_commit", "timestamp": 1722525137 }
This receipt serves as exact evidence for deletion claims as well, logging the precise byte counts freed and bounded error codes encountered during the OPFSDirectoryHandle.removeEntry() operation, ensuring verifiable auditing without compromising user privacy.
14. TDD Backlog and Clean Cutover Criteria
Because the application is pre-publication, the development sequence must prioritize a clean cutover to this formalized architecture, explicitly prohibiting the retention of legacy loaders, fallback readers, or dual storage contracts for unreleased behavior. The TDD implementation sequence must follow this progression:
1. Establish the Service Worker and CSP to definitively guarantee the network sandbox and privacy assertions.
2. Implement the Stage-1 Fixed-Header preflight parser in Rust/WASM, backed by tests injecting corrupted headers.
3. Implement the main-thread to worker chunking protocol featuring the MAX\_INFLIGHT backpressure logic and generation UUIDs.
4. Implement the OPFS FileSystemSyncAccessHandle writer and the streaming hash verification, gated by browser-specific support checks.
5. Implement the Web Locks coordination and IndexedDB atomic pointer swap.
The superseded unpublished loader and storage path must be permanently deleted when the stop conditions are met. The exact cutover criteria are defined as:
- The new ingestion pipeline successfully streams a multi-gigabyte artifact into OPFS across Chrome, Firefox, and Safari on desktop without triggering a main-thread freeze exceeding 50ms.
- The memory.grow detachment protection is proven via automated testing (yielding zero TypeError: detached ArrayBuffer errors during model execution).
- The model switching semantics are verified via memory profiling to release VRAM immediately upon invoking GPUBuffer.destroy()23.
15. Unknowns Requiring Local Verification
As an independent architect without access to the private application source code, specific variables require authorized local verification by the internal engineering team:
1. Rust Arena Allocator Overhead: The exact internal fragmentation overhead of the Rust wee\_alloc or dlmalloc implementation utilized inside the WASM environment remains unknown. This will slightly modify the [Figure omitted from source export] variable in the peak memory formula, requiring local profiling to establish the precise safety margin.
2. WebGPU Driver Stability on Mobile: While Safari formally supports WebGPU on iOS 175, the precise threshold at which the iOS kernel aggressively jetsams the WebKit process for VRAM spikes must be empirically tested with the specific .slm tensor shapes to prevent silent crashing.
3. Storage Bucket Expiration: Verification is required to determine whether Chromium's Draft Storage Buckets API (durability: 'strict')15 introduces measurable latency that negatively impacts the streaming ingestion rate compared to the default OPFS best-effort flush.
16. Primary Source Literature Review
The assertions within this report are derived from a rigorous analysis of current primary documentation and living standards. The foundation of the file system architecture relies on the W3C File System Access API specifications, specifically the integration of the Origin Private File System and FileSystemSyncAccessHandle designed for synchronous, high-performance worker execution1. Observations regarding readwrite-unsafe modes are documented in Chromium issue trackers and experimental origin trial logs1. Memory derivations for WebGPU are strictly dictated by the W3C WebGPU Working Draft (updated 2025/2026), which rigidly defines adapter limits, maxStorageBufferBindingSize, and the critical 256-byte minStorageBufferOffsetAlignment6. The handling of WebAssembly linear memory, specifically the Memory64 proposal and the catastrophic detachment of JavaScript array views upon memory.grow, is sourced from the WebAssembly Core Specification and V8 implementation notes8. Multi-tab coordination strategies are verified against the W3C Web Locks API specification, detailing the lifecycle of exclusive locks and the resolution of deadlocks upon agent termination13. Finally, the overarching privacy and storage quota mechanics are informed by the WHATWG HTML Living Standard and MDN Web Docs compatibility matrices, ensuring all recommended boundaries align with immutable platform guarantees19.
Works cited
1. FileSystemFileHandle: createSyncAccessHandle() method \- Web APIs | MDN, https://developer.mozilla.org/en-US/docs/Web/API/FileSystemFileHandle/createSyncAccessHandle
2. Origin private file system \- Web APIs | MDN, https://developer.mozilla.org/en-US/docs/Web/API/File\_System\_API/Origin\_private\_file\_system
3. The Current State Of SQLite Persistence On The Web: May 2026 Update \- PowerSync, https://powersync.com/blog/sqlite-persistence-on-the-web
4. WebGPU bugs are holding back the browser AI revolution | by Marcelo Emmerich | Medium, https://medium.com/@marcelo.emmerich/webgpu-bugs-are-holding-back-the-browser-ai-revolution-27d5f8c1dfca
5. Running Language Models Directly in the Browser | by Jaime Garcia Diaz \- Medium, https://medium.com/@garciadiazjaime/running-language-models-directly-in-the-browser-0e869bea8933
6. WebGPU \- W3C, https://www.w3.org/TR/webgpu/
7. GPUSupportedLimits \- Web APIs | MDN, https://developer.mozilla.org/en-US/docs/Web/API/GPUSupportedLimits
8. Discrepancy in Handling of BigInt in WebAssembly.Memory Initialization \[377213711\] \- Chromium Issue, https://issues.chromium.org/issues/377213711
9. Intent to Ship: Streams API: transferable streams \- Google Groups, https://groups.google.com/a/chromium.org/g/blink-dev/c/1LStSgBt6AM
10. Web Platform APIs \- Deno Docs, https://docs.deno.com/api/web/about/
11. Using Web Workers \- Web APIs \- MDN Web Docs, https://developer.mozilla.org/en-US/docs/Web/API/Web\_Workers\_API/Using\_web\_workers
12. Window: postMessage() method \- Web APIs | MDN, https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage
13. Web Locks API \- W3C, https://www.w3.org/TR/web-locks/
14. Web Locks API \- MDN Web Docs \- Mozilla, https://developer.mozilla.org/en-US/docs/Web/API/Web\_Locks\_API
15. Not all storage is created equal: introducing Storage Buckets | Blog \- Chrome for Developers, https://developer.chrome.com/docs/web-platform/storage-buckets
16. standards-positions/activities.yml at main · mozilla/standards-positions \- GitHub, https://github.com/mozilla/standards-positions/blob/main/activities.yml
17. Mozilla Standards Positions, https://mozilla.github.io/standards-positions/
18. Storage Buckets \- GitHub Pages, https://wicg.github.io/storage-buckets/explainer.html
19. Storage quotas and eviction criteria \- Web APIs \- MDN Web Docs, https://developer.mozilla.org/en-US/docs/Web/API/Storage\_API/Storage\_quotas\_and\_eviction\_criteria
20. StorageManager: estimate() method \- Web APIs | MDN, https://developer.mozilla.org/en-US/docs/Web/API/StorageManager/estimate
21. Slug text rendering with WebGPU and Rust, https://gabdube.github.io/articles/rust\_slug/rust\_slug.html
22. wgpu package \- github.com/gogpu/wgpu \- Go Packages, https://pkg.go.dev/github.com/gogpu/wgpu@v0.30.22
23. WebGPU Explainer, https://gpuweb.github.io/gpuweb/explainer/
24. 101 Chrome Exploitation — Part 2: Common Browser Vulnerability Patterns \- Operation Zero, https://opzero.ru/en/press/101-chrome-exploitation-part-2-common-browser-vulnerability-patterns/
25. WebAssembly Limitations | qouteall notes, https://qouteall.fun/qouteall-blog/2025/WebAsembly%20Limitations
26. Efficient and Safe Integration of User-Defined Operators into Modern Database Systems, https://d-nb.info/1318627222/34
27. Weaver: Fuzzing JavaScript Engines at the JavaScript-WebAssembly Boundary \- arXiv, https://arxiv.org/html/2603.18789
28. WASM | HardCaml Wiki \- GitBook, https://ocamlstreet.gitbook.io/hardcaml-wiki/wasm
29. File System API \- MDN Web Docs, https://developer.mozilla.org/en-US/docs/Web/API/File\_System\_API
30. web-locks/EXPLAINER.md at main \- GitHub, https://github.com/w3c/web-locks/blob/main/EXPLAINER.md
31. Content Security Policy \- Mozilla \- MDN Web Docs, https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/Content\_Security\_Policy
32. Content-Security-Policy: script-src directive \- HTTP \- MDN Web Docs, https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Headers/Content-Security-Policy/script-src
33. Index \- Web APIs, https://udn.realityripple.com/docs/Web/API/Index
34. UDN Search, http://udn.realityripple.com/search?q=request
35. WebGPU \- W3C, https://www.w3.org/TR/2021/WD-webgpu-20211220/
36. Page Lifecycle API | Web Platform \- Chrome for Developers, https://developer.chrome.com/docs/web-platform/page-lifecycle-api
37. WebRunner | A framework for Web automation \- GitHub Pages, https://integration-automation.github.io/WebRunner/
38. Storage for the web | Articles, https://web.dev/articles/storage-for-the-web