Mitchell Foutz All writing

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.

  1. ext4 in the guest. The root filesystem is mounted with rw,relatime,discard,errors=remount-ro,data=ordered. The discard option makes ext4 send TRIM or UNMAP requests to its block device as files are deleted. fstrim -av sends the same requests for free space on demand.
  2. The virtual disk. The WSL2 VM presents ext4.vhdx to the guest as a block device. The guest's discards arrive at this layer.
  3. 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.

  1. 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.integrated.defaultProfile.windows to PowerShell or Command Prompt, open a Windows folder, disable the ms-vscode-remote.remote-wsl extension and reload the window, and set window.restoreWindows to none for the duration. The notes rate disabling the extension as the most effective single control.

  2. 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 that apt-get clean frees about 0.33 GB. The fstrim count is informational. If fstrim fails, the run continues, because the discard mount option has already issued discards for the deleted files. Success: df -h / reports used space at or below the last recorded figure.

  3. Stop running containers. wsl --shutdown stops 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 ps

    Success: docker ps lists no running containers.

  4. 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
  5. 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, SessionId

    Success requires both parts: --list --running reports no running distributions, and no vmmemWSL, wslhost or vmwp process remains. wslservice running alone, with no VM, does not hold the file. If a wslhost remains, find the application that started it:

    Get-CimInstance Win32_Process -Filter "Name='wslhost.exe'" |
      Select-Object ProcessId, ParentProcessId, CreationDate, CommandLine

    Resolve 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 that Stop-Process on vmmemWSL returns access denied.

  6. 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)}}
  7. 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
    exit

    An elevated wrapper captures its own transcript, because the notes record that Start-Process -Verb RunAs cannot 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-Transcript

    Per the notes, compacting without attach vdisk readonly fails or does less work, and read-only attachment keeps stray writes out of the ext4 image. automount disable suppresses 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.log contains "DiskPart successfully compacted the virtual disk file." and DISKPART_EXIT=0.

  8. 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.vhdx in the same LocalState directory can be deleted; WSL recreates it at the next boot.

  9. 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_OK prints, used space matches step 2, and the container log shows a clean start. Then re-enable the WSL extension and restore window.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:

ItemValue in the notesBasis
ext4.vhdx beforeabout 250 GBMarked unverified
ext4.vhdx afterabout 145 to 160 GBExpectation
Free space gained on C:about 90 to 105 GBDerived from the 250 GB estimate and the 140 GiB of live data
Gain that triggers the fallbacksunder 10 GBThreshold

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.

  1. 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.

  2. 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

    -NoDriveLetter serves the same purpose as automount disable. If Optimize-VHD is missing, Enable-WindowsOptionalFeature -Online -FeatureName Microsoft-Hyper-V-Management-PowerShell installs it and may require a reboot.

  3. Find the remaining handle holder with handle64.exe -accepteula ext4.vhdx, or in Resource Monitor on the CPU tab under Associated Handles.

  4. 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 .ps1 file in %USERPROFILE%\wsl-compact and run it with powershell -NoProfile -File. Run from a file, a throw ends 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.ps1 exports 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 makes wsl --export fail; 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.ps1 only after export-verify.ps1 printed EXPORT_VERIFIED. It is the destructive step: wsl --unregister deletes 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