Repository navigation
fix(wasm): Stop buffering whole files in tab memory on StorageFile writes - #23880
ramezgerges merged 25 commits into
Conversation
_length compounded on every write (+= of a Max) instead of tracking the actual stream end, and SetLength wrote a stray zero byte at the current position when extending. File System Access truncate() both shrinks and zero-pad extends, so use it for both directions. Co-Authored-By: Claude Fable 5 <[email protected]>
An exception escaping the async void Dispose (e.g. an allocation failure during the final copy) is fatal to the runtime, and a failed copy leaked the cache file (~file size of in-memory FS space). Co-Authored-By: Claude Fable 5 <[email protected]>
Replace per-byte JS loops with single HEAPU8.slice copies in the native write stream and SaveAs, drop the dead _buffer field, and revoke the download object URL (previously pinned the whole blob until page close). Co-Authored-By: Claude Fable 5 <[email protected]>
(int)stream.Length silently overflowed past 2GB. Co-Authored-By: Claude Fable 5 <[email protected]>
NativeWriteStream cached the whole payload in a single MEMFS file, i.e. one contiguous JS ArrayBuffer. Chromium caps a single ArrayBuffer between 1.5 and 2 GiB regardless of available memory, and MEMFS grows by reallocate-and-copy (~2.1x transient peaks), so large saves failed deterministically around 2 GB and flakily under memory pressure, taking down the runtime. The cache is now a JS-side list of 2 MB chunks: no contiguous allocation, no growth spikes, and no data in the WASM linear memory. Flushes now copy only the dirty range instead of rewriting the whole target, and the read stream used to stage existing content is no longer leaked. Co-Authored-By: Claude Fable 5 <[email protected]>
The fallback save picker staged content in a MEMFS temp file (one contiguous JS ArrayBuffer, persisted to IndexedDB), then read it all into a single managed byte[] in the 32-bit WASM heap (hard 2 GB cap) and copied it once more into a JS Uint8Array for the Blob - a ~3x peak across three memory pools. The picker now hands out a StorageFile backed by the chunked JS buffer, and CompleteUpdatesAsync builds the download Blob directly from the chunks: no managed materialization, no MEMFS file, no IndexedDB persistence, no 2 GB ceiling. Note: the fallback file no longer has a real path on the in-memory filesystem; access it via storage APIs rather than System.IO on .Path. Co-Authored-By: Claude Fable 5 <[email protected]>
Buffer views opened with FileAccessMode.Read now refuse writes; ownership (lifetime) and writability (access mode) are independent. Co-Authored-By: Claude Fable 5 <[email protected]>
Manual sample streaming up to 4 GB through OpenStreamForWriteAsync in 2 MB chunks, via the save picker, app storage, and a real file copy - with a JS-heap readout to observe the write path's memory behavior on WebAssembly. Co-Authored-By: Claude Fable 5 <[email protected]>
New files were written with LF endings, tripping IDE0055 on analyzer-enabled builds. Also remove the hand-written .js/.d.ts siblings for NativeChunkedBuffer - the build compiles ts/ sources into the single bundled output; per-file artifacts are stale editor leftovers, not a convention to follow. Co-Authored-By: Claude Fable 5 <[email protected]>
The TypeScript build compiles ts/**/*.ts into a single bundled output; the per-file .js files were editor compile-on-save artifacts committed over time and are referenced by nothing. Co-Authored-By: Claude Fable 5 <[email protected]>
Cross-project TypeScript typing flows through the bundled js/Uno.Wasm.d.ts (see Uno.UI tsconfig include); the per-file declaration files next to their .ts sources were editor artifacts consumed by nothing. Co-Authored-By: Claude Fable 5 <[email protected]>
The download-picker buffer held the payload for the page's lifetime (it is only freed by DeleteAsync, which nothing calls) while the Blob kept a second copy, so each save cost ~2x the file size and never gave it back. The chunks are now dropped as soon as the Blob owns the data, and the previous save's object URL is revoked when a new save starts instead of only on its 40s backstop timer - at most one payload is resident at a time. Co-Authored-By: Claude Fable 5 <[email protected]>
WasmConfiguration is a global that other picker samples mutate, so which path a save takes was invisible. The sample now reports the effective mode, allows forcing the download fallback, and restores the default when unloaded. Co-Authored-By: Claude Fable 5 <[email protected]>
Committing a save built one Blob holding the whole payload. Browsers cap blob storage, and an oversized blob is marked broken, so the download fails with a bare "network error" - reported on Brave for 2GB+ saves, which always take this path since Brave does not expose the File System Access picker. The payload is now streamed into an origin-private (OPFS) file, with each staged chunk released as it lands on disk, and the download is served from that file - a File handle references the stored file rather than copying it, so nothing file-sized is held in memory or blob storage. Falls back to the previous Blob when OPFS is missing. Co-Authored-By: Claude Fable 5 <[email protected]>
The staged file was removed as soon as the next save started, or after 40s - both can happen while the browser is still reading a multi-GB download out of it, which fails the download with a bare network error. Entries are now namespaced per page session: a save reclaims leftovers from previous sessions (the payload counts against the origin quota, which is only 2 GB in some browsers) but never touches one that may still be downloading, and the current entry is held for 15 minutes. The sample's picker-mode readout also used __WASM__, which is not defined on the Skia WebAssembly head, so it always reported the platform picker and the fallback toggle did nothing. Co-Authored-By: Claude Fable 5 <[email protected]>
There was a problem hiding this comment.
Pull request overview
This PR targets WebAssembly StorageFile write paths to avoid buffering entire files in browser tab memory during OpenStreamForWriteAsync()/CompleteUpdatesAsync(), enabling multi‑GB saves without crashing due to ArrayBuffer/WASM heap limits.
Changes:
- Replace per-byte heap copies with single bulk copies (
HEAPU8.slice) in TS interop write/download paths. - Introduce a JS-backed, chunked staging buffer and a managed
Streamwrapper to keep large payloads out of contiguous allocations and the WASM heap. - Remove stale compiled
.js/.d.tssiblings undersrc/Uno.UWP/ts/and add a manual SamplesApp validation page.
Cross-cutting note: the PR description references a private issue (unoplatform/kahua-private#526) rather than a public, fully-qualified GitHub issue URL; this will need to be adjusted to match the repository’s PR issue-linking requirements.
Reviewed changes
Copilot reviewed 24 out of 38 changed files in this pull request and generated 3 comments.
Show a summary per file
| File | Description |
|---|---|
| src/Uno.UWP/ts/Windows/Storage/Streams/NativeFileWriteStream.ts | Bulk-copy from WASM heap before write() await |
| src/Uno.UWP/ts/Windows/Storage/Streams/NativeFileWriteStream.js | Remove stale compiled artifact |
| src/Uno.UWP/ts/Windows/Storage/Streams/NativeFileWriteStream.d.ts | Remove stale compiled artifact |
| src/Uno.UWP/ts/Windows/Storage/Streams/NativeFileReadStream.js | Remove stale compiled artifact |
| src/Uno.UWP/ts/Windows/Storage/Streams/NativeFileReadStream.d.ts | Remove stale compiled artifact |
| src/Uno.UWP/ts/Windows/Storage/Streams/NativeChunkedBuffer.ts | New JS chunked buffer + OPFS-backed download path |
| src/Uno.UWP/ts/Windows/Storage/StorageFolder.js | Remove stale compiled artifact |
| src/Uno.UWP/ts/Windows/Storage/StorageFolder.d.ts | Remove stale compiled artifact |
| src/Uno.UWP/ts/Windows/Storage/Pickers/NativeFilePickerAcceptTypeItem.js | Remove stale compiled artifact |
| src/Uno.UWP/ts/Windows/Storage/Pickers/NativeFilePickerAcceptTypeItem.d.ts | Remove stale compiled artifact |
| src/Uno.UWP/ts/Windows/Storage/Pickers/NativeFilePickerAcceptType.js | Remove stale compiled artifact |
| src/Uno.UWP/ts/Windows/Storage/Pickers/NativeFilePickerAcceptType.d.ts | Remove stale compiled artifact |
| src/Uno.UWP/ts/Windows/Storage/Pickers/FolderPicker.Native.js | Remove stale compiled artifact |
| src/Uno.UWP/ts/Windows/Storage/Pickers/FolderPicker.Native.d.ts | Remove stale compiled artifact |
| src/Uno.UWP/ts/Windows/Storage/Pickers/FileSavePicker.ts | Bulk-copy + revoke download URL on delay |
| src/Uno.UWP/ts/Windows/Storage/Pickers/FileSavePicker.js | Remove stale compiled artifact |
| src/Uno.UWP/ts/Windows/Storage/Pickers/FileSavePicker.d.ts | Remove stale compiled artifact |
| src/Uno.UWP/ts/Windows/Storage/Pickers/FileOpenPicker.js | Remove stale compiled artifact |
| src/Uno.UWP/ts/Windows/Storage/Pickers/FileOpenPicker.d.ts | Remove stale compiled artifact |
| src/Uno.UWP/ts/Windows/Storage/NativeStorageItemInfo.js | Remove stale compiled artifact |
| src/Uno.UWP/ts/Windows/Storage/NativeStorageItemInfo.d.ts | Remove stale compiled artifact |
| src/Uno.UWP/ts/Windows/Storage/NativeStorageItem.js | Remove stale compiled artifact |
| src/Uno.UWP/ts/Windows/Storage/NativeStorageItem.d.ts | Remove stale compiled artifact |
| src/Uno.UWP/ts/Windows/Storage/NativeStorageFolder.js | Remove stale compiled artifact |
| src/Uno.UWP/ts/Windows/Storage/NativeStorageFolder.d.ts | Remove stale compiled artifact |
| src/Uno.UWP/ts/Windows/Storage/NativeStorageFile.js | Remove stale compiled artifact |
| src/Uno.UWP/ts/Windows/Storage/NativeStorageFile.d.ts | Remove stale compiled artifact |
| src/Uno.UWP/ts/Windows/Storage/ApplicationDataContainer.js | Remove stale compiled artifact |
| src/Uno.UWP/ts/Windows/Storage/ApplicationDataContainer.d.ts | Remove stale compiled artifact |
| src/Uno.UWP/Storage/Streams/Internal/NativeWriteStreamAdapter.wasm.cs | Fix length accounting / SetLength behavior (and queue interaction) |
| src/Uno.UWP/Storage/Streams/Internal/NativeWriteStream.wasm.cs | Stage writes in chunked buffer + partial flush to target |
| src/Uno.UWP/Storage/Streams/Internal/ChunkedBufferStream.wasm.cs | New managed Stream over JS chunked buffer |
| src/Uno.UWP/Storage/StorageFile.downloadPicker.wasm.cs | New download-picker StorageFile backed by chunked buffer |
| src/Uno.UWP/Storage/Pickers/FileSavePicker.wasm.cs | Download fallback now returns chunked-buffer-backed file |
| src/Uno.UWP/Storage/CachedFileManager.wasm.cs | Await download commit via chunked buffer (no managed byte[] materialization) |
| src/Uno.UWP/js/Uno.Wasm.d.ts | Add typings for NativeChunkedBuffer, update write stream typing |
| src/SamplesApp/SamplesApp.Samples/Windows_Storage/Pickers/FileSavePicker_LargeFileWrite.xaml.cs | Manual sample to exercise large streaming saves |
| src/SamplesApp/SamplesApp.Samples/Windows_Storage/Pickers/FileSavePicker_LargeFileWrite.xaml | UI for manual large-save validation |
Comments suppressed due to low confidence (1)
src/Uno.UWP/Storage/Streams/Internal/ChunkedBufferStream.wasm.cs:105
- Same disposal concern as Read(): Write should throw ObjectDisposedException when the stream has been disposed, to match the repo’s stream patterns and to avoid invoking JS interop on a released buffer.
public override void Write(byte[] buffer, int offset, int count)
{
if (!_canWrite)
{
throw new NotSupportedException("This stream was opened for read access only.");
}
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
ProcessPendingAsync iterated the queue without draining it, so every queued operation was replayed on each later write, truncate or close - and since those operations call back into it, a queued task could recurse indefinitely. Also treat a short read while committing staged content as an error rather than silently truncating the destination, and throw ObjectDisposedException from a disposed ChunkedBufferStream instead of calling through to a released buffer. Co-Authored-By: Claude Fable 5 <[email protected]>
There was a problem hiding this comment.
Pull request overview
Copilot reviewed 24 out of 38 changed files in this pull request and generated 2 comments.
Comments suppressed due to low confidence (1)
src/Uno.UWP/Storage/Streams/Internal/NativeWriteStreamAdapter.wasm.cs:141
- ProcessPendingAsync dequeues a task and awaits it while there may still be tasks queued. Because the queued delegates call back into ProcessPendingAsync via WriteAsync/TruncateAsync (see Write/SetLength), this creates depth-first execution that can reorder operations (e.g., later writes running before earlier ones). To preserve FIFO ordering, drain the current queue into a local batch first, then execute that batch (and repeat if new tasks were enqueued during execution).
private async Task ProcessPendingAsync()
{
// Dequeue before running: the queued operations call back into this method,
// so leaving them queued would replay them and recurse indefinitely.
while (_pendingTasks.TryDequeue(out var pendingTask))
{
await pendingTask();
}
}
A negative Position (set directly or through Seek) reached the JS buffer as a negative offset, and truncating below the cursor left it past the end, so the next write opened a zero-filled gap. Co-Authored-By: Claude Fable 5 <[email protected]>
|
🤖 Your WebAssembly Skia Sample App stage site is ready! Visit it here: https://unowasmprstaging.z20.web.core.windows.net/pr-23880/wasm-skia-net9/index.html |
There was a problem hiding this comment.
Pull request overview
Copilot reviewed 24 out of 38 changed files in this pull request and generated 4 comments.
Comments suppressed due to low confidence (3)
src/SamplesApp/SamplesApp.Samples/Windows_Storage/Pickers/FileSavePicker_LargeFileWrite.xaml.cs:109
- SaveViaPickerAsync never resets _busy on completion/cancellation/error, so after setting _busy it needs a finally to reliably clear it.
catch (Exception ex)
{
Log($"FAILED: {ex.GetType().Name}: {ex.Message}");
}
}
src/SamplesApp/SamplesApp.Samples/Windows_Storage/Pickers/FileSavePicker_LargeFileWrite.xaml.cs:145
- SaveToAppStorageAsync never resets _busy on completion/cancellation/error, so after setting _busy it needs a finally to reliably clear it.
catch (Exception ex)
{
Log($"FAILED: {ex.GetType().Name}: {ex.Message}");
}
}
src/SamplesApp/SamplesApp.Samples/Windows_Storage/Pickers/FileSavePicker_LargeFileWrite.xaml.cs:253
- WriteGeneratedAsync should restore the prior _busy state in finally (rather than always setting false) so that callers that already set _busy keep the sample locked until they finish.
_busy = false;
Two commits of the same file shared one staged entry name, so the first retention timer could delete the file a later download was still reading. In the sample, the busy flag was checked but only set inside the write loop, which also cleared it while the enclosing operation was still committing - so a second run could start mid-commit.
The download picker now streams its content to the browser through the chunked buffer, leaving FileSavePicker.SaveAs without callers.
Bring the adapter in line with the chunked stream: reject negative lengths and move the cursor to the new end when truncating below it. Also clear the chunk list explicitly when a released buffer is reused, so the reset does not depend on the release path having emptied it. Co-Authored-By: Claude Fable 5 <[email protected]>
Starting another save revoked the previous object URL immediately, which can abort a download the browser has queued but not yet dereferenced. The URL is now released after a delay long enough to cover pickup, without keeping it alive for the whole file retention. Co-Authored-By: Claude Fable 5 <[email protected]>
There was a problem hiding this comment.
Pull request overview
Copilot reviewed 25 out of 39 changed files in this pull request and generated 2 comments.
Comments suppressed due to low confidence (1)
src/Uno.UWP/Storage/Streams/Internal/NativeWriteStream.wasm.cs:126
- CopyToTargetAsync should restore the staged cache stream position after committing so FlushAsync is not observable via Position changes. Without this, any code that continues writing after a flush may write at the wrong offset.
Ideally this restoration should be in a try/finally so it also runs on commit failures.
await targetStream.CloseAsync();
_dirtyStart = long.MaxValue;
_dirtyEnd = 0;
A resize turns existing target bytes into a zero-filled gap in the staged copy, but the writable preserves the target's own bytes there, so shrinking then extending left stale content behind. The resized range is now marked dirty and committed. Committing also read through the staged stream without restoring the caller's position, so a flush moved the cursor and the next write landed in the wrong place. Co-Authored-By: Claude Fable 5 <[email protected]>
There was a problem hiding this comment.
Pull request overview
Copilot reviewed 25 out of 39 changed files in this pull request and generated no new comments.
Comments suppressed due to low confidence (1)
src/Uno.UWP/Storage/Streams/Internal/NativeWriteStream.wasm.cs:155
- FlushAsync accepts a CancellationToken but never observes it. Since this path can copy large dirty ranges back to the browser file, a pre-check avoids doing a user-visible, potentially long-running commit after cancellation has already been requested.
public override async Task FlushAsync(CancellationToken cancellationToken)
{
if (_pendingChanges)
{
await CopyToTargetAsync();
_pendingChanges = false;
}
}
|
🤖 Your WebAssembly Skia Sample App stage site is ready! Visit it here: https://unowasmprstaging.z20.web.core.windows.net/pr-23880/wasm-skia-net9/index.html |
|
The build 224271 found UI Test snapshots differences: Details
|
GitHub Issue: closes unoplatform/kahua-private#526
PR Type:
🐞 Bugfix
What changed? 🚀
On WebAssembly, saving a file through
StorageFile.OpenStreamForWriteAsync()buffered the entire payload in the browser tab's memory before committing it, so large saves failed — deterministically past ~2 GB, and unpredictably below that on memory-pressured machines. An app streaming 2 MB chunks gained nothing: the buffering happened a layer below it.Native (File System Access) write path
NativeWriteStreamstaged every write in a cache file underApplicationData.TemporaryFolder, i.e. a single contiguousUint8Arrayin emscripten's in-memory filesystem, and copied it to the destination only on flush/dispose. Two independent ceilings followed:ArrayBufferallocation beyond ~1.5–2 GiB regardless of free memory (measured: the same allocation succeeds at 4 GiB in Node, so it is a browser allocator limit, not a V8 one).The staging buffer is now a JS-side list of 2 MB chunks: no contiguous allocation, no growth spikes, and nothing file-sized in the 32-bit WASM linear memory. Flushing also copies only the range written since the last commit instead of rewriting the whole target.
Download-based fallback path (Firefox, Safari, mobile Chromium, Brave)
This path was worse: the destination was an in-memory-filesystem temp file, which
CachedFileManager.CompleteUpdatesAsyncthen read into one managedbyte[]in the WASM heap (a hard 2 GB cap, with an(int)cast that silently overflowed past it) before JS copied it again into aUint8Arrayfor the Blob — ~3× peak across three memory pools.The picker now hands out a
StorageFilebacked by the same chunked buffer, and committing streams the payload into an origin-private (OPFS) file, releasing each chunk as it lands on disk. The download is served fromhandle.getFile(), which references the stored file rather than copying it, so nothing file-sized is held in memory or in blob storage. Falls back to the previous in-memory Blob when OPFS is unavailable.Staged files are namespaced per page session, so a save reclaims leftovers from earlier sessions — the payload counts against the origin storage quota, which is as low as 2 GB in some browsers — without disturbing a download still reading from the current session's file.
Also fixed in the same paths
NativeWriteStreamAdaptercompoundedLengthon every write (+=of aMax), corruptingSeek(SeekOrigin.End)and every consumer ofLength;SetLengthwrote a stray zero byte at the current position when extending instead of extending the file.NativeWriteStream'sasync voiddisposal was fatal to the runtime — which is exactly what an allocation failure during the final copy produced — and a failed copy leaked the cache.CompleteUpdatesAsyncwas fire-and-forget, so commit failures vanished; it is now awaited.HEAPU8.slice()copies, and the download object URL is now revoked (it previously pinned the whole payload until the page closed).FileAccessMode.Readno longer accept writes..js/.d.tssiblings undersrc/Uno.UWP/ts/: the build compilests/**/*.tsinto a single bundled output, and those per-file artifacts were editor leftovers referenced by nothing.Validation
Runtime-validated against a reproduction app driving
FileSavePicker→OpenStreamForWriteAsync→CompleteUpdatesAsync, fail-before/pass-after on the same scenario:RangeError: Array buffer allocation failed, .NET runtime deadAlso verified manually in Brave (which does not expose the File System Access picker, so every save takes the fallback path) with a 4 GB save through the new sample.
PR Checklist ✅
Screenshots Compare Test Runresults.Behavioral note for reviewers: the file returned by the download-based save picker no longer has a path on the in-memory filesystem, since its content is staged outside it. It must be accessed through the storage APIs rather than
System.IOon.Path.Providerstill reportsWasmDownloadPicker.A manual sample is included (
FileSavePicker_LargeFileWrite, category Windows.Storage) that streams up to 4 GB through the save picker, app storage, and a real file copy, and reports the effective picker mode. No runtime tests are added: the failure only reproduces in a browser against real picker/OPFS APIs, which the runtime test hosts do not provide.