You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Stream resource downloads to disk instead of buffering them in memory - #7918
ResourceManagerUtils.DownloadResource called HttpClient.GetAsync without an HttpCompletionOption, so the default ResponseContentRead buffered the whole response body in memory before returning.
For large resources such as FastTextWikipedia300D (wiki.en.vec, ~6.6 GB), Content-Length exceeds HttpClient.MaxResponseContentBufferSize (2 GB). The request fails immediately (before any bytes are transferred) with Cannot write more bytes to the buffer than the configured maximum buffer size, and each of the retries repeats the same failure. See the analysis and measurements in the issue thread.
Changes
Use HttpCompletionOption.ResponseHeadersRead and copy the response stream straight to the temp file, keeping memory use constant.
Share a single HttpClient with an infinite per-request timeout; the existing outer timeout and the CancellationToken still bound the operation.
Replace the thread-affine Mutex with a cross-process file lock. After an await, the continuation can run on a different thread than the one that acquired the Mutex, which makes ReleaseMutex throw.
Dispose the HttpResponseMessage, drop the redundant second EnsureSuccessStatusCode call, and also handle HttpRequestException and TaskCanceledException.
Make DownloadResourceinternal so it can be tested (InternalsVisibleTo for Microsoft.ML.Core.Tests already exists).
Local results: the 5 new tests and the existing WordEmbeddings tests pass on macOS arm64. I did not download the full 6.6 GB model in the test suite; a ~120 s sample against the live CDN is described in the issue.
DownloadResource called HttpClient.GetAsync without an HttpCompletionOption,
so the default ResponseContentRead buffered the whole body before returning.
For large resources such as FastTextWikipedia300D (wiki.en.vec, ~6.6 GB) the
Content-Length exceeds HttpClient.MaxResponseContentBufferSize (2 GB), so the
request failed immediately with "Cannot write more bytes to the buffer than
the configured maximum buffer size" and every retry repeated the failure.
Changes:
- Use HttpCompletionOption.ResponseHeadersRead and copy the response stream
straight to the temp file, keeping memory use constant.
- Share a single HttpClient with an infinite per-request timeout; the existing
outer timeout and the CancellationToken still bound the operation.
- Replace the thread-affine Mutex with a cross-process file lock, since the
continuation after an await can run on a different thread than the one that
acquired the Mutex, which makes ReleaseMutex throw.
- Dispose the HttpResponseMessage, drop the redundant second
EnsureSuccessStatusCode call, and also handle HttpRequestException and
TaskCanceledException.
- Make DownloadResource internal so it can be tested.
Add offline loopback tests covering streaming to disk, HTTP error statuses,
redirect to the default page, cancellation, and concurrent downloads of the
same file.
Fixesdotnet#5532
The reason will be displayed to describe this comment to others. Learn more.
🟡 Changes recommended
Unsupported APIs in the new tests break Windows net48 compilation, while unisolated allocation measurements risk flaky failures and overly broad I/O retries can mask permanent filesystem errors.
Updates ML.NET’s shared resource downloader to avoid buffering entire responses in memory, addressing the large-model download limit reported in #5532.
Changes:
Stream responses directly to temporary files, reuse one HttpClient, and improve response disposal and error handling.
Replace the thread-affine mutex with a file lock for concurrent download coordination.
Add five loopback tests covering streaming, HTTP errors, default-page redirects, cancellation, and concurrent downloads.
- Guard GC.GetTotalAllocatedBytes with #if NET, replace Array.Fill with a
loop and use the byte[] WriteAsync overload so the tests compile on net48.
- Only retry lock acquisition on lock contention. Other I/O errors (missing
directory, full disk) are returned immediately instead of looping until the
download timeout. Add a test for the missing directory case.
- Run the download tests in a collection with parallelization disabled so the
allocation measurement is not affected by other tests.
The reason will be displayed to describe this comment to others. Learn more.
Copilot was unable to review this pull request because the user who requested the review has insufficient remaining quota. Try requesting a review at a lower effort level.
Hi! The only failing job is Windows_x64 Debug_Build: AutoML AutoFitRecommendationTest (AutoFitTests.cs:540, R² threshold), which doesn't touch the download code. It passed in the Release leg and all other legs, including Windows_x64_NetFx48. Could someone re-run the failed job? Thanks!
❌ Patch coverage is 93.31476% with 24 lines in your changes missing coverage. Please review.
✅ Project coverage is 70.92%. Comparing base (f603ac3) to head (83acbfd). ⚠️ Report is 1 commits behind head on main.
Hi @svick , could you please re-run the failed MacOS_x64 Release_Build job (and the MachineLearning-CI check that depends on it)?
It failed on Microsoft.ML.IntegrationTests.Evaluation.TrainAndEvaluateLightGbm with "Library not loaded: @rpath/libomp.dylib", so libomp is missing on that Helix machine. The same job passed on the previous run of this PR, and the change since then is only the merge of main. This PR doesn't touch anything native or LightGBM-related.
@Viniirb Sure, I'm rerunning the CI job. Note that the only important job is Build Analysis. If we have a known unrelated test issue (like here), one of the jobs might fail, but Build Analysis stays successful. So your PR was already good with regards to CI.
Now you'll just have to be patient with us while we review it. Thanks.
The reason will be displayed to describe this comment to others. Learn more.
🟡 Changes recommended
On .NET Framework 4.8, stalled response-body reads can defeat cancellation and retain download locks, while lock-acquisition failures can allow unsynchronized downloads or trigger indefinite retries.
- Return UnauthorizedAccessException from the download lock instead of
falling through to an unsynchronized download that could race at
File.Move.
- Detect lock contention by error code (ERROR_SHARING_VIOLATION and
ERROR_LOCK_VIOLATION on Windows, EWOULDBLOCK on Unix) instead of the
lock file's existence, so unrelated I/O failures are surfaced rather
than retried indefinitely.
- Abort a stalled response body on cancellation. On .NET Framework a
pending read ignores the token, so a server that stops sending after
the headers kept the download lock held.
- Add tests for a stalled body and a read-only lock file.
Pushed a follow-up commit addressing the latest Copilot review:
Lock acquisition now returns UnauthorizedAccessException instead of continuing unlocked.
IsLockContention now checks the error code (sharing/lock violation on Windows, EWOULDBLOCK on Unix) instead of whether the lock file exists, so unrelated I/O errors are surfaced.
The response is disposed when the token is cancelled, so a body that stalls after the headers can't keep the lock held on .NET Framework. Note that this read-with-token behavior already existed before this PR; I fixed it here since it was a one-line change.
Added tests for the stalled body and a read-only lock file.
I could only verify the net48 part through CI, so I'll keep an eye on the Windows_x64_NetFx48 leg.
response.Headers.Location can be a relative URI (for example, /payload), but accessing Uri.Host on it throws InvalidOperationException. Since every response is passed through this helper before its status is checked, even a successful response carrying a relative Location header fails instead of being downloaded. Check IsAbsoluteUri before inspecting the host, or resolve the Location against the response request URI first.
Uri.Host throws InvalidOperationException on a relative URI, so a
response carrying a relative Location header failed the download even
when it was otherwise successful. Check IsAbsoluteUri before reading
the host, and add a test for a relative redirect Location.
Pushed a follow-up commit (7f6b176) for the latest Copilot review.
IsDefaultPage now checks IsAbsoluteUri before reading Host. A relative Location header (for example /payload) made Uri.Host throw InvalidOperationException, so a response carrying one failed even when it was otherwise fine.
Added DownloadHandlesRelativeRedirectLocation. It disables auto-redirect so the 3xx response reaches the check. It fails with InvalidOperationException without the fix and passes with it.
I ran the download behavior tests locally on net8.0. I can't run the net48 leg locally, so I'll watch Windows_x64_NetFx48 in CI.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Fixes #5532
Problem
ResourceManagerUtils.DownloadResourcecalledHttpClient.GetAsyncwithout anHttpCompletionOption, so the defaultResponseContentReadbuffered the whole response body in memory before returning.For large resources such as
FastTextWikipedia300D(wiki.en.vec, ~6.6 GB),Content-LengthexceedsHttpClient.MaxResponseContentBufferSize(2 GB). The request fails immediately (before any bytes are transferred) withCannot write more bytes to the buffer than the configured maximum buffer size, and each of the retries repeats the same failure. See the analysis and measurements in the issue thread.Changes
HttpCompletionOption.ResponseHeadersReadand copy the response stream straight to the temp file, keeping memory use constant.HttpClientwith an infinite per-request timeout; the existing outer timeout and theCancellationTokenstill bound the operation.Mutexwith a cross-process file lock. After anawait, the continuation can run on a different thread than the one that acquired theMutex, which makesReleaseMutexthrow.HttpResponseMessage, drop the redundant secondEnsureSuccessStatusCodecall, and also handleHttpRequestExceptionandTaskCanceledException.DownloadResourceinternalso it can be tested (InternalsVisibleToforMicrosoft.ML.Core.Testsalready exists).Tests
Added offline loopback tests (
TestResourceDownloadBehavior) covering:Added offline loopback tests (
TestResourceDownloadBehavior) covering:Local results: the 5 new tests and the existing
WordEmbeddingstests pass on macOS arm64. I did not download the full 6.6 GB model in the test suite; a ~120 s sample against the live CDN is described in the issue.