Why trimming does not shrink a WSL disk
I freed 59.7 GiB inside a WSL2 distro and running fstrim in the guest did not shrink the host file. The guest's discards stop at ext4.vhdx, a dynamically expanding virtual disk with sparse mode off; the space returns to Windows only through offline compaction of that file with the WSL VM fully stopped.
- Published
- 2026-10-28 (draft)
- Topic
- Tooling
- Environment
- WSL2, WSL 2.7.10.0, guest kernel 6.18.33.2-2
- Measured
- 2026-09-10 and 2026-09-11
- Verification
- Self-reported. The investigation notes are a private record that is not published, so the cleanup and size measurements cannot be checked independently.
Symptom: 59.7 GiB freed in the guest, none returned to the host
On 2026-09-10 I removed 59.7 GiB of data inside an Ubuntu distro running under WSL2: the Docker build cache, 123 unused Docker images, the npm and uv caches, and the caches of vscode-cpptools, Playwright, huggingface, Puppeteer, the AWS CLI, pip and VS Code extension packages. My notes from the next day record that none of that space had returned to the Windows drive.
The guest filesystem held 135.3 GiB of live data on 2026-09-10 and 140 GiB on 2026-09-11, inside an ext4 virtual capacity of 1007 GiB. The host file, ext4.vhdx, was estimated at about 250 GB. The notes mark that estimate as unverified.
The notes stop before the compaction ran. They contain no measured size of ext4.vhdx before or after, so the charts below show guest-side measurements only, and the expected reduction later in this article is an estimate.
Why the virtual disk keeps its size
A deleted file passes through three layers on its way to the Windows drive. The discards stop at the third.
flowchart TB del["File deleted in the guest"] --> fs["ext4 on /, mounted with discard"] fs -->|"TRIM or UNMAP, also from fstrim"| dev["Virtual disk of the WSL2 VM"] dev --> vhdx["ext4.vhdx: dynamically expanding, sparse off"] vhdx -.->|"discarded blocks stay allocated"| host["Host file size unchanged"] compact["diskpart or Optimize-VHD, VM stopped"] -->|"exclusive handle"| vhdx
- ext4 in the guest. The root filesystem is mounted with
rw,relatime,discard,errors=remount-ro,data=ordered. Thediscardoption makes ext4 send TRIM or UNMAP requests to its block device as files are deleted.fstrim -avsends the same requests for free space on demand. - The virtual disk. The WSL2 VM presents ext4.vhdx to the guest as a block device. The guest's discards arrive at this layer.
- ext4.vhdx on the host. The file is a dynamically expanding VHDX. It grows as the guest writes and does not shrink by itself. Sparse mode is off for this file, so the virtual disk layer does not punch holes in it when discards arrive. The discarded blocks stay allocated in the host file.
The byte count that fstrim -av prints is the amount of discard the guest issued. The notes give "797 GiB trimmed" as an example of that output. Inference: a figure larger than both the 140 GiB of live data and the estimated 250 GB host file cannot describe a reduction in the host file.
With sparse mode off, the notes identify offline compaction as the in-place way to return the space: diskpart with compact vdisk, or the Hyper-V cmdlet Optimize-VHD. Compaction needs an exclusive handle on ext4.vhdx. A running WSL VM holds that handle, so the VM must be fully stopped and must stay stopped until compaction finishes.
Why the first attempt failed
On 2026-09-10 I tried to turn sparse mode on with wsl --manage <distro> --set-sparse true --allow-unsafe. The command returned WSL_E_DISTRO_NOT_STOPPED on every attempt. After every wsl --shutdown, vmmemWSL and two wslhost processes in session 1 were still running.
The cause was a VS Code Remote-WSL window hosting a Claude Code session inside the distro. The notes record that the Remote-WSL server reconnected within milliseconds of each shutdown and re-attached the VHDX before the next command ran. The notes attribute two wslhost instances in session 1 to an interactive application. Docker Desktop, Task Scheduler, Microsoft Defender and startup tasks were ruled out.
The revised procedure leaves sparse mode off. The notes record that Microsoft disabled sparse VHD support by default after reports of data corruption, which is the reason the flag is named --allow-unsafe. Sparse mode would reclaim space automatically, at a nonzero risk of losing the whole filesystem. The notes schedule offline compaction instead: quarterly, or whenever the VHDX exceeds about 1.5 times the live data size.
Procedure
The notes were written as a runbook for a coding agent in a Windows terminal, with me approving each UAC prompt. Each step has a success condition. When a condition is not met, the run stops and nothing later is attempted.
Paths are generic. <distro> is the WSL distro name, <distro package> is its package directory under %LOCALAPPDATA%\Packages, <container> is a running container, and the scripts live in %USERPROFILE%\wsl-compact. Each PowerShell script that reads wsl.exe output sets $env:WSL_UTF8 = 1 first. Without it, wsl.exe emits UTF-16LE, which Windows PowerShell 5.1 renders with interleaved null bytes.
-
Close every path back into the distro. Close Remote-WSL windows; integrated terminals and Windows Terminal tabs that run a WSL shell; File Explorer windows on the distro's network share and any drive letter mapped to it; Docker Desktop; and IDEs with a WSL interpreter. In the VS Code window that stays open, set
terminal.to PowerShell or Command Prompt, open a Windows folder, disable theintegrated. defaultProfile. windows ms-vscode-remote.remote-wslextension and reload the window, and setwindow.restoreWindowstononefor the duration. The notes rate disabling the extension as the most effective single control. -
Reclaim inside the guest and trim. The commands run as root through
wsl.exe -u root, so no password prompt appears.wsl.exe -d <distro> -u root -- journalctl --vacuum-size=100M wsl.exe -d <distro> -u root -- apt-get clean wsl.exe -d <distro> -u root -- fstrim -av wsl.exe -d <distro> -u root -- df -h /The notes estimate that the journal vacuum frees about 0.46 GB of the 0.56 GB in
/var/log/journal, and thatapt-get cleanfrees about 0.33 GB. Thefstrimcount is informational. Iffstrimfails, the run continues, because thediscardmount option has already issued discards for the deleted files. Success:df -h /reports used space at or below the last recorded figure. -
Stop running containers.
wsl --shutdownstops the VM abruptly. One Neo4j container was running. A 60 second timeout gives it time to checkpoint.wsl.exe -d <distro> -u root -- docker stop -t 60 <container> wsl.exe -d <distro> -u root -- docker psSuccess:
docker pslists no running containers. -
Optional: exclude the distro directory from Microsoft Defender. Administrator. The notes' reasoning: Defender cannot read ext4 contents, and the block changes that compaction produces trigger a full rescan of a file estimated at about 250 GB.
The exclusion persists until it is removed. The script below records whether the path was already excluded, adds it only if it was not, and step 9 removes only an exclusion added here. The record is written once: when step 4 is run again after a failed or interrupted run, the existing record is kept, so a retry does not mistake the exclusion added by the first attempt for one that existed before the procedure. The record and the removal are additions by this article; the notes add the exclusion and do not remove it.
$work = "$env:USERPROFILE\wsl-compact" $localState = "$env:LOCALAPPDATA\Packages\<distro package>\LocalState" $record = "$work\defender-exclusion.txt" $excluded = @((Get-MpPreference).ExclusionPath) -contains $localState if (-not (Test-Path -LiteralPath $record)) { Set-Content -Path $record -Value $(if ($excluded) { 'PREEXISTING' } else { 'ADDED' }) } if (-not $excluded) { Add-MpPreference -ExclusionPath $localState } Get-Content -Path $record (Get-MpPreference).ExclusionPath -
Shut down WSL and confirm it stayed down.
$env:WSL_UTF8 = 1 wsl.exe --shutdown Start-Sleep -Seconds 15 wsl.exe --list --running Get-Process -ErrorAction SilentlyContinue | Where-Object { $_.Name -match '^(vmmemWSL|wslhost|vmwp)$' } | Select-Object Name, Id, SessionIdSuccess requires both parts:
--list --runningreports no running distributions, and novmmemWSL,wslhostorvmwpprocess remains.wslservicerunning alone, with no VM, does not hold the file. If awslhostremains, find the application that started it:Get-CimInstance Win32_Process -Filter "Name='wslhost.exe'" | Select-Object ProcessId, ParentProcessId, CreationDate, CommandLineResolve the parent with
Get-Process -Id <ParentProcessId>and close it. If that finds nothing,Restart-Service WSLService -Force(administrator) takes the VM down. The notes record thatStop-ProcessonvmmemWSLreturns access denied. -
Record the size before. No elevation needed.
$vhdx = "$env:LOCALAPPDATA\Packages\<distro package>\LocalState\ext4.vhdx" Get-Item $vhdx | Select-Object Name, @{n='SizeGB';e={[math]::Round($_.Length/1GB,2)}}, LastWriteTime Get-PSDrive C | Select-Object @{n='FreeGB';e={[math]::Round($_.Free/1GB,2)}} -
Compact. Administrator. The diskpart script,
compact.txt, saved as ASCII:automount disable select vdisk file="<full path to ext4.vhdx>" attach vdisk readonly compact vdisk detach vdisk automount enable exitAn elevated wrapper captures its own transcript, because the notes record that
Start-Process -Verb RunAscannot be combined with-RedirectStandardOutput:$work = "$env:USERPROFILE\wsl-compact" Start-Transcript -Path "$work\compact.log" -Force diskpart /s "$work\compact.txt" Write-Output "DISKPART_EXIT=$LASTEXITCODE" Stop-TranscriptPer the notes, compacting without
attach vdisk readonlyfails or does less work, and read-only attachment keeps stray writes out of the ext4 image.automount disablesuppresses the "You need to format the disk" dialog that Windows raises for a volume it cannot read; clicking Format there would destroy the distro. The notes expect several minutes to tens of minutes with no progress output, and set the tool timeout at 45 minutes or more. Success:compact.logcontains "DiskPart successfully compacted the virtual disk file." andDISKPART_EXIT=0. -
Record the size after with the step 6 commands and compare. If the gain is under 10 GB, go to the fallbacks below. While WSL is still stopped,
swap.vhdxin the sameLocalStatedirectory can be deleted; WSL recreates it at the next boot. -
Restart and verify.
wsl.exe -d <distro> -- bash -lc "df -h / && echo FS_OK" wsl.exe -d <distro> -u root -- docker start <container> wsl.exe -d <distro> -u root -- docker logs --tail 30 <container>Success:
FS_OKprints, used space matches step 2, and the container log shows a clean start. Then re-enable the WSL extension and restorewindow.restoreWindows.If step 4 ran, remove the exclusion it added. Administrator. A path that was excluded before step 4 stays excluded. The record is deleted only after the exclusion list shows the intended state, so the next run of the procedure starts with a new record; if the removal fails, the record stays and this block can be run again.
$ErrorActionPreference = 'Stop' $work = "$env:USERPROFILE\wsl-compact" $localState = "$env:LOCALAPPDATA\Packages\<distro package>\LocalState" $record = "$work\defender-exclusion.txt" $added = (Get-Content -Path $record) -eq 'ADDED' if ($added) { Remove-MpPreference -ExclusionPath $localState } $excluded = @((Get-MpPreference).ExclusionPath) -contains $localState if ($added -and $excluded) { throw "exclusion is still present: $localState" } Remove-Item -LiteralPath $record (Get-MpPreference).ExclusionPath
Before and after sizes
The notes contain no measured size of ext4.vhdx before or after compaction. The figures they give for checking the result are estimates:
| Item | Value in the notes | Basis |
|---|---|---|
| ext4.vhdx before | about 250 GB | Marked unverified |
| ext4.vhdx after | about 145 to 160 GB | Expectation |
| Free space gained on C: | about 90 to 105 GB | Derived from the 250 GB estimate and the 140 GiB of live data |
| Gain that triggers the fallbacks | under 10 GB | Threshold |
No chart is drawn for these figures, because none has a measured source. A measured result needs the two readings from steps 6 and 8, and the notes instruct the operator to report those readings and to treat the estimates as sanity checks only.
If compaction reclaims little
The notes give these checks in order.
Confirm the VHDX was detached during the run. Repeat step 5 until both conditions hold, then repeat step 7. The notes name a silent partial failure as the most common cause.
-
Run the Hyper-V optimizer. Administrator. The notes describe it as more thorough than diskpart and record that its PowerShell module is available without the full hypervisor.
Mount-VHD -Path $vhdx -ReadOnly -NoDriveLetter Optimize-VHD -Path $vhdx -Mode Full Dismount-VHD -Path $vhdx-NoDriveLetterserves the same purpose asautomount disable. IfOptimize-VHDis missing,Enable-WindowsOptionalFeature -Online -FeatureName Microsoft-Hyper-V-Management-PowerShellinstalls it and may require a reboot. Find the remaining handle holder with
handle64.exe -accepteula ext4.vhdx, or in Resource Monitor on the CPU tab under Associated Handles.-
Export and reimport. This builds a new VHDX that contains only live data. The notes estimate the tar for 140 GiB of live data at roughly 100 GB or more, written to a different physical drive.
The notes give export, unregister and import as one sequence. Here they are split into two scripts, and the first one stops before anything is deleted. Save each as a
.ps1file in%USERPROFILE%\wsl-compactand run it withpowershell -NoProfile -File. Run from a file, athrowends the script. Pasted into a console, the lines can run one at a time, depending on the console, and a failed line then does not stop the lines after it. The exit code checks, the hash check and the verification distro are additions by this article.export-verify.ps1exports the distro, checks the export, records the SHA-256 hash of the tar, imports the tar under a second name and starts it. A full backup drive makeswsl --exportfail; the script then stops. The verification distro is kept: it is a second, started copy of the data and is removed only after the replacement has started. It needs about as much free space on the backup drive as the distro's live data, in addition to the tar. Hashing reads the whole tar, so each hash adds a full read of roughly 100 GB.$ErrorActionPreference = 'Stop' $env:WSL_UTF8 = 1 $work = "$env:USERPROFILE\wsl-compact" $tar = "<backup drive>:\<distro>-backup.tar" wsl.exe --shutdown wsl.exe --export <distro> $tar if ($LASTEXITCODE -ne 0) { throw "wsl --export exited with $LASTEXITCODE" } $exported = Get-Item -LiteralPath $tar if ($exported.Length -le 0) { throw "export file is empty: $tar" } $hash = (Get-FileHash -LiteralPath $tar -Algorithm SHA256).Hash wsl.exe --import <distro>-verify "<backup drive>:\<distro>-verify" $tar if ($LASTEXITCODE -ne 0) { throw "verification import exited with $LASTEXITCODE" } wsl.exe -d <distro>-verify -u root -- df -h / if ($LASTEXITCODE -ne 0) { throw "verification distro did not start" } wsl.exe --terminate <distro>-verify Set-Content -Path "$work\export-verified.txt" -Value $hash Write-Output "EXPORT_VERIFIED sha256=$hash"Run
replace.ps1only afterexport-verify.ps1printedEXPORT_VERIFIED. It is the destructive step:wsl --unregisterdeletes the distro and its ext4.vhdx and cannot be undone. The script refuses to run when the verification record is missing, when the tar's SHA-256 hash differs from the recorded one, or when the verification distro is no longer registered. It removes the verification distro last, after the replacement has been imported and started; until then, a failed import leaves both the tar and the verification distro.$ErrorActionPreference = 'Stop' $env:WSL_UTF8 = 1 $work = "$env:USERPROFILE\wsl-compact" $tar = "<backup drive>:\<distro>-backup.tar" $verifiedHash = (Get-Content -Path "$work\export-verified.txt").Trim() $currentHash = (Get-FileHash -LiteralPath $tar -Algorithm SHA256).Hash if ($currentHash -ne $verifiedHash) { throw "tar hash differs from the verified export" } if (@(wsl.exe --list --quiet) -notcontains '<distro>-verify') { throw "verification distro is not registered" } wsl.exe --shutdown wsl.exe --unregister <distro> if ($LASTEXITCODE -ne 0) { throw "wsl --unregister exited with $LASTEXITCODE" } wsl.exe --import <distro> "$env:LOCALAPPDATA\Packages\<distro package>\LocalState" $tar if ($LASTEXITCODE -ne 0) { throw "wsl --import exited with $LASTEXITCODE; the tar and <distro>-verify are kept" } wsl.exe -d <distro> -u root -- df -h / if ($LASTEXITCODE -ne 0) { throw "reimported distro did not start; <distro>-verify is kept" } wsl.exe --unregister <distro>-verify if ($LASTEXITCODE -ne 0) { throw "wsl --unregister of the verification distro exited with $LASTEXITCODE" } Write-Output "REIMPORTED"After the import the default user is root. Restore
/etc/wsl.conf, keeping the existing[boot]section:[boot] systemd=true [user] default=<user>
Limits and risks
- Back up first. When the notes were written, no backup of the 140 GiB inside the VHDX existed, and the notes identify an interrupted in-place compaction as the one step that can leave the VHDX damaged. The
wsl --exportcommand from fallback 4, written to a different physical drive before step 7, provides that backup. Running it first is my recommendation; the recorded procedure does not include it. - Shut WSL down and keep it down. Any client that re-attaches the distro during compaction takes the handle back. On 2026-09-10 a Remote-WSL window did this within milliseconds of every shutdown.
- Administrator rights are needed for
diskpart(step 7),Add-MpPreference(step 4),Remove-MpPreference(step 9),Restart-Service WSLService(step 5 fallback) and the Hyper-V cmdlets (fallback 2). Guest commands throughwsl.exe -u root,wsl --shutdownand the size readings run unelevated. From an unelevated terminal each elevated step raises one UAC prompt, and an unattended prompt stalls the run. - Do not zero-fill free space in the guest to help compaction. The notes record that it would first inflate the VHDX toward the 1007 GiB virtual capacity, which the C: drive could not hold.
- Do not click Format on any disk dialog during the run. A dialog means
automount disabledid not take effect; the notes say to dismiss it and abort. - Automount can stay disabled. If diskpart aborts between
automount disableandautomount enable, newly attached USB drives stop mounting. Recovery isautomount enablefrom an elevated diskpart. - The Defender exclusion in step 4 stops scanning of the distro directory until step 9 removes it. The notes accept that because Defender cannot read ext4 contents. If the run stops before step 9, the exclusion stays in place;
defender-exclusion.txtrecords whether to remove it. - Scope. All observations come from one machine running WSL 2.7.10.0 with guest kernel 6.18.33.2-2. The notes do not record the Windows build. The compaction result was not measured, as stated above.